mirror of
https://github.com/mvschwarz/openrig.git
synced 2026-11-11 17:32:22 -10:00
Compare commits
7
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9079345a9a | ||
|
|
85dd8d2988 | ||
|
|
44bea397da | ||
|
|
16e7119e42 | ||
|
|
9ba51dc273 | ||
|
|
e9ccd4aacd | ||
|
|
c17b825490 |
No files matched your search
+20
-125
@@ -1,31 +1,16 @@
|
||||
name: Tests
|
||||
|
||||
# Builds, type-checks and runs every test suite on a clean GitHub runner, and records the file
|
||||
# list each published package would contain. Each suite is its own job so one failure does not
|
||||
# hide the others. No provider credentials or operator configuration are supplied.
|
||||
# Package suites deny external networking; scenario runtime has no external route.
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
pull_request:
|
||||
branches: [main]
|
||||
workflow_dispatch:
|
||||
|
||||
on: workflow_dispatch
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: tests-${{ github.event_name }}-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
build-and-package:
|
||||
cleanup-results-and-effects:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
timeout-minutes: 15
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
ref: c6d41cb90154585f1f1eca815085c086fe69318e
|
||||
fetch-depth: 0
|
||||
persist-credentials: false
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
@@ -33,110 +18,20 @@ jobs:
|
||||
cache: npm
|
||||
- run: npm ci
|
||||
- run: npm run build
|
||||
- name: Record the published file list of each package
|
||||
- name: Original main ignores the override and reaches no cleanup fault
|
||||
run: |
|
||||
set -euo pipefail
|
||||
mkdir -p pack-lists
|
||||
for p in cli daemon tui; do
|
||||
(cd packages/$p && npm pack --dry-run --json --ignore-scripts) \
|
||||
| node -e 'let s="";process.stdin.on("data",d=>s+=d).on("end",()=>{for(const f of JSON.parse(s)[0].files)console.log(f.path)})' \
|
||||
| sort > pack-lists/$p.txt
|
||||
echo "$p: $(wc -l < pack-lists/$p.txt) files"
|
||||
done
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: pack-lists
|
||||
path: pack-lists/
|
||||
|
||||
typecheck:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
persist-credentials: false
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 22
|
||||
cache: npm
|
||||
- run: npm ci
|
||||
- run: npm run lint
|
||||
|
||||
repo-checks:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
persist-credentials: false
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 22
|
||||
cache: npm
|
||||
- run: npm ci
|
||||
- run: npm run test:repo
|
||||
|
||||
package-tests:
|
||||
if: ${{ github.event_name != 'push' }}
|
||||
# macOS, the platform OpenRig runs on: several daemon and cli tests read macOS ps columns,
|
||||
# file-inode behaviour and release tags.
|
||||
runs-on: macos-latest
|
||||
timeout-minutes: 45
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
package: [daemon, cli, tui, ui]
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
persist-credentials: false
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 22
|
||||
cache: npm
|
||||
- run: brew install tmux
|
||||
- run: npm ci
|
||||
- name: Build the packages the tests import
|
||||
run: npm run build
|
||||
- name: Run the suite without ambient credentials or external network
|
||||
git checkout aa097e6dc8b035934a6a4376110d687018ca7d17 -- packages/daemon/src/domain/types.ts packages/daemon/src/domain/rigspec-instantiator.ts packages/daemon/src/domain/bootstrap-orchestrator.ts packages/cli/src/commands/up.ts packages/cli/src/commands/bundle.ts
|
||||
EXPECT_ENV_CLEANUP_BASELINE=1 npx vitest run packages/daemon/test/bootstrap-orchestrator.test.ts -t 'cleanup failure accounting'
|
||||
- name: Prior forwarding head must expose exactly twelve missing failure-reporting assertions
|
||||
run: |
|
||||
suite_root=$(mktemp -d "$RUNNER_TEMP/opr-test.XXXXXX")
|
||||
suite_root=$(cd "$suite_root" && pwd -P)
|
||||
mkdir -p "$suite_root/home" "$suite_root/bin"
|
||||
# Same system bytes, nonprivileged mode; no system file is changed.
|
||||
/usr/bin/install -m 0755 /bin/ps "$suite_root/bin/ps"
|
||||
# Only this job's temporary sockets (including tmux) are reachable.
|
||||
env -i HOME="$suite_root/home" PATH="$PATH" TMPDIR="$suite_root" TMUX_TMPDIR="$suite_root" \
|
||||
CI=true TERM=xterm-256color \
|
||||
sandbox-exec -D IPC_ROOT="$suite_root" -p '(version 1)(allow default)(deny network-outbound)(allow network-outbound (remote ip "localhost:*"))(allow network-outbound (subpath (param "IPC_ROOT")))' \
|
||||
/bin/bash -s "${{ matrix.package }}" <<'SUITE'
|
||||
set -euo pipefail
|
||||
node scripts/ci-macos-process-probe.mjs
|
||||
# The production readers use bare ps. Select real system bytes only after
|
||||
# self/owned-child observation and network/IPC confinement are proved.
|
||||
export PATH="$TMPDIR/bin:$PATH"
|
||||
test "$(command -v ps)" = "$TMPDIR/bin/ps"
|
||||
exec npm run test -w "packages/$1"
|
||||
SUITE
|
||||
|
||||
installed-scenario:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 35
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
persist-credentials: false
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 22
|
||||
cache: npm
|
||||
- run: npm ci
|
||||
- name: Installed package, daemon restart, and seeded durability failure
|
||||
run: bash scripts/run-pr-scenarios.sh
|
||||
- uses: actions/upload-artifact@v4
|
||||
if: always()
|
||||
with:
|
||||
name: installed-scenario-evidence
|
||||
path: dist/pr-scenarios/
|
||||
if-no-files-found: error
|
||||
git checkout 9ba51dc2733160d867f0f7bf418d725b7bd3c1fd -- packages/daemon/src/domain/types.ts packages/daemon/src/domain/rigspec-instantiator.ts packages/daemon/src/domain/bootstrap-orchestrator.ts packages/cli/src/commands/up.ts packages/cli/src/commands/bundle.ts
|
||||
set +e
|
||||
npx vitest run packages/daemon/test/bootstrap-orchestrator.test.ts -t 'cleanup failure accounting' --reporter=json --outputFile=/tmp/cleanup-prior.json
|
||||
result=$?
|
||||
set -e
|
||||
test "$result" = 1
|
||||
node -e 'const r=require("/tmp/cleanup-prior.json"); const f=r.testResults.flatMap(x=>x.assertionResults).filter(x=>x.status==="failed"); if(r.numFailedTests!==12 || r.numPassedTests!==0 || f.length!==12 || f.some(x=>!x.fullName.includes("cleanup failure accounting")))process.exit(1); console.log("Exactly12 prior forwarding-head cleanup-accounting target failures.")'
|
||||
- name: Candidate preserves cleanup guidance and non-success results with effects measured
|
||||
run: |
|
||||
git checkout c6d41cb90154585f1f1eca815085c086fe69318e -- packages/daemon/src/domain/types.ts packages/daemon/src/domain/rigspec-instantiator.ts packages/daemon/src/domain/bootstrap-orchestrator.ts packages/cli/src/commands/up.ts packages/cli/src/commands/bundle.ts
|
||||
npx vitest run packages/daemon/test/bootstrap-orchestrator.test.ts packages/daemon/test/rigspec-instantiator.test.ts packages/daemon/test/up-route-env.test.ts packages/daemon/test/node-launcher-one-off-env.test.ts packages/daemon/test/seat-env.test.ts packages/cli/test/up.test.ts packages/cli/test/bundle.test.ts
|
||||
@@ -429,6 +429,9 @@ const ROUTING_LABELS: Array<[string, string]> = [
|
||||
|
||||
/** Render the daemon's reason verbatim, including continuation guidance when available. */
|
||||
export function startupAttentionSummary(data: Record<string, unknown>): string[] {
|
||||
if (data["code"] === "seat_env_cleanup_failed") {
|
||||
return ((data["errors"] as string[] | undefined) ?? []).map(error => `Launch incomplete: ${error}`);
|
||||
}
|
||||
const stages = data["stages"] as Array<{ detail?: { attentionNodes?: Array<{ sessionName?: string; logicalId?: string; reason?: string }> } }> | undefined;
|
||||
const lines: string[] = [];
|
||||
for (const stage of Array.isArray(stages) ? stages : []) {
|
||||
|
||||
@@ -234,6 +234,7 @@ team back with its conversations, run rig up <rig-name> --existing, not the spec
|
||||
for (const line of formatRemoteUpFailure(opts.host, result)) console.error(line);
|
||||
process.exitCode = 1;
|
||||
}
|
||||
if ((result.data as Record<string, unknown> | undefined)?.code === "seat_env_cleanup_failed") process.exitCode = 1;
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -507,6 +508,7 @@ team back with its conversations, run rig up <rig-name> --existing, not the spec
|
||||
if (opts.json) {
|
||||
console.log(JSON.stringify(res.data));
|
||||
if (res.status >= 400) process.exitCode = res.status === 409 ? 1 : 2;
|
||||
else if (res.data["code"] === "seat_env_cleanup_failed") process.exitCode = 1;
|
||||
const rigResult = res.data["rigResult"] as string | undefined;
|
||||
if (rigResult === "partially_restored" || rigResult === "failed" || rigResult === "not_attempted") process.exitCode = 1;
|
||||
return;
|
||||
|
||||
@@ -61,6 +61,8 @@ export interface BootstrapStageResult {
|
||||
|
||||
/** Full bootstrap result */
|
||||
export interface BootstrapResult {
|
||||
/** A started launch failed to remove one-off env from tmux session state. */
|
||||
code?: string;
|
||||
runId: string;
|
||||
status: BootstrapStatus;
|
||||
stages: BootstrapStageResult[];
|
||||
@@ -635,10 +637,15 @@ export class BootstrapOrchestrator {
|
||||
}
|
||||
|
||||
const nonInterruptive = opts.nonInterruptive ?? (new SettingsStore().resolveOne("launch.non_interruptive").value === true);
|
||||
const instantiateOutcome = await this.deps.rigInstantiator.instantiate(spec, { nonInterruptive });
|
||||
const instantiateOutcome = await this.deps.rigInstantiator.instantiate(spec, { nonInterruptive, ...(opts.envOverride ? { env: opts.envOverride } : {}) });
|
||||
if ((instantiateOutcome.ok || "rigId" in instantiateOutcome) && (nonInterruptive || opts.nonInterruptive === false)) warnings.push(nonInterruptiveSummary(nonInterruptive));
|
||||
|
||||
this.deps.bootstrapRepo.journalAction(run.id, seqCounter++, "rig_import", null, spec.name, instantiateOutcome.ok ? "completed" : "failed", {
|
||||
const envCleanupErrors = instantiateOutcome.ok ? instantiateOutcome.result.envCleanupErrors
|
||||
: instantiateOutcome.code === "instantiate_error" ? instantiateOutcome.envCleanupErrors : undefined;
|
||||
const cleanupFailed = Boolean(envCleanupErrors?.length);
|
||||
if (envCleanupErrors) errors.push(...envCleanupErrors);
|
||||
|
||||
this.deps.bootstrapRepo.journalAction(run.id, seqCounter++, "rig_import", null, spec.name, instantiateOutcome.ok && !cleanupFailed ? "completed" : "failed", {
|
||||
detailJson: JSON.stringify(instantiateOutcome),
|
||||
});
|
||||
|
||||
@@ -647,16 +654,16 @@ export class BootstrapOrchestrator {
|
||||
stages.push({ stage: "import_rig", status: "failed", detail: instantiateOutcome });
|
||||
const finalStatus: BootstrapStatus = hasExecFailures || packageInstallFailed ? "partial" : "failed";
|
||||
this.deps.bootstrapRepo.updateRunStatus(run.id, finalStatus);
|
||||
return { runId: run.id, status: finalStatus, stages, errors, warnings };
|
||||
return { runId: run.id, status: finalStatus, stages, errors, warnings, ...(cleanupFailed ? { code: "seat_env_cleanup_failed" as const } : {}) };
|
||||
}
|
||||
|
||||
stages.push({ stage: "import_rig", status: "ok", detail: instantiateOutcome.result });
|
||||
stages.push({ stage: "import_rig", status: cleanupFailed ? "failed" : "ok", detail: instantiateOutcome.result });
|
||||
if (instantiateOutcome.result.warnings?.length) {
|
||||
warnings.push(...instantiateOutcome.result.warnings);
|
||||
}
|
||||
|
||||
// --- DONE ---
|
||||
const finalStatus: BootstrapStatus = hasExecFailures || packageInstallFailed ? "partial" : "completed";
|
||||
const finalStatus: BootstrapStatus = hasExecFailures || packageInstallFailed || cleanupFailed ? "partial" : "completed";
|
||||
this.deps.bootstrapRepo.updateRunStatus(run.id, finalStatus, { rigId: instantiateOutcome.result.rigId });
|
||||
|
||||
return {
|
||||
@@ -664,6 +671,7 @@ export class BootstrapOrchestrator {
|
||||
status: finalStatus,
|
||||
stages,
|
||||
rigId: instantiateOutcome.result.rigId,
|
||||
...(cleanupFailed ? { code: "seat_env_cleanup_failed" as const } : {}),
|
||||
errors,
|
||||
warnings,
|
||||
};
|
||||
|
||||
@@ -66,7 +66,7 @@ export class RigInstantiator {
|
||||
this.tmuxAdapter = deps.tmuxAdapter;
|
||||
}
|
||||
|
||||
async instantiate(spec: RigSpec, opts?: { nonInterruptive?: boolean }): Promise<InstantiateOutcome> {
|
||||
async instantiate(spec: RigSpec, opts?: { nonInterruptive?: boolean; env?: SeatEnv }): Promise<InstantiateOutcome> {
|
||||
// 1. Validate
|
||||
const raw = RigSpecCodec.parse(RigSpecCodec.serialize(spec));
|
||||
const validation = RigSpecSchema.validate(raw);
|
||||
@@ -148,9 +148,10 @@ export class RigInstantiator {
|
||||
const nodeResults: { logicalId: string; status: "launched" | "failed"; error?: string }[] = [];
|
||||
const launchedSessionNames: string[] = [];
|
||||
const instantiateWarnings: string[] = [];
|
||||
const envCleanupErrors: string[] = [];
|
||||
|
||||
for (const logicalId of launchOrder) {
|
||||
const result = await this.nodeLauncher.launchNode(rigId!, logicalId);
|
||||
const result = await this.nodeLauncher.launchNode(rigId!, logicalId, opts?.env ? { env: opts.env } : undefined);
|
||||
if (result.ok) {
|
||||
nodeResults.push({ logicalId, status: "launched" });
|
||||
launchedSessionNames.push(result.sessionName);
|
||||
@@ -159,6 +160,7 @@ export class RigInstantiator {
|
||||
}
|
||||
} else {
|
||||
nodeResults.push({ logicalId, status: "failed", error: result.message });
|
||||
if (result.code === "seat_env_cleanup_failed") envCleanupErrors.push(`${logicalId}: ${result.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -180,7 +182,8 @@ export class RigInstantiator {
|
||||
return {
|
||||
ok: false,
|
||||
code: "instantiate_error",
|
||||
message: "all node launches failed",
|
||||
message: envCleanupErrors.length ? `all node launches failed — ${envCleanupErrors.join("; ")}` : "all node launches failed",
|
||||
...(envCleanupErrors.length ? { envCleanupErrors } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -211,6 +214,7 @@ export class RigInstantiator {
|
||||
this.eventBus.emit({
|
||||
type: "rig.imported",
|
||||
rigId: rigId!,
|
||||
...(envCleanupErrors.length ? { envCleanupErrors } : {}),
|
||||
specName: spec.name,
|
||||
specVersion: spec.version,
|
||||
});
|
||||
|
||||
@@ -1339,7 +1339,7 @@ export type InstantiateOutcome =
|
||||
| { ok: true; result: InstantiateResult }
|
||||
| { ok: false; code: "validation_failed"; errors: string[] }
|
||||
| { ok: false; code: "preflight_failed"; errors: string[]; warnings: string[] }
|
||||
| { ok: false; code: "instantiate_error"; message: string }
|
||||
| { ok: false; code: "instantiate_error"; message: string; envCleanupErrors?: string[] }
|
||||
| { ok: false; code: "cycle_error"; message: string }
|
||||
| { ok: false; code: "service_boot_failed"; message: string }
|
||||
| { ok: false; code: "compose_project_conflict"; message: string }
|
||||
@@ -1376,6 +1376,8 @@ export interface AttentionNode {
|
||||
}
|
||||
|
||||
export interface InstantiateResult {
|
||||
/** Value-free failures taking one-off launch env out of session state. */
|
||||
envCleanupErrors?: string[];
|
||||
rigId: string;
|
||||
specName: string;
|
||||
specVersion: string;
|
||||
|
||||
@@ -159,7 +159,7 @@ describe("BootstrapOrchestrator", () => {
|
||||
};
|
||||
}
|
||||
|
||||
function buildOrchestrator(opts?: { exec?: ExecFn; instantiator?: unknown; podInstantiator?: unknown }) {
|
||||
function buildOrchestrator(opts?: { exec?: ExecFn; instantiator?: unknown; podInstantiator?: unknown; bundleSourceResolver?: unknown }) {
|
||||
const exec = opts?.exec ?? createMockExec({
|
||||
"tmux -V": "tmux 3.4",
|
||||
"claude --version": "claude 1.0.0",
|
||||
@@ -195,7 +195,7 @@ describe("BootstrapOrchestrator", () => {
|
||||
packageInstallService,
|
||||
rigInstantiator: instantiator as any,
|
||||
fsOps: realFsOps(),
|
||||
bundleSourceResolver: null,
|
||||
bundleSourceResolver: (opts?.bundleSourceResolver ?? null) as any,
|
||||
podInstantiator: opts?.podInstantiator as any,
|
||||
});
|
||||
}
|
||||
@@ -228,6 +228,187 @@ describe("BootstrapOrchestrator", () => {
|
||||
expect(instantiate).toHaveBeenCalledWith(expect.any(String), expect.any(String), expect.objectContaining({ nonInterruptive: expected }));
|
||||
});
|
||||
|
||||
describe.each(["flat spec", "v1 bundle"])("one-off launch environment: %s", (format) => {
|
||||
async function source(singleSeat = false) {
|
||||
const specPath = writeSpec(singleSeat ? SIMPLE_SPEC_YAML : SIMPLE_SPEC_YAML.replace(" runtime: claude-code", " runtime: claude-code\n - id: reviewer\n runtime: codex"));
|
||||
if (format === "flat spec") return { sourceRef: specPath };
|
||||
const { LegacyBundleAssembler } = await import("../src/domain/bundle-assembler.js");
|
||||
const { pack } = await import("../src/domain/bundle-archive.js");
|
||||
const pkgDir = path.join(tmpDir, "package");
|
||||
writePkg(pkgDir, VALID_MANIFEST_YAML, { "skills/helper/SKILL.md": "# Helper" });
|
||||
const staging = path.join(tmpDir, "bundle");
|
||||
new LegacyBundleAssembler({ fsOps: {
|
||||
readFile: (p) => fs.readFileSync(p, "utf-8"), exists: fs.existsSync,
|
||||
mkdirp: (p) => fs.mkdirSync(p, { recursive: true }),
|
||||
writeFile: (p, content) => fs.writeFileSync(p, content),
|
||||
copyDir: (from, to) => fs.cpSync(from, to, { recursive: true }),
|
||||
} }).assemble({
|
||||
specPath, outputDir: staging, bundleName: "env-fixture", bundleVersion: "1.0.0",
|
||||
packages: [{ name: "test-pkg", version: "1.0.0", sourcePath: pkgDir, originalSource: "./package", manifestHash: "fixture" }],
|
||||
});
|
||||
const { computeIntegrity, writeIntegrity } = await import("../src/domain/bundle-integrity.js");
|
||||
const integrityFs = {
|
||||
...realFsOps(), readFileBuffer: (p: string) => fs.readFileSync(p),
|
||||
writeFile: (p: string, content: string) => fs.writeFileSync(p, content),
|
||||
walkFiles: realFsOps().listFiles,
|
||||
};
|
||||
writeIntegrity(staging, computeIntegrity(staging, integrityFs), integrityFs);
|
||||
const sourceRef = path.join(tmpDir, "env.rigbundle");
|
||||
await pack(staging, sourceRef);
|
||||
return { sourceRef, sourceKind: "rig_bundle" };
|
||||
}
|
||||
|
||||
async function realLaunch(fault?: { removal: "confirmed" | "unconfirmed" | "throw"; createFailure?: boolean }) {
|
||||
const { RigRepository } = await import("../src/domain/rig-repository.js");
|
||||
const { SessionRegistry } = await import("../src/domain/session-registry.js");
|
||||
const { EventBus } = await import("../src/domain/event-bus.js");
|
||||
const { NodeLauncher } = await import("../src/domain/node-launcher.js");
|
||||
const { RigInstantiator } = await import("../src/domain/rigspec-instantiator.js");
|
||||
const { RigSpecPreflight } = await import("../src/domain/rigspec-preflight.js");
|
||||
const { LegacyBundleSourceResolver } = await import("../src/domain/bundle-source-resolver.js");
|
||||
const rigRepo = new RigRepository(db);
|
||||
const sessionRegistry = new SessionRegistry(db);
|
||||
const eventBus = new EventBus(db);
|
||||
// Only the terminal/process boundary is inert; bootstrap, instantiation, launch and SQLite are real.
|
||||
const started: Array<{ session: string; hasProbe: boolean }> = [];
|
||||
const live = new Map<string, Record<string, string>>();
|
||||
const tmux = {
|
||||
createSession: vi.fn(async (session: string, _cwd: string, env: Record<string, string> = {}) => {
|
||||
if (fault?.createFailure && session.endsWith("-dev")) return { ok: false, code: "fixture_create_failed", message: "fixture create failure" };
|
||||
started.push({ session, hasProbe: "DOCSDESK_ENV_PROBE" in env });
|
||||
live.set(session, { ...env });
|
||||
return { ok: true };
|
||||
}),
|
||||
killSession: vi.fn(async (session: string) => {
|
||||
if (fault?.removal === "throw") throw new Error("private removal fault");
|
||||
if (fault?.removal === "unconfirmed") return { ok: false, code: "fixture_kill_failed", message: "private removal fault" };
|
||||
live.delete(session);
|
||||
return { ok: true };
|
||||
}),
|
||||
hasSession: async () => false, listPanes: async () => [],
|
||||
listSessions: async () => [], listWindows: async () => [],
|
||||
unsetSessionEnv: vi.fn(async (session: string, key: string) => {
|
||||
if (fault && session.endsWith("-dev")) throw new Error("private unset fault");
|
||||
delete live.get(session)?.[key];
|
||||
}),
|
||||
} as unknown as import("../src/adapters/tmux.js").TmuxAdapter;
|
||||
const nodeLauncher = new NodeLauncher({ db, rigRepo, sessionRegistry, eventBus, tmuxAdapter: tmux });
|
||||
const preflight = new RigSpecPreflight({ rigRepo, tmuxAdapter: tmux, exec: async () => "fixture runtime" });
|
||||
const instantiator = new RigInstantiator({ db, rigRepo, sessionRegistry, eventBus, nodeLauncher, preflight });
|
||||
const orch = buildOrchestrator({ instantiator, bundleSourceResolver: new LegacyBundleSourceResolver({ fsOps: realFsOps() }) });
|
||||
return { orch, tmux, rigRepo, started, live };
|
||||
}
|
||||
|
||||
it("delivers the synthetic override to every first pane without saving it for later launches", async () => {
|
||||
const { orch, tmux, rigRepo } = await realLaunch();
|
||||
const envOverride = { DOCSDESK_ENV_PROBE: "synthetic=with spaces" };
|
||||
const result = await orch.bootstrap({ mode: "apply", ...await source(), envOverride });
|
||||
expect(result.status, JSON.stringify(result)).toBe("completed");
|
||||
expect(tmux.createSession).toHaveBeenCalledTimes(2);
|
||||
for (const call of vi.mocked(tmux.createSession).mock.calls) {
|
||||
expect(call[2]).toMatchObject(envOverride);
|
||||
expect(call[2]?.OPENRIG_SEAT_ENV_KEYS).toBe("DOCSDESK_ENV_PROBE");
|
||||
expect(tmux.unsetSessionEnv).toHaveBeenCalledWith(call[0], "DOCSDESK_ENV_PROBE");
|
||||
}
|
||||
expect(rigRepo.getRig(result.rigId!)!.nodes.every((node) => !node.env)).toBe(true);
|
||||
});
|
||||
|
||||
describe.each([true, false])("cleanup failure accounting, single seat=%s", (singleSeat) => {
|
||||
it.each(["confirmed", "unconfirmed", "throw"] as const)("reports the stopped launch and retained effects when removal is %s", async (removal) => {
|
||||
const { orch, tmux, rigRepo, started, live } = await realLaunch({ removal });
|
||||
const input = await source(singleSeat);
|
||||
const { createTestApp } = await import("./helpers/test-app.js");
|
||||
const { app } = createTestApp(db, { tmux, appDeps: { bootstrapOrchestrator: orch }, upRouterFsOps: {
|
||||
exists: fs.existsSync, readFile: (p) => fs.readFileSync(p, "utf-8"), readHead: (p, n) => fs.readFileSync(p).subarray(0, n),
|
||||
} });
|
||||
const { upCommand } = await import("../../cli/src/commands/up.js");
|
||||
const { STATE_FILE } = await import("../../cli/src/daemon-lifecycle.js");
|
||||
let observed: { status: number; data: Record<string, unknown> } | undefined;
|
||||
let projectOnly = false;
|
||||
const client = {
|
||||
get: async () => ({ status: 200, data: {} }),
|
||||
post: async (route: string, body: unknown) => {
|
||||
if (route !== "/api/up") return { status: 200, data: {} }; // bundle behavior preview has no fixture behavior
|
||||
if (projectOnly) return observed!;
|
||||
const response = await app.request(route, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });
|
||||
observed = { status: response.status, data: await response.json() };
|
||||
return observed;
|
||||
},
|
||||
};
|
||||
const deps = { clientFactory: () => client, lifecycleDeps: {
|
||||
exists: (p: string) => p === STATE_FILE,
|
||||
readFile: (p: string) => p === STATE_FILE ? JSON.stringify({ pid: 123, port: 7433, db: "fixture", startedAt: "fixture" }) : null,
|
||||
isProcessAlive: () => true, fetch: async () => ({ ok: true }),
|
||||
} } as unknown as import("../../cli/src/commands/status.js").StatusDeps;
|
||||
async function render(json = false) {
|
||||
const lines: string[] = [];
|
||||
const saved = { log: console.log, error: console.error, exit: process.exitCode };
|
||||
process.exitCode = undefined;
|
||||
console.log = console.error = (...args: unknown[]) => { lines.push(args.join(" ")); };
|
||||
let exit = 0;
|
||||
try {
|
||||
await upCommand(deps).parseAsync(["node", "rig", input.sourceRef, "--env", "DOCSDESK_ENV_PROBE=synthetic-private-value", ...(json ? ["--json"] : [])]);
|
||||
exit = Number(process.exitCode ?? 0);
|
||||
} finally { console.log = saved.log; console.error = saved.error; process.exitCode = saved.exit; }
|
||||
return { text: lines.join("\n"), exit };
|
||||
}
|
||||
const human = await render();
|
||||
projectOnly = true; // JSON renders the same retained HTTP response; it does not launch again.
|
||||
const json = await render(true);
|
||||
const baseline = process.env.EXPECT_ENV_CLEANUP_BASELINE === "1";
|
||||
const effects = { started, surviving: [...live].map(([session, env]) => ({ session, hasProbe: "DOCSDESK_ENV_PROBE" in env })), killCalls: vi.mocked(tmux.killSession).mock.calls.map(c => c[0]), boundSessions: db.prepare("SELECT tmux_session FROM bindings").all(), rigs: rigRepo.listRigs().length };
|
||||
console.info("LEGACY_ENV_CLEANUP_OBSERVATION=" + JSON.stringify({ format, singleSeat, removal, baseline, http: observed?.status, status: observed?.data.status, human, jsonExit: json.exit, effects }));
|
||||
expect(started).toHaveLength(singleSeat ? 1 : 2);
|
||||
expect(started.every(s => s.hasProbe === !baseline)).toBe(true);
|
||||
if (baseline) {
|
||||
expect(observed?.status).toBe(201);
|
||||
expect(observed?.data.status).toBe("completed");
|
||||
expect([human.exit, json.exit]).toEqual([0, 0]);
|
||||
expect(human.text).toContain("Status: completed");
|
||||
expect(tmux.killSession).not.toHaveBeenCalled();
|
||||
expect(live.size).toBe(singleSeat ? 1 : 2);
|
||||
} else {
|
||||
expect(observed?.status).toBe(singleSeat ? 500 : 200);
|
||||
expect(observed?.data.status).toBe(singleSeat ? "failed" : "partial");
|
||||
expect([human.exit, json.exit]).toEqual(singleSeat ? [2, 2] : [1, 1]);
|
||||
expect(human.text).toContain("DOCSDESK_ENV_PROBE");
|
||||
expect(human.text).toContain(started.find(s => s.session.endsWith("-dev"))!.session);
|
||||
expect(human.text).toContain(removal === "confirmed" ? "session was removed" : "check it and remove it");
|
||||
expect(human.text).not.toContain("synthetic-private-value");
|
||||
expect(human.text).not.toContain("private unset fault");
|
||||
expect(JSON.stringify(observed?.data.errors)).toContain("DOCSDESK_ENV_PROBE");
|
||||
expect(tmux.killSession).toHaveBeenCalledTimes(1);
|
||||
expect(live.size).toBe((singleSeat ? 0 : 1) + (removal === "confirmed" ? 0 : 1));
|
||||
expect([...live].some(([session, env]) => session.endsWith("-dev") && "DOCSDESK_ENV_PROBE" in env)).toBe(removal !== "confirmed");
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it("does not normalize an unrelated mixed legacy create failure", async () => {
|
||||
const { orch } = await realLaunch({ removal: "confirmed", createFailure: true });
|
||||
const result = await orch.bootstrap({ mode: "apply", ...await source() });
|
||||
expect(result.status).toBe("completed");
|
||||
expect(result.errors).toEqual([]);
|
||||
});
|
||||
|
||||
it("keeps a launch without an override unchanged", async () => {
|
||||
const { orch, tmux } = await realLaunch();
|
||||
const result = await orch.bootstrap({ mode: "apply", ...await source() });
|
||||
expect(result.status, JSON.stringify(result)).toBe("completed");
|
||||
expect(tmux.createSession).toHaveBeenCalledTimes(2);
|
||||
for (const call of vi.mocked(tmux.createSession).mock.calls) expect(call[2]?.DOCSDESK_ENV_PROBE).toBeUndefined();
|
||||
expect(tmux.unsetSessionEnv).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not launch a pane in plan mode even with an override", async () => {
|
||||
const { orch, tmux, rigRepo } = await realLaunch();
|
||||
const result = await orch.bootstrap({ mode: "plan", ...await source(), envOverride: { DOCSDESK_ENV_PROBE: "synthetic" } });
|
||||
expect(result.status, JSON.stringify(result)).toBe("planned");
|
||||
expect(tmux.createSession).not.toHaveBeenCalled();
|
||||
expect(rigRepo.listRigs()).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
// T1: Plan mode returns plan, 0 bootstrap_actions rows
|
||||
it("plan mode returns plan with zero bootstrap_actions rows", async () => {
|
||||
const specPath = writeSpec(SIMPLE_SPEC_YAML);
|
||||
|
||||
Reference in new issue
Block a user