From b1e10406351b96782bb967c8a77945857ab8dc66 Mon Sep 17 00:00:00 2001 From: Eduardo Marquez <55303379+DocksDocks@users.noreply.github.com> Date: Tue, 1 Dec 2026 20:12:43 -0300 Subject: [PATCH 01/11] Add the bridge from Effect code into engine code that is not Effect yet - bridgeSync and bridgePromise run a legacy call as Effect.uninterruptible over Effect.try or Effect.tryPromise, with the typed LegacyStepFailed (step, message, cause), so an interrupt waits until the legacy work settles and no scope closes under it (#290, bridge rule D1). - Tests: an interrupt during a bridged Promise ends only after it settles; a rejection or a throw becomes LegacyStepFailed with its step and message. Verified: bun x --no-install vitest run (unit and toggles rows of plan #294); bun run check:types; bun cli/scripts/verify-ci-tools.ts; bun run golden:dryrun --prove-red; bun run golden:mutation --prove-red; bun run smoke:package; ./docks-kit sync --dry-run; bun run check --- cli/src/engine-native/bridge.ts | 37 ++++++++++++++ cli/test/unit/bridge.test.ts | 89 +++++++++++++++++++++++++++++++++ 2 files changed, 126 insertions(+) create mode 100644 cli/src/engine-native/bridge.ts create mode 100644 cli/test/unit/bridge.test.ts diff --git a/cli/src/engine-native/bridge.ts b/cli/src/engine-native/bridge.ts new file mode 100644 index 00000000..0720fe83 --- /dev/null +++ b/cli/src/engine-native/bridge.ts @@ -0,0 +1,37 @@ +/** + * The bridge from Effect code into engine code that is not Effect code yet + * (plan DocksDocks/docks-kit#290, bridge rule D1). A bridged step runs without + * interruption, so an interrupt waits until the legacy work settles and no + * scope, such as a held lock, closes under it. A throw or a rejection becomes + * `LegacyStepFailed` with the original value as its cause. The last child of + * #290 removes this module with its last caller. + */ +import { Effect, Schema } from "effect"; + +import { errorMessage } from "./errorText"; + +/** A bridged step threw or rejected; `cause` is the original value. */ +export class LegacyStepFailed extends Schema.TaggedError< + LegacyStepFailed, + { readonly brand: unique symbol } +>()("LegacyStepFailed", { + step: Schema.String, + message: Schema.String, + cause: Schema.Defect(), +}) {} + +const stepFailure = + (step: string) => + (cause: unknown): LegacyStepFailed => + new LegacyStepFailed({ step, message: errorMessage(cause), cause }); + +/** Run the synchronous legacy step `run` as the step `step`. */ +export const bridgeSync = (step: string, run: () => A): Effect.Effect => + Effect.uninterruptible(Effect.try({ try: run, catch: stepFailure(step) })); + +/** Run the legacy Promise step `run` as the step `step`; an interrupt waits until it settles. */ +export const bridgePromise = ( + step: string, + run: () => PromiseLike, +): Effect.Effect => + Effect.uninterruptible(Effect.tryPromise({ try: () => run(), catch: stepFailure(step) })); diff --git a/cli/test/unit/bridge.test.ts b/cli/test/unit/bridge.test.ts new file mode 100644 index 00000000..8f9c8f98 --- /dev/null +++ b/cli/test/unit/bridge.test.ts @@ -0,0 +1,89 @@ +/** + * The bridge into engine code that is not Effect code yet (plan #290, D1): an + * interrupt waits until the bridged work settles, and a throw or a rejection + * becomes `LegacyStepFailed` with the step and the original message. + */ +import { setImmediate as nextTurn } from "node:timers/promises"; +import { Effect, Exit, Fiber } from "effect"; +import { describe, expect, it } from "vitest"; + +import { bridgePromise, bridgeSync } from "../../src/engine-native/bridge"; + +describe("bridgePromise", () => { + it("ends an interrupted run only after the bridged Promise settles", async () => { + const gate = Promise.withResolvers(); + const started = Promise.withResolvers(); + const events: Array = []; + const fiber = Effect.runFork( + bridgePromise("gated step", () => { + started.resolve(); + return gate.promise.then((value) => { + events.push(`settled ${value}`); + return value; + }); + }), + ); + await started.promise; + + const interrupted = Effect.runPromise(Fiber.interrupt(fiber)).then(() => { + events.push("interrupt returned"); + }); + for (let turn = 0; turn < 5; turn += 1) await nextTurn(); + expect(events).toEqual([]); + + gate.resolve("late"); + await interrupted; + expect(events).toEqual(["settled late", "interrupt returned"]); + expect(Exit.hasInterrupts(await Effect.runPromise(Fiber.await(fiber)))).toBe(true); + }); + + it("fails with the step and the message of a rejection", async () => { + const cause = new Error("install failed"); + const error = await Effect.runPromise( + Effect.flip(bridgePromise("bun install", () => Promise.reject(cause))), + ); + + expect(error).toMatchObject({ + _tag: "LegacyStepFailed", + step: "bun install", + message: "install failed", + }); + expect(error.cause).toBe(cause); + }); + + it("fails with the step and the message of a throw before the Promise", async () => { + const error = await Effect.runPromise( + Effect.flip( + bridgePromise("plugin pass", () => { + throw new Error("no inventory"); + }), + ), + ); + + expect(error).toMatchObject({ + _tag: "LegacyStepFailed", + step: "plugin pass", + message: "no inventory", + }); + }); +}); + +describe("bridgeSync", () => { + it("fails with the step and the message of a throw", () => { + const cause = new Error("EACCES: permission denied"); + const error = Effect.runSync( + Effect.flip( + bridgeSync("deploy AGENTS.md", () => { + throw cause; + }), + ), + ); + + expect(error).toMatchObject({ + _tag: "LegacyStepFailed", + step: "deploy AGENTS.md", + message: "EACCES: permission denied", + }); + expect(error.cause).toBe(cause); + }); +}); From 6d2cf6efcf30dd5ea4a95dd1f5501913db8adbfa Mon Sep 17 00:00:00 2001 From: Eduardo Marquez <55303379+DocksDocks@users.noreply.github.com> Date: Tue, 1 Dec 2026 20:13:19 -0300 Subject: [PATCH 02/11] Run the engine seam and the sync orchestration as Effect code Steps lease and seam of #294 (one commit: syncDispatch consumes the new lease API): - logger.ts: acquireTerminal is a scoped resource (LeaseHeld); withExclusive takes an Effect under a one-permit Semaphore and fails with LeaseReentered before it waits. The write rethrows stay. - runEngineNative returns an Effect over the engine layers and FileSystem; help, usage refusals, and an invalid lock wait are typed failures turned into their exit codes; ExitError is gone. - engineSync takes the home lock, resolves the folders under it, then takes the folder locks, in one scope, with the current sync poll (wall clock, deadline before preparation, last attempt). - ompSync and modeToolchain are Effects; every call into later-owned code goes through bridge.ts. - engine.ts and main.ts map each failure and defect to the same failure text as before. - Tests move to the Effect run; a new case shows that an interrupt during a bridged pass keeps the home and folder locks until the pass settles. Verified: bun x --no-install vitest run (unit and toggles rows of plan #294); bun run check:types; bun cli/scripts/verify-ci-tools.ts; bun run golden:dryrun --prove-red; bun run golden:mutation --prove-red; bun run smoke:package; ./docks-kit sync --dry-run; bun run check --- cli/src/engine-native/engineCtx.ts | 47 ++- cli/src/engine-native/index.ts | 80 +++-- cli/src/engine-native/logger.ts | 128 +++++--- cli/src/engine-native/modes.ts | 84 ++--- cli/src/engine-native/ompSync.ts | 118 ++++--- cli/src/engine-native/parseArgs.ts | 26 +- cli/src/engine-native/parseHelp.ts | 24 +- cli/src/engine-native/services.ts | 5 +- cli/src/engine-native/syncDispatch.ts | 377 ++++++++++++----------- cli/src/engine.ts | 49 ++- cli/src/main.ts | 22 +- cli/src/services.ts | 25 +- cli/test/lib/engineRun.ts | 25 ++ cli/test/unit/engine-di.test.ts | 7 +- cli/test/unit/engine.test.ts | 39 ++- cli/test/unit/envGlobals.test.ts | 24 +- cli/test/unit/folderLockCreate.test.ts | 15 +- cli/test/unit/logger.test.ts | 354 ++++++++++++--------- cli/test/unit/ompPluginInventory.test.ts | 11 +- cli/test/unit/ompRemovals.test.ts | 6 +- cli/test/unit/syncLock.test.ts | 104 +++++-- cli/test/unit/toolchain.test.ts | 28 +- 22 files changed, 977 insertions(+), 621 deletions(-) create mode 100644 cli/test/lib/engineRun.ts diff --git a/cli/src/engine-native/engineCtx.ts b/cli/src/engine-native/engineCtx.ts index 4ef4a89d..95443d76 100644 --- a/cli/src/engine-native/engineCtx.ts +++ b/cli/src/engine-native/engineCtx.ts @@ -1,12 +1,17 @@ /** - * EngineNative run context: the shared `Ctx` shape plus its construction from - * the environment. Split from index.ts, which re-exports the public surface - * so existing import paths keep working. + * EngineNative run context: the shared `Ctx` shape, the `EngineContext` + * service that carries it through the Effect code, and its construction from + * the environment. Code that is not Effect code yet reads and writes the same + * plain `Ctx`, which the Effect code passes on. */ +import { Context, Effect, Schema } from "effect"; + +import { kitHome } from "../kitHome"; +import { bridgeSync } from "./bridge"; +import type { BunRuntimeState } from "./bun"; +import { errorMessage } from "./errorText"; import { engineHome } from "./home"; import type { TerminalLease } from "./logger"; -import type { BunRuntimeState } from "./bun"; -import { kitHome } from "../kitHome"; import type { EngineServices } from "./services"; export interface Ctx { @@ -26,6 +31,20 @@ export interface Ctx { readonly failures: Array; } +/** The run context of one engine operation. */ +export class EngineContext extends Context.Service()( + "docks-kit/EngineContext", +) {} + +/** `kitHome()` refused the kit home, for example an explicit `DOCKS_KIT_HOME` without a manifest. */ +export class KitHomeInvalid extends Schema.TaggedError< + KitHomeInvalid, + { readonly brand: unique symbol } +>()("KitHomeInvalid", { + message: Schema.String, + cause: Schema.Defect(), +}) {} + export interface CtxOptions { /** * True only on the harness-private native-raw channel: seed `Ctx` from the @@ -40,12 +59,19 @@ export interface CtxOptions { * Build the run context. HOME applies on every path; * the env globals apply only when `options.envGlobals` is true. */ -export function makeCtx(services: EngineServices, options: CtxOptions): Ctx { +export const makeCtx = Effect.fn("makeCtx")(function* ( + services: EngineServices, + options: CtxOptions, +) { const env = process.env; - const home = engineHome(env); + const home = yield* bridgeSync("engineHome", () => engineHome(env)); const globals: NodeJS.ProcessEnv = options.envGlobals ? env : {}; - return { - repoDir: kitHome(), + const repoDir = yield* Effect.try({ + try: () => kitHome(), + catch: (cause) => new KitHomeInvalid({ message: errorMessage(cause), cause }), + }); + const ctx: Ctx = { + repoDir, home, dryRun: globals["DRY_RUN"] === "1", verbose: globals["DOCKS_KIT_VERBOSE"] === "1", @@ -55,4 +81,5 @@ export function makeCtx(services: EngineServices, options: CtxOptions): Ctx { }, failures: [], }; -} + return ctx; +}); diff --git a/cli/src/engine-native/index.ts b/cli/src/engine-native/index.ts index b819d375..a8860922 100644 --- a/cli/src/engine-native/index.ts +++ b/cli/src/engine-native/index.ts @@ -10,32 +10,46 @@ * module keeps the entry routing and re-exports the public surface so * existing import paths keep working. */ -import { makeCtx, type Ctx } from "./engineCtx"; +import { Effect, type FileSystem } from "effect"; + +import { DependencyManagerService, LoggerService, PlatformService } from "../services"; +import type { LegacyStepFailed } from "./bridge"; +import { EngineContext, makeCtx, type KitHomeInvalid } from "./engineCtx"; +import type { LeaseHeld } from "./logger"; import { modeToolchain } from "./modes"; -import { ExitError } from "./parseArgs"; -import { makeEngineServices, type EngineServices, type Logger } from "./services"; -import { engineSync } from "./syncDispatch"; +import type { Logger } from "./services"; +import { engineSync, type LockAcquireError } from "./syncDispatch"; export type { Ctx } from "./engineCtx"; export { runBounded } from "./syncConcurrency"; export type { SyncConcurrency, SyncTask } from "./syncConcurrency"; +/** A run that failed: each failure keeps the original value that the seam prints. */ +export type EngineFailure = LegacyStepFailed | LockAcquireError | KitHomeInvalid | LeaseHeld; + /** - * Run one engine operation. `options.envGlobals` defaults to false; only the - * main.ts native-raw branch sets it, so the public CLI ignores env globals. + * Run one engine operation and succeed with its exit code. Help, a refused + * usage, and an invalid lock wait are already exit codes, after their text. + * `options.envGlobals` defaults to false; only the main.ts native-raw branch + * sets it, so the public CLI ignores env globals. */ -export async function runEngineNative( +export const runEngineNative: ( + argv: ReadonlyArray, + options?: { readonly envGlobals?: boolean }, +) => Effect.Effect< + number, + EngineFailure, + LoggerService | DependencyManagerService | PlatformService | FileSystem.FileSystem +> = Effect.fn("runEngineNative")(function* ( argv: ReadonlyArray, - services?: EngineServices, options: { readonly envGlobals?: boolean } = {}, -): Promise { - let ctx!: Ctx; - const baseServices = services ?? makeEngineServices(); - const baseLogger = baseServices.logger; +) { + const baseLogger = yield* LoggerService; const logger: Logger = { change: (msg) => baseLogger.change(msg), progress: (msg) => baseLogger.progress(msg), clearProgress: () => baseLogger.clearProgress(), + // `ctx` exists before any line prints: makeCtx prints nothing. verbose: (msg) => { if (ctx.verbose) baseLogger.verbose(msg); }, @@ -44,23 +58,25 @@ export async function runEngineNative( echo: (line) => baseLogger.echo(line), acquireTerminal: (message) => baseLogger.acquireTerminal(message), }; - const runServices: EngineServices = { - logger, - deps: baseServices.deps, - platform: baseServices.platform, - }; - try { - ctx = makeCtx(runServices, { envGlobals: options.envGlobals === true }); - switch (argv[0]) { - case "toolchain": - return await modeToolchain(ctx, argv.slice(1)); - case "sync": - return await engineSync(ctx, argv.slice(1)); - default: - return await engineSync(ctx, argv); - } - } catch (e) { - if (e instanceof ExitError) return e.code; - throw e; - } -} + const ctx = yield* makeCtx( + { logger, deps: yield* DependencyManagerService, platform: yield* PlatformService }, + { envGlobals: options.envGlobals === true }, + ); + const operation = + argv[0] === "toolchain" + ? modeToolchain(argv.slice(1)) + : engineSync(argv[0] === "sync" ? argv.slice(1) : argv); + const refused = (message: string) => + Effect.sync(() => { + logger.err(message); + return 2; + }); + return yield* operation.pipe( + Effect.provideService(EngineContext, ctx), + Effect.catchTags({ + HelpShown: () => Effect.succeed(0), + UsageRefused: (refusal) => refused(refusal.message), + LockWaitInvalid: (invalid) => refused(invalid.message), + }), + ); +}); diff --git a/cli/src/engine-native/logger.ts b/cli/src/engine-native/logger.ts index 50a0f291..43dfefd0 100644 --- a/cli/src/engine-native/logger.ts +++ b/cli/src/engine-native/logger.ts @@ -1,4 +1,4 @@ -import { AsyncLocalStorage } from "node:async_hooks"; +import { Context, Effect, Schema, Semaphore, type Scope } from "effect"; /** * Leveled stderr logger, one run-scoped terminal lease, and stdout data @@ -11,12 +11,37 @@ import { AsyncLocalStorage } from "node:async_hooks"; export interface TerminalLease { /** Replace the coordinator-owned transient line. */ readonly update: (message: string) => void; - /** Serialize actions admitted by this lease. After release, new actions bypass its queue. */ - readonly withExclusive: (action: () => T | Promise) => Promise; - /** Restore ordinary progress without waiting for actions already admitted by this lease. */ + /** + * Run `action` as a terminal-exclusive section, one section of this lease + * at a time. After release, a new section runs at once, outside the queue. + * A section that starts another section of the same logger fails with + * `LeaseReentered` before it waits, so it cannot wait on itself. + */ + readonly withExclusive: ( + action: Effect.Effect, + ) => Effect.Effect; + /** Restore ordinary progress without waiting for sections already admitted by this lease. */ readonly release: () => void; } +/** A second terminal lease of a logger while the first is held. */ +export class LeaseHeld extends Schema.TaggedError()( + "LeaseHeld", + { message: Schema.String }, +) {} + +/** A terminal-exclusive section started another section of the same logger. */ +export class LeaseReentered extends Schema.TaggedError< + LeaseReentered, + { readonly brand: unique symbol } +>()("LeaseReentered", { message: Schema.String }) {} + +/** The logger whose terminal-exclusive section the current fiber runs, if any. */ +const ExclusiveOwner = Context.Reference( + "docks-kit/engine-native/logger/ExclusiveOwner", + { defaultValue: () => undefined }, +); + export interface Logger { /** `[ok]` green — an operation actually mutated something. Always visible. */ readonly change: (msg: string) => void; @@ -30,8 +55,13 @@ export interface Logger { readonly err: (msg: string) => void; /** stdout data line (dry-run report, summary, usage) — never filtered. */ readonly echo: (line: string) => void; - /** Acquire the run-scoped coordinator lease for terminal progress and input. */ - readonly acquireTerminal: (message: string) => TerminalLease; + /** + * Hold the run-scoped coordinator lease for terminal progress and input + * until the scope closes. Fails with `LeaseHeld` while another lease is held. + */ + readonly acquireTerminal: ( + message: string, + ) => Effect.Effect; } export interface LoggerSinks { @@ -77,7 +107,8 @@ export function makeLogger(sinks: LoggerSinks): Logger { let progressPending = false; let activeLease: TerminalLease | undefined; let bufferedWrites: Array<() => void> | undefined; - const exclusiveContext = new AsyncLocalStorage<{ active: boolean }>(); + // Marks the fibers inside a terminal-exclusive section of this logger. + const exclusiveOwner = {}; const eraseProgress = (): void => { if (!progressPending || progressWrite === undefined) return; @@ -119,45 +150,57 @@ export function makeLogger(sinks: LoggerSinks): Logger { writeDurable(() => errWrite(`\x1b[1;32m[ok]\x1b[0m ${msg}\n`)); }; - const acquireTerminal = (message: string): TerminalLease => { - if (activeLease !== undefined) throw new Error("terminal lease already acquired"); - + const openLease = (message: string, permit: Semaphore.Semaphore): TerminalLease => { let coordinatorMessage = message; - let exclusiveTail = Promise.resolve(); let exclusivePending = 0; + // The section holds the permit from its first buffered write to its flush. + const section = (action: Effect.Effect): Effect.Effect => + permit.withPermits(1)( + Effect.acquireUseRelease( + Effect.sync(() => { + eraseProgress(); + bufferedWrites ??= []; + }), + () => Effect.provideService(action, ExclusiveOwner, exclusiveOwner), + () => + Effect.sync(() => { + try { + if (bufferedWrites !== undefined) flushDurable(bufferedWrites); + } finally { + bufferedWrites = undefined; + } + }), + ), + ); const lease: TerminalLease = { update: (nextMessage) => { if (activeLease !== lease) return; coordinatorMessage = nextMessage; if (exclusivePending === 0) drawProgress(coordinatorMessage); }, - withExclusive: async (action: () => T | Promise): Promise => { - if (exclusiveContext.getStore()?.active === true) { - throw new Error("terminal lease withExclusive cannot be re-entered"); - } - if (activeLease !== lease) return await action(); - exclusivePending += 1; - const previous = exclusiveTail; - const { promise, resolve: unlock } = Promise.withResolvers(); - exclusiveTail = promise; - await previous; - eraseProgress(); - bufferedWrites ??= []; - const owner = { active: true }; - try { - return await exclusiveContext.run(owner, action); - } finally { - owner.active = false; - try { - if (bufferedWrites !== undefined) flushDurable(bufferedWrites); - } finally { - bufferedWrites = undefined; - exclusivePending -= 1; - unlock(); - if (activeLease === lease && exclusivePending === 0) drawProgress(coordinatorMessage); + withExclusive: (action) => + Effect.gen(function* () { + if ((yield* ExclusiveOwner) === exclusiveOwner) { + return yield* new LeaseReentered({ + message: "terminal lease withExclusive cannot be re-entered", + }); } - } - }, + if (activeLease !== lease) return yield* action; + // Counted from admission, so `update` draws nothing while a section waits or runs. + return yield* Effect.acquireUseRelease( + Effect.sync(() => { + exclusivePending += 1; + }), + () => section(action), + () => + Effect.sync(() => { + exclusivePending -= 1; + if (activeLease === lease && exclusivePending === 0) { + drawProgress(coordinatorMessage); + } + }), + ); + }), release: () => { if (activeLease !== lease) return; activeLease = undefined; @@ -169,6 +212,17 @@ export function makeLogger(sinks: LoggerSinks): Logger { return lease; }; + const acquireTerminal = (message: string): Effect.Effect => + Effect.acquireRelease( + Effect.gen(function* () { + if (activeLease !== undefined) { + return yield* new LeaseHeld({ message: "terminal lease already acquired" }); + } + return openLease(message, yield* Semaphore.make(1)); + }), + (lease) => Effect.sync(() => lease.release()), + ); + return { change: ok, verbose: ok, diff --git a/cli/src/engine-native/modes.ts b/cli/src/engine-native/modes.ts index 632ca188..3a8f019a 100644 --- a/cli/src/engine-native/modes.ts +++ b/cli/src/engine-native/modes.ts @@ -1,15 +1,21 @@ /** * Direct mode for `toolchain`. Same public argv vocabulary, golden-tested - * messages, same exit codes. + * messages, same exit codes. Each call into `toolchain.ts` and `bun.ts`, which + * a later child of plan #290 moves, runs through the bridge. */ -import type { Ctx } from "./index"; +import { Effect } from "effect"; + +import { bridgePromise, bridgeSync } from "./bridge"; import { bunBootstrap } from "./bun"; +import { EngineContext } from "./engineCtx"; +import { UsageRefused } from "./parseHelp"; import { belowFloor, field, installedVersion, outdatedReport, present, report } from "./toolchain"; const TOOLCHAIN_USAGE = "Usage: toolchain [check|ensure [--dry-run]|outdated [--refresh]]"; -export async function modeToolchain(ctx: Ctx, args: ReadonlyArray): Promise { - const { echo, err, verbose, warn } = ctx.services.logger; +export const modeToolchain = Effect.fn("modeToolchain")(function* (args: ReadonlyArray) { + const ctx = yield* EngineContext; + const { echo, verbose, warn } = ctx.services.logger; const words = args.filter((arg) => !arg.startsWith("--")); const op = words[0] ?? "check"; const tool = words[1] ?? ""; @@ -18,50 +24,46 @@ export async function modeToolchain(ctx: Ctx, args: ReadonlyArray): Prom else if (arg === "--dry-run") ctx.dryRun = true; } if (words.length > (op === "ensure" ? 2 : 1)) { - err(TOOLCHAIN_USAGE); - return 2; + return yield* new UsageRefused({ message: TOOLCHAIN_USAGE }); } if (op === "check") { - await report(ctx); + yield* bridgePromise("report", () => report(ctx)); return 0; } if (op === "outdated") { - await outdatedReport(ctx, { refresh: args.includes("--refresh") }); + yield* bridgePromise("outdatedReport", () => + outdatedReport(ctx, { refresh: args.includes("--refresh") }), + ); return 0; } - if (op !== "ensure") { - err(TOOLCHAIN_USAGE); - return 2; - } - if (tool === "") { - err("Usage: toolchain ensure "); - return 2; + if (op !== "ensure") return yield* new UsageRefused({ message: TOOLCHAIN_USAGE }); + if (tool === "") return yield* new UsageRefused({ message: "Usage: toolchain ensure " }); + if (tool !== "bun") { + return yield* new UsageRefused({ + message: "toolchain ensure supports managed tools only (bun)", + }); } - switch (tool) { - case "bun": { - // `bun` is the one managed tool, and its bootstrap is silent when Bun is - // already installed. Probe first so the no-op confirmation the `--verbose` - // contract promises is not mistaken for a fresh install. - const alreadyInstalled = present(ctx, "bun"); - if ((await bunBootstrap(ctx, ctx.services)).kind !== "ready") return 1; - if (alreadyInstalled) { - // A present tool whose --version cannot be read reports `unknown` in the - // doctor table; keep the same vocabulary rather than an empty pair of - // parentheses. `ensure` never upgrades (policy `present`), but a Bun - // below the kit floor is a real problem, so it warns on every run. - const probed = await installedVersion(ctx, "bun"); - const floor = field("bun", "floor"); - const label = probed === "" ? "version unknown" : probed; - if (belowFloor(probed, floor)) { - warn(`bun ${probed} is below the kit floor ${floor}; run bun upgrade`); - } else if (ctx.dryRun) echo(`[dry-run] bun present (${label})`); - else verbose(`bun present (${label})`); - } - return 0; - } - default: - err("toolchain ensure supports managed tools only (bun)"); - return 2; + // `bun` is the one managed tool, and its bootstrap is silent when Bun is + // already installed. Probe first so the no-op confirmation the `--verbose` + // contract promises is not mistaken for a fresh install. + const alreadyInstalled = yield* bridgeSync("present", () => present(ctx, "bun")); + const runtime = yield* bridgePromise("bunBootstrap", () => bunBootstrap(ctx, ctx.services)); + if (runtime.kind !== "ready") return 1; + if (alreadyInstalled) { + // A present tool whose --version cannot be read reports `unknown` in the + // doctor table; keep the same vocabulary rather than an empty pair of + // parentheses. `ensure` never upgrades (policy `present`), but a Bun + // below the kit floor is a real problem, so it warns on every run. + const probed = yield* bridgePromise("installedVersion", () => installedVersion(ctx, "bun")); + const floor = yield* bridgeSync("field", () => field("bun", "floor")); + const below = yield* bridgeSync("belowFloor", () => belowFloor(probed, floor)); + const label = probed === "" ? "version unknown" : probed; + yield* Effect.sync(() => { + if (below) warn(`bun ${probed} is below the kit floor ${floor}; run bun upgrade`); + else if (ctx.dryRun) echo(`[dry-run] bun present (${label})`); + else verbose(`bun present (${label})`); + }); } -} + return 0; +}); diff --git a/cli/src/engine-native/ompSync.ts b/cli/src/engine-native/ompSync.ts index 94f72892..b336dda4 100644 --- a/cli/src/engine-native/ompSync.ts +++ b/cli/src/engine-native/ompSync.ts @@ -2,8 +2,9 @@ * EngineNative sync pipeline. config.yml merges through mergeOmpConfig * and models.yml through mergeOmpModels. Both preserve user-only keys. * Paths come from ompPaths because profiles, PI_CONFIG_DIR, - * PI_CODING_AGENT_DIR, and XDG roots each move them. `runSync` resolves them - * once, before it takes the folder locks, and the pipeline writes only there. + * PI_CODING_AGENT_DIR, and XDG roots each move them. `engineSync` resolves + * them once, before it takes the folder locks, and the pipeline writes only + * there. * Resolution stays within the environment and filesystem probes so no omp * subcommand runs under ctx.dryRun. * @@ -14,10 +15,13 @@ * surface. */ +import { Effect } from "effect"; + +import { bridgePromise, bridgeSync } from "./bridge"; import { bunBootstrap } from "./bun"; +import { EngineContext, type Ctx } from "./engineCtx"; import { p } from "./exec"; import { recordFailure } from "./failures"; -import type { Ctx } from "./index"; import { ompPaths, type OmpPaths } from "./ompPaths"; import { mergeOmpConfig, mergeOmpModels } from "./ompYaml"; import { ensureDirectory, syncMergedYaml, syncWholeFile } from "./ompFileDeploy"; @@ -37,74 +41,96 @@ export interface OmpWriteFolders { readonly paths: OmpPaths; } +/** The omp paths of the run context `ctx`, from the environment and the XDG data root probe. */ +const currentOmpPaths = (ctx: Ctx) => + bridgeSync("ompPaths", () => + ompPaths({ + home: ctx.home, + env: process.env, + platform: ctx.services.platform.raw(), + }), + ); + /** - * Resolve the omp paths of this run. `runSync` calls it once, takes a folder - * lock in each folder, and gives the result to `ompSync`. A second resolution - * could pick an XDG data root that another sync created after the locks. + * Resolve the omp paths of this run. `engineSync` resolves them once, under + * the sync lock, takes a folder lock in each folder, and gives the result to + * `ompSync`. A second resolution could pick an XDG data root that another + * sync created after the locks. */ -export function ompWriteFolders(ctx: Ctx): OmpWriteFolders { - const paths = ompPaths({ - home: ctx.home, - env: process.env, - platform: ctx.services.platform.raw(), - }); - return { paths }; -} +export const ompWriteFolders = Effect.fn("ompWriteFolders")(function* () { + const paths = yield* currentOmpPaths(yield* EngineContext); + const folders: OmpWriteFolders = { paths }; + return folders; +}); -/** Run the omp pipeline in `folders`, the folders that `runSync` resolved and locked. */ -export async function ompSync(ctx: Ctx, folders: OmpWriteFolders): Promise { - await bunBootstrap(ctx, ctx.services); +/** + * Run the omp pipeline in `folders`, the folders that `engineSync` resolved + * and locked. Each pass that a later child of plan #290 moves runs through + * the bridge, so an interrupt waits until the pass settles. + */ +export const ompSync = Effect.fn("ompSync")(function* (folders: OmpWriteFolders) { + const ctx = yield* EngineContext; + yield* bridgePromise("bunBootstrap", () => bunBootstrap(ctx, ctx.services)); const { paths } = folders; const agentDir = paths.agentDir; - if (!ctx.dryRun) ensureDirectory(agentDir); + if (!ctx.dryRun) yield* bridgeSync("ensureDirectory", () => ensureDirectory(agentDir)); - syncWholeFile( - ctx, - "SoT/.omp/AGENTS.md", - p(agentDir, "AGENTS.md"), - "omp AGENTS.md already in sync", - "omp AGENTS.md synced", + yield* bridgeSync("syncWholeFile AGENTS.md", () => + syncWholeFile( + ctx, + "SoT/.omp/AGENTS.md", + p(agentDir, "AGENTS.md"), + "omp AGENTS.md already in sync", + "omp AGENTS.md synced", + ), ); - syncWholeFile( - ctx, - "SoT/.omp/mcp.json", - p(agentDir, "mcp.json"), - "omp mcp.json already in sync", - "omp mcp.json synced", + yield* bridgeSync("syncWholeFile mcp.json", () => + syncWholeFile( + ctx, + "SoT/.omp/mcp.json", + p(agentDir, "mcp.json"), + "omp mcp.json already in sync", + "omp mcp.json synced", + ), ); const configFile = p(agentDir, "config.yml"); - const configBackedUp = syncMergedYaml(ctx, "SoT/.omp/config.yml", configFile, mergeOmpConfig); + const configBackedUp = yield* bridgeSync("syncMergedYaml config.yml", () => + syncMergedYaml(ctx, "SoT/.omp/config.yml", configFile, mergeOmpConfig), + ); // mergeOmpConfig is additive, so the prune must run on the merged result. - syncOmpRemovals(ctx, configFile, configBackedUp); + yield* bridgeSync("syncOmpRemovals", () => syncOmpRemovals(ctx, configFile, configBackedUp)); const modelsFile = p(agentDir, "models.yml"); - const modelsBackedUp = syncMergedYaml(ctx, "SoT/.omp/models.yml", modelsFile, mergeOmpModels); - syncOmpModelRemovals(ctx, modelsFile, modelsBackedUp); + const modelsBackedUp = yield* bridgeSync("syncMergedYaml models.yml", () => + syncMergedYaml(ctx, "SoT/.omp/models.yml", modelsFile, mergeOmpModels), + ); + yield* bridgeSync("syncOmpModelRemovals", () => + syncOmpModelRemovals(ctx, modelsFile, modelsBackedUp), + ); // The plugin pass links this directory, so the files must exist first. The // files deploy also without git: git gates only the omp plugin commands. - syncKitPlugin(ctx); + yield* bridgeSync("syncKitPlugin", () => syncKitPlugin(ctx)); - const pluginsInstalled = await syncPlugins(ctx, paths); + const pluginsInstalled = yield* bridgePromise("syncPlugins", () => syncPlugins(ctx, paths)); // omp adopts `$XDG_DATA_HOME/omp` once it exists. When another sync created // it during this run, a later omp process uses that root and does not see // the plugins of the locked root. The next sync locks and fills the new root. if (!ctx.dryRun) { - const currentRoot = ompPaths({ - home: ctx.home, - env: process.env, - platform: ctx.services.platform.raw(), - }).dataRoot; + const currentRoot = (yield* currentOmpPaths(ctx)).dataRoot; if (currentRoot !== paths.dataRoot) { - recordFailure( - ctx, - `omp data root moved to ${currentRoot} during the sync; run docks-kit sync again`, + yield* Effect.sync(() => + recordFailure( + ctx, + `omp data root moved to ${currentRoot} during the sync; run docks-kit sync again`, + ), ); } } - return { pluginsInstalled, agentDir }; -} + const state: OmpState = { pluginsInstalled, agentDir }; + return state; +}); // -------------------------------------------------------------- summary ---- diff --git a/cli/src/engine-native/parseArgs.ts b/cli/src/engine-native/parseArgs.ts index be286367..45285dd2 100644 --- a/cli/src/engine-native/parseArgs.ts +++ b/cli/src/engine-native/parseArgs.ts @@ -1,15 +1,18 @@ /** * EngineNative flag layer: the argv dispatch loop of `docks-kit sync`. - * Help text and the early-exit error live in parseHelp.ts (re-exported here - * so existing `from "./parseArgs"` imports keep working). + * Help text and the intended aborts live in parseHelp.ts. */ -import type { Ctx } from "./index"; -import { ExitError, printUsage } from "./parseHelp"; +import { Effect } from "effect"; -export { ExitError } from "./parseHelp"; +import { EngineContext } from "./engineCtx"; +import { HelpShown, printUsage, UsageRefused } from "./parseHelp"; -export function parseArgs(ctx: Ctx, args: ReadonlyArray): void { - const { err } = ctx.services.logger; +/** + * Read the sync flags into the run context. `-h` or `--help` prints the help + * and fails with `HelpShown`; any other word fails with `UsageRefused`. + */ +export const parseArgs = Effect.fn("parseArgs")(function* (args: ReadonlyArray) { + const ctx = yield* EngineContext; for (const arg of args) { switch (arg) { case "--dry-run": @@ -20,11 +23,10 @@ export function parseArgs(ctx: Ctx, args: ReadonlyArray): void { continue; case "-h": case "--help": - printUsage(ctx); - throw new ExitError(0); + yield* Effect.sync(() => printUsage(ctx)); + return yield* new HelpShown(); default: - err(`Unknown arg: ${arg}`); - throw new ExitError(2); + return yield* new UsageRefused({ message: `Unknown arg: ${arg}` }); } } -} +}); diff --git a/cli/src/engine-native/parseHelp.ts b/cli/src/engine-native/parseHelp.ts index ebb60a35..26b90902 100644 --- a/cli/src/engine-native/parseHelp.ts +++ b/cli/src/engine-native/parseHelp.ts @@ -1,16 +1,24 @@ /** - * Help text and the early-exit signal for the EngineNative flag layer. - * Kept dependency-free (besides injected ctx) so the dispatch loop and its - * callers can share it without import cycles. + * Help text and the intended aborts of the EngineNative flag layer. Kept + * dependency-free (besides injected ctx) so the dispatch loop and its callers + * can share it without import cycles. `index.ts runEngineNative` turns each + * abort into its exit code. */ +import { Schema } from "effect"; import type { Ctx } from "./index"; -export class ExitError extends Error { - constructor(readonly code: number) { - super(`exit ${code}`); - } -} +/** The run printed its help; it exits 0. */ +export class HelpShown extends Schema.TaggedError()( + "HelpShown", + {}, +) {} + +/** The arguments are not a usage of the operation; the run prints `message` and exits 2. */ +export class UsageRefused extends Schema.TaggedError< + UsageRefused, + { readonly brand: unique symbol } +>()("UsageRefused", { message: Schema.String }) {} export function printUsage(ctx: Ctx): void { const { echo } = ctx.services.logger; diff --git a/cli/src/engine-native/services.ts b/cli/src/engine-native/services.ts index d75cc92f..9906135b 100644 --- a/cli/src/engine-native/services.ts +++ b/cli/src/engine-native/services.ts @@ -1,8 +1,9 @@ /** * Shared service factory — the single construction point for the engine's * injectable capabilities (Output Policy in DESIGN.md). The Effect rim wraps - * these in Layers (cli/src/services.ts); the harness-private native-raw entry - * calls it directly, so every execution path shares one implementation. + * them in Layers (cli/src/services.ts `engineServicesLayer`), which main.ts + * provides to the public CLI and to the harness-private native-raw entry, so + * every execution path shares one implementation. */ import { DEPENDENCIES, diff --git a/cli/src/engine-native/syncDispatch.ts b/cli/src/engine-native/syncDispatch.ts index e4636f18..ed0c05b6 100644 --- a/cli/src/engine-native/syncDispatch.ts +++ b/cli/src/engine-native/syncDispatch.ts @@ -3,15 +3,14 @@ * pipeline, then print the summary and advice. Split from index.ts; the * `sync`/`toolchain` entry routing still lives there. */ -import { existsSync, mkdirSync, realpathSync } from "node:fs"; +import { existsSync, realpathSync } from "node:fs"; import { basename, dirname, join } from "node:path"; -import { Clock, Effect, Schema, type Scope } from "effect"; +import { Cause, Clock, Effect, FileSystem, Schema, type Scope } from "effect"; +import { EngineContext, type Ctx } from "./engineCtx"; import { errorMessage } from "./errorText"; -import type { Ctx } from "./index"; import { compareCodepoints } from "./jq"; import { - acquireKitLock, KIT_LOCK_POLL_MS, preparePrivateLockDirectory, releaseKitLock, @@ -23,19 +22,15 @@ import { ompSummary, ompSync, ompWriteFolders, - type OmpState, type OmpWriteFolders, } from "./ompSync"; -import { ExitError, parseArgs } from "./parseArgs"; +import { parseArgs } from "./parseArgs"; import { folderSyncLockPath, syncLockPath } from "./scratch"; /** The default time that a sync waits for another sync to release the sync lock. */ export const SYNC_LOCK_WAIT_MS = 120_000; const SYNC_LOCK_WAIT_ERROR = "DOCKS_KIT_SYNC_LOCK_WAIT_MS must be a non-negative safe integer"; -/** Print one error line, as `Logger.err` does. */ -type ErrorSink = (message: string) => void; - /** The wait bound from `DOCKS_KIT_SYNC_LOCK_WAIT_MS`, or undefined for an invalid value. */ function configuredLockWaitMs(): number | undefined { const configured = process.env["DOCKS_KIT_SYNC_LOCK_WAIT_MS"]; @@ -46,120 +41,11 @@ function configuredLockWaitMs(): number | undefined { return undefined; } -/** - * The sync lock wait bound: `DOCKS_KIT_SYNC_LOCK_WAIT_MS` in ms, or - * `SYNC_LOCK_WAIT_MS` when unset or empty. A value above - * `Number.MAX_SAFE_INTEGER` exits 2: `Number` would round it or make it - * Infinity, and an Infinity wait never ends. - */ -function syncLockWaitMs(err: ErrorSink): number { - const waitMs = configuredLockWaitMs(); - if (waitMs !== undefined) return waitMs; - err(SYNC_LOCK_WAIT_ERROR); - throw new ExitError(2); -} - /** The line that a run prints when another sync keeps the lock at `path` past the wait bound. */ function heldLine(path: string): string { return `another docks-kit sync holds ${path}; run sync again after it ends`; } -/** - * Make the folder of the folder lock `path` before the lock, with mode 0700 - * for each folder that this creates, as `ompFileDeploy.ts ensureDirectory` - * gives the parents of an omp folder. An existing folder keeps its mode: - * `mkdirSync` applies `mode` only to the folders that it creates. - */ -function makeLockFolder(path: string): void { - mkdirSync(dirname(path), { recursive: true, mode: 0o700 }); -} - -/** - * Run `body` under each lock of `paths`, taken in that order. When another - * sync keeps a lock past the wait bound, print the held line and return 1 - * without a call to `body`. Each taken lock goes when the run ends, also when - * it throws; the OS releases the locks when the process ends. - * - * With `privateDirectory` false, each path is a folder lock. A missing folder - * is created just before its lock, so the locks of its ancestors in the set - * are already held. - */ -async function withKitLocks( - err: ErrorSink, - paths: ReadonlyArray, - privateDirectory: boolean, - body: () => Promise, -): Promise { - const waitMs = syncLockWaitMs(err); - const held: Array = []; - try { - for (const path of paths) { - if (!privateDirectory) makeLockFolder(path); - const result = await acquireKitLock(path, { waitMs, privateDirectory }); - if (result.kind === "held") { - err(heldLine(path)); - return 1; - } - held.push(result.lock); - } - return await body(); - } finally { - for (const lock of held.reverse()) releaseKitLock(lock); - } -} - -/** - * Run `body` under the sync lock `syncLockPath(ctx.home)`. Two syncs of the - * same home meet at this lock. A dry run takes no lock: `--dry-run` or the - * `DRY_RUN` env global sets `ctx.dryRun`. `makeCtx` reads the env global only - * on the channel that reads env globals. - */ -async function withSyncLock(ctx: Ctx, body: () => Promise): Promise { - if (ctx.dryRun) return await body(); - return await withKitLocks(ctx.services.logger.err, [syncLockPath(ctx.home)], true, body); -} - -/** - * The canonical path of `folder`, which can be missing: the real path of its - * nearest existing ancestor, joined with the rest of the path. - */ -function canonicalFolder(folder: string): string { - const missing: Array = []; - let current = folder; - while (!existsSync(current) && dirname(current) !== current) { - missing.unshift(basename(current)); - current = dirname(current); - } - return join(realpathSync.native(current), ...missing); -} - -/** - * The folder lock path of each folder, by the canonical path of the folder, - * with no duplicates, sorted by folder. Every sync takes its folder locks in - * this order, so no two syncs can wait on each other in a cycle. An ancestor - * sorts before its descendants, and a nested folder keeps its own lock. - */ -export function folderLockPaths(folders: ReadonlyArray): Array { - const canonical = new Set(folders.map(canonicalFolder)); - return [...canonical].sort(compareCodepoints).map(folderSyncLockPath); -} - -/** - * Run `body` under the folder lock of each folder in `folders`. Take it after - * the sync lock. Syncs of different homes can share an omp folder, and - * their home locks differ. A missing folder is created under the - * locks of its ancestors in the set. A dry run takes no folder lock and - * creates nothing. - */ -async function withFolderLocks( - ctx: Ctx, - folders: ReadonlyArray, - body: () => Promise, -): Promise { - if (ctx.dryRun) return await body(); - return await withKitLocks(ctx.services.logger.err, folderLockPaths(folders), false, body); -} - /** `DOCKS_KIT_SYNC_LOCK_WAIT_MS` is not a non-negative safe integer; the run exits 2. */ export class LockWaitInvalid extends Schema.TaggedError< LockWaitInvalid, @@ -187,6 +73,12 @@ export class LockAcquireError extends Schema.TaggedError< cause: Schema.Defect(), }) {} +/** + * The sync lock wait bound: `DOCKS_KIT_SYNC_LOCK_WAIT_MS` in ms, or + * `SYNC_LOCK_WAIT_MS` when unset or empty. A value above + * `Number.MAX_SAFE_INTEGER` fails: `Number` would round it or make it + * Infinity, and an Infinity wait never ends. + */ const lockWaitMs: Effect.Effect = Effect.suspend(() => { const waitMs = configuredLockWaitMs(); return waitMs === undefined @@ -204,10 +96,49 @@ const lockFailure = (path: string) => (cause: unknown) => const NANOS_PER_MS = 1_000_000n; /** - * Take the lock at `path` for the rest of the scope, polling until the wait - * bound ends. The lock folder is prepared once. The bound runs on the - * monotonic clock, so a wall-clock change cannot extend it, and no try starts - * after it. Each try and the release that the scope registers for it run + * How a lock wait polls. A sync keeps the poll that it had with + * `kitLock.ts acquireKitLock`: the wall clock, a sync lock deadline that + * starts before its lock folder is prepared, and one more try after the sleep + * that reaches the deadline. The root tier toggles run on the monotonic clock, + * so a wall-clock change cannot extend their wait, and start no try after it. + */ +interface LockPoll { + /** The clock of the wait bound, in ns. */ + readonly now: Effect.Effect; + /** True: the deadline starts before the lock folder is prepared. */ + readonly deadlineFirst: boolean; + /** True: try once more after the sleep that reaches the deadline. */ + readonly lastAttempt: boolean; +} + +const wallClockNanos = Effect.map(Clock.currentTimeMillis, (ms) => BigInt(ms) * NANOS_PER_MS); + +const SYNC_HOME_POLL: LockPoll = { now: wallClockNanos, deadlineFirst: true, lastAttempt: true }; +const SYNC_FOLDER_POLL: LockPoll = { now: wallClockNanos, deadlineFirst: false, lastAttempt: true }; +const TOGGLE_POLL: LockPoll = { + now: Clock.monotonicTimeNanos, + deadlineFirst: false, + lastAttempt: false, +}; + +/** + * Make the folder of the folder lock `path` before the lock, with mode 0700 + * for each folder that this creates, as `ompFileDeploy.ts ensureDirectory` + * gives the parents of an omp folder. An existing folder keeps its mode: the + * mode applies only to the folders that the call creates. + */ +const makeLockFolder = Effect.fn("makeLockFolder")(function* (path: string) { + const fs = yield* FileSystem.FileSystem; + yield* fs + .makeDirectory(dirname(path), { recursive: true, mode: 0o700 }) + .pipe(Effect.mapError((error) => lockFailure(path)(error.cause ?? error))); +}); + +/** + * Take the lock at `path` for the rest of the scope, polling as `poll` says + * until the wait bound ends. The lock folder is prepared once: with + * `privateDirectory`, the private folder of the sync lock, else the folder of + * a folder lock. Each try and the release that the scope registers for it run * without interruption; only the sleep between two tries can be interrupted, * when no lock of a try is held. */ @@ -215,15 +146,21 @@ const scopedKitLock = ( path: string, privateDirectory: boolean, waitMs: number, -): Effect.Effect => + poll: LockPoll, +): Effect.Effect => Effect.acquireRelease( Effect.gen(function* () { - yield* Effect.try({ - try: () => (privateDirectory ? preparePrivateLockDirectory(path) : makeLockFolder(path)), - catch: lockFailure(path), - }); - const clock = yield* Clock.Clock; - const deadline = (yield* clock.monotonicTimeNanos) + BigInt(waitMs) * NANOS_PER_MS; + const prepare = privateDirectory + ? Effect.try({ try: () => preparePrivateLockDirectory(path), catch: lockFailure(path) }) + : makeLockFolder(path); + let deadline: bigint; + if (poll.deadlineFirst) { + deadline = (yield* poll.now) + BigInt(waitMs) * NANOS_PER_MS; + yield* prepare; + } else { + yield* prepare; + deadline = (yield* poll.now) + BigInt(waitMs) * NANOS_PER_MS; + } const held = new KitLockHeld({ path, message: heldLine(path) }); for (;;) { const lock = yield* Effect.try({ @@ -231,22 +168,76 @@ const scopedKitLock = ( catch: lockFailure(path), }); if (lock !== undefined) return lock; - const remaining = deadline - (yield* clock.monotonicTimeNanos); + const remaining = deadline - (yield* poll.now); if (remaining <= 0n) return yield* held; const sleepMs = Math.min(KIT_LOCK_POLL_MS, Math.ceil(Number(remaining) / 1e6)); yield* Effect.interruptible(Effect.sleep(sleepMs)); - if ((yield* clock.monotonicTimeNanos) >= deadline) return yield* held; + if (!poll.lastAttempt && (yield* poll.now) >= deadline) return yield* held; } }), (lock) => Effect.sync(() => releaseKitLock(lock)), ); +/** + * The canonical path of `folder`, which can be missing: the real path of its + * nearest existing ancestor, joined with the rest of the path. The probe is + * `existsSync`, which follows a junction and treats every error as missing, + * so the walk goes up as far as before; the real path is the native one. + */ +const canonicalFolder = Effect.fn("canonicalFolder")(function* (folder: string, label: string) { + const missing: Array = []; + let current = folder; + while (!(yield* Effect.sync(() => existsSync(current))) && dirname(current) !== current) { + missing.unshift(basename(current)); + current = dirname(current); + } + const ancestor = current; + const real = yield* Effect.try({ + try: () => realpathSync.native(ancestor), + catch: lockFailure(label), + }); + return join(real, ...missing); +}); + +/** + * The folder lock path of each folder, by the canonical path of the folder, + * with no duplicates, sorted by folder. Every sync takes its folder locks in + * this order, so no two syncs can wait on each other in a cycle. An ancestor + * sorts before its descendants, and a nested folder keeps its own lock. + */ +export const folderLockPaths = Effect.fn("folderLockPaths")(function* ( + folders: ReadonlyArray, +) { + const canonical = new Set(); + for (const folder of folders) canonical.add(yield* canonicalFolder(folder, folders.join(", "))); + return [...canonical].sort(compareCodepoints).map(folderSyncLockPath); +}); + +/** Hold the sync lock of `home` for the rest of the scope. Two runs of the same home meet here. */ +const homeLock = (home: string, waitMs: number, poll: LockPoll) => + scopedKitLock(syncLockPath(home), true, waitMs, poll); + +/** + * Hold the folder lock of each folder in `folders` for the rest of the scope, + * after the sync lock: runs of different homes can share an omp folder, and + * their sync locks differ. A missing folder is created under the locks of its + * ancestors in the set. + */ +const folderLocks = Effect.fn("folderLocks")(function* ( + folders: ReadonlyArray, + waitMs: number, + poll: LockPoll, +) { + for (const path of yield* folderLockPaths(folders)) { + yield* scopedKitLock(path, false, waitMs, poll); + } +}); + /** * Hold the sync lock of `home`, then the folder lock of each folder in * `folders`, for the rest of the scope, with the wait and the held line of a * sync. A command that writes a sync file outside a sync run uses it. The - * folder lock paths are resolved after the sync lock, and a missing folder is - * created under the locks of its ancestors in the set. Each taken lock goes + * folder lock paths are resolved after the sync lock. Each taken lock goes * when the scope closes: after the run, a failure, or an interrupt. */ export const homeAndFolderLocks = Effect.fn("homeAndFolderLocks")(function* ( @@ -254,70 +245,84 @@ export const homeAndFolderLocks = Effect.fn("homeAndFolderLocks")(function* ( folders: ReadonlyArray, ) { const waitMs = yield* lockWaitMs; - const homeLock = syncLockPath(home); - yield* scopedKitLock(homeLock, true, waitMs); - const paths = yield* Effect.try({ - try: () => folderLockPaths(folders), - catch: lockFailure(folders.join(", ")), - }); - for (const path of paths) yield* scopedKitLock(path, false, waitMs); + yield* homeLock(home, waitMs, TOGGLE_POLL); + yield* folderLocks(folders, waitMs, TOGGLE_POLL); }); /** - * Run a sync. `parseArgs` reads the flags first, so an unknown argument exits - * 2 and `-h` or `--help` exits 0 before any lock or write, and `--dry-run` - * sets `ctx.dryRun` before the lock check. The sync lock comes next, then the - * folder locks of the omp folders that `runSync` resolves. + * Run a sync. `parseArgs` reads the flags first, so an unknown argument and + * `-h` or `--help` end the run before any lock or write, and `--dry-run` sets + * `ctx.dryRun` before the lock check. A dry run takes no lock: `--dry-run` or + * the `DRY_RUN` env global sets `ctx.dryRun`, and `makeCtx` reads the env + * global only on the channel that reads env globals. A writing sync takes the + * sync lock, then resolves the omp folders under it, then takes their folder + * locks, all in one scope. When another sync keeps a lock past the wait bound, + * the run prints the held line and returns 1 before the pipeline. */ -export async function engineSync(ctx: Ctx, args: ReadonlyArray): Promise { - parseArgs(ctx, args); - return await withSyncLock(ctx, () => runSync(ctx)); -} +export const engineSync = Effect.fn("engineSync")(function* (args: ReadonlyArray) { + const ctx = yield* EngineContext; + yield* parseArgs(args); + if (ctx.dryRun) return yield* runPipeline(yield* ompWriteFolders()); + return yield* Effect.scoped(lockedSync(ctx)).pipe( + Effect.catchTag("KitLockHeld", (held) => + Effect.sync(() => { + ctx.services.logger.err(held.message); + return 1; + }), + ), + ); +}); -async function runSync(ctx: Ctx): Promise { - // The folders that hold omp files. A writing sync creates its folders - // anyway, so `withFolderLocks` creates each missing one under the locks of - // its ancestors in the set. The omp folders are resolved once, here: the - // omp pipeline and its omp children use these paths, so a data root that - // appears after the locks cannot move them. - const omp = ompWriteFolders(ctx); - const folders = [omp.paths.agentDir, omp.paths.dataRoot]; - return await withFolderLocks(ctx, folders, () => runPipeline(ctx, omp)); -} +/** + * The writing sync under its locks. The omp folders are resolved once, under + * the sync lock: the omp pipeline and its omp children use these paths, so a + * data root that appears after the locks cannot move them. A missing folder + * is created under the locks of its ancestors in the set. + */ +const lockedSync = Effect.fn("lockedSync")(function* (ctx: Ctx) { + const waitMs = yield* lockWaitMs; + yield* homeLock(ctx.home, waitMs, SYNC_HOME_POLL); + const omp = yield* ompWriteFolders(); + yield* folderLocks([omp.paths.agentDir, omp.paths.dataRoot], waitMs, SYNC_FOLDER_POLL); + return yield* runPipeline(omp); +}); /** Run the omp pipeline in the omp folders `omp`, then print the summary and advice. */ -async function runPipeline(ctx: Ctx, omp: OmpWriteFolders): Promise { +const runPipeline = Effect.fn("runPipeline")(function* (omp: OmpWriteFolders) { + const ctx = yield* EngineContext; const { acquireTerminal, echo } = ctx.services.logger; - const lease = acquireTerminal("Syncing omp..."); - ctx.terminalLease = lease; - let ompState: OmpState; - try { - try { - ompState = await ompSync(ctx, omp); - } finally { - lease.release(); - ctx.terminalLease = undefined; - } - } catch (error) { - // A rejected pipeline skips the summary. Print the failures that it recorded before it stopped. - printFailures(ctx); - throw error; - } - - echo(""); - echo("--- Sync complete ---"); - echo(`Repo: ${ctx.repoDir}`); - ompSummary(ctx, ompState); + const ompState = yield* Effect.scoped( + Effect.gen(function* () { + ctx.terminalLease = yield* acquireTerminal("Syncing omp..."); + yield* Effect.addFinalizer(() => + Effect.sync(() => { + ctx.terminalLease = undefined; + }), + ); + return yield* ompSync(omp); + }), + ).pipe( + // A failed pipeline skips the summary. Print the failures that it recorded before it stopped. + Effect.onError((cause) => + Cause.hasInterruptsOnly(cause) ? Effect.void : Effect.sync(() => printFailures(ctx)), + ), + ); - const advice = ompNextSteps(ctx); - if (advice.length > 0) { + return yield* Effect.sync(() => { echo(""); - for (const line of advice) echo(line); - } - if (printFailures(ctx)) return 1; - return 0; -} + echo("--- Sync complete ---"); + echo(`Repo: ${ctx.repoDir}`); + ompSummary(ctx, ompState); + + const advice = ompNextSteps(ctx); + if (advice.length > 0) { + echo(""); + for (const line of advice) echo(line); + } + return printFailures(ctx) ? 1 : 0; + }); +}); /** Print the `--- Failures ---` ledger. Returns true when the ledger has entries. */ function printFailures(ctx: Ctx): boolean { diff --git a/cli/src/engine.ts b/cli/src/engine.ts index 6d802a91..42f00765 100644 --- a/cli/src/engine.ts +++ b/cli/src/engine.ts @@ -1,8 +1,7 @@ import { CliError } from "effect/cli"; -import { Console, Effect } from "effect"; -import { runEngineNative } from "./engine-native"; +import { Cause, Console, Effect, Option } from "effect"; +import { runEngineNative, type EngineFailure } from "./engine-native"; import { targetForHost } from "./engine-native/os/targets"; -import { DependencyManagerService, LoggerService, PlatformService } from "./services"; /** * The single seam between the typed CLI and EngineNative. Engine execution @@ -21,7 +20,26 @@ const requireSupportedHost = () => { ); }; -const failureMessage = (error: unknown): string => { +/** The value that a failed run threw or rejected with, which its message comes from. */ +const originalFailure = (error: EngineFailure): unknown => { + switch (error._tag) { + case "LegacyStepFailed": + case "KitHomeInvalid": + case "LockAcquireError": + return error.cause; + case "LeaseHeld": + return error; + } +}; + +/** + * The detail of a failed run: the message of the original failure, or of a + * defect such as a stream write error, else `unknown error`. The public seam + * and the raw channel of main.ts print it. + */ +export const engineFailureDetail = (cause: Cause.Cause): string => { + const failure = Cause.findErrorOption(cause); + const error = Option.isSome(failure) ? originalFailure(failure.value) : Cause.squash(cause); if (error instanceof Error && error.message !== "") return error.message; return typeof error === "string" && error !== "" ? error : "unknown error"; }; @@ -32,17 +50,18 @@ export const engine = (args: ReadonlyArray) => if (bashEngineRequested()) { return yield* bail(bashRemovedMessage, 2); } - const logger = yield* LoggerService; - const deps = yield* DependencyManagerService; - const platform = yield* PlatformService; - const code = yield* Effect.tryPromise({ - try: () => runEngineNative(args, { logger, deps, platform }, { envGlobals: false }), - catch: (error) => - new CliError.UserError({ - cause: error, - userMessage: `engine operation '${args.join(" ") || "default"}' failed: ${failureMessage(error)}`, - }), - }); + const code = yield* runEngineNative(args, { envGlobals: false }).pipe( + Effect.catchCause((cause) => + Cause.hasInterruptsOnly(cause) + ? Effect.interrupt + : Effect.fail( + new CliError.UserError({ + cause: Cause.squash(cause), + userMessage: `engine operation '${args.join(" ") || "default"}' failed: ${engineFailureDetail(cause)}`, + }), + ), + ), + ); if (code !== 0) { return yield* Effect.sync(() => process.exit(code)); } diff --git a/cli/src/main.ts b/cli/src/main.ts index 0cc307fc..5f491b09 100755 --- a/cli/src/main.ts +++ b/cli/src/main.ts @@ -1,11 +1,12 @@ #!/usr/bin/env bun import { Command, CliOutput } from "effect/cli"; import { BunRuntime, BunServices } from "@effect/platform-bun"; -import { Effect, Layer } from "effect"; +import { Effect, Exit, Layer } from "effect"; import { EngineServicesLive } from "./services"; import { GENERATED_PACKAGE_VERSION } from "./generated/sotPayload"; import { COMMANDS, prepareArgv } from "./argv"; import { rootCommand, TIER_USAGE } from "./commands/root"; +import { engineFailureDetail } from "./engine"; import { runEngineNative } from "./engine-native"; import { OmpYamlReader } from "./engine-native/ompFastMode"; @@ -43,15 +44,16 @@ if (process.env["DOCKS_KIT_ENGINE"] === "native-raw") { // `exit` event, and exec.ts then cannot end its bounded probes. process.once("SIGINT", () => process.exit(130)); process.once("SIGTERM", () => process.exit(143)); - try { - process.exit(await runEngineNative(rawArgs, undefined, { envGlobals: true })); - } catch (error) { - let detail = "unknown error"; - if (error instanceof Error && error.message !== "") detail = error.message; - else if (typeof error === "string" && error !== "") detail = error; - process.stderr.write(`docks-kit raw operation '${rawOperation}' failed: ${detail}\n`); - process.exit(1); - } + const exit = await Effect.runPromiseExit( + runEngineNative(rawArgs, { envGlobals: true }).pipe( + Effect.provide(Layer.mergeAll(BunServices.layer, EngineServicesLive)), + ), + ); + if (Exit.isSuccess(exit)) process.exit(exit.value); + process.stderr.write( + `docks-kit raw operation '${rawOperation}' failed: ${engineFailureDetail(exit.cause)}\n`, + ); + process.exit(1); } // Validate and normalize before parsing because the kit refuses to guess at unrecognized diff --git a/cli/src/services.ts b/cli/src/services.ts index 679a8537..3b755dc2 100644 --- a/cli/src/services.ts +++ b/cli/src/services.ts @@ -1,8 +1,9 @@ /** - * Effect rim over the engine's injectable capabilities: Context.Tags with + * Effect rim over the engine's injectable capabilities: Context.Services with * live layers built from the shared factory (engine-native/services.ts) plus - * named test-layer constructors. Composed ONCE at main.ts — command code - * accesses services via `yield*`, never by re-providing. + * named test-layer constructors. Composed ONCE at main.ts, for the public CLI + * and the raw golden channel — command code accesses services via `yield*`, + * never by re-providing. */ import { Context, Layer } from "effect"; import { makeLogger, type Logger, type LoggerSinks } from "./engine-native/logger"; @@ -10,6 +11,7 @@ import { makeEngineServices, makePlatform, type DependencyManager, + type EngineServices, type Platform, } from "./engine-native/services"; @@ -24,12 +26,17 @@ export class PlatformService extends Context.Service( "docks-kit/Platform", ) {} -const live = makeEngineServices(); - -export const LoggerLive = Layer.succeed(LoggerService, live.logger); -export const DependencyManagerLive = Layer.succeed(DependencyManagerService, live.deps); -export const PlatformLive = Layer.succeed(PlatformService, live.platform); -export const EngineServicesLive = Layer.mergeAll(LoggerLive, DependencyManagerLive, PlatformLive); +/** The three engine services of `services` as one layer. */ +export const engineServicesLayer = ( + services: EngineServices, +): Layer.Layer => + Layer.mergeAll( + Layer.succeed(LoggerService, services.logger), + Layer.succeed(DependencyManagerService, services.deps), + Layer.succeed(PlatformService, services.platform), + ); + +export const EngineServicesLive = engineServicesLayer(makeEngineServices()); export const LoggerTest = (sinks: LoggerSinks): Layer.Layer => Layer.succeed(LoggerService, makeLogger(sinks)); diff --git a/cli/test/lib/engineRun.ts b/cli/test/lib/engineRun.ts new file mode 100644 index 00000000..ca468428 --- /dev/null +++ b/cli/test/lib/engineRun.ts @@ -0,0 +1,25 @@ +/** + * Run EngineNative in-process with test engine services, under the layers + * that main.ts provides with the live ones. + */ +import { BunServices } from "@effect/platform-bun"; +import { Effect, Layer } from "effect"; + +import { runEngineNative } from "../../src/engine-native"; +import type { EngineServices } from "../../src/engine-native/services"; +import { engineServicesLayer } from "../../src/services"; + +/** The layers of one engine run: the Bun platform services and `services`. */ +export const engineLayer = (services: EngineServices) => + Layer.mergeAll(BunServices.layer, engineServicesLayer(services)); + +/** Run the engine operation `argv` with `services` and resolve with its exit code. */ +export function runEngine( + argv: ReadonlyArray, + services: EngineServices, + options?: { readonly envGlobals?: boolean }, +): Promise { + return Effect.runPromise( + runEngineNative(argv, options).pipe(Effect.provide(engineLayer(services))), + ); +} diff --git a/cli/test/unit/engine-di.test.ts b/cli/test/unit/engine-di.test.ts index c79ac634..ce4209f5 100644 --- a/cli/test/unit/engine-di.test.ts +++ b/cli/test/unit/engine-di.test.ts @@ -4,9 +4,10 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import { setImmediate as nextTurn } from "node:timers/promises"; -import { runBounded, runEngineNative } from "../../src/engine-native"; +import { runBounded } from "../../src/engine-native"; import { syncLockPath } from "../../src/engine-native/scratch"; import { makeEngineServices } from "../../src/engine-native/services"; +import { runEngine } from "../lib/engineRun"; describe("sync pipeline coordinator", () => { function gatedFailure(reason: unknown) { @@ -163,7 +164,7 @@ describe("native CLI argument and output behavior", () => { stderr: (chunk) => void stderr.push(chunk), }, }); - expect(await runEngineNative(["sync", "--help"], services)).toBe(0); + expect(await runEngine(["sync", "--help"], services)).toBe(0); const help = stdout.join(""); expect(help).toContain("Usage: docks-kit sync [flags]"); for (const flag of ["--dry-run", "--verbose"]) { @@ -183,7 +184,7 @@ describe("native CLI argument and output behavior", () => { sinks: { stdout: () => {}, stderr: (chunk) => void stderr.push(chunk) }, }); - expect(await runEngineNative(["sync", "--skip-plugin-refresh"], services)).toBe(2); + expect(await runEngine(["sync", "--skip-plugin-refresh"], services)).toBe(2); expect(stderr.join("")).toContain("Unknown arg: --skip-plugin-refresh"); for (const folder of [".omp", ".pi", ".docks-kit"]) { diff --git a/cli/test/unit/engine.test.ts b/cli/test/unit/engine.test.ts index 57b9b0a4..b4977e51 100644 --- a/cli/test/unit/engine.test.ts +++ b/cli/test/unit/engine.test.ts @@ -1,4 +1,5 @@ -import { Effect } from "effect"; +import { BunServices } from "@effect/platform-bun"; +import { Effect, Layer } from "effect"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; const mocks = vi.hoisted(() => ({ runEngineNative: vi.fn() })); @@ -6,6 +7,7 @@ const mocks = vi.hoisted(() => ({ runEngineNative: vi.fn() })); vi.mock("../../src/engine-native", () => ({ runEngineNative: mocks.runEngineNative })); import { engine } from "../../src/engine"; +import { LegacyStepFailed } from "../../src/engine-native/bridge"; import { EngineServicesLive } from "../../src/services"; beforeEach(() => { @@ -27,7 +29,9 @@ afterEach(() => { }); const runEngine = (args: ReadonlyArray) => - Effect.runPromise(Effect.provide(engine(args), EngineServicesLive)); + Effect.runPromise( + Effect.provide(engine(args), Layer.mergeAll(BunServices.layer, EngineServicesLive)), + ); describe("supported host boundary", () => { it.each([ @@ -40,7 +44,7 @@ describe("supported host boundary", () => { async (platform, arch) => { vi.spyOn(process, "platform", "get").mockReturnValue(platform); vi.spyOn(process, "arch", "get").mockReturnValue(arch); - mocks.runEngineNative.mockResolvedValue(37); + mocks.runEngineNative.mockReturnValue(Effect.succeed(37)); await expect(runEngine(["toolchain"])).rejects.toThrow("exit 37"); expect(console.error).not.toHaveBeenCalled(); @@ -83,8 +87,16 @@ describe("EngineNative Effect seam", () => { expect(mocks.runEngineNative).not.toHaveBeenCalled(); }); - it("maps a rejected EngineNative Promise to a user-facing CLI failure", async () => { - mocks.runEngineNative.mockRejectedValue(new Error("native engine failed")); + it("maps a failed EngineNative step to a user-facing CLI failure with the original message", async () => { + mocks.runEngineNative.mockReturnValue( + Effect.fail( + new LegacyStepFailed({ + step: "syncPlugins", + message: "native engine failed", + cause: new Error("native engine failed"), + }), + ), + ); await expect(runEngine(["toolchain"])).rejects.toMatchObject({ _tag: "UserError", @@ -92,8 +104,17 @@ describe("EngineNative Effect seam", () => { }); }); - it("reports the default operation and unknown cause when the native engine rejects silently", async () => { - mocks.runEngineNative.mockRejectedValue(new Error("")); + it("maps a defect of the run, such as a stream write error, to the same CLI failure", async () => { + mocks.runEngineNative.mockReturnValue(Effect.die(new Error("write EIO"))); + + await expect(runEngine(["sync"])).rejects.toMatchObject({ + _tag: "UserError", + message: "engine operation 'sync' failed: write EIO", + }); + }); + + it("reports the default operation and unknown cause when the native engine fails silently", async () => { + mocks.runEngineNative.mockReturnValue(Effect.die(new Error(""))); await expect(runEngine([])).rejects.toMatchObject({ _tag: "UserError", @@ -102,10 +123,10 @@ describe("EngineNative Effect seam", () => { }); it("runs the public engine with env globals disabled", async () => { - mocks.runEngineNative.mockResolvedValue(0); + mocks.runEngineNative.mockReturnValue(Effect.succeed(0)); await runEngine(["sync", "--dry-run"]); - expect(mocks.runEngineNative).toHaveBeenCalledWith(["sync", "--dry-run"], expect.anything(), { + expect(mocks.runEngineNative).toHaveBeenCalledWith(["sync", "--dry-run"], { envGlobals: false, }); }); diff --git a/cli/test/unit/envGlobals.test.ts b/cli/test/unit/envGlobals.test.ts index 1b80eb6b..28969176 100644 --- a/cli/test/unit/envGlobals.test.ts +++ b/cli/test/unit/envGlobals.test.ts @@ -2,8 +2,8 @@ import { afterEach, beforeEach, describe, expect, it } from "vitest"; import { mkdtempSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; +import { Effect } from "effect"; -import { runEngineNative } from "../../src/engine-native"; import { DEPENDENCIES } from "../../src/engine-native/deps"; import { makePlatform, @@ -11,6 +11,7 @@ import { type EngineServices, type Logger, } from "../../src/engine-native/services"; +import { runEngine } from "../lib/engineRun"; interface LogRecord { readonly level: "change" | "verbose" | "warn" | "err" | "echo"; @@ -26,11 +27,12 @@ function stubServices(records: Array): EngineServices { warn: (message) => void records.push({ level: "warn", message }), err: (message) => void records.push({ level: "err", message }), echo: (message) => void records.push({ level: "echo", message }), - acquireTerminal: () => ({ - update: () => {}, - withExclusive: async (action) => await action(), - release: () => {}, - }), + acquireTerminal: () => + Effect.succeed({ + update: () => {}, + withExclusive: (action) => action, + release: () => {}, + }), }; const platform = makePlatform("linux"); const deps: DependencyManager = { @@ -79,14 +81,12 @@ describe("engine env globals", () => { const advice = "Restart omp to load any refreshed plugins, skills, or tools."; const publicRecords: Array = []; - expect(await runEngineNative(["sync", "--dry-run"], stubServices(publicRecords))).toBe(0); + expect(await runEngine(["sync", "--dry-run"], stubServices(publicRecords))).toBe(0); expect(publicRecords.some(({ message }) => message === advice)).toBe(false); const rawRecords: Array = []; expect( - await runEngineNative(["sync", "--dry-run"], stubServices(rawRecords), { - envGlobals: true, - }), + await runEngine(["sync", "--dry-run"], stubServices(rawRecords), { envGlobals: true }), ).toBe(0); expect(rawRecords.some(({ message }) => message === advice)).toBe(true); }); @@ -94,9 +94,7 @@ describe("engine env globals", () => { it("ignores flags when selecting a toolchain operation", async () => { const records: Array = []; - expect(await runEngineNative(["toolchain", "--verbose", "ensure"], stubServices(records))).toBe( - 2, - ); + expect(await runEngine(["toolchain", "--verbose", "ensure"], stubServices(records))).toBe(2); expect(records).toEqual([{ level: "err", message: "Usage: toolchain ensure " }]); }); }); diff --git a/cli/test/unit/folderLockCreate.test.ts b/cli/test/unit/folderLockCreate.test.ts index 797ab2a4..e287de90 100644 --- a/cli/test/unit/folderLockCreate.test.ts +++ b/cli/test/unit/folderLockCreate.test.ts @@ -17,7 +17,8 @@ import { } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { Effect, Fiber } from "effect"; +import { BunServices } from "@effect/platform-bun"; +import { Effect, Fiber, type FileSystem } from "effect"; import { afterEach, describe, expect, it, vi } from "vitest"; import { acquireKitLock, releaseKitLock, type KitLock } from "../../src/engine-native/kitLock"; @@ -38,6 +39,10 @@ function tempRoot(): string { return realpathSync.native(created); } +/** Run `effect` with the Bun platform services, whose `FileSystem` makes the lock folders. */ +const runWithPlatform = (effect: Effect.Effect): Promise => + Effect.runPromise(effect.pipe(Effect.provide(BunServices.layer))); + /** Take the lock at `path` as another run does, or throw when it is held. */ async function takeLock(path: string, privateDirectory: boolean): Promise { const held = await acquireKitLock(path, { waitMs: 0, privateDirectory }); @@ -53,7 +58,7 @@ describe("folders under the folder locks", () => { chmodSync(parent, 0o755); const folder = join(parent, "omp", "agent"); - await Effect.runPromise(Effect.scoped(homeAndFolderLocks(root, [folder]))); + await runWithPlatform(Effect.scoped(homeAndFolderLocks(root, [folder]))); expect(statSync(folder).isDirectory()).toBe(true); if (POSIX) { @@ -74,7 +79,7 @@ describe("homeAndFolderLocks lock lifetime", () => { const held = await takeLock(folderLock, false); try { - const error = await Effect.runPromise( + const error = await runWithPlatform( Effect.flip(Effect.scoped(homeAndFolderLocks(root, [folder]))), ); @@ -96,7 +101,7 @@ describe("homeAndFolderLocks lock lifetime", () => { const held = await takeLock(folderSyncLockPath(folder), false); try { - await Effect.runPromise( + await runWithPlatform( Effect.gen(function* () { const fiber = yield* Effect.forkChild(Effect.scoped(homeAndFolderLocks(root, [folder]))); // Wait until the run holds the home lock and polls the folder lock. A @@ -131,7 +136,7 @@ describe("homeAndFolderLocks lock lifetime", () => { const root = tempRoot(); const folder = join(root, "agent"); - const error = await Effect.runPromise( + const error = await runWithPlatform( Effect.flip(Effect.scoped(homeAndFolderLocks(root, [folder]))), ); diff --git a/cli/test/unit/logger.test.ts b/cli/test/unit/logger.test.ts index ff41bace..cf97dd6b 100644 --- a/cli/test/unit/logger.test.ts +++ b/cli/test/unit/logger.test.ts @@ -1,4 +1,5 @@ import { EventEmitter } from "node:events"; +import { Cause, Deferred, Effect, Exit, Fiber, type Scope } from "effect"; import { describe, expect, it } from "vitest"; import { makeLogger, writeIgnoringEpipe } from "../../src/engine-native/logger"; @@ -50,112 +51,128 @@ describe("logger progress channel", () => { }); describe("logger terminal lease", () => { + /** Run `body` with a scope for the leases that it takes. */ + const scoped = (body: Effect.Effect): Promise => + Effect.runPromise(Effect.scoped(body)); + it("serializes terminal-exclusive sections and suspends progress redraw", async () => { const chunks: Array = []; const events: Array = []; - let enterFirst!: () => void; - let releaseFirst!: () => void; - const firstEntered = new Promise((resolve) => { - enterFirst = resolve; - }); - const firstGate = new Promise((resolve) => { - releaseFirst = resolve; - }); const logger = makeLogger({ progress: (chunk) => void chunks.push(chunk) }); - const lease = logger.acquireTerminal("Syncing Claude, Codex..."); - - const first = lease.withExclusive(async () => { - events.push("first:start"); - enterFirst(); - await firstGate; - events.push("first:finish"); - }); - const second = lease.withExclusive(() => { - events.push("second:start"); - events.push("second:finish"); - }); - await firstEntered; - lease.update("Syncing Codex..."); - logger.progress("pipeline-owned progress"); - - expect(chunks).toEqual(["\r\x1b[2K\x1b[2mSyncing Claude, Codex...\x1b[0m", "\r\x1b[2K"]); - expect(events).toEqual(["first:start"]); - releaseFirst(); - await Promise.all([first, second]); - expect(events).toEqual(["first:start", "first:finish", "second:start", "second:finish"]); - expect(chunks).toEqual([ - "\r\x1b[2K\x1b[2mSyncing Claude, Codex...\x1b[0m", - "\r\x1b[2K", - "\r\x1b[2K\x1b[2mSyncing Codex...\x1b[0m", - ]); - - lease.release(); - expect(chunks.at(-1)).toBe("\r\x1b[2K"); + await scoped( + Effect.gen(function* () { + const lease = yield* logger.acquireTerminal("Syncing Claude, Codex..."); + const firstEntered = yield* Deferred.make(); + const firstGate = yield* Deferred.make(); + const first = yield* Effect.forkChild( + lease.withExclusive( + Effect.gen(function* () { + events.push("first:start"); + yield* Deferred.succeed(firstEntered, undefined); + yield* Deferred.await(firstGate); + events.push("first:finish"); + }), + ), + { startImmediately: true }, + ); + const second = yield* Effect.forkChild( + lease.withExclusive( + Effect.sync(() => { + events.push("second:start"); + events.push("second:finish"); + }), + ), + { startImmediately: true }, + ); + yield* Deferred.await(firstEntered); + lease.update("Syncing Codex..."); + logger.progress("pipeline-owned progress"); + + expect(chunks).toEqual(["\r\x1b[2K\x1b[2mSyncing Claude, Codex...\x1b[0m", "\r\x1b[2K"]); + expect(events).toEqual(["first:start"]); + + yield* Deferred.succeed(firstGate, undefined); + yield* Fiber.join(first); + yield* Fiber.join(second); + expect(events).toEqual(["first:start", "first:finish", "second:start", "second:finish"]); + expect(chunks).toEqual([ + "\r\x1b[2K\x1b[2mSyncing Claude, Codex...\x1b[0m", + "\r\x1b[2K", + "\r\x1b[2K\x1b[2mSyncing Codex...\x1b[0m", + ]); + + lease.release(); + expect(chunks.at(-1)).toBe("\r\x1b[2K"); + }), + ); }); - it("rejects nested terminal-exclusive sections and accepts the next section", async () => { + it("fails a nested terminal-exclusive section before it waits and accepts the next section", async () => { const logger = makeLogger({}); - const lease = logger.acquireTerminal("Syncing..."); - await expect( - lease.withExclusive(async () => { - await lease.withExclusive(() => {}); - }), - ).rejects.toThrow("terminal lease withExclusive cannot be re-entered"); - await expect(lease.withExclusive(() => "continued")).resolves.toBe("continued"); + await scoped( + Effect.gen(function* () { + const lease = yield* logger.acquireTerminal("Syncing..."); - lease.release(); + const nested = yield* Effect.flip(lease.withExclusive(lease.withExclusive(Effect.void))); + expect(nested).toMatchObject({ + _tag: "LeaseReentered", + message: "terminal lease withExclusive cannot be re-entered", + }); + expect(yield* lease.withExclusive(Effect.succeed("continued"))).toBe("continued"); + }), + ); }); it("buffers durable output during an exclusive section and flushes it in call order", async () => { const writes: Array = []; - let entered!: () => void; - let finish!: () => void; - const actionEntered = new Promise((resolve) => { - entered = resolve; - }); - const actionGate = new Promise((resolve) => { - finish = resolve; - }); const logger = makeLogger({ progress: (chunk) => void writes.push(`progress:${chunk}`), stderr: (chunk) => void writes.push(`stderr:${chunk}`), stdout: (chunk) => void writes.push(`stdout:${chunk}`), }); - const lease = logger.acquireTerminal("Syncing Claude, Codex..."); - - const exclusive = lease.withExclusive(async () => { - logger.change("Claude changed"); - logger.echo("Codex summary"); - logger.warn("skills warning"); - logger.verbose("Claude steady"); - logger.err("failure now"); - entered(); - await actionGate; - }); - await actionEntered; - - expect(writes).toEqual([ - "progress:\r\x1b[2K\x1b[2mSyncing Claude, Codex...\x1b[0m", - "progress:\r\x1b[2K", - "stderr:\x1b[1;31m[err]\x1b[0m failure now\n", - ]); - - finish(); - await exclusive; - expect(writes).toEqual([ - "progress:\r\x1b[2K\x1b[2mSyncing Claude, Codex...\x1b[0m", - "progress:\r\x1b[2K", - "stderr:\x1b[1;31m[err]\x1b[0m failure now\n", - "stderr:\x1b[1;32m[ok]\x1b[0m Claude changed\n", - "stdout:Codex summary\n", - "stderr:\x1b[1;33m[warn]\x1b[0m skills warning\n", - "stderr:\x1b[1;32m[ok]\x1b[0m Claude steady\n", - "progress:\r\x1b[2K\x1b[2mSyncing Claude, Codex...\x1b[0m", - ]); - lease.release(); + await scoped( + Effect.gen(function* () { + const lease = yield* logger.acquireTerminal("Syncing Claude, Codex..."); + const entered = yield* Deferred.make(); + const gate = yield* Deferred.make(); + const exclusive = yield* Effect.forkChild( + lease.withExclusive( + Effect.gen(function* () { + logger.change("Claude changed"); + logger.echo("Codex summary"); + logger.warn("skills warning"); + logger.verbose("Claude steady"); + logger.err("failure now"); + yield* Deferred.succeed(entered, undefined); + yield* Deferred.await(gate); + }), + ), + ); + yield* Deferred.await(entered); + + expect(writes).toEqual([ + "progress:\r\x1b[2K\x1b[2mSyncing Claude, Codex...\x1b[0m", + "progress:\r\x1b[2K", + "stderr:\x1b[1;31m[err]\x1b[0m failure now\n", + ]); + + yield* Deferred.succeed(gate, undefined); + yield* Fiber.join(exclusive); + expect(writes).toEqual([ + "progress:\r\x1b[2K\x1b[2mSyncing Claude, Codex...\x1b[0m", + "progress:\r\x1b[2K", + "stderr:\x1b[1;31m[err]\x1b[0m failure now\n", + "stderr:\x1b[1;32m[ok]\x1b[0m Claude changed\n", + "stdout:Codex summary\n", + "stderr:\x1b[1;33m[warn]\x1b[0m skills warning\n", + "stderr:\x1b[1;32m[ok]\x1b[0m Claude steady\n", + "progress:\r\x1b[2K\x1b[2mSyncing Claude, Codex...\x1b[0m", + ]); + }), + ); }); it("flushes durable output and restores progress when exclusive work fails", async () => { @@ -164,44 +181,68 @@ describe("logger terminal lease", () => { progress: (chunk) => void writes.push(`progress:${chunk}`), stderr: (chunk) => void writes.push(`stderr:${chunk}`), }); - const lease = logger.acquireTerminal("Syncing..."); - await expect( - lease.withExclusive(() => { - logger.change("Saved"); - throw new Error("install failed"); + await scoped( + Effect.gen(function* () { + const lease = yield* logger.acquireTerminal("Syncing..."); + + const failure = yield* Effect.flip( + lease.withExclusive( + Effect.sync(() => logger.change("Saved")).pipe( + Effect.andThen(Effect.fail("install failed")), + ), + ), + ); + expect(failure).toBe("install failed"); + expect(writes).toEqual([ + "progress:\r\x1b[2K\x1b[2mSyncing...\x1b[0m", + "progress:\r\x1b[2K", + "stderr:\x1b[1;32m[ok]\x1b[0m Saved\n", + "progress:\r\x1b[2K\x1b[2mSyncing...\x1b[0m", + ]); }), - ).rejects.toThrow("install failed"); - expect(writes).toEqual([ - "progress:\r\x1b[2K\x1b[2mSyncing...\x1b[0m", - "progress:\r\x1b[2K", - "stderr:\x1b[1;32m[ok]\x1b[0m Saved\n", - "progress:\r\x1b[2K\x1b[2mSyncing...\x1b[0m", - ]); - - lease.release(); + ); }); it("finishes admitted work without restoring a released lease over its successor", async () => { const progress: Array = []; const logger = makeLogger({ progress: (chunk) => void progress.push(chunk) }); - const first = logger.acquireTerminal("first"); - const admitted = first.withExclusive(() => "admitted"); - first.release(); - const second = logger.acquireTerminal("second"); - first.update("stale"); - first.release(); - expect(progress).toEqual([ - "\r\x1b[2K\x1b[2mfirst\x1b[0m", - "\r\x1b[2K", - "\r\x1b[2K\x1b[2msecond\x1b[0m", - ]); - await expect(admitted).resolves.toBe("admitted"); - expect(progress.at(-1)).toBe("\r\x1b[2K"); - second.update("current"); - await expect(first.withExclusive(() => "direct")).resolves.toBe("direct"); - expect(progress.at(-1)).toBe("\r\x1b[2K\x1b[2mcurrent\x1b[0m"); - second.release(); + + await scoped( + Effect.gen(function* () { + const first = yield* logger.acquireTerminal("first"); + const blockerEntered = yield* Deferred.make(); + const gate = yield* Deferred.make(); + const blocker = yield* Effect.forkChild( + first.withExclusive( + Deferred.succeed(blockerEntered, undefined).pipe(Effect.andThen(Deferred.await(gate))), + ), + { startImmediately: true }, + ); + yield* Deferred.await(blockerEntered); + // Admitted while the lease is active; it waits behind the blocker. + const admitted = yield* Effect.forkChild(first.withExclusive(Effect.succeed("admitted")), { + startImmediately: true, + }); + first.release(); + const second = yield* logger.acquireTerminal("second"); + first.update("stale"); + first.release(); + expect(progress).toEqual([ + "\r\x1b[2K\x1b[2mfirst\x1b[0m", + "\r\x1b[2K", + "\r\x1b[2K\x1b[2msecond\x1b[0m", + ]); + + yield* Deferred.succeed(gate, undefined); + yield* Fiber.join(blocker); + expect(yield* Fiber.join(admitted)).toBe("admitted"); + expect(progress.at(-1)).toBe("\r\x1b[2K"); + second.update("current"); + expect(yield* first.withExclusive(Effect.succeed("direct"))).toBe("direct"); + expect(progress.at(-1)).toBe("\r\x1b[2K\x1b[2mcurrent\x1b[0m"); + }), + ); }); it("flushes pending and reentrant writes even when a sink throws", async () => { @@ -216,35 +257,70 @@ describe("logger terminal lease", () => { } }, }); - const lease = logger.acquireTerminal("sync"); - const action = lease.withExclusive(() => { - logger.echo("first"); - logger.echo("second"); - }); - await expect(action).rejects.toBe(failure); - lease.release(); + + await scoped( + Effect.gen(function* () { + const lease = yield* logger.acquireTerminal("sync"); + const exit = yield* Effect.exit( + lease.withExclusive( + Effect.sync(() => { + logger.echo("first"); + logger.echo("second"); + }), + ), + ); + expect(Exit.isFailure(exit) && Cause.squash(exit.cause)).toBe(failure); + }), + ); expect(lines).toEqual(["first\n", "second\n", "last\n"]); }); - it("returns transient progress control after the terminal lease is released", () => { + it("returns transient progress control after the terminal lease is released", async () => { const chunks: Array = []; const logger = makeLogger({ progress: (chunk) => void chunks.push(chunk) }); - const lease = logger.acquireTerminal("Syncing..."); - logger.progress("ignored"); - logger.clearProgress(); - expect(() => logger.acquireTerminal("Another sync")).toThrow("terminal lease already acquired"); - expect(chunks).toEqual(["\r\x1b[2K\x1b[2mSyncing...\x1b[0m"]); + await scoped( + Effect.gen(function* () { + const lease = yield* logger.acquireTerminal("Syncing..."); + + logger.progress("ignored"); + logger.clearProgress(); + const held = yield* Effect.flip(logger.acquireTerminal("Another sync")); + expect(held).toMatchObject({ + _tag: "LeaseHeld", + message: "terminal lease already acquired", + }); + expect(chunks).toEqual(["\r\x1b[2K\x1b[2mSyncing...\x1b[0m"]); + + lease.release(); + logger.progress("Done"); + logger.clearProgress(); + expect(chunks).toEqual([ + "\r\x1b[2K\x1b[2mSyncing...\x1b[0m", + "\r\x1b[2K", + "\r\x1b[2K\x1b[2mDone\x1b[0m", + "\r\x1b[2K", + ]); + }), + ); + }); - lease.release(); - logger.progress("Done"); - logger.clearProgress(); - expect(chunks).toEqual([ - "\r\x1b[2K\x1b[2mSyncing...\x1b[0m", - "\r\x1b[2K", - "\r\x1b[2K\x1b[2mDone\x1b[0m", - "\r\x1b[2K", - ]); + it("releases the terminal lease when its scope closes, also after a failure", async () => { + const chunks: Array = []; + const logger = makeLogger({ progress: (chunk) => void chunks.push(chunk) }); + + const failure = await Effect.runPromise( + Effect.flip( + Effect.scoped( + logger.acquireTerminal("Syncing...").pipe(Effect.andThen(Effect.fail("pass failed"))), + ), + ), + ); + expect(failure).toBe("pass failed"); + expect(chunks).toEqual(["\r\x1b[2K\x1b[2mSyncing...\x1b[0m", "\r\x1b[2K"]); + + await scoped(logger.acquireTerminal("Next sync")); + expect(chunks.at(-1)).toBe("\r\x1b[2K"); }); }); diff --git a/cli/test/unit/ompPluginInventory.test.ts b/cli/test/unit/ompPluginInventory.test.ts index b8ec548e..fb8cd62c 100644 --- a/cli/test/unit/ompPluginInventory.test.ts +++ b/cli/test/unit/ompPluginInventory.test.ts @@ -43,7 +43,9 @@ vi.mock("../../src/engine-native/bun", () => ({ bunBootstrap: async () => ({ kind: "ready", executable: "bun" }), })); +import { Effect } from "effect"; import type { Ctx } from "../../src/engine-native"; +import { EngineContext } from "../../src/engine-native/engineCtx"; import { piIntercomNotice, syncPlugins } from "../../src/engine-native/ompPlugins"; import { ompNextSteps, @@ -180,14 +182,17 @@ function makeCtx( } as unknown as Ctx; } -/** Run the omp pipeline in the folders that a sync of `ctx` resolves, as `runSync` does. */ +/** Run the omp pipeline in the folders that a sync of `ctx` resolves, as `engineSync` does. */ function syncOmp(ctx: Ctx): Promise { - return ompSync(ctx, ompWriteFolders(ctx)); + return Effect.runPromise( + Effect.flatMap(ompWriteFolders(), ompSync).pipe(Effect.provideService(EngineContext, ctx)), + ); } /** Run the plugin pass on the omp paths that a sync of `ctx` resolves. */ function syncOmpPlugins(ctx: Ctx): Promise { - return syncPlugins(ctx, ompWriteFolders(ctx).paths); + const folders = Effect.runSync(ompWriteFolders().pipe(Effect.provideService(EngineContext, ctx))); + return syncPlugins(ctx, folders.paths); } /** Every `omp` argv the pipeline spawned, as one joined string per call. */ diff --git a/cli/test/unit/ompRemovals.test.ts b/cli/test/unit/ompRemovals.test.ts index eaa7c454..7842cee7 100644 --- a/cli/test/unit/ompRemovals.test.ts +++ b/cli/test/unit/ompRemovals.test.ts @@ -34,6 +34,8 @@ vi.mock("../../src/engine-native/bun", () => ({ bunBootstrap: async () => ({ kind: "ready", executable: "bun" }), })); +import { Effect } from "effect"; +import { EngineContext } from "../../src/engine-native/engineCtx"; import { syncOmpModelRemovals, syncOmpRemovals } from "../../src/engine-native/ompRemovals"; import { ompSync, ompWriteFolders } from "../../src/engine-native/ompSync"; import { DEPENDENCIES } from "../../src/engine-native/deps"; @@ -119,7 +121,9 @@ async function runOmpSync(root: string): Promise { try { const ctx = { ...testCtx(root), home: root }; - await ompSync(ctx, ompWriteFolders(ctx)); + await Effect.runPromise( + Effect.flatMap(ompWriteFolders(), ompSync).pipe(Effect.provideService(EngineContext, ctx)), + ); } finally { for (const [key, value] of Object.entries(restore)) { if (value === undefined) delete process.env[key]; diff --git a/cli/test/unit/syncLock.test.ts b/cli/test/unit/syncLock.test.ts index d5be4208..524fa29d 100644 --- a/cli/test/unit/syncLock.test.ts +++ b/cli/test/unit/syncLock.test.ts @@ -1,8 +1,8 @@ /** * Spec for the sync lock (plans #161 and #164). `engineSync` parses its * arguments first: an unknown argument exits 2, and `-h` or `--help` exits 0, - * before any lock. It then takes `/sync-lock.db` through - * `kitLock.ts acquireKitLock`, unless the run is a dry run (`--dry-run`, or the + * before any lock. It then takes `/sync-lock.db` as a + * scoped `kitLock.ts` lock, unless the run is a dry run (`--dry-run`, or the * `DRY_RUN` env global, which sets `ctx.dryRun`). * When another holder keeps the lock past the wait bound, the run prints * `another docks-kit sync holds ; run sync again after it ends` and @@ -35,6 +35,8 @@ import { } from "node:fs"; import { tmpdir } from "node:os"; import { basename, join } from "node:path"; +import { setImmediate as nextTurn } from "node:timers/promises"; +import { Effect, Fiber } from "effect"; import { describe, expect, it, vi } from "vitest"; import type * as ExecModule from "../../src/engine-native/exec"; @@ -64,6 +66,7 @@ import { type Logger, } from "../../src/engine-native/services"; import { folderLockPaths } from "../../src/engine-native/syncDispatch"; +import { engineLayer, runEngine } from "../lib/engineRun"; const WAIT_MS = "100"; const UNKNOWN_ARG_ERROR = "Unknown arg: --bogus"; @@ -141,10 +144,8 @@ function ompServices(records: Array, beforePipelines: () => void): Engin ...base, logger: { ...base.logger, - acquireTerminal: (message) => { - beforePipelines(); - return base.logger.acquireTerminal(message); - }, + acquireTerminal: (message) => + Effect.sync(beforePipelines).pipe(Effect.andThen(base.logger.acquireTerminal(message))), }, deps: makeDependencyManager(base.platform, { commandExists: (name) => Object.hasOwn(present, name), @@ -185,7 +186,12 @@ async function holdingLock(home: string, body: () => Promise): Promise { - const result = await acquireKitLock(syncLock(home), { waitMs: 0 }); + return await probeLock(syncLock(home), true); +} + +/** Try the lock at `path` once, release it when the try took it, and return the result kind. */ +async function probeLock(path: string, privateDirectory: boolean): Promise { + const result = await acquireKitLock(path, { waitMs: 0, privateDirectory }); if (result.kind === "acquired") releaseKitLock(result.lock); return result.kind; } @@ -232,7 +238,7 @@ describe("sync under the sync lock", () => { const before = snapshot(home); const records: Array = []; - expect(await runEngineNative(["sync"], recordingServices(records))).toBe(1); + expect(await runEngine(["sync"], recordingServices(records))).toBe(1); expect(records).toContain(heldLine(home)); expect(snapshot(home)).toEqual(before); @@ -245,7 +251,7 @@ describe("sync under the sync lock", () => { await holdingLock(home, async () => { const records: Array = []; - expect(await runEngineNative(["sync", "--dry-run"], recordingServices(records))).toBe(0); + expect(await runEngine(["sync", "--dry-run"], recordingServices(records))).toBe(0); expect(records).not.toContain(heldLine(home)); }); @@ -263,11 +269,9 @@ describe("sync under the sync lock", () => { const records: Array = []; // Only the raw channel reads the env globals. - expect( - await runEngineNative(["sync"], recordingServices(records), { - envGlobals: true, - }), - ).toBe(0); + expect(await runEngine(["sync"], recordingServices(records), { envGlobals: true })).toBe( + 0, + ); expect(records).not.toContain(heldLine(home)); expect({ home: snapshot(home), shared: snapshot(shared) }).toEqual(before); @@ -285,7 +289,7 @@ describe("sync under the sync lock", () => { const records: Array = []; // The public CLI ignores DRY_RUN, so this run writes and must wait. - expect(await runEngineNative(["sync"], recordingServices(records))).toBe(1); + expect(await runEngine(["sync"], recordingServices(records))).toBe(1); expect(records).toContain(heldLine(home)); expect(snapshot(home)).toEqual(before); @@ -299,7 +303,7 @@ describe("sync under the sync lock", () => { for (const flag of ["-h", "--help"]) { const records: Array = []; - expect(await runEngineNative(["sync", flag], recordingServices(records))).toBe(0); + expect(await runEngine(["sync", flag], recordingServices(records))).toBe(0); expect(records).not.toContain(heldLine(home)); } @@ -311,7 +315,7 @@ describe("sync under the sync lock", () => { await withHome(async (home) => { const failed: Array = []; - expect(await runEngineNative(["sync", "--bogus"], recordingServices(failed))).toBe(2); + expect(await runEngine(["sync", "--bogus"], recordingServices(failed))).toBe(2); expect(failed).toContain(UNKNOWN_ARG_ERROR); expect(existsSync(syncLock(home))).toBe(false); @@ -320,7 +324,7 @@ describe("sync under the sync lock", () => { await holdingLock(home, async () => { const blocked: Array = []; - expect(await runEngineNative(["sync", "--bogus"], recordingServices(blocked))).toBe(2); + expect(await runEngine(["sync", "--bogus"], recordingServices(blocked))).toBe(2); expect(blocked).toContain(UNKNOWN_ARG_ERROR); expect(blocked).not.toContain(heldLine(home)); @@ -336,7 +340,7 @@ describe("sync under the sync lock", () => { process.env["DOCKS_KIT_SYNC_LOCK_WAIT_MS"] = waitMs; const records: Array = []; - expect(await runEngineNative(["sync"], recordingServices(records))).toBe(2); + expect(await runEngine(["sync"], recordingServices(records))).toBe(2); expect(records).toContain(WAIT_ERROR); expect(snapshot(home)).toEqual(before); @@ -355,7 +359,7 @@ describe("folder lock paths", () => { mkdirSync(second); symlinkSync(first, link, "junction"); - expect(folderLockPaths([second, link, first])).toEqual([ + expect(Effect.runSync(folderLockPaths([second, link, first]))).toEqual([ join(first, FOLDER_LOCK), join(second, FOLDER_LOCK), ]); @@ -373,7 +377,7 @@ describe("folder locks of a shared omp folder", () => { const before = snapshot(shared); const records: Array = []; - expect(await runEngineNative(["sync"], recordingServices(records))).toBe(1); + expect(await runEngine(["sync"], recordingServices(records))).toBe(1); expect(records).toContain(heldLineFor(lock)); expect(snapshot(shared)).toEqual(before); @@ -395,7 +399,7 @@ describe("folder locks of a shared omp folder", () => { const before = snapshot(shared); const records: Array = []; - expect(await runEngineNative(["sync"], recordingServices(records))).toBe(1); + expect(await runEngine(["sync"], recordingServices(records))).toBe(1); expect(records).toContain(heldLineFor(lock)); expect(snapshot(shared)).toEqual(before); @@ -422,7 +426,7 @@ describe("folder locks of a shared omp folder", () => { const before = snapshot(intercom); const records: Array = []; - expect(await runEngineNative(["sync"], recordingServices(records))).toBe(0); + expect(await runEngine(["sync"], recordingServices(records))).toBe(0); expect(records).not.toContain(heldLineFor(lock)); expect(snapshot(intercom)).toEqual(before); @@ -447,7 +451,7 @@ describe("folder locks of a shared omp folder", () => { const before = snapshot(shared); const records: Array = []; - expect(await runEngineNative(["sync"], recordingServices(records))).toBe(1); + expect(await runEngine(["sync"], recordingServices(records))).toBe(1); expect(records).toContain(heldLineFor(lock)); expect(snapshot(shared)).toEqual(before); @@ -468,7 +472,7 @@ describe("folder locks of a shared omp folder", () => { process.env["PI_CONFIG_DIR"] = configDir; // The first sync creates the missing data root and takes its lock. - expect(await runEngineNative(["sync"], recordingServices([]))).toBe(0); + expect(await runEngine(["sync"], recordingServices([]))).toBe(0); expect(existsSync(join(dataRoot, FOLDER_LOCK))).toBe(true); await withHome(async (secondHome) => { @@ -477,7 +481,7 @@ describe("folder locks of a shared omp folder", () => { await holdingFolderLock(dataRoot, async (lock) => { const records: Array = []; - expect(await runEngineNative(["sync"], recordingServices(records))).toBe(1); + expect(await runEngine(["sync"], recordingServices(records))).toBe(1); expect(records).toContain(heldLineFor(lock)); }); @@ -497,7 +501,7 @@ describe("folder locks of a shared omp folder", () => { const before = { home: snapshot(home), shared: snapshot(shared) }; const records: Array = []; - expect(await runEngineNative(["sync", "--dry-run"], recordingServices(records))).toBe(0); + expect(await runEngine(["sync", "--dry-run"], recordingServices(records))).toBe(0); expect(records).not.toContain(heldLineFor(lock)); expect({ home: snapshot(home), shared: snapshot(shared) }).toEqual(before); @@ -536,7 +540,7 @@ describe("omp children of a sync", () => { // A later omp process adopts the candidate and does not see the // plugins of the locked root, so the sync must not report success. - expect(await runEngineNative(["sync"], services)).toBe(1); + expect(await runEngine(["sync"], services)).toBe(1); const moved = `omp data root moved to ${candidate} during the sync; run docks-kit sync again`; expect(records).toContain(moved); expect(records).toContain("--- Failures ---"); @@ -563,3 +567,47 @@ describe("omp children of a sync", () => { ); } }); + +describe("interrupt of a sync", () => { + it("keeps the sync lock and the omp folder locks until an interrupted bridged pass settles", async () => { + await withHome(async (home) => { + await withSharedFolder(async (shared) => { + process.env["PI_CODING_AGENT_DIR"] = shared; + const folderLock = join(shared, FOLDER_LOCK); + const entered = Promise.withResolvers(); + const bunPath = Promise.withResolvers(); + const base = recordingServices([]); + const services: EngineServices = { + ...base, + deps: { + ...base.deps, + // The Bun bootstrap, the first bridged pass of the pipeline, waits here. + path: (id) => { + if (id !== "bun") return base.deps.path(id); + entered.resolve(); + return bunPath.promise; + }, + }, + }; + const fiber = Effect.runFork( + runEngineNative(["sync"]).pipe(Effect.provide(engineLayer(services))), + ); + await entered.promise; + + let interruptReturned = false; + const interrupted = Effect.runPromise(Fiber.interrupt(fiber)).then(() => { + interruptReturned = true; + }); + for (let turn = 0; turn < 5; turn += 1) await nextTurn(); + expect(interruptReturned).toBe(false); + expect(await probe(home)).toBe("held"); + expect(await probeLock(folderLock, false)).toBe("held"); + + bunPath.resolve("/opt/stub/bin/bun"); + await interrupted; + expect(await probe(home)).toBe("acquired"); + expect(await probeLock(folderLock, false)).toBe("acquired"); + }); + }); + }); +}); diff --git a/cli/test/unit/toolchain.test.ts b/cli/test/unit/toolchain.test.ts index 78c3dc5e..5619f2ee 100644 --- a/cli/test/unit/toolchain.test.ts +++ b/cli/test/unit/toolchain.test.ts @@ -1,17 +1,24 @@ import { mkdirSync, readFileSync, rmSync, symlinkSync } from "node:fs"; import { join } from "node:path"; import { stripVTControlCharacters } from "node:util"; +import { Effect } from "effect"; import { afterAll, describe, expect, it } from "vitest"; import type { Ctx } from "../../src/engine-native"; +import { EngineContext } from "../../src/engine-native/engineCtx"; import { modeToolchain } from "../../src/engine-native/modes"; import { makeEngineServices } from "../../src/engine-native/services"; import { report } from "../../src/engine-native/toolchain"; import { BUN_RUNTIME } from "../lib/cliEntry"; +import { runEngine } from "../lib/engineRun"; import { runPublicCli } from "../lib/goldenExecution"; import { cleanupTemporaryDirs, makeStubDir, temporaryDir } from "../lib/goldenResources"; import { SPAWN_TIMEOUT_MS } from "../lib/spawnTimeout"; import { floorVersion, verifiedVersion } from "../lib/toolchainManifest"; +/** Run the toolchain mode `args` in the run context `ctx`. */ +const runMode = (ctx: Ctx, args: ReadonlyArray): Promise => + Effect.runPromise(modeToolchain(args).pipe(Effect.provideService(EngineContext, ctx))); + afterAll(cleanupTemporaryDirs); describe("toolchain report", () => { @@ -199,7 +206,7 @@ describe("public toolchain ensure", () => { }, } as unknown as Ctx; - expect(await modeToolchain(ctx, ["ensure", "bun", "--verbose"])).toBe(0); + expect(await runMode(ctx, ["ensure", "bun", "--verbose"])).toBe(0); expect(stderr.map(stripVTControlCharacters)).toEqual([`[ok] bun present (${description})\n`]); }, ); @@ -223,7 +230,7 @@ describe("public toolchain ensure", () => { }, } as unknown as Ctx; - expect(await modeToolchain(ctx, ["ensure", "bun"])).toBe(0); + expect(await runMode(ctx, ["ensure", "bun"])).toBe(0); expect(stderr.map(stripVTControlCharacters)).toEqual([ `[warn] bun 1.4.0 is below the kit floor ${floorVersion("bun")}; run bun upgrade\n`, ]); @@ -255,17 +262,14 @@ describe("engine toolchain argument errors", () => { ])("exits 2 for $args without printing a report", async ({ args, diagnostic }) => { const stdout: Array = []; const stderr: Array = []; - const ctx = { - home: "/unused-invalid-toolchain-home", - services: makeEngineServices({ - sinks: { - stdout: (chunk) => void stdout.push(chunk), - stderr: (chunk) => void stderr.push(chunk), - }, - }), - } as Ctx; + const services = makeEngineServices({ + sinks: { + stdout: (chunk) => void stdout.push(chunk), + stderr: (chunk) => void stderr.push(chunk), + }, + }); - expect(await modeToolchain(ctx, args)).toBe(2); + expect(await runEngine(["toolchain", ...args], services)).toBe(2); expect(stdout).toEqual([]); expect(stderr).toEqual([expect.stringContaining(diagnostic)]); }); From 0cc06467040d1eaf965156cd9c5993b2cc49c3a7 Mon Sep 17 00:00:00 2001 From: Eduardo Marquez <55303379+DocksDocks@users.noreply.github.com> Date: Tue, 1 Dec 2026 20:13:19 -0300 Subject: [PATCH 03/11] Point the engine and sync guidance to the Effect seam - The ExitError, dispatch, lock-release, and failure-path rules, the run signature, the ompSync anchor, the lock of sync in tidy-context, and the parser and service-wiring entries of DESIGN.md. Verified: bun x --no-install vitest run (unit and toggles rows of plan #294); bun run check:types; bun cli/scripts/verify-ci-tools.ts; bun run golden:dryrun --prove-red; bun run golden:mutation --prove-red; bun run smoke:package; ./docks-kit sync --dry-run; bun run check --- .agents/skills/engine-native-context/SKILL.md | 23 +-- .../sync-orchestration-context/SKILL.md | 149 ++++++++++-------- .../references/dispatch-flow.md | 85 ++++++---- .agents/skills/tidy-context/SKILL.md | 2 +- cli/src/engine-native/DESIGN.md | 43 ++--- 5 files changed, 177 insertions(+), 125 deletions(-) diff --git a/.agents/skills/engine-native-context/SKILL.md b/.agents/skills/engine-native-context/SKILL.md index 908c7044..62d6386a 100644 --- a/.agents/skills/engine-native-context/SKILL.md +++ b/.agents/skills/engine-native-context/SKILL.md @@ -1,26 +1,26 @@ --- name: engine-native-context -description: "Use when modifying cli/src/engine-native, the cli/src/engine.ts engine seam or requireSupportedHost, the cli/src/main.ts native-raw harness path, cli/test/golden-dryrun.ts, cli/test/golden-mutation.ts, cli/test/lib/golden*.ts, or cli/test/goldens; covers the golden-regression contract, the removed-engine failure for DOCKS_KIT_ENGINE value bash, the p() slash-join rule, ExitError aborts, jq.ts JSON helpers, prove-red, GOLDEN_FILTER, and supported-host rejection before engine execution. Not for sync flags or sync dispatch (use sync-orchestration-context) or toolchain pins and installs (use toolchain-context)." +description: "Use when modifying cli/src/engine-native, the cli/src/engine.ts engine seam or requireSupportedHost, the cli/src/main.ts native-raw harness path, cli/test/golden-dryrun.ts, cli/test/golden-mutation.ts, cli/test/lib/golden*.ts, or cli/test/goldens; covers the golden-regression contract, the removed-engine failure for DOCKS_KIT_ENGINE value bash, the p() slash-join rule, the typed engine aborts (HelpShown, UsageRefused, LockWaitInvalid), jq.ts JSON helpers, prove-red, GOLDEN_FILTER, and supported-host rejection before engine execution. Not for sync flags or sync dispatch (use sync-orchestration-context) or toolchain pins and installs (use toolchain-context)." user-invocable: false metadata: pattern: tool-wrapper source_files: - path: cli/src/engine-native/index.ts - lines: "1-66" + lines: "1-82" - path: cli/src/engine.ts - lines: "1-53" + lines: "1-72" - path: cli/src/main.ts - lines: "1-60" + lines: "1-78" - path: cli/src/engine-native/exec.ts lines: "1-346" - path: cli/src/engine-native/jq.ts lines: "1-38" - path: cli/src/engine-native/parseHelp.ts - lines: "1-25" + lines: "1-33" - path: cli/src/engine-native/os/targets.ts lines: "1-64" - path: cli/test/unit/engine.test.ts - lines: "1-112" + lines: "1-133" - path: cli/test/golden-dryrun.ts lines: "1-199" - path: cli/test/golden-mutation.ts @@ -39,7 +39,7 @@ metadata: lines: "1-18" - path: cli/test/lib/goldenProveRed.ts lines: "1-63" - updated: "2026-11-27" + updated: "2026-12-01" --- # EngineNative Golden Contract @@ -72,10 +72,11 @@ Engine output is snapshotted and must use forward slashes across platforms. -Use `ExitError` (`parseHelp.ts`, re-exported by `parseArgs.ts`) for intentional -engine aborts and validation failures; `index.ts runEngineNative` turns it into -the exit code. Swallowing a failed child process turns a real sync failure into a -success log. +End an intentional engine abort or a validation failure with a typed failure +in the error channel: `HelpShown` or `UsageRefused` (`parseHelp.ts`), or +`LockWaitInvalid` (`syncDispatch.ts`). `index.ts runEngineNative` turns each +into its exit code after its text; never throw for an abort. Swallowing a +failed child process turns a real sync failure into a success log. ## Golden Suites diff --git a/.agents/skills/sync-orchestration-context/SKILL.md b/.agents/skills/sync-orchestration-context/SKILL.md index c4de2c05..c8a7a429 100644 --- a/.agents/skills/sync-orchestration-context/SKILL.md +++ b/.agents/skills/sync-orchestration-context/SKILL.md @@ -1,6 +1,6 @@ --- name: sync-orchestration-context -description: "Use when editing docks-kit, cli/src/main.ts, cli/src/argv.ts, cli/src/argvValidate.ts, cli/src/engine.ts, or cli/src/engine-native index.ts, engineCtx.ts, syncDispatch.ts, syncConcurrency.ts, parseArgs.ts, parseHelp.ts, or modes.ts: sync flags, the sync locks (withSyncLock, withFolderLocks, folderLockPaths, homeAndFolderLocks, sync-lock.db, DOCKS_KIT_SYNC_LOCK_WAIT_MS), the failure ledger, or dry-run and idempotency rules. Not for toolchain (use toolchain-context), omp (use omp-sync-context), the lock module itself (use tidy-context), or the golden harness (use engine-native-context)." +description: "Use when editing docks-kit, cli/src/main.ts, cli/src/argv.ts, cli/src/argvValidate.ts, cli/src/engine.ts, or cli/src/engine-native index.ts, engineCtx.ts, syncDispatch.ts, syncConcurrency.ts, parseArgs.ts, parseHelp.ts, bridge.ts, or modes.ts: sync flags, the sync locks (engineSync, folderLockPaths, homeAndFolderLocks, sync-lock.db, DOCKS_KIT_SYNC_LOCK_WAIT_MS), the failure ledger, the typed aborts, or dry-run and idempotency rules. Not for toolchain (use toolchain-context), omp (use omp-sync-context), the lock module itself (use tidy-context), or the golden harness (use engine-native-context)." user-invocable: false metadata: pattern: tool-wrapper @@ -8,7 +8,7 @@ metadata: - path: docks-kit lines: "1-100" - path: cli/src/main.ts - lines: "1-60" + lines: "1-78" - path: cli/src/commands/root.ts lines: "1-133" - path: cli/src/argv.ts @@ -18,7 +18,7 @@ metadata: - path: cli/src/argvSurface.ts lines: "1-351" - path: cli/src/engine.ts - lines: "1-53" + lines: "1-72" - path: cli/src/kitHome.ts lines: "1-99" - path: cli/src/payload.ts @@ -30,11 +30,13 @@ metadata: - path: cli/src/commands/update.ts lines: "1-282" - path: cli/src/engine-native/index.ts - lines: "1-66" + lines: "1-82" - path: cli/src/engine-native/engineCtx.ts - lines: "1-58" + lines: "1-85" - path: cli/src/engine-native/syncDispatch.ts - lines: "1-215" + lines: "1-335" + - path: cli/src/engine-native/bridge.ts + lines: "1-37" - path: cli/src/engine-native/kitLock.ts lines: "1-121" - path: cli/src/engine-native/syncConcurrency.ts @@ -42,20 +44,20 @@ metadata: - path: cli/src/engine-native/failures.ts lines: "1-16" - path: cli/src/engine-native/parseArgs.ts - lines: "1-30" + lines: "1-32" - path: cli/src/engine-native/parseHelp.ts - lines: "1-25" + lines: "1-33" - path: cli/src/engine-native/modes.ts - lines: "1-67" + lines: "1-69" - path: cli/src/engine-native/ompSync.ts - lines: "1-122" + lines: "1-155" - path: cli/src/engine-native/ompPlugins.ts lines: "1-374" - path: cli/src/engine-native/bun.ts lines: "1-120" - path: cli/src/engine-native/toolchain.ts lines: "1-237" - updated: "2026-11-27" + updated: "2026-12-01" --- # Sync Engine Orchestration @@ -85,12 +87,15 @@ kit-home resolution order and the other `kitHome()` callers. -Use `ExitError` (defined in `parseHelp.ts`, imported through `parseArgs.ts`) for -intentional exit-2 validation failures and command-abort parity. Unknown flags -and positional words must abort before any mutation. `sync` declares no -positional argument, so on the public CLI `effect/cli` refuses a word such as -`omp` with `Unexpected positional argument: "omp"` and exit 1; on the raw -channel `parseArgs` prints `Unknown arg: ` and throws `ExitError(2)`. +End an intended engine abort with a typed failure in the error channel: +`HelpShown` and `UsageRefused` (`parseHelp.ts`) and `LockWaitInvalid` +(`syncDispatch.ts`). `index.ts runEngineNative` turns `HelpShown` into exit 0 +and prints the message of `UsageRefused` or `LockWaitInvalid`, then exit 2. +Unknown flags and positional words must abort before any mutation. `sync` +declares no positional argument, so on the public CLI `effect/cli` refuses a +word such as `omp` with `Unexpected positional argument: "omp"` and exit 1; on +the raw channel `parseArgs` fails with `UsageRefused`, and the run prints +`Unknown arg: ` and exits 2. (verify: `bunx vitest run cli/test/unit/removedNames.test.ts -t "refuses each sync target word as an unexpected positional argument"`) @@ -98,7 +103,7 @@ channel `parseArgs` prints `Unknown arg: ` and throws `ExitError(2)`. Report a failed kit-managed harness-CLI operation through `failures.ts recordFailure`, never a bare `warn`. `syncDispatch.ts engineSync, failure ledger` prints every recorded message under `--- Failures ---` after the -summary and returns 1, so exit 2 stays reserved for `ExitError` validation +summary and returns 1, so exit 2 stays reserved for the typed validation aborts and exit 1 means a mutation did not happen. A skip is not a failure: a missing harness CLI, missing git, an unavailable plugin inventory, and a missing Bun pin in `SoT/toolchain.json` keep exit 0. Probe before spawning, so a host @@ -133,10 +138,10 @@ For the doctor report and Bun managed install, use | Invocation | Path | Notes | |-----------|------|-------| | `./docks-kit ` | Host check, then Bun-from-source | The launcher rejects a host outside the support matrix, finds or installs Bun, runs `bun install --frozen-lockfile` when `node_modules/effect` is absent, and then runs `cli/src/main.ts`. It never runs a file in `cli/dist/`, so a leftover binary cannot mask newer source. | -| `cli/src/main.ts` | Raw-channel branch, then `prepareArgv`, then the Effect CLI root command | `DOCKS_KIT_ENGINE=native-raw` skips `prepareArgv` and Effect and calls `runEngineNative` directly with `{ envGlobals: true }`. Otherwise `sync` and `toolchain` run through `engine(args)`. Some other commands call engine-native modules directly, for example: the root tier toggles in `commands/root.ts` call `syncDispatch.ts homeAndFolderLocks` and `ompFastMode.ts toggleDeployedOpenAiTier`, and `tidy` and `scratch` call their own modules. `main.ts` adds `argv.ts COMMANDS`, the one subcommand list that the argv surfaces also use, to `commands/root.ts rootCommand` through `Command.withSubcommands`. A new subcommand needs an entry there and a line in the hand-written root overview `root.ts SUMMARY`. A new engine mode also needs a `case` arm in `index.ts runEngineNative`. | +| `cli/src/main.ts` | Raw-channel branch, then `prepareArgv`, then the Effect CLI root command | `DOCKS_KIT_ENGINE=native-raw` bypasses `prepareArgv` and the Effect CLI: it runs the `runEngineNative` Effect with `{ envGlobals: true }`, the live engine layers, and `BunServices.layer`, and exits with its code. Otherwise `sync` and `toolchain` run through `engine(args)`. Some other commands call engine-native modules directly, for example: the root tier toggles in `commands/root.ts` call `syncDispatch.ts homeAndFolderLocks` and `ompFastMode.ts toggleDeployedOpenAiTier`, and `tidy` and `scratch` call their own modules. `main.ts` adds `argv.ts COMMANDS`, the one subcommand list that the argv surfaces also use, to `commands/root.ts rootCommand` through `Command.withSubcommands`. A new subcommand needs an entry there and a line in the hand-written root overview `root.ts SUMMARY`. A new engine mode also needs a `case` arm in `index.ts runEngineNative`. | | `cli/src/argv.ts` | `prepareArgv` | Validates and normalizes argv before Effect parses it. See § Public Argv Layer. | -| `cli/src/engine.ts` | `engine` | Exits 2 on an unsupported host or `DOCKS_KIT_ENGINE=bash`, then runs EngineNative in-process with `{ envGlobals: false }`. `native-raw` is the harness-private golden channel. | -| `cli/src/engine-native/index.ts` | `runEngineNative(argv, services?, options?)` | Builds `ctx` through `engineCtx.ts makeCtx`, then dispatches `toolchain` and `sync`. Any other first word also runs sync. `options.envGlobals` defaults to false; only the `main.ts` `native-raw` branch passes `{ envGlobals: true }`. | +| `cli/src/engine.ts` | `engine` | Exits 2 on an unsupported host or `DOCKS_KIT_ENGINE=bash`, then yields EngineNative in-process with `{ envGlobals: false }`, and maps a failed run or a defect to `engine operation '' failed: ` (`engineFailureDetail`). `native-raw` is the harness-private golden channel. | +| `cli/src/engine-native/index.ts` | `runEngineNative(argv, options?)` | An Effect that reads `LoggerService`, `DependencyManagerService`, `PlatformService`, and `FileSystem` from its layers, builds `ctx` through `engineCtx.ts makeCtx`, provides it as `EngineContext`, then dispatches `toolchain` and `sync`. Any other first word also runs sync. It succeeds with the exit code and fails with `EngineFailure`. `options.envGlobals` defaults to false; only the `main.ts` `native-raw` branch passes `{ envGlobals: true }`. | (verify: `bunx vitest run cli/test/unit/engine.test.ts -t "runs the public engine with env globals disabled"` and `bunx vitest run cli/test/unit/argv.test.ts -t "resolves every registered subcommand"`) @@ -172,48 +177,55 @@ checks in this order: ### Flag Parsing -`parseArgs(ctx, args)` owns the engine flag vocabulary. +`parseArgs(args)`, which reads `EngineContext`, owns the engine flag vocabulary. `.agents/skills/sync-orchestration-context/references/flag-matrix.md` is the only flag table: each flag's `Ctx` field, consumer, and layer scope. Do not copy it here. -`parseArgs` accepts only flags. Any other word prints `Unknown arg: ` -and throws `ExitError(2)`. Do not add compatibility behavior for a removed -word or flag. +`parseArgs` accepts only flags. Any other word fails with +`UsageRefused({ message: "Unknown arg: " })`, which exits 2. Do not add +compatibility behavior for a removed word or flag. ### Dispatch Order -`index.ts runEngineNative` builds `ctx` through `engineCtx.ts makeCtx`. -`makeCtx` reads the unprefixed env globals (`DRY_RUN` and -`DOCKS_KIT_VERBOSE`; see `CtxOptions`) only when +`index.ts runEngineNative` builds `ctx` through `engineCtx.ts makeCtx` and +provides it as the `EngineContext` service. `makeCtx` reads the unprefixed +env globals (`DRY_RUN` and `DOCKS_KIT_VERBOSE`; see `CtxOptions`) only when `options.envGlobals` is true. `runEngineNative` then switches on the first word. `toolchain` runs `modeToolchain`, and `sync` or any other word runs `syncDispatch.ts engineSync`. `engineSync` runs `parseArgs` first and the -remaining steps inside `withSyncLock` (see § Sync Lock): +remaining steps in one lock scope (see § Sync Lock): 1. `parseArgs` reads the flags, before any lock: an unknown argument exits 2 and `-h` or `--help` exits 0. Dependency checks occur only at the operation that consumes the tool; there is no global dependency preflight. -2. `runSync` resolves the omp folders once (`ompSync.ts ompWriteFolders`). A - writing sync takes their folder locks (see § Sync Lock), and - `runPipeline` runs the remaining steps. -3. `runPipeline` takes the terminal lease and runs `ompSync`. On a rejection, - `runPipeline` prints no summary. It prints the `--- Failures ---` ledger - for the failures recorded before the rejection, then rethrows it. - Unprobed: no unit test rejects the pipeline inside `engineSync`. Read the - `catch` arm (verify: - `grep -n "A rejected pipeline skips the summary" cli/src/engine-native/syncDispatch.ts`) +2. A writing sync takes the sync lock, then resolves the omp folders once, + under it (`ompSync.ts ompWriteFolders`), then takes their folder locks (see + § Sync Lock), and `runPipeline` runs the remaining steps. +3. `runPipeline` takes the terminal lease, a scoped resource of + `logger.ts acquireTerminal`, and runs `ompSync`. When the pipeline fails, + `runPipeline` prints no summary: its `Effect.onError` handler prints the + `--- Failures ---` ledger for the failures recorded before the failure, and + the failure ends the run. + Unprobed: no unit test fails the pipeline inside `engineSync`. Read the + handler (verify: + `grep -n "A failed pipeline skips the summary" cli/src/engine-native/syncDispatch.ts`) 4. The `--- Sync complete ---` summary prints, then the omp next-step notes. 5. When any step called `recordFailure`, the `--- Failures ---` ledger lists each message, and `engineSync` returns 1. +Each call into a module that a later child of plan #290 moves runs through +`bridge.ts bridgeSync` or `bridgePromise`, so an interrupt waits until that +step settles (`references/dispatch-flow.md`). + The omp pipeline reads SoT from the embedded payload. ### Sync Lock -`syncDispatch.ts withSyncLock(ctx, body)` runs `body` under -`~/.cache/docks-kit/sync-lock.db` (`scratch.ts syncLockPath`, a -`kitLock.ts acquireKitLock` lock; `tidy-context` owns the lock module). +`syncDispatch.ts engineSync` takes `~/.cache/docks-kit/sync-lock.db` +(`scratch.ts syncLockPath`) as a scoped lock over the `kitLock.ts` +primitives `tryAcquireKitLock` and `releaseKitLock` (`tidy-context` owns the +lock module). - `engineSync` runs `parseArgs` before the lock. An unknown argument exits 2 and `-h` or `--help` exits 0 before any lock or write, also while another @@ -225,15 +237,25 @@ The omp pipeline reads SoT from the embedded payload. writes and takes the lock. - The wait bound is `SYNC_LOCK_WAIT_MS` (120 000 ms). `DOCKS_KIT_SYNC_LOCK_WAIT_MS` (a non-negative safe integer, in ms) overrides - it; unset or empty means the default. Any other value prints + it; unset or empty means the default. Any other value fails with + `LockWaitInvalid`, so the run prints `DOCKS_KIT_SYNC_LOCK_WAIT_MS must be a non-negative safe integer` and exits 2. A digit string above `Number.MAX_SAFE_INTEGER` also exits 2, because `Number` would round it or make it Infinity. -- Held past the bound: print +- The poll of a sync keeps the contention outcome of the former Promise poll: + the deadline is on the wall clock (`Clock.currentTimeMillis`), the sync lock + deadline starts before its lock folder is prepared, and one more try runs + after the sleep that reaches the deadline. The root tier toggles poll on the + monotonic clock and start no try after the deadline. +- Held past the bound: `KitLockHeld`, so the run prints `another docks-kit sync holds ; run sync again after it ends` and - return 1, with no call to `body`. -- The lock goes in `finally`, also when `body` throws. A signal needs no - handler: the OS releases the lock when the process ends. + returns 1 before the pipeline. +- Every lock of a sync is an `Effect.acquireRelease` in one scope, so it goes + when the scope closes: after the run, a failure, or an interrupt. An + interrupt during a bridged pass waits until the pass settles, and the locks + stay held until then. A signal needs no handler: the OS releases the lock + when the process ends. + (verify: `bunx vitest run cli/test/unit/syncLock.test.ts -t "keeps the sync lock and the omp folder locks until an interrupted bridged pass settles"`) (verify: `bunx vitest run cli/test/unit/syncLock.test.ts -t "exits 1 with the held line and leaves HOME unchanged"`, `bunx vitest run cli/test/unit/syncLock.test.ts -t "takes no lock in a dry run"`, `bunx vitest run cli/test/unit/syncLock.test.ts -t "rejects an unknown argument with exit 2 before it takes the lock"`, `bunx vitest run cli/test/unit/engine-di.test.ts -t "with exit 2 before it takes a lock or writes an omp file"`, `bunx vitest run cli/test/unit/syncLock.test.ts -t "exits 2 when the lock wait is not a non-negative safe integer"`, `bunx vitest run cli/test/unit/syncLock.test.ts -t "DRY_RUN env global"`, and `bunx vitest run cli/test/unit/syncLock.test.ts -t "prints the help with -h and --help while another sync holds the lock"`) @@ -242,26 +264,27 @@ Folder locks: two homes can share an omp folder (`PI_CODING_AGENT_DIR`, each writer of such a folder also takes `/.docks-kit-sync-lock.db` (`scratch.ts folderSyncLockPath`). -- `runSync` takes them after `parseArgs`, through - `withFolderLocks(ctx, folders, body)`, for the two folders of - `ompSync.ts ompWriteFolders`: the omp agent folder and the omp data root. - `runSync` resolves them once, before the locks, and passes - them into `ompSync` (see `omp-sync-context`). +- `engineSync` takes them after `parseArgs` and the sync lock, for the two + folders of `ompSync.ts ompWriteFolders`: the omp agent folder and the omp + data root. It resolves them once, under the sync lock, and passes them into + `ompSync` (see `omp-sync-context`). - `folderLockPaths` canonicalizes each folder without the need for it to - exist: the real path of its nearest existing ancestor, joined with the rest. + exist: the real path (`realpathSync.native`) of its nearest existing + ancestor (probed with `existsSync`), joined with the rest. It removes duplicates, keeps nested folders, and sorts by folder, so an ancestor comes before its descendants. Every run takes the locks in that order, after the home lock, so no two runs wait on each other in a cycle. -- `withKitLocks` creates a missing folder (`mkdirSync`, recursive, mode 0700) - just before its lock, so the locks of its ancestors in the set are already - held. The mode applies only to the folders that the call creates: it runs no - chmod, and the lock keeps the folder mode (`privateDirectory: false`). The - omp pipeline then runs `ensureDirectory` (mode 0700) under the locks. -- `homeAndFolderLocks(home, folders)` is a scoped Effect that takes the home - lock and the folder locks outside a sync run, one `Effect.acquireRelease` - per lock. Each try (`kitLock.ts tryAcquireKitLock`) and its release run - without interruption; only the sleep between two tries can be interrupted. - It fails with `LockWaitInvalid`, `KitLockHeld`, or `LockAcquireError`. +- A folder lock creates its missing folder (`FileSystem.makeDirectory`, + recursive, mode 0700) just before the lock, so the locks of its ancestors in + the set are already held. The mode applies only to the folders that the call + creates: it runs no chmod, and the lock keeps the folder mode. The omp + pipeline then runs `ensureDirectory` (mode 0700) under the locks. +- `homeAndFolderLocks(home, folders)` is a scoped Effect that composes the + same sync lock and folder locks outside a sync run, one + `Effect.acquireRelease` per lock. Each try (`kitLock.ts tryAcquireKitLock`) + and its release run without interruption; only the sleep between two tries + can be interrupted. It fails with `LockWaitInvalid`, `KitLockHeld`, or + `LockAcquireError`, and needs `FileSystem`. `docks-kit --fast` and `docks-kit --ultrafast` use it for the omp agent folder (see `omp-sync-context`). - A dry run (`ctx.dryRun`) takes no folder lock and creates no folder. The @@ -298,7 +321,7 @@ each writer of such a folder also takes `/.docks-kit-sync-lock.db` not a `sync` flag prints `Unknown arg: ` and exits 2, at once and without a `~/.cache/docks-kit/sync-lock.db`. (verify: `bunx vitest run cli/test/unit/removedNames.test.ts -t "refuses each sync target word as an unexpected positional argument"` and `bunx vitest run cli/test/unit/syncLock.test.ts -t "rejects an unknown argument with exit 2 before it takes the lock"`) -- Never call `withSyncLock` inside a run that already holds the sync lock. A +- Never take the sync lock again inside a run that already holds it. A second acquire in one process finds the lock held, waits the full bound, and exits 1. diff --git a/.agents/skills/sync-orchestration-context/references/dispatch-flow.md b/.agents/skills/sync-orchestration-context/references/dispatch-flow.md index f8e19ff2..a25ed6ba 100644 --- a/.agents/skills/sync-orchestration-context/references/dispatch-flow.md +++ b/.agents/skills/sync-orchestration-context/references/dispatch-flow.md @@ -26,14 +26,25 @@ |-- bun install --frozen-lockfile when node_modules/effect is absent `-- bun cli/src/main.ts "$@" |-- DOCKS_KIT_ENGINE=native-raw - | `-- runEngineNative(rawArgs, undefined, { envGlobals: true }) + | `-- runEngineNative(rawArgs, { envGlobals: true }) run with the live layers and + | BunServices.layer `-- prepareArgv(argv) argv.ts; argvValidate.ts rejects with exit 2 `-- Effect CLI root command subcommands: argv.ts COMMANDS `-- mutating commands call engine(args) `-- cli/src/engine.ts - `-- runEngineNative(args, services, { envGlobals: false }) + `-- yield* runEngineNative(args, { envGlobals: false }) ``` +`runEngineNative` is an Effect that succeeds with the exit code. Its services +come from the layers that `main.ts` provides (`cli/src/services.ts +engineServicesLayer` and `BunServices.layer`); it takes no services +parameter. A failed run (`index.ts EngineFailure`) or a defect, such as a +stream write error, prints the message of the original failure: +`engine.ts engineFailureDetail` gives it to the `CliError.UserError` of the +public seam and to the `docks-kit raw operation '' failed:` line of +the raw channel. +(verify: `bunx vitest run cli/test/unit/engine.test.ts -t "maps a defect of the run"`) + `kitHome()` (`kitHome.ts resolveKitHome`) identifies a kit root by a `package.json` whose `name` is `docks-kit`. It checks `DOCKS_KIT_HOME` first. Next, it takes the nearest such ancestor of the module directory or the cwd, @@ -48,36 +59,52 @@ from the current directory. ## Sync Execution Order ```text -runEngineNative(argv, services?, options?) index.ts -|-- makeCtx(services, { envGlobals }) engineCtx.ts; env globals only when true -`-- switch (argv[0]) - |-- toolchain -> modeToolchain(ctx, args) modes.ts; no lock - `-- sync/default -> engineSync(ctx, args) syncDispatch.ts - |-- parseArgs(ctx, args) flags only, before any lock; any other - | word: Unknown arg, exit 2; -h, --help: exit 0 - |-- withSyncLock(ctx, ...) ~/.cache/docks-kit/sync-lock.db; none when - | ctx.dryRun (--dry-run or DRY_RUN); held - | past the wait bound: held line, returns 1 - |-- ompWriteFolders(ctx) resolved once, before the locks; ompSync - | and its omp children use the result - |-- withFolderLocks(ctx, folders, ...) /.docks-kit-sync-lock.db of the - | ompWriteFolders agent and data root - | folders; canonical, sorted - | ancestor-first; a missing folder is made - | under the locks of its ancestors in the - | set; none in a dry run - `-- runPipeline(ctx, omp) - |-- ompSync(ctx, omp) ompSync.ts; on a rejection, runPipeline - | prints the "--- Failures ---" ledger and - | rethrows - |-- "--- Sync complete ---" summary - |-- omp next steps - `-- "--- Failures ---" ledger when recordFailure ran; returns 1 - releaseKitLock of each lock in finally +runEngineNative(argv, options?) index.ts; an Effect +|-- makeCtx({ logger, deps, platform }, ...) engineCtx.ts; env globals only when true; +| kitHome() failure: KitHomeInvalid +|-- switch (argv[0]), with EngineContext = ctx +| |-- toolchain -> modeToolchain(args) modes.ts; no lock +| `-- sync/default -> engineSync(args) syncDispatch.ts +| |-- parseArgs(args) flags only, before any lock; any other +| | word: UsageRefused; -h, --help: HelpShown +| |-- dry run (--dry-run or DRY_RUN): ompWriteFolders, then runPipeline; no lock +| `-- Effect.scoped, one scope for every lock +| |-- sync lock ~/.cache/docks-kit/sync-lock.db; invalid +| | wait: LockWaitInvalid +| |-- ompWriteFolders() resolved once, under the sync lock; ompSync +| | and its omp children use the result +| |-- folder locks /.docks-kit-sync-lock.db of the +| | ompWriteFolders agent and data root +| | folders; canonical, sorted +| | ancestor-first; a missing folder is made +| | under the locks of its ancestors in the +| | set +| `-- runPipeline(omp) +| |-- ompSync(omp) ompSync.ts; on a failure, the Effect.onError +| | handler of runPipeline prints the +| | "--- Failures ---" ledger, and the failure +| | ends the run +| |-- "--- Sync complete ---" summary +| |-- omp next steps +| `-- "--- Failures ---" ledger when recordFailure ran; returns 1 +| the scope releases each lock: after the run, a failure, or an interrupt; +| KitLockHeld: held line, returns 1 +`-- HelpShown: 0; UsageRefused and LockWaitInvalid: the message, then 2 ``` +Each call from this Effect code into a module that a later child of plan +#290 moves (`bun.ts`, `ompFileDeploy.ts`, `ompKitPlugin.ts`, `ompPlugins.ts`, +`ompRemovals.ts`, `ompPaths.ts`, `toolchain.ts`, `home.ts`) goes through +`bridge.ts bridgeSync` or `bridgePromise`. A bridged step runs without +interruption, so an interrupt of a sync waits until the pass settles, and +the scope keeps the sync lock and the folder locks until then; a throw or a +rejection is `LegacyStepFailed`. The ledger stays a plain append +(`failures.ts recordFailure`), which the Effect code calls through +`Effect.sync`. +(verify: `bunx vitest run cli/test/unit/syncLock.test.ts -t "keeps the sync lock and the omp folder locks until an interrupted bridged pass settles"`) + `ompSync` owns its step order. Read the function body, not a copy here -(verify: `sed -n '/^export async function ompSync/,/^}/p' cli/src/engine-native/ompSync.ts`). +(verify: `sed -n '/^export const ompSync/,/^});/p' cli/src/engine-native/ompSync.ts`). The order rules that matter: - `ompSync` starts with `bun.ts bunBootstrap`, which is memoized on diff --git a/.agents/skills/tidy-context/SKILL.md b/.agents/skills/tidy-context/SKILL.md index 76110e61..399fd397 100644 --- a/.agents/skills/tidy-context/SKILL.md +++ b/.agents/skills/tidy-context/SKILL.md @@ -70,7 +70,7 @@ Pointers here name concepts, not coordinates — if a path or symbol moved, trus - `cli/src/engine-native/tidy.ts` — `applyTidy` — performs a `TidyPlan` and appends to `tidy.log`; its caller holds `tidy-lock.db` (verify: `bunx vitest run cli/test/unit/tidy.test.ts -t "containers first, then the worktree"`) - `cli/src/engine-native/tidy.ts` — `TidyHost`, `defaultTidyHost` — the injection seam for `git`, `docker`, `dockerEndpoint`, `run`, `processes`, `now` (verify: `grep -n "export interface TidyHost" cli/src/engine-native/tidy.ts`) - `cli/src/commands/tidy.ts` — `runTidy` — `tidyCommand` resolves the inputs and calls it. With `--apply`, it takes `tidy-lock.db` before `planTidy` and releases it before `--report` runs (verify: `bunx vitest run cli/test/unit/tidy.test.ts -t "plans only under the lock"` and `bunx vitest run cli/test/unit/tidy.test.ts -t "releases the lock before the report runs"`) -- `cli/src/engine-native/kitLock.ts` — `acquireKitLock`, `releaseKitLock` — the SQLite lock of `tidy --apply` and of sync. It imports only `node:` modules, so a test child can load it alone (verify: `grep -n 'from "' cli/src/engine-native/kitLock.ts`) +- `cli/src/engine-native/kitLock.ts` — `acquireKitLock`, `releaseKitLock` — the SQLite lock of `tidy --apply`; sync and the root tier toggles take their locks as scoped Effects over `tryAcquireKitLock` and `releaseKitLock` (`syncDispatch.ts engineSync`, `homeAndFolderLocks`). It imports only `node:` modules, so a test child can load it alone (verify: `grep -n 'from "' cli/src/engine-native/kitLock.ts`) - `cli/src/engine-native/processes.ts` — `processExited` — true only when `process.kill(pid, 0)` throws ESRCH. `tidy.ts darwinProcesses` (the macOS cwd probe) uses it to tell an exited PID from an unreadable cwd. Unprobed: no unit test runs the macOS probe (verify: `grep -n "processExited(pid)" cli/src/engine-native/tidy.ts`) - `cli/src/engine-native/tidyReport.ts` — `buildTidyReport` — read-only sections; reuses `tidy.ts` helpers (verify: `grep -n 'from "./tidy"' cli/src/engine-native/tidyReport.ts`) - `cli/src/engine-native/scratch.ts` — `kitCacheDir`, `scratchRoot`, `tidyApplyLockPath`, `syncLockPath` — owner of `~/.cache/docks-kit`, its `scratch/` child, and the lock files `tidy-lock.db` and `sync-lock.db` (verify: `grep -n -e "export function kitCacheDir" -e "LockPath(home" cli/src/engine-native/scratch.ts`) diff --git a/cli/src/engine-native/DESIGN.md b/cli/src/engine-native/DESIGN.md index 7cebb693..ec48fb29 100644 --- a/cli/src/engine-native/DESIGN.md +++ b/cli/src/engine-native/DESIGN.md @@ -162,32 +162,33 @@ unprefixed `Ctx` env globals (`engineCtx.ts makeCtx` reads `DRY_RUN` and `DOCKS_KIT_VERBOSE`). `main.ts` passes `{ envGlobals: true }` to `runEngineNative` only on that channel. The public `engine()` seam ignores these variables. -The default service factory returns a raw Logger. `runEngineNative` wraps the -default or injected Logger with explicit delegates and owns the sole -`ctx.verbose` gate. +The service factory builds a Logger without a verbosity gate, and main.ts +provides it as `LoggerService` (`cli/src/services.ts engineServicesLayer`). +`runEngineNative` wraps the provided Logger with explicit delegates and owns +the sole `ctx.verbose` gate. There is no factory-level verbosity callback, module-global verbosity flag, or active logger binding. ## Module Map -| Module | Owns | -| -------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `parseArgs.ts` | engine usage and the argv dispatch loop; re-exports the `parseHelp.ts` help text and early-exit error | -| `index.ts` | entry routing (`toolchain`/`sync`) and the run-scoped verbosity gate | -| `engineCtx.ts` | `Ctx` shape and `makeCtx`; the unprefixed env globals apply only on the native-raw channel | -| `syncDispatch.ts` | sync and folder locks, the omp pipeline call, run summary, next-step blocks, and the `--- Failures ---` ledger | -| `syncConcurrency.ts` | input-ordered bounded pool (`runBounded`) for the tidy probes | -| `../payload.ts` | generated text payload reads and presentation-only source labels | -| `bun.ts` | per-run memoized Bun resolution/bootstrap shared by the omp pipeline and direct toolchain ensure | -| `ompSync.ts` | omp pipeline orchestration and summary; `ompFileDeploy.ts`, `ompPlugins.ts`, and `ompRemovals.ts` own the file, plugin (with the marketplace-plugin retirement), and retired-key passes; `ompPaths.ts` resolves roots; `ompYaml.ts` merges YAML | -| `toolchain.ts` | tool presence/version probes, verified-version floor reporting, report table | -| `modes.ts` | direct `toolchain` mode | -| `jq.ts` | the `Json` value type, object narrowing, jq-compatible codepoint ordering, and a parse that yields `undefined` instead of throwing | -| `exec.ts` | slash-stable path helpers, host-aware PATH probes and invocation, capture/spawn wrappers, and change-detecting write/copy helpers | -| `logger.ts` | Logger shape + stable raw stdout/stderr sink factory; the run-scoped verbosity gate lives in `index.ts` | -| `deps.ts` | external-tool registry: identity, presence probe, supported-host install hints; the Bun hint renders the pinned download-then-run installer of the host (`HostOs.bunInstaller`) | -| `os/` | host reader, injected platform normalization, and per-OS `HostOs` fact modules | -| `services.ts` | shared raw-Logger + DependencyManager + Platform factory; `makeDependencyManager` owns the per-manager missing-tool dedup, and callers supply the current run Logger to `warnMissing`; wrapped in Effect Layers at `cli/src/services.ts`, with the run-scoped Logger gate applied only by `runEngineNative` | +| Module | Owns | +| -------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `parseArgs.ts` | the argv dispatch loop as an Effect; help and an unknown argument fail with the `parseHelp.ts` aborts `HelpShown` and `UsageRefused`, which hold the help text and the refusal | +| `index.ts` | entry routing (`toolchain`/`sync`) as the Effect `runEngineNative`, which turns the intended aborts into exit codes, and the run-scoped verbosity gate | +| `engineCtx.ts` | `Ctx` shape, the `EngineContext` service that carries it, and `makeCtx`; the unprefixed env globals apply only on the native-raw channel | +| `syncDispatch.ts` | sync and folder locks, the omp pipeline call, run summary, next-step blocks, and the `--- Failures ---` ledger | +| `syncConcurrency.ts` | input-ordered bounded pool (`runBounded`) for the tidy probes | +| `../payload.ts` | generated text payload reads and presentation-only source labels | +| `bun.ts` | per-run memoized Bun resolution/bootstrap shared by the omp pipeline and direct toolchain ensure | +| `ompSync.ts` | omp pipeline orchestration and summary; `ompFileDeploy.ts`, `ompPlugins.ts`, and `ompRemovals.ts` own the file, plugin (with the marketplace-plugin retirement), and retired-key passes; `ompPaths.ts` resolves roots; `ompYaml.ts` merges YAML | +| `toolchain.ts` | tool presence/version probes, verified-version floor reporting, report table | +| `modes.ts` | direct `toolchain` mode | +| `jq.ts` | the `Json` value type, object narrowing, jq-compatible codepoint ordering, and a parse that yields `undefined` instead of throwing | +| `exec.ts` | slash-stable path helpers, host-aware PATH probes and invocation, capture/spawn wrappers, and change-detecting write/copy helpers | +| `logger.ts` | Logger shape + stable raw stdout/stderr sink factory; the run-scoped verbosity gate lives in `index.ts` | +| `deps.ts` | external-tool registry: identity, presence probe, supported-host install hints; the Bun hint renders the pinned download-then-run installer of the host (`HostOs.bunInstaller`) | +| `os/` | host reader, injected platform normalization, and per-OS `HostOs` fact modules | +| `services.ts` | shared Logger + DependencyManager + Platform factory; `makeDependencyManager` owns the per-manager missing-tool dedup, and callers supply the current run Logger to `warnMissing`; provided as Effect Layers by `cli/src/services.ts engineServicesLayer`, with the run-scoped Logger gate applied only by `runEngineNative` | ## Platform Support From 65c65dc32cee752a8dd999c3cae47fa9fc3be6e1 Mon Sep 17 00:00:00 2001 From: Eduardo Marquez <55303379+DocksDocks@users.noreply.github.com> Date: Tue, 1 Dec 2026 20:38:37 -0300 Subject: [PATCH 04/11] Repair code-review round 1 of the Effect seam - Signals: while an engine run is active, SIGINT or SIGTERM exits at once (public 130; raw 130 and 143 as before); in-process interrupts still wait for bridged work. Spawned tests on POSIX. - The seams report the later cleanup error when a finalizer throws after a failure, as finally did. - Logger: atomic lease claim published after the first draw; per-section exclusive markers across loggers; a nullish buffered-write throw stays a failure. - Bridge: failure text without coercion (unknown error); kitHome() through bridgeSync as KitHomeInvalid. - Tests: both folder locks and no AGENTS.md write in the interrupt case, gated fibers settled in finally, TestClock deadline cases, the ledger before a failed pass, a public env-globals dry run, tryAcquireKitLock in the lock fixtures. - Guidance: dispatch pointers, interrupt-only ledger skip, HelpShown, withExclusive usage. Verified: bun x --no-install vitest run (unit, toggles, signals rows and syncPipelineFailure.test.ts); bun run check:types; bun run golden:dryrun; bun run golden:mutation; bun run check --- .agents/skills/engine-native-context/SKILL.md | 6 +- .agents/skills/host-platform-context/SKILL.md | 6 +- .agents/skills/omp-sync-context/SKILL.md | 11 +- .../sync-orchestration-context/SKILL.md | 55 ++++--- .../references/dispatch-flow.md | 5 +- cli/src/engine-native/DESIGN.md | 7 +- cli/src/engine-native/bridge.ts | 17 +- cli/src/engine-native/engineCtx.ts | 11 +- cli/src/engine-native/logger.ts | 56 ++++--- cli/src/engine-native/parseHelp.ts | 6 +- cli/src/engine.ts | 43 ++++-- cli/test/unit/bridge.test.ts | 40 +++-- cli/test/unit/engine.test.ts | 57 ++++++- cli/test/unit/folderLockCreate.test.ts | 26 ++-- cli/test/unit/logger.test.ts | 122 ++++++++++++++- cli/test/unit/syncLock.test.ts | 135 ++++++++++++---- cli/test/unit/syncPipelineFailure.test.ts | 144 +++++++++++++++++ cli/test/unit/syncSignals.test.ts | 146 ++++++++++++++++++ 18 files changed, 750 insertions(+), 143 deletions(-) create mode 100644 cli/test/unit/syncPipelineFailure.test.ts create mode 100644 cli/test/unit/syncSignals.test.ts diff --git a/.agents/skills/engine-native-context/SKILL.md b/.agents/skills/engine-native-context/SKILL.md index 62d6386a..59cb50d2 100644 --- a/.agents/skills/engine-native-context/SKILL.md +++ b/.agents/skills/engine-native-context/SKILL.md @@ -8,7 +8,7 @@ metadata: - path: cli/src/engine-native/index.ts lines: "1-82" - path: cli/src/engine.ts - lines: "1-72" + lines: "1-97" - path: cli/src/main.ts lines: "1-78" - path: cli/src/engine-native/exec.ts @@ -16,11 +16,11 @@ metadata: - path: cli/src/engine-native/jq.ts lines: "1-38" - path: cli/src/engine-native/parseHelp.ts - lines: "1-33" + lines: "1-31" - path: cli/src/engine-native/os/targets.ts lines: "1-64" - path: cli/test/unit/engine.test.ts - lines: "1-133" + lines: "1-176" - path: cli/test/golden-dryrun.ts lines: "1-199" - path: cli/test/golden-mutation.ts diff --git a/.agents/skills/host-platform-context/SKILL.md b/.agents/skills/host-platform-context/SKILL.md index 1022c3d5..1d43e966 100644 --- a/.agents/skills/host-platform-context/SKILL.md +++ b/.agents/skills/host-platform-context/SKILL.md @@ -28,12 +28,12 @@ metadata: - path: cli/src/engine-native/processes.ts lines: "1-16" - path: cli/src/engine-native/logger.ts - lines: "1-192" + lines: "1-266" - path: cli/src/engine-native/services.ts lines: "1-88" - path: cli/src/services.ts lines: "1-42" - updated: "2026-11-23" + updated: "2026-12-01" --- # Host Platform Layer @@ -49,7 +49,7 @@ Rewrite a user file through `atomicWrite.ts replaceFile`. It keeps a symlinked t -Run an inherited-stdio child (installer, sudo prompt) inside `ctx.terminalLease?.withExclusive`. Do not nest `withExclusive`. +Run an inherited-stdio child (installer, sudo prompt) as an Effect passed to `ctx.terminalLease.withExclusive`, and yield the Effect that it returns; with no lease, run the child Effect directly. Do not nest `withExclusive`: a nested call fails with `LeaseReentered`. ## When to Use diff --git a/.agents/skills/omp-sync-context/SKILL.md b/.agents/skills/omp-sync-context/SKILL.md index 621034b9..7e41b515 100644 --- a/.agents/skills/omp-sync-context/SKILL.md +++ b/.agents/skills/omp-sync-context/SKILL.md @@ -35,7 +35,7 @@ metadata: lines: "1-63" - path: cli/src/engine-native/ompChild.ts lines: "1-26" - updated: "2026-11-27" + updated: "2026-12-01" --- # omp Sync Context @@ -210,10 +210,11 @@ So a writing sync also takes `/.docks-kit-sync-lock.db` in each folder of `ompSync.ts ompWriteFolders`: the `ompPaths` `agentDir` and the `ompPaths` `dataRoot`. -- `syncDispatch.ts runSync` calls `ompWriteFolders` once, before the locks, - and passes the result into `ompSync`. `ompSync` writes only into these - locked folders. A second resolution could pick a `$XDG_DATA_HOME/omp` - folder that another sync created after the locks. +- `syncDispatch.ts lockedSync` calls `ompWriteFolders` once, after the sync + lock and before the folder locks, and passes the result into `ompSync`; a + dry run (`engineSync`) resolves them the same way and takes no lock. + `ompSync` writes only into these locked folders. A second resolution could + pick a `$XDG_DATA_HOME/omp` folder that another sync created after the locks. - Every `omp` command of the plugin pass starts through `ompChild.ts spawnOmp`. When the locked data root is the config root, the child gets no `XDG_DATA_HOME`, so the omp resolver keeps the locked root. diff --git a/.agents/skills/sync-orchestration-context/SKILL.md b/.agents/skills/sync-orchestration-context/SKILL.md index c8a7a429..3bef9220 100644 --- a/.agents/skills/sync-orchestration-context/SKILL.md +++ b/.agents/skills/sync-orchestration-context/SKILL.md @@ -18,7 +18,7 @@ metadata: - path: cli/src/argvSurface.ts lines: "1-351" - path: cli/src/engine.ts - lines: "1-72" + lines: "1-97" - path: cli/src/kitHome.ts lines: "1-99" - path: cli/src/payload.ts @@ -32,11 +32,11 @@ metadata: - path: cli/src/engine-native/index.ts lines: "1-82" - path: cli/src/engine-native/engineCtx.ts - lines: "1-85" + lines: "1-86" - path: cli/src/engine-native/syncDispatch.ts lines: "1-335" - path: cli/src/engine-native/bridge.ts - lines: "1-37" + lines: "1-46" - path: cli/src/engine-native/kitLock.ts lines: "1-121" - path: cli/src/engine-native/syncConcurrency.ts @@ -46,7 +46,7 @@ metadata: - path: cli/src/engine-native/parseArgs.ts lines: "1-32" - path: cli/src/engine-native/parseHelp.ts - lines: "1-33" + lines: "1-31" - path: cli/src/engine-native/modes.ts lines: "1-69" - path: cli/src/engine-native/ompSync.ts @@ -138,7 +138,7 @@ For the doctor report and Bun managed install, use | Invocation | Path | Notes | |-----------|------|-------| | `./docks-kit ` | Host check, then Bun-from-source | The launcher rejects a host outside the support matrix, finds or installs Bun, runs `bun install --frozen-lockfile` when `node_modules/effect` is absent, and then runs `cli/src/main.ts`. It never runs a file in `cli/dist/`, so a leftover binary cannot mask newer source. | -| `cli/src/main.ts` | Raw-channel branch, then `prepareArgv`, then the Effect CLI root command | `DOCKS_KIT_ENGINE=native-raw` bypasses `prepareArgv` and the Effect CLI: it runs the `runEngineNative` Effect with `{ envGlobals: true }`, the live engine layers, and `BunServices.layer`, and exits with its code. Otherwise `sync` and `toolchain` run through `engine(args)`. Some other commands call engine-native modules directly, for example: the root tier toggles in `commands/root.ts` call `syncDispatch.ts homeAndFolderLocks` and `ompFastMode.ts toggleDeployedOpenAiTier`, and `tidy` and `scratch` call their own modules. `main.ts` adds `argv.ts COMMANDS`, the one subcommand list that the argv surfaces also use, to `commands/root.ts rootCommand` through `Command.withSubcommands`. A new subcommand needs an entry there and a line in the hand-written root overview `root.ts SUMMARY`. A new engine mode also needs a `case` arm in `index.ts runEngineNative`. | +| `cli/src/main.ts` | Raw-channel branch, then `prepareArgv`, then the Effect CLI root command | `DOCKS_KIT_ENGINE=native-raw` bypasses `prepareArgv` and the Effect CLI: it runs the `runEngineNative` Effect with `{ envGlobals: true }`, the live engine layers, and `BunServices.layer`, and exits with its code; a SIGINT exits 130 and a SIGTERM 143 at once. Otherwise `sync` and `toolchain` run through `engine(args)`. Some other commands call engine-native modules directly, for example: the root tier toggles in `commands/root.ts` call `syncDispatch.ts homeAndFolderLocks` and `ompFastMode.ts toggleDeployedOpenAiTier`, and `tidy` and `scratch` call their own modules. `main.ts` adds `argv.ts COMMANDS`, the one subcommand list that the argv surfaces also use, to `commands/root.ts rootCommand` through `Command.withSubcommands`. A new subcommand needs an entry there and a line in the hand-written root overview `root.ts SUMMARY`. A new engine mode also needs a branch in the mode selection of `index.ts runEngineNative`, which picks `modeToolchain` for `toolchain` and `engineSync` otherwise. | | `cli/src/argv.ts` | `prepareArgv` | Validates and normalizes argv before Effect parses it. See § Public Argv Layer. | | `cli/src/engine.ts` | `engine` | Exits 2 on an unsupported host or `DOCKS_KIT_ENGINE=bash`, then yields EngineNative in-process with `{ envGlobals: false }`, and maps a failed run or a defect to `engine operation '' failed: ` (`engineFailureDetail`). `native-raw` is the harness-private golden channel. | | `cli/src/engine-native/index.ts` | `runEngineNative(argv, options?)` | An Effect that reads `LoggerService`, `DependencyManagerService`, `PlatformService`, and `FileSystem` from its layers, builds `ctx` through `engineCtx.ts makeCtx`, provides it as `EngineContext`, then dispatches `toolchain` and `sync`. Any other first word also runs sync. It succeeds with the exit code and fails with `EngineFailure`. `options.envGlobals` defaults to false; only the `main.ts` `native-raw` branch passes `{ envGlobals: true }`. | @@ -191,32 +191,45 @@ compatibility behavior for a removed word or flag. `index.ts runEngineNative` builds `ctx` through `engineCtx.ts makeCtx` and provides it as the `EngineContext` service. `makeCtx` reads the unprefixed env globals (`DRY_RUN` and `DOCKS_KIT_VERBOSE`; see `CtxOptions`) only when -`options.envGlobals` is true. `runEngineNative` then switches on the first -word. `toolchain` runs `modeToolchain`, and `sync` or any other word runs -`syncDispatch.ts engineSync`. `engineSync` runs `parseArgs` first and the -remaining steps in one lock scope (see § Sync Lock): +`options.envGlobals` is true. `runEngineNative` then selects the mode by the +first word: `toolchain` runs `modeToolchain`, and `sync` or any other word +runs `syncDispatch.ts engineSync`. `engineSync` runs `parseArgs` first; then a +dry run resolves the omp folders and runs `runPipeline` with no lock, and a +writing sync runs `lockedSync` in one lock scope (see § Sync Lock): 1. `parseArgs` reads the flags, before any lock: an unknown argument exits 2 and `-h` or `--help` exits 0. Dependency checks occur only at the operation that consumes the tool; there is no global dependency preflight. -2. A writing sync takes the sync lock, then resolves the omp folders once, - under it (`ompSync.ts ompWriteFolders`), then takes their folder locks (see - § Sync Lock), and `runPipeline` runs the remaining steps. +2. `lockedSync` takes the sync lock, then resolves the omp folders once, + between the sync lock and the folder locks (`ompSync.ts ompWriteFolders`), + then takes their folder locks (see § Sync Lock), and `runPipeline` runs the + remaining steps. 3. `runPipeline` takes the terminal lease, a scoped resource of `logger.ts acquireTerminal`, and runs `ompSync`. When the pipeline fails, `runPipeline` prints no summary: its `Effect.onError` handler prints the `--- Failures ---` ledger for the failures recorded before the failure, and - the failure ends the run. - Unprobed: no unit test fails the pipeline inside `engineSync`. Read the - handler (verify: - `grep -n "A failed pipeline skips the summary" cli/src/engine-native/syncDispatch.ts`) + the failure ends the run. An interrupt-only cause prints no ledger. When a + cleanup step (the terminal release or the ledger write) then throws, the + seams print that later error (`engine.ts engineFailureDetail`), as + `finally` did. + (verify: `bunx vitest run cli/test/unit/syncPipelineFailure.test.ts`) 4. The `--- Sync complete ---` summary prints, then the omp next-step notes. 5. When any step called `recordFailure`, the `--- Failures ---` ledger lists each message, and `engineSync` returns 1. Each call into a module that a later child of plan #290 moves runs through `bridge.ts bridgeSync` or `bridgePromise`, so an interrupt waits until that -step settles (`references/dispatch-flow.md`). +step settles (`references/dispatch-flow.md`). The bridge text of a failure is +`bridge.ts failureText`, which never coerces the thrown value. `kitHome()` +(`cli/src/kitHome.ts`, #297) is bridged the same way, and `makeCtx` maps its +`LegacyStepFailed` to `KitHomeInvalid` with the original message and cause. + +While an engine run is active, a SIGINT or SIGTERM ends the process at once, +as before the Effect seam, because a bridged pass cannot stop its `omp` or +installer child until #297: exit 130 on the public channel (`engine.ts +exitOnSignal`, installed only for the run) and 130 or 143 on the raw channel +(`main.ts`). The OS releases the locks with the process. +(verify: `bunx vitest run cli/test/unit/syncSignals.test.ts`) The omp pipeline reads SoT from the embedded payload. @@ -252,10 +265,10 @@ lock module). returns 1 before the pipeline. - Every lock of a sync is an `Effect.acquireRelease` in one scope, so it goes when the scope closes: after the run, a failure, or an interrupt. An - interrupt during a bridged pass waits until the pass settles, and the locks - stay held until then. A signal needs no handler: the OS releases the lock - when the process ends. - (verify: `bunx vitest run cli/test/unit/syncLock.test.ts -t "keeps the sync lock and the omp folder locks until an interrupted bridged pass settles"`) + in-process interrupt during a bridged pass waits until the pass settles, and + the locks stay held until then. A SIGINT or SIGTERM ends the process at once + (see § Dispatch Order), and the OS releases the locks with it. + (verify: `bunx vitest run cli/test/unit/syncLock.test.ts -t "keeps the sync lock and the omp folder locks until an interrupted bridged pass settles"` and `bunx vitest run cli/test/unit/syncLock.test.ts -t "lock wait deadline"`) (verify: `bunx vitest run cli/test/unit/syncLock.test.ts -t "exits 1 with the held line and leaves HOME unchanged"`, `bunx vitest run cli/test/unit/syncLock.test.ts -t "takes no lock in a dry run"`, `bunx vitest run cli/test/unit/syncLock.test.ts -t "rejects an unknown argument with exit 2 before it takes the lock"`, `bunx vitest run cli/test/unit/engine-di.test.ts -t "with exit 2 before it takes a lock or writes an omp file"`, `bunx vitest run cli/test/unit/syncLock.test.ts -t "exits 2 when the lock wait is not a non-negative safe integer"`, `bunx vitest run cli/test/unit/syncLock.test.ts -t "DRY_RUN env global"`, and `bunx vitest run cli/test/unit/syncLock.test.ts -t "prints the help with -h and --help while another sync holds the lock"`) diff --git a/.agents/skills/sync-orchestration-context/references/dispatch-flow.md b/.agents/skills/sync-orchestration-context/references/dispatch-flow.md index a25ed6ba..80c634bd 100644 --- a/.agents/skills/sync-orchestration-context/references/dispatch-flow.md +++ b/.agents/skills/sync-orchestration-context/references/dispatch-flow.md @@ -83,7 +83,8 @@ runEngineNative(argv, options?) index.ts; an Effect | |-- ompSync(omp) ompSync.ts; on a failure, the Effect.onError | | handler of runPipeline prints the | | "--- Failures ---" ledger, and the failure -| | ends the run +| | ends the run; an interrupt-only cause +| | prints no ledger | |-- "--- Sync complete ---" summary | |-- omp next steps | `-- "--- Failures ---" ledger when recordFailure ran; returns 1 @@ -94,7 +95,7 @@ runEngineNative(argv, options?) index.ts; an Effect Each call from this Effect code into a module that a later child of plan #290 moves (`bun.ts`, `ompFileDeploy.ts`, `ompKitPlugin.ts`, `ompPlugins.ts`, -`ompRemovals.ts`, `ompPaths.ts`, `toolchain.ts`, `home.ts`) goes through +`ompRemovals.ts`, `ompPaths.ts`, `toolchain.ts`, `home.ts`, `../kitHome.ts`) goes through `bridge.ts bridgeSync` or `bridgePromise`. A bridged step runs without interruption, so an interrupt of a sync waits until the pass settles, and the scope keeps the sync lock and the folder locks until then; a throw or a diff --git a/cli/src/engine-native/DESIGN.md b/cli/src/engine-native/DESIGN.md index ec48fb29..e1515a56 100644 --- a/cli/src/engine-native/DESIGN.md +++ b/cli/src/engine-native/DESIGN.md @@ -116,8 +116,9 @@ the deliverable (the report table for `toolchain check`), so nothing prints after it. The schema below applies to `sync` only. The `--- Sync complete ---` block (stdout, `echo`) prints after the omp -pipeline settles, also on dry-run. When the pipeline rejects, `syncDispatch.ts` -`engineSync` skips the block and prints only the `--- Failures ---` ledger. +pipeline settles, also on dry-run. When the pipeline fails, `syncDispatch.ts` +`runPipeline` skips the block and prints only the `--- Failures ---` ledger; an +interrupt-only cause prints no ledger. The block starts with a `Repo:` line and adds the `omp:` and `omp plugins:` inventory lines. Dry-run leaves out the `omp plugins:` line. Next-step advice lines print only when their trigger changed this run (an omp plugin operation, @@ -173,7 +174,7 @@ active logger binding. | Module | Owns | | -------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `parseArgs.ts` | the argv dispatch loop as an Effect; help and an unknown argument fail with the `parseHelp.ts` aborts `HelpShown` and `UsageRefused`, which hold the help text and the refusal | +| `parseArgs.ts` | the argv dispatch loop as an Effect; `-h` and `--help` print the help and fail with `parseHelp.ts HelpShown`, the signal that the help was printed; an unknown argument fails with `UsageRefused`, which holds the refusal | | `index.ts` | entry routing (`toolchain`/`sync`) as the Effect `runEngineNative`, which turns the intended aborts into exit codes, and the run-scoped verbosity gate | | `engineCtx.ts` | `Ctx` shape, the `EngineContext` service that carries it, and `makeCtx`; the unprefixed env globals apply only on the native-raw channel | | `syncDispatch.ts` | sync and folder locks, the omp pipeline call, run summary, next-step blocks, and the `--- Failures ---` ledger | diff --git a/cli/src/engine-native/bridge.ts b/cli/src/engine-native/bridge.ts index 0720fe83..1e5e6fe1 100644 --- a/cli/src/engine-native/bridge.ts +++ b/cli/src/engine-native/bridge.ts @@ -6,9 +6,7 @@ * `LegacyStepFailed` with the original value as its cause. The last child of * #290 removes this module with its last caller. */ -import { Effect, Schema } from "effect"; - -import { errorMessage } from "./errorText"; +import { Effect, Predicate, Schema } from "effect"; /** A bridged step threw or rejected; `cause` is the original value. */ export class LegacyStepFailed extends Schema.TaggedError< @@ -20,10 +18,21 @@ export class LegacyStepFailed extends Schema.TaggedError< cause: Schema.Defect(), }) {} +/** + * The text of a thrown or rejected value, as the engine seam printed it: the + * message of an `Error`, a non-empty string, else `unknown error`. It never + * coerces the value, so a value without a string form, such as + * `Object.create(null)`, cannot throw here. + */ +export const failureText = (cause: unknown): string => { + if (Predicate.isError(cause) && cause.message !== "") return cause.message; + return typeof cause === "string" && cause !== "" ? cause : "unknown error"; +}; + const stepFailure = (step: string) => (cause: unknown): LegacyStepFailed => - new LegacyStepFailed({ step, message: errorMessage(cause), cause }); + new LegacyStepFailed({ step, message: failureText(cause), cause }); /** Run the synchronous legacy step `run` as the step `step`. */ export const bridgeSync = (step: string, run: () => A): Effect.Effect => diff --git a/cli/src/engine-native/engineCtx.ts b/cli/src/engine-native/engineCtx.ts index 95443d76..77dcbdb5 100644 --- a/cli/src/engine-native/engineCtx.ts +++ b/cli/src/engine-native/engineCtx.ts @@ -9,7 +9,6 @@ import { Context, Effect, Schema } from "effect"; import { kitHome } from "../kitHome"; import { bridgeSync } from "./bridge"; import type { BunRuntimeState } from "./bun"; -import { errorMessage } from "./errorText"; import { engineHome } from "./home"; import type { TerminalLease } from "./logger"; import type { EngineServices } from "./services"; @@ -66,10 +65,12 @@ export const makeCtx = Effect.fn("makeCtx")(function* ( const env = process.env; const home = yield* bridgeSync("engineHome", () => engineHome(env)); const globals: NodeJS.ProcessEnv = options.envGlobals ? env : {}; - const repoDir = yield* Effect.try({ - try: () => kitHome(), - catch: (cause) => new KitHomeInvalid({ message: errorMessage(cause), cause }), - }); + // kitHome() moves with #297; until then it is bridged, and its refusal is KitHomeInvalid. + const repoDir = yield* bridgeSync("kitHome", () => kitHome()).pipe( + Effect.mapError( + (failed) => new KitHomeInvalid({ message: failed.message, cause: failed.cause }), + ), + ); const ctx: Ctx = { repoDir, home, diff --git a/cli/src/engine-native/logger.ts b/cli/src/engine-native/logger.ts index 43dfefd0..3cfda0af 100644 --- a/cli/src/engine-native/logger.ts +++ b/cli/src/engine-native/logger.ts @@ -36,10 +36,20 @@ export class LeaseReentered extends Schema.TaggedError< { readonly brand: unique symbol } >()("LeaseReentered", { message: Schema.String }) {} -/** The logger whose terminal-exclusive section the current fiber runs, if any. */ -const ExclusiveOwner = Context.Reference( - "docks-kit/engine-native/logger/ExclusiveOwner", - { defaultValue: () => undefined }, +/** One terminal-exclusive section: the logger that runs it, and whether it still runs. */ +interface ExclusiveSection { + readonly owner: object; + active: boolean; +} + +/** + * The terminal-exclusive sections that the current fiber runs in, of any + * logger. A fiber forked inside a section inherits the list, and the section + * ends its own entry when it ends, so a fiber that outlives it is not refused. + */ +const ExclusiveSections = Context.Reference>( + "docks-kit/engine-native/logger/ExclusiveSections", + { defaultValue: () => [] }, ); export interface Logger { @@ -107,7 +117,7 @@ export function makeLogger(sinks: LoggerSinks): Logger { let progressPending = false; let activeLease: TerminalLease | undefined; let bufferedWrites: Array<() => void> | undefined; - // Marks the fibers inside a terminal-exclusive section of this logger. + // Identifies the sections of this logger in `ExclusiveSections`. const exclusiveOwner = {}; const eraseProgress = (): void => { @@ -133,6 +143,8 @@ export function makeLogger(sinks: LoggerSinks): Logger { write(); }; const flushDurable = (writes: Array<() => void>): void => { + // A sink can throw any value, `undefined` included, so the flag records the throw. + let failed = false; let firstError: unknown; // Drain in batches: sinks can append more writes while the current batch runs. while (writes.length > 0) { @@ -140,11 +152,12 @@ export function makeLogger(sinks: LoggerSinks): Logger { try { write(); } catch (error) { - firstError ??= error; + if (!failed) firstError = error; + failed = true; } } } - if (firstError !== undefined) throw firstError; + if (failed) throw firstError; }; const ok = (msg: string): void => { writeDurable(() => errWrite(`\x1b[1;32m[ok]\x1b[0m ${msg}\n`)); @@ -157,13 +170,18 @@ export function makeLogger(sinks: LoggerSinks): Logger { const section = (action: Effect.Effect): Effect.Effect => permit.withPermits(1)( Effect.acquireUseRelease( - Effect.sync(() => { + Effect.sync((): ExclusiveSection => { eraseProgress(); bufferedWrites ??= []; + return { owner: exclusiveOwner, active: true }; }), - () => Effect.provideService(action, ExclusiveOwner, exclusiveOwner), - () => + (entered) => + Effect.flatMap(ExclusiveSections, (sections) => + Effect.provideService(action, ExclusiveSections, [...sections, entered]), + ), + (entered) => Effect.sync(() => { + entered.active = false; try { if (bufferedWrites !== undefined) flushDurable(bufferedWrites); } finally { @@ -180,7 +198,8 @@ export function makeLogger(sinks: LoggerSinks): Logger { }, withExclusive: (action) => Effect.gen(function* () { - if ((yield* ExclusiveOwner) === exclusiveOwner) { + const sections = yield* ExclusiveSections; + if (sections.some((entered) => entered.owner === exclusiveOwner && entered.active)) { return yield* new LeaseReentered({ message: "terminal lease withExclusive cannot be re-entered", }); @@ -207,19 +226,20 @@ export function makeLogger(sinks: LoggerSinks): Logger { eraseProgress(); }, }; - activeLease = lease; + // Publish the lease only after its first draw, so a failed draw leaves no lease behind. drawProgress(coordinatorMessage); + activeLease = lease; return lease; }; const acquireTerminal = (message: string): Effect.Effect => Effect.acquireRelease( - Effect.gen(function* () { - if (activeLease !== undefined) { - return yield* new LeaseHeld({ message: "terminal lease already acquired" }); - } - return openLease(message, yield* Semaphore.make(1)); - }), + // The check and the claim run in one synchronous step, so two acquires cannot both pass. + Effect.suspend(() => + activeLease === undefined + ? Effect.succeed(openLease(message, Semaphore.makeUnsafe(1))) + : Effect.fail(new LeaseHeld({ message: "terminal lease already acquired" })), + ), (lease) => Effect.sync(() => lease.release()), ); diff --git a/cli/src/engine-native/parseHelp.ts b/cli/src/engine-native/parseHelp.ts index 26b90902..c55787cf 100644 --- a/cli/src/engine-native/parseHelp.ts +++ b/cli/src/engine-native/parseHelp.ts @@ -1,8 +1,6 @@ /** - * Help text and the intended aborts of the EngineNative flag layer. Kept - * dependency-free (besides injected ctx) so the dispatch loop and its callers - * can share it without import cycles. `index.ts runEngineNative` turns each - * abort into its exit code. + * Help text and the intended aborts of the EngineNative flag layer. + * `index.ts runEngineNative` turns each abort into its exit code. */ import { Schema } from "effect"; diff --git a/cli/src/engine.ts b/cli/src/engine.ts index 42f00765..28a4867d 100644 --- a/cli/src/engine.ts +++ b/cli/src/engine.ts @@ -1,6 +1,7 @@ import { CliError } from "effect/cli"; -import { Cause, Console, Effect, Option } from "effect"; +import { Cause, Console, Effect } from "effect"; import { runEngineNative, type EngineFailure } from "./engine-native"; +import { failureText } from "./engine-native/bridge"; import { targetForHost } from "./engine-native/os/targets"; /** @@ -33,24 +34,48 @@ const originalFailure = (error: EngineFailure): unknown => { }; /** - * The detail of a failed run: the message of the original failure, or of a - * defect such as a stream write error, else `unknown error`. The public seam - * and the raw channel of main.ts print it. + * The detail of a failed run: the message of the last failure or defect of + * the run, else `unknown error`. A cleanup step that throws after a failed + * pass, such as the terminal release, the ledger write, or a buffered flush, + * comes after the pass failure, so its error wins, as it did with `finally`. + * The public seam and the raw channel of main.ts print it. */ export const engineFailureDetail = (cause: Cause.Cause): string => { - const failure = Cause.findErrorOption(cause); - const error = Option.isSome(failure) ? originalFailure(failure.value) : Cause.squash(cause); - if (error instanceof Error && error.message !== "") return error.message; - return typeof error === "string" && error !== "" ? error : "unknown error"; + const last = cause.reasons.filter((reason) => !Cause.isInterruptReason(reason)).at(-1); + if (last === undefined) return failureText(undefined); + return failureText(Cause.isFailReason(last) ? originalFailure(last.error) : last.defect); }; +/** + * While the engine runs, a SIGINT or SIGTERM ends the process at once with + * 130, as the Promise seam did: an `omp` or installer child of a bridged pass + * cannot be stopped from Effect code until #297, so an interrupt would wait + * for it. The OS releases the SQLite locks with the process. Other commands + * keep the interrupt of `BunRuntime.runMain`. + */ +const exitOnSignal = Effect.acquireRelease( + Effect.sync(() => { + const exit = (): never => process.exit(130); + process.on("SIGINT", exit); + process.on("SIGTERM", exit); + return exit; + }), + (exit) => + Effect.sync(() => { + process.off("SIGINT", exit); + process.off("SIGTERM", exit); + }), +); + export const engine = (args: ReadonlyArray) => Effect.gen(function* () { yield* requireSupportedHost(); if (bashEngineRequested()) { return yield* bail(bashRemovedMessage, 2); } - const code = yield* runEngineNative(args, { envGlobals: false }).pipe( + const code = yield* Effect.scoped( + Effect.andThen(exitOnSignal, runEngineNative(args, { envGlobals: false })), + ).pipe( Effect.catchCause((cause) => Cause.hasInterruptsOnly(cause) ? Effect.interrupt diff --git a/cli/test/unit/bridge.test.ts b/cli/test/unit/bridge.test.ts index 8f9c8f98..6115000e 100644 --- a/cli/test/unit/bridge.test.ts +++ b/cli/test/unit/bridge.test.ts @@ -23,18 +23,38 @@ describe("bridgePromise", () => { }); }), ); - await started.promise; + try { + await started.promise; - const interrupted = Effect.runPromise(Fiber.interrupt(fiber)).then(() => { - events.push("interrupt returned"); - }); - for (let turn = 0; turn < 5; turn += 1) await nextTurn(); - expect(events).toEqual([]); + const interrupted = Effect.runPromise(Fiber.interrupt(fiber)).then(() => { + events.push("interrupt returned"); + }); + for (let turn = 0; turn < 5; turn += 1) await nextTurn(); + expect(events).toEqual([]); + + gate.resolve("late"); + await interrupted; + expect(events).toEqual(["settled late", "interrupt returned"]); + expect(Exit.hasInterrupts(await Effect.runPromise(Fiber.await(fiber)))).toBe(true); + } finally { + // A failed assertion must not leave the fiber waiting on the gate. + gate.resolve("cleanup"); + await Effect.runPromise(Fiber.interrupt(fiber)); + } + }); + + it("keeps a rejection value without a string form as the cause, with the text unknown error", async () => { + const cause: unknown = Object.create(null); + const error = await Effect.runPromise( + Effect.flip(bridgePromise("plugin pass", () => Promise.reject(cause))), + ); - gate.resolve("late"); - await interrupted; - expect(events).toEqual(["settled late", "interrupt returned"]); - expect(Exit.hasInterrupts(await Effect.runPromise(Fiber.await(fiber)))).toBe(true); + expect(error).toMatchObject({ + _tag: "LegacyStepFailed", + step: "plugin pass", + message: "unknown error", + }); + expect(error.cause).toBe(cause); }); it("fails with the step and the message of a rejection", async () => { diff --git a/cli/test/unit/engine.test.ts b/cli/test/unit/engine.test.ts index b4977e51..88480ae1 100644 --- a/cli/test/unit/engine.test.ts +++ b/cli/test/unit/engine.test.ts @@ -1,6 +1,10 @@ +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; import { BunServices } from "@effect/platform-bun"; import { Effect, Layer } from "effect"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import type * as EngineNativeModule from "../../src/engine-native"; const mocks = vi.hoisted(() => ({ runEngineNative: vi.fn() })); @@ -8,7 +12,12 @@ vi.mock("../../src/engine-native", () => ({ runEngineNative: mocks.runEngineNati import { engine } from "../../src/engine"; import { LegacyStepFailed } from "../../src/engine-native/bridge"; -import { EngineServicesLive } from "../../src/services"; +import { + makeDependencyManager, + makeEngineServices, + makePlatform, +} from "../../src/engine-native/services"; +import { engineServicesLayer, EngineServicesLive } from "../../src/services"; beforeEach(() => { mocks.runEngineNative.mockReset(); @@ -123,11 +132,45 @@ describe("EngineNative Effect seam", () => { }); it("runs the public engine with env globals disabled", async () => { - mocks.runEngineNative.mockReturnValue(Effect.succeed(0)); - - await runEngine(["sync", "--dry-run"]); - expect(mocks.runEngineNative).toHaveBeenCalledWith(["sync", "--dry-run"], { - envGlobals: false, - }); + const actual = await vi.importActual("../../src/engine-native"); + mocks.runEngineNative.mockImplementation(actual.runEngineNative); + const home = mkdtempSync(join(tmpdir(), "engine-public-")); + vi.stubEnv("HOME", home); + vi.stubEnv("USERPROFILE", home); + vi.stubEnv("PI_CODING_AGENT_DIR", ""); + vi.stubEnv("XDG_DATA_HOME", ""); + // The raw channel reads DOCKS_KIT_VERBOSE; the public seam must ignore it. + vi.stubEnv("DOCKS_KIT_VERBOSE", "1"); + const advice = "Restart omp to load any refreshed plugins, skills, or tools.\n"; + const platform = makePlatform("linux"); + const dryRun = async (args: ReadonlyArray): Promise> => { + const stdout: Array = []; + const services = { + ...makeEngineServices({ + sinks: { stdout: (chunk) => void stdout.push(chunk), stderr: () => {} }, + }), + platform, + deps: makeDependencyManager(platform, { + commandExists: (name) => name === "bun", + capture: async () => "", + which: (name) => (name === "bun" ? "/opt/stub/bin/bun" : ""), + }), + }; + await Effect.runPromise( + Effect.provide( + engine(args), + Layer.mergeAll(BunServices.layer, engineServicesLayer(services)), + ), + ); + return stdout; + }; + + try { + expect(await dryRun(["sync", "--dry-run"])).not.toContain(advice); + // The same line is the verbose-only output that the flag selects. + expect(await dryRun(["sync", "--dry-run", "--verbose"])).toContain(advice); + } finally { + rmSync(home, { recursive: true, force: true }); + } }); }); diff --git a/cli/test/unit/folderLockCreate.test.ts b/cli/test/unit/folderLockCreate.test.ts index e287de90..04720592 100644 --- a/cli/test/unit/folderLockCreate.test.ts +++ b/cli/test/unit/folderLockCreate.test.ts @@ -21,7 +21,7 @@ import { BunServices } from "@effect/platform-bun"; import { Effect, Fiber, type FileSystem } from "effect"; import { afterEach, describe, expect, it, vi } from "vitest"; -import { acquireKitLock, releaseKitLock, type KitLock } from "../../src/engine-native/kitLock"; +import { releaseKitLock, tryAcquireKitLock, type KitLock } from "../../src/engine-native/kitLock"; import { folderSyncLockPath, syncLockPath } from "../../src/engine-native/scratch"; import { homeAndFolderLocks } from "../../src/engine-native/syncDispatch"; @@ -44,10 +44,10 @@ const runWithPlatform = (effect: Effect.Effect { - const held = await acquireKitLock(path, { waitMs: 0, privateDirectory }); - if (held.kind !== "acquired") throw new Error(`expected a free lock at ${path}`); - return held.lock; +function takeLock(path: string, privateDirectory: boolean): KitLock { + const held = tryAcquireKitLock(path, { privateDirectory }); + if (held === undefined) throw new Error(`expected a free lock at ${path}`); + return held; } describe("folders under the folder locks", () => { @@ -76,7 +76,7 @@ describe("homeAndFolderLocks lock lifetime", () => { const folder = join(root, "agent"); mkdirSync(folder); const folderLock = folderSyncLockPath(folder); - const held = await takeLock(folderLock, false); + const held = takeLock(folderLock, false); try { const error = await runWithPlatform( @@ -87,7 +87,7 @@ describe("homeAndFolderLocks lock lifetime", () => { _tag: "KitLockHeld", message: `another docks-kit sync holds ${folderLock}; run sync again after it ends`, }); - releaseKitLock(await takeLock(syncLockPath(root), true)); + releaseKitLock(takeLock(syncLockPath(root), true)); } finally { releaseKitLock(held); } @@ -98,7 +98,7 @@ describe("homeAndFolderLocks lock lifetime", () => { const root = tempRoot(); const folder = join(root, "agent"); mkdirSync(folder); - const held = await takeLock(folderSyncLockPath(folder), false); + const held = takeLock(folderSyncLockPath(folder), false); try { await runWithPlatform( @@ -109,12 +109,10 @@ describe("homeAndFolderLocks lock lifetime", () => { // probe stops long before the 10-second lock wait could end. let running = false; for (let probe = 0; probe < 200 && !running; probe += 1) { - const result = yield* Effect.promise(() => - acquireKitLock(syncLockPath(root), { waitMs: 0, privateDirectory: true }), - ); - if (result.kind === "held") running = true; + const lock = tryAcquireKitLock(syncLockPath(root), { privateDirectory: true }); + if (lock === undefined) running = true; else { - releaseKitLock(result.lock); + releaseKitLock(lock); yield* Effect.sleep(10); } } @@ -125,7 +123,7 @@ describe("homeAndFolderLocks lock lifetime", () => { }), ); - releaseKitLock(await takeLock(syncLockPath(root), true)); + releaseKitLock(takeLock(syncLockPath(root), true)); } finally { releaseKitLock(held); } diff --git a/cli/test/unit/logger.test.ts b/cli/test/unit/logger.test.ts index cf97dd6b..47603173 100644 --- a/cli/test/unit/logger.test.ts +++ b/cli/test/unit/logger.test.ts @@ -1,7 +1,9 @@ import { EventEmitter } from "node:events"; -import { Cause, Deferred, Effect, Exit, Fiber, type Scope } from "effect"; +import { Cause, Deferred, Effect, Exit, Fiber, Result, type Scope } from "effect"; import { describe, expect, it } from "vitest"; +import { engineFailureDetail } from "../../src/engine"; +import { bridgeSync } from "../../src/engine-native/bridge"; import { makeLogger, writeIgnoringEpipe } from "../../src/engine-native/logger"; describe("logger progress channel", () => { @@ -322,6 +324,124 @@ describe("logger terminal lease", () => { await scoped(logger.acquireTerminal("Next sync")); expect(chunks.at(-1)).toBe("\r\x1b[2K"); }); + + it("leaves no lease behind when its first draw throws", async () => { + const drawFailure = new Error("progress closed"); + let failDraw = true; + const logger = makeLogger({ + progress: () => { + if (failDraw) throw drawFailure; + }, + }); + + const exit = await Effect.runPromiseExit(Effect.scoped(logger.acquireTerminal("Syncing..."))); + expect(Exit.isFailure(exit) && Cause.squash(exit.cause)).toBe(drawFailure); + + failDraw = false; + const next = await Effect.runPromiseExit(Effect.scoped(logger.acquireTerminal("Next sync"))); + expect(Exit.isSuccess(next)).toBe(true); + }); + + it("grants one of two concurrent acquires and refuses the other with LeaseHeld", async () => { + const logger = makeLogger({}); + + const results = await scoped( + Effect.all( + [ + Effect.result(logger.acquireTerminal("first")), + Effect.result(logger.acquireTerminal("second")), + ], + { concurrency: "unbounded" }, + ), + ); + + expect(results.filter(Result.isSuccess)).toHaveLength(1); + expect(results.filter(Result.isFailure).map((result) => result.failure._tag)).toEqual([ + "LeaseHeld", + ]); + }); + + it("fails a section of a logger nested through a section of another logger", async () => { + const first = makeLogger({}); + const second = makeLogger({}); + + const nested = await scoped( + Effect.gen(function* () { + const a = yield* first.acquireTerminal("first"); + const b = yield* second.acquireTerminal("second"); + return yield* Effect.flip(a.withExclusive(b.withExclusive(a.withExclusive(Effect.void)))); + }), + ); + + expect(nested).toMatchObject({ _tag: "LeaseReentered" }); + }); + + it("admits a section of a fiber that a section forked and that outlives it", async () => { + const logger = makeLogger({}); + + const later = await scoped( + Effect.gen(function* () { + const lease = yield* logger.acquireTerminal("Syncing..."); + const go = yield* Deferred.make(); + const child = yield* lease.withExclusive( + Effect.forkDetach( + Deferred.await(go).pipe( + Effect.andThen(lease.withExclusive(Effect.succeed("after the section"))), + ), + ), + ); + yield* Deferred.succeed(go, undefined); + return yield* Fiber.join(child); + }), + ); + + expect(later).toBe("after the section"); + }); + + it("keeps an undefined throw of a buffered write as a failure of the section", async () => { + const logger = makeLogger({ + stdout: () => { + // A sink can throw any value; `undefined` must still fail the section. + throw undefined; + }, + }); + + const exit = await scoped( + Effect.gen(function* () { + const lease = yield* logger.acquireTerminal("sync"); + return yield* Effect.exit(lease.withExclusive(Effect.sync(() => logger.echo("summary")))); + }), + ); + + expect(Exit.isFailure(exit)).toBe(true); + }); + + it("reports the flush error at the seam when the section failed before its flush", async () => { + const flushFailure = new Error("flush failed"); + const logger = makeLogger({ + stdout: () => { + throw flushFailure; + }, + }); + + const exit = await scoped( + Effect.gen(function* () { + const lease = yield* logger.acquireTerminal("sync"); + return yield* Effect.exit( + lease + .withExclusive( + bridgeSync("install", () => { + logger.echo("installing"); + throw new Error("install failed"); + }), + ) + .pipe(Effect.catchTag("LeaseReentered", (error) => Effect.die(error))), + ); + }), + ); + + expect(Exit.isFailure(exit) && engineFailureDetail(exit.cause)).toBe("flush failed"); + }); }); describe("closed downstream reader", () => { diff --git a/cli/test/unit/syncLock.test.ts b/cli/test/unit/syncLock.test.ts index 524fa29d..6aed36db 100644 --- a/cli/test/unit/syncLock.test.ts +++ b/cli/test/unit/syncLock.test.ts @@ -36,7 +36,9 @@ import { import { tmpdir } from "node:os"; import { basename, join } from "node:path"; import { setImmediate as nextTurn } from "node:timers/promises"; +import { BunServices } from "@effect/platform-bun"; import { Effect, Fiber } from "effect"; +import { TestClock } from "effect/testing"; import { describe, expect, it, vi } from "vitest"; import type * as ExecModule from "../../src/engine-native/exec"; @@ -56,7 +58,7 @@ vi.mock("../../src/engine-native/exec", async () => { import { runEngineNative } from "../../src/engine-native"; import { p } from "../../src/engine-native/exec"; -import { acquireKitLock, releaseKitLock } from "../../src/engine-native/kitLock"; +import { releaseKitLock, tryAcquireKitLock } from "../../src/engine-native/kitLock"; import { ompPaths } from "../../src/engine-native/ompPaths"; import { kitCacheDir } from "../../src/engine-native/scratch"; import { @@ -65,7 +67,7 @@ import { type EngineServices, type Logger, } from "../../src/engine-native/services"; -import { folderLockPaths } from "../../src/engine-native/syncDispatch"; +import { folderLockPaths, homeAndFolderLocks } from "../../src/engine-native/syncDispatch"; import { engineLayer, runEngine } from "../lib/engineRun"; const WAIT_MS = "100"; @@ -173,27 +175,28 @@ function snapshot(home: string): Record { return entries; } -/** Hold the sync lock of `home` while `body` runs. */ +/** Hold the sync lock of `home` while `body` runs, as another sync does. */ async function holdingLock(home: string, body: () => Promise): Promise { - const held = await acquireKitLock(syncLock(home), { waitMs: 0 }); - if (held.kind !== "acquired") throw new Error(`expected a free lock at ${syncLock(home)}`); + const held = tryAcquireKitLock(syncLock(home), { privateDirectory: true }); + if (held === undefined) throw new Error(`expected a free lock at ${syncLock(home)}`); try { await body(); } finally { - releaseKitLock(held.lock); + releaseKitLock(held); } } /** Try the sync lock of `home` once, release it when the try took it, and return the result kind. */ -async function probe(home: string): Promise { - return await probeLock(syncLock(home), true); +function probe(home: string): string { + return probeLock(syncLock(home), true); } /** Try the lock at `path` once, release it when the try took it, and return the result kind. */ -async function probeLock(path: string, privateDirectory: boolean): Promise { - const result = await acquireKitLock(path, { waitMs: 0, privateDirectory }); - if (result.kind === "acquired") releaseKitLock(result.lock); - return result.kind; +function probeLock(path: string, privateDirectory: boolean): string { + const lock = tryAcquireKitLock(path, { privateDirectory }); + if (lock === undefined) return "held"; + releaseKitLock(lock); + return "acquired"; } /** The lock file that a writing sync takes inside an omp folder. */ @@ -222,12 +225,12 @@ async function holdingFolderLock( body: (lock: string) => Promise, ): Promise { const lock = join(folder, FOLDER_LOCK); - const held = await acquireKitLock(lock, { waitMs: 0, privateDirectory: false }); - if (held.kind !== "acquired") throw new Error(`expected a free lock at ${lock}`); + const held = tryAcquireKitLock(lock, { privateDirectory: false }); + if (held === undefined) throw new Error(`expected a free lock at ${lock}`); try { await body(lock); } finally { - releaseKitLock(held.lock); + releaseKitLock(held); } } @@ -382,7 +385,7 @@ describe("folder locks of a shared omp folder", () => { expect(records).toContain(heldLineFor(lock)); expect(snapshot(shared)).toEqual(before); }); - expect(await probe(home)).toBe("acquired"); + expect(probe(home)).toBe("acquired"); }); }); }); @@ -456,7 +459,7 @@ describe("folder locks of a shared omp folder", () => { expect(records).toContain(heldLineFor(lock)); expect(snapshot(shared)).toEqual(before); }); - expect(await probe(home)).toBe("acquired"); + expect(probe(home)).toBe("acquired"); }); }); }, @@ -485,9 +488,9 @@ describe("folder locks of a shared omp folder", () => { expect(records).toContain(heldLineFor(lock)); }); - expect(await probe(secondHome)).toBe("acquired"); + expect(probe(secondHome)).toBe("acquired"); }); - expect(await probe(firstHome)).toBe("acquired"); + expect(probe(firstHome)).toBe("acquired"); }); }); }); @@ -573,7 +576,6 @@ describe("interrupt of a sync", () => { await withHome(async (home) => { await withSharedFolder(async (shared) => { process.env["PI_CODING_AGENT_DIR"] = shared; - const folderLock = join(shared, FOLDER_LOCK); const entered = Promise.withResolvers(); const bunPath = Promise.withResolvers(); const base = recordingServices([]); @@ -592,21 +594,86 @@ describe("interrupt of a sync", () => { const fiber = Effect.runFork( runEngineNative(["sync"]).pipe(Effect.provide(engineLayer(services))), ); - await entered.promise; + try { + await entered.promise; + // The folder locks of the omp agent folder and the omp data root. + const { agentDir, dataRoot } = ompPaths({ + home, + env: process.env, + platform: process.platform, + }); + const folderLocks = Effect.runSync(folderLockPaths([agentDir, dataRoot])); + expect(folderLocks).toHaveLength(2); - let interruptReturned = false; - const interrupted = Effect.runPromise(Fiber.interrupt(fiber)).then(() => { - interruptReturned = true; - }); - for (let turn = 0; turn < 5; turn += 1) await nextTurn(); - expect(interruptReturned).toBe(false); - expect(await probe(home)).toBe("held"); - expect(await probeLock(folderLock, false)).toBe("held"); - - bunPath.resolve("/opt/stub/bin/bun"); - await interrupted; - expect(await probe(home)).toBe("acquired"); - expect(await probeLock(folderLock, false)).toBe("acquired"); + let interruptReturned = false; + const interrupted = Effect.runPromise(Fiber.interrupt(fiber)).then(() => { + interruptReturned = true; + }); + for (let turn = 0; turn < 5; turn += 1) await nextTurn(); + expect(interruptReturned).toBe(false); + expect(probe(home)).toBe("held"); + for (const lock of folderLocks) expect(probeLock(lock, false), lock).toBe("held"); + + bunPath.resolve("/opt/stub/bin/bun"); + await interrupted; + expect(probe(home)).toBe("acquired"); + for (const lock of folderLocks) expect(probeLock(lock, false), lock).toBe("acquired"); + // The interrupt ended the run before the first pass after the bootstrap. + expect(existsSync(join(agentDir, "AGENTS.md"))).toBe(false); + } finally { + // A failed assertion must not leave the sync holding its locks during cleanup. + bunPath.resolve("/opt/stub/bin/bun"); + await Effect.runPromise(Fiber.interrupt(fiber)); + } + }); + }); + }); +}); + +describe("lock wait deadline", () => { + /** + * Run `attempt` while the test holds the sync lock of `home`, on the test + * clock with the 100 ms wait of `withHome`: the lock is still held at the + * try at 50 ms and is released just before the clock reaches the deadline. + */ + const releasedAtDeadline = (home: string, attempt: Effect.Effect) => + Effect.gen(function* () { + const held = tryAcquireKitLock(syncLock(home), { privateDirectory: true }); + if (held === undefined) throw new Error(`expected a free lock at ${syncLock(home)}`); + const fiber = yield* Effect.forkChild(attempt, { startImmediately: true }); + yield* TestClock.adjust(50); + for (let turn = 0; turn < 10; turn += 1) yield* Effect.yieldNow; + releaseKitLock(held); + yield* TestClock.adjust(50); + return yield* Fiber.await(fiber); + }).pipe(Effect.provide(TestClock.layer())); + + it("takes a sync lock that its holder releases at the deadline, with one last try", async () => { + await withHome(async (home) => { + const records: Array = []; + const exit = await Effect.runPromise( + releasedAtDeadline(home, runEngineNative(["sync"])).pipe( + Effect.provide(engineLayer(recordingServices(records))), + ), + ); + + expect(exit).toMatchObject({ _tag: "Success", value: 0 }); + expect(records).not.toContain(heldLine(home)); + }); + }); + + it("reports a lock that its holder releases at the deadline as held on the tier toggle poll", async () => { + await withHome(async (home) => { + const exit = await Effect.runPromise( + releasedAtDeadline( + home, + Effect.flip(Effect.scoped(homeAndFolderLocks(home, [join(home, "agent")]))), + ).pipe(Effect.provide(BunServices.layer)), + ); + + expect(exit).toMatchObject({ + _tag: "Success", + value: { _tag: "KitLockHeld", message: heldLine(home) }, }); }); }); diff --git a/cli/test/unit/syncPipelineFailure.test.ts b/cli/test/unit/syncPipelineFailure.test.ts new file mode 100644 index 00000000..81e0fdf7 --- /dev/null +++ b/cli/test/unit/syncPipelineFailure.test.ts @@ -0,0 +1,144 @@ +/** + * A failed omp pipeline (plan #294): the run prints the `--- Failures ---` + * ledger of the failures recorded before the failure, prints no summary, and + * fails. When a cleanup step then throws, such as the ledger write or the + * terminal release, the seams report that later error, as `finally` did. + */ +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { Effect, Exit } from "effect"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import type { Ctx } from "../../src/engine-native"; +import type * as OmpPluginsModule from "../../src/engine-native/ompPlugins"; + +const mocks = vi.hoisted(() => ({ + syncPlugins: vi.fn<(ctx: Ctx) => Promise>(), +})); + +vi.mock("../../src/engine-native/ompPlugins", async (importOriginal) => ({ + ...(await importOriginal()), + syncPlugins: mocks.syncPlugins, +})); +vi.mock("../../src/engine-native/bun", () => ({ + bunBootstrap: async () => ({ kind: "ready", executable: "bun" }), +})); + +import { engineFailureDetail } from "../../src/engine"; +import { runEngineNative } from "../../src/engine-native"; +import { recordFailure } from "../../src/engine-native/failures"; +import { makeEngineServices } from "../../src/engine-native/services"; +import { engineLayer } from "../lib/engineRun"; + +const ENV_KEYS = [ + "HOME", + "USERPROFILE", + "DOCKS_KIT_HOME", + "DRY_RUN", + "DOCKS_KIT_VERBOSE", + "PI_CODING_AGENT_DIR", + "OMP_PROFILE", + "PI_PROFILE", + "PI_CONFIG_DIR", + "XDG_DATA_HOME", +] as const; + +let home = ""; +let previous = new Map(); + +beforeEach(() => { + home = mkdtempSync(join(tmpdir(), "sync-pipeline-failure-")); + previous = new Map(ENV_KEYS.map((key) => [key, process.env[key]])); + for (const key of ENV_KEYS) delete process.env[key]; + // engineHome reads USERPROFILE on win32, so both keys point at the temp home. + process.env["HOME"] = home; + process.env["USERPROFILE"] = home; + mocks.syncPlugins.mockReset(); +}); + +afterEach(() => { + for (const [key, value] of previous) { + if (value === undefined) delete process.env[key]; + else process.env[key] = value; + } + rmSync(home, { recursive: true, force: true }); +}); + +const LEDGER_ENTRY = "omp plugin link failed"; +const PASS_FAILURE = new Error("plugin pass broke"); + +/** Run a dry-run sync with the logger sinks of `options` and return its exit. */ +function failedSync(options: Parameters[0]) { + return Effect.runPromiseExit( + runEngineNative(["sync", "--dry-run"]).pipe( + Effect.provide(engineLayer(makeEngineServices(options))), + ), + ); +} + +describe("a failed omp pipeline", () => { + it("prints the ledger recorded before the failure, no summary, and fails", async () => { + const stdout: Array = []; + mocks.syncPlugins.mockImplementation((ctx) => { + recordFailure(ctx, LEDGER_ENTRY); + return Promise.reject(PASS_FAILURE); + }); + + const exit = await failedSync({ + sinks: { stdout: (chunk) => void stdout.push(chunk), stderr: () => {} }, + }); + + expect(stdout).toContain("--- Failures ---\n"); + expect(stdout).toContain(`- ${LEDGER_ENTRY}\n`); + expect(stdout).not.toContain("--- Sync complete ---\n"); + expect(Exit.isFailure(exit) && exit.cause.reasons).toEqual([ + expect.objectContaining({ + _tag: "Fail", + error: expect.objectContaining({ _tag: "LegacyStepFailed", step: "syncPlugins" }), + }), + ]); + expect(Exit.isFailure(exit) && engineFailureDetail(exit.cause)).toBe("plugin pass broke"); + }); + + it("reports a ledger write error that follows the failure", async () => { + const writeFailure = new Error("ledger write failed"); + mocks.syncPlugins.mockImplementation((ctx) => { + recordFailure(ctx, LEDGER_ENTRY); + return Promise.reject(PASS_FAILURE); + }); + + const exit = await failedSync({ + sinks: { + stdout: (chunk) => { + if (chunk === "--- Failures ---\n") throw writeFailure; + }, + stderr: () => {}, + }, + }); + + expect(Exit.isFailure(exit) && engineFailureDetail(exit.cause)).toBe("ledger write failed"); + }); + + it("reports a terminal release error that follows the failure", async () => { + const releaseFailure = new Error("progress closed"); + let failErase = false; + mocks.syncPlugins.mockImplementation((ctx) => { + // Draw a progress line, so the release erases it, then fail the pass. + ctx.terminalLease?.update("Syncing omp plugins..."); + failErase = true; + return Promise.reject(PASS_FAILURE); + }); + + const exit = await failedSync({ + sinks: { + stdout: () => {}, + stderr: () => {}, + progress: (chunk) => { + if (failErase && chunk === "\r\x1b[2K") throw releaseFailure; + }, + }, + }); + + expect(Exit.isFailure(exit) && engineFailureDetail(exit.cause)).toBe("progress closed"); + }); +}); diff --git a/cli/test/unit/syncSignals.test.ts b/cli/test/unit/syncSignals.test.ts new file mode 100644 index 00000000..4811ceef --- /dev/null +++ b/cli/test/unit/syncSignals.test.ts @@ -0,0 +1,146 @@ +/** + * Signals during a sync (plan #294, Research: Signals). A bridged pass cannot + * stop an `omp` child until #297, so while an engine run is active a SIGINT + * or SIGTERM to the CLI process ends it at once, as before the Effect seam: + * exit 130 for both on the public channel, and 143 for SIGTERM and 130 for + * SIGINT on the raw channel. The OS releases the sync lock with the process, + * so the next sync can take it. + */ +import { spawn, type ChildProcess } from "node:child_process"; +import { existsSync, readFileSync } from "node:fs"; +import { delimiter, join } from "node:path"; +import { setTimeout as sleep } from "node:timers/promises"; +import { afterAll, afterEach, describe, expect, it } from "vitest"; + +import { releaseKitLock, tryAcquireKitLock } from "../../src/engine-native/kitLock"; +import { syncLockPath } from "../../src/engine-native/scratch"; +import { BUN_RUNTIME, cliEntry } from "../lib/cliEntry"; +import { + cleanupTemporaryDirs, + makeStubDir, + ompStubBody, + processIsAlive, + temporaryDir, +} from "../lib/goldenResources"; +import { SPAWN_TIMEOUT_MS } from "../lib/spawnTimeout"; + +/** The environment key that names the pid file of the waiting `omp` stub. */ +const PID_FILE = "SYNC_SIGNAL_STUB_PID"; + +/** + * The `omp` stub: `plugin list`, the first `omp` child of a sync pass, writes + * its pid and then waits until it is killed, so the bridged plugin pass of the + * sync never settles. Every other command answers as the golden stub does. + */ +const WAITING_OMP = `if (args[0] === "plugin" && args[1] === "list") { + // The body goes inside the switch of the generated runner, which takes no other static import. + const { writeFileSync } = await import("node:fs") + writeFileSync(process.env["${PID_FILE}"], String(process.pid)) + // A keep-alive, not a test delay: the stub waits until the test kills it. + setInterval(() => {}, 1000) +} else { +${ompStubBody()} +}`; + +/** How long a signalled CLI may take to exit; a wait for the stub would never end. */ +const EXIT_BOUND_MS = 10_000; + +const stubPidFiles: Array = []; +const children: Array = []; + +afterEach(() => { + for (const child of children.splice(0)) child.kill("SIGKILL"); + for (const pidFile of stubPidFiles.splice(0)) { + if (!existsSync(pidFile)) continue; + const pid = Number(readFileSync(pidFile, "utf8")); + if (processIsAlive(pid)) process.kill(pid, "SIGKILL"); + } +}); +afterAll(cleanupTemporaryDirs); + +/** Wait until `path` exists; fail after the spawn bound. The child gives no other signal. */ +async function waitForFile(path: string): Promise { + const deadline = Date.now() + SPAWN_TIMEOUT_MS; + while (!existsSync(path)) { + if (Date.now() > deadline) throw new Error(`${path} did not appear`); + await sleep(20); + } +} + +/** The exit code of `child`, or `timed out` when it runs past `boundMs`. */ +function exitWithin(child: ChildProcess, boundMs: number): Promise { + const { promise, resolve } = Promise.withResolvers(); + // The bound only caps a CLI that waits for the stub; a prompt exit resolves first. + const timer = setTimeout(() => resolve("timed out"), boundMs); + child.once("exit", (code, signal) => { + clearTimeout(timer); + resolve(code ?? `signal ${String(signal)}`); + }); + return promise; +} + +/** Start `docks-kit sync` on `channel` in a fresh home, with the waiting `omp` stub first on PATH. */ +function startSync(channel: "public" | "raw"): { + child: ChildProcess; + home: string; + pidFile: string; +} { + const nativeHost = { nativeHost: true } as const; + const stubs = makeStubDir({ omp: WAITING_OMP }, nativeHost); + const home = temporaryDir("sync-signals-home-"); + const pidFile = join(temporaryDir("sync-signals-pid-"), "omp.pid"); + stubPidFiles.push(pidFile); + const child = spawn(BUN_RUNTIME, [cliEntry(), "sync"], { + env: { + HOME: home, + USERPROFILE: home, + PATH: `${stubs}${delimiter}${process.env["PATH"] ?? ""}`, + LC_ALL: "C", + TERM: "dumb", + BUN_INSTALL_CACHE_DIR: temporaryDir("sync-signals-bun-cache-"), + BUN_RUNTIME_TRANSPILER_CACHE_PATH: temporaryDir("sync-signals-bun-transpiler-"), + [PID_FILE]: pidFile, + ...(channel === "raw" ? { DOCKS_KIT_ENGINE: "native-raw" } : {}), + }, + stdio: ["ignore", "ignore", "ignore"], + }); + children.push(child); + return { child, home, pidFile }; +} + +/** True when a new run can take the sync lock of `home`; the probe gives it back at once. */ +function syncLockFree(home: string): boolean { + const lock = tryAcquireKitLock(syncLockPath(home), { privateDirectory: false }); + if (lock === undefined) return false; + releaseKitLock(lock); + return true; +} + +describe.skipIf(process.platform === "win32")( + "signals during a sync (skipped on Windows: Bun's ChildProcess.kill force-terminates the process there instead of delivering the signal)", + () => { + for (const [channel, signal, code] of [ + ["public", "SIGTERM", 130], + ["public", "SIGINT", 130], + ["raw", "SIGTERM", 143], + ["raw", "SIGINT", 130], + ] as const) { + it( + `exits ${code} on one ${signal} while an omp child of the ${channel} sync waits, and frees the sync lock`, + async () => { + const { child, home, pidFile } = startSync(channel); + await waitForFile(pidFile); + // The sync holds its lock while the plugin pass waits for the stub. + expect(syncLockFree(home)).toBe(false); + + // The signal goes to the CLI process only, not to its process group. + child.kill(signal); + + expect(await exitWithin(child, EXIT_BOUND_MS)).toBe(code); + expect(syncLockFree(home)).toBe(true); + }, + SPAWN_TIMEOUT_MS, + ); + } + }, +); From 12720ef3ec19a31d00e941826d9e221d8e02897e Mon Sep 17 00:00:00 2001 From: Eduardo Marquez <55303379+DocksDocks@users.noreply.github.com> Date: Tue, 1 Dec 2026 20:50:24 -0300 Subject: [PATCH 05/11] Repair code-review round 2 of the Effect seam - The engine-run signal listeners run first (prependListener), so a delivered signal exits 130. - The signal test runs the CLI in its own process group, kills only that group in teardown, watches exit and spawn errors from launch, and runs a second sync to its end after the signal. - failureText reads an Error message at most once and falls back to unknown error on any throw. - acquireTerminal reserves the lease before the first draw, so a reentrant acquire gets LeaseHeld. - The verbose dry-run test clears PI_CONFIG_DIR, OMP_PROFILE, and PI_PROFILE. - Guidance: the mode-selection anchor, and the failed-pipeline ledger conditions in DESIGN.md, the sync-orchestration skill, and dispatch-flow.md. Verified: bun x --no-install vitest run (unit, toggles, signals rows, syncPipelineFailure.test.ts, skillMetadata.test.ts); bun run check:types; bun run golden:dryrun; bun run golden:mutation; bun run check --- .agents/skills/engine-native-context/SKILL.md | 4 +- .agents/skills/host-platform-context/SKILL.md | 2 +- .../sync-orchestration-context/SKILL.md | 12 +- .../references/dispatch-flow.md | 11 +- cli/src/engine-native/DESIGN.md | 7 +- cli/src/engine-native/bridge.ts | 16 +- cli/src/engine-native/logger.ts | 25 ++- cli/src/engine.ts | 9 +- cli/test/unit/bridge.test.ts | 15 ++ cli/test/unit/engine.test.ts | 11 +- cli/test/unit/logger.test.ts | 19 ++ cli/test/unit/syncSignals.test.ts | 176 ++++++++++++------ 12 files changed, 214 insertions(+), 93 deletions(-) diff --git a/.agents/skills/engine-native-context/SKILL.md b/.agents/skills/engine-native-context/SKILL.md index 59cb50d2..fe4180a8 100644 --- a/.agents/skills/engine-native-context/SKILL.md +++ b/.agents/skills/engine-native-context/SKILL.md @@ -8,7 +8,7 @@ metadata: - path: cli/src/engine-native/index.ts lines: "1-82" - path: cli/src/engine.ts - lines: "1-97" + lines: "1-98" - path: cli/src/main.ts lines: "1-78" - path: cli/src/engine-native/exec.ts @@ -20,7 +20,7 @@ metadata: - path: cli/src/engine-native/os/targets.ts lines: "1-64" - path: cli/test/unit/engine.test.ts - lines: "1-176" + lines: "1-183" - path: cli/test/golden-dryrun.ts lines: "1-199" - path: cli/test/golden-mutation.ts diff --git a/.agents/skills/host-platform-context/SKILL.md b/.agents/skills/host-platform-context/SKILL.md index 1d43e966..8543fed3 100644 --- a/.agents/skills/host-platform-context/SKILL.md +++ b/.agents/skills/host-platform-context/SKILL.md @@ -28,7 +28,7 @@ metadata: - path: cli/src/engine-native/processes.ts lines: "1-16" - path: cli/src/engine-native/logger.ts - lines: "1-266" + lines: "1-275" - path: cli/src/engine-native/services.ts lines: "1-88" - path: cli/src/services.ts diff --git a/.agents/skills/sync-orchestration-context/SKILL.md b/.agents/skills/sync-orchestration-context/SKILL.md index 3bef9220..80da617e 100644 --- a/.agents/skills/sync-orchestration-context/SKILL.md +++ b/.agents/skills/sync-orchestration-context/SKILL.md @@ -18,7 +18,7 @@ metadata: - path: cli/src/argvSurface.ts lines: "1-351" - path: cli/src/engine.ts - lines: "1-97" + lines: "1-98" - path: cli/src/kitHome.ts lines: "1-99" - path: cli/src/payload.ts @@ -36,7 +36,7 @@ metadata: - path: cli/src/engine-native/syncDispatch.ts lines: "1-335" - path: cli/src/engine-native/bridge.ts - lines: "1-46" + lines: "1-54" - path: cli/src/engine-native/kitLock.ts lines: "1-121" - path: cli/src/engine-native/syncConcurrency.ts @@ -205,10 +205,10 @@ writing sync runs `lockedSync` in one lock scope (see § Sync Lock): then takes their folder locks (see § Sync Lock), and `runPipeline` runs the remaining steps. 3. `runPipeline` takes the terminal lease, a scoped resource of - `logger.ts acquireTerminal`, and runs `ompSync`. When the pipeline fails, - `runPipeline` prints no summary: its `Effect.onError` handler prints the - `--- Failures ---` ledger for the failures recorded before the failure, and - the failure ends the run. An interrupt-only cause prints no ledger. When a + `logger.ts acquireTerminal`, and runs `ompSync`. A failed pipeline skips + the summary; the `Effect.onError` handler of `runPipeline` + prints the `--- Failures ---` ledger only when entries were recorded and the cause is not interrupt-only, + and the failure ends the run. When a cleanup step (the terminal release or the ledger write) then throws, the seams print that later error (`engine.ts engineFailureDetail`), as `finally` did. diff --git a/.agents/skills/sync-orchestration-context/references/dispatch-flow.md b/.agents/skills/sync-orchestration-context/references/dispatch-flow.md index 80c634bd..eaf9810e 100644 --- a/.agents/skills/sync-orchestration-context/references/dispatch-flow.md +++ b/.agents/skills/sync-orchestration-context/references/dispatch-flow.md @@ -62,7 +62,7 @@ from the current directory. runEngineNative(argv, options?) index.ts; an Effect |-- makeCtx({ logger, deps, platform }, ...) engineCtx.ts; env globals only when true; | kitHome() failure: KitHomeInvalid -|-- switch (argv[0]), with EngineContext = ctx +|-- mode selection in index.ts runEngineNative, with EngineContext = ctx | |-- toolchain -> modeToolchain(args) modes.ts; no lock | `-- sync/default -> engineSync(args) syncDispatch.ts | |-- parseArgs(args) flags only, before any lock; any other @@ -80,11 +80,10 @@ runEngineNative(argv, options?) index.ts; an Effect | | under the locks of its ancestors in the | | set | `-- runPipeline(omp) -| |-- ompSync(omp) ompSync.ts; on a failure, the Effect.onError -| | handler of runPipeline prints the -| | "--- Failures ---" ledger, and the failure -| | ends the run; an interrupt-only cause -| | prints no ledger +| |-- ompSync(omp) ompSync.ts; a failure skips the summary; the +| | Effect.onError handler of runPipeline +| | prints the `--- Failures ---` ledger only when entries were recorded and the cause is not interrupt-only; +| | the failure ends the run | |-- "--- Sync complete ---" summary | |-- omp next steps | `-- "--- Failures ---" ledger when recordFailure ran; returns 1 diff --git a/cli/src/engine-native/DESIGN.md b/cli/src/engine-native/DESIGN.md index e1515a56..913149ed 100644 --- a/cli/src/engine-native/DESIGN.md +++ b/cli/src/engine-native/DESIGN.md @@ -116,9 +116,10 @@ the deliverable (the report table for `toolchain check`), so nothing prints after it. The schema below applies to `sync` only. The `--- Sync complete ---` block (stdout, `echo`) prints after the omp -pipeline settles, also on dry-run. When the pipeline fails, `syncDispatch.ts` -`runPipeline` skips the block and prints only the `--- Failures ---` ledger; an -interrupt-only cause prints no ledger. +pipeline settles, also on dry-run. A failed pipeline skips that block; +`syncDispatch.ts runPipeline` +prints the `--- Failures ---` ledger only when entries were recorded and the cause is not interrupt-only. +An interrupt-only cause prints no ledger. The block starts with a `Repo:` line and adds the `omp:` and `omp plugins:` inventory lines. Dry-run leaves out the `omp plugins:` line. Next-step advice lines print only when their trigger changed this run (an omp plugin operation, diff --git a/cli/src/engine-native/bridge.ts b/cli/src/engine-native/bridge.ts index 1e5e6fe1..4276ca50 100644 --- a/cli/src/engine-native/bridge.ts +++ b/cli/src/engine-native/bridge.ts @@ -21,12 +21,20 @@ export class LegacyStepFailed extends Schema.TaggedError< /** * The text of a thrown or rejected value, as the engine seam printed it: the * message of an `Error`, a non-empty string, else `unknown error`. It never - * coerces the value, so a value without a string form, such as - * `Object.create(null)`, cannot throw here. + * coerces the value and reads `message` once, and a check or a `message` + * getter that throws also gives `unknown error`, so it cannot throw itself. */ export const failureText = (cause: unknown): string => { - if (Predicate.isError(cause) && cause.message !== "") return cause.message; - return typeof cause === "string" && cause !== "" ? cause : "unknown error"; + if (typeof cause === "string") return cause !== "" ? cause : "unknown error"; + try { + if (Predicate.isError(cause)) { + const message: unknown = cause.message; + if (typeof message === "string" && message !== "") return message; + } + } catch { + // A value whose check or `message` getter throws has no readable text. + } + return "unknown error"; }; const stepFailure = diff --git a/cli/src/engine-native/logger.ts b/cli/src/engine-native/logger.ts index 3cfda0af..37d89581 100644 --- a/cli/src/engine-native/logger.ts +++ b/cli/src/engine-native/logger.ts @@ -226,20 +226,29 @@ export function makeLogger(sinks: LoggerSinks): Logger { eraseProgress(); }, }; - // Publish the lease only after its first draw, so a failed draw leaves no lease behind. - drawProgress(coordinatorMessage); activeLease = lease; return lease; }; const acquireTerminal = (message: string): Effect.Effect => Effect.acquireRelease( - // The check and the claim run in one synchronous step, so two acquires cannot both pass. - Effect.suspend(() => - activeLease === undefined - ? Effect.succeed(openLease(message, Semaphore.makeUnsafe(1))) - : Effect.fail(new LeaseHeld({ message: "terminal lease already acquired" })), - ), + // The check and the reservation run in one synchronous step, so two + // acquires cannot both pass, and a sink that acquires again during the + // first draw gets LeaseHeld. A draw that throws gives the reservation back. + Effect.suspend(() => { + if (activeLease !== undefined) { + return Effect.fail(new LeaseHeld({ message: "terminal lease already acquired" })); + } + const lease = openLease(message, Semaphore.makeUnsafe(1)); + return Effect.sync(() => drawProgress(message)).pipe( + Effect.onError(() => + Effect.sync(() => { + if (activeLease === lease) activeLease = undefined; + }), + ), + Effect.as(lease), + ); + }), (lease) => Effect.sync(() => lease.release()), ); diff --git a/cli/src/engine.ts b/cli/src/engine.ts index 28a4867d..112db743 100644 --- a/cli/src/engine.ts +++ b/cli/src/engine.ts @@ -50,14 +50,15 @@ export const engineFailureDetail = (cause: Cause.Cause): string = * While the engine runs, a SIGINT or SIGTERM ends the process at once with * 130, as the Promise seam did: an `omp` or installer child of a bridged pass * cannot be stopped from Effect code until #297, so an interrupt would wait - * for it. The OS releases the SQLite locks with the process. Other commands - * keep the interrupt of `BunRuntime.runMain`. + * for it. The listeners go first, before the interrupt listeners of + * `BunRuntime.runMain`, and leave when the run ends, so other commands keep + * that interrupt. The OS releases the SQLite locks with the process. */ const exitOnSignal = Effect.acquireRelease( Effect.sync(() => { const exit = (): never => process.exit(130); - process.on("SIGINT", exit); - process.on("SIGTERM", exit); + process.prependListener("SIGINT", exit); + process.prependListener("SIGTERM", exit); return exit; }), (exit) => diff --git a/cli/test/unit/bridge.test.ts b/cli/test/unit/bridge.test.ts index 6115000e..75d29269 100644 --- a/cli/test/unit/bridge.test.ts +++ b/cli/test/unit/bridge.test.ts @@ -71,6 +71,21 @@ describe("bridgePromise", () => { expect(error.cause).toBe(cause); }); + it("keeps an Error whose message getter throws as the cause, with the text unknown error", async () => { + const cause = new Error("hidden"); + Object.defineProperty(cause, "message", { + get: () => { + throw new Error("message getter failed"); + }, + }); + const error = await Effect.runPromise( + Effect.flip(bridgePromise("plugin pass", () => Promise.reject(cause))), + ); + + expect(error.message).toBe("unknown error"); + expect(error.cause).toBe(cause); + }); + it("fails with the step and the message of a throw before the Promise", async () => { const error = await Effect.runPromise( Effect.flip( diff --git a/cli/test/unit/engine.test.ts b/cli/test/unit/engine.test.ts index 88480ae1..a420f989 100644 --- a/cli/test/unit/engine.test.ts +++ b/cli/test/unit/engine.test.ts @@ -137,8 +137,15 @@ describe("EngineNative Effect seam", () => { const home = mkdtempSync(join(tmpdir(), "engine-public-")); vi.stubEnv("HOME", home); vi.stubEnv("USERPROFILE", home); - vi.stubEnv("PI_CODING_AGENT_DIR", ""); - vi.stubEnv("XDG_DATA_HOME", ""); + for (const key of [ + "PI_CODING_AGENT_DIR", + "PI_CONFIG_DIR", + "OMP_PROFILE", + "PI_PROFILE", + "XDG_DATA_HOME", + ]) { + vi.stubEnv(key, undefined); + } // The raw channel reads DOCKS_KIT_VERBOSE; the public seam must ignore it. vi.stubEnv("DOCKS_KIT_VERBOSE", "1"); const advice = "Restart omp to load any refreshed plugins, skills, or tools.\n"; diff --git a/cli/test/unit/logger.test.ts b/cli/test/unit/logger.test.ts index 47603173..06be8c35 100644 --- a/cli/test/unit/logger.test.ts +++ b/cli/test/unit/logger.test.ts @@ -325,6 +325,25 @@ describe("logger terminal lease", () => { expect(chunks.at(-1)).toBe("\r\x1b[2K"); }); + it("refuses an acquire that a sink starts during the first draw with LeaseHeld", async () => { + const nested: Array> = []; + const logger = makeLogger({ + progress: () => { + if (nested.length === 0) { + nested.push(Effect.runSyncExit(Effect.scoped(logger.acquireTerminal("nested")))); + } + }, + }); + + const outer = await Effect.runPromiseExit(Effect.scoped(logger.acquireTerminal("Syncing..."))); + + expect(Exit.isSuccess(outer)).toBe(true); + expect(nested).toHaveLength(1); + expect(Exit.isFailure(nested[0]!) && Cause.squash(nested[0]!.cause)).toMatchObject({ + _tag: "LeaseHeld", + }); + }); + it("leaves no lease behind when its first draw throws", async () => { const drawFailure = new Error("progress closed"); let failDraw = true; diff --git a/cli/test/unit/syncSignals.test.ts b/cli/test/unit/syncSignals.test.ts index 4811ceef..962d43be 100644 --- a/cli/test/unit/syncSignals.test.ts +++ b/cli/test/unit/syncSignals.test.ts @@ -4,7 +4,10 @@ * or SIGTERM to the CLI process ends it at once, as before the Effect seam: * exit 130 for both on the public channel, and 143 for SIGTERM and 130 for * SIGINT on the raw channel. The OS releases the sync lock with the process, - * so the next sync can take it. + * so the next sync of the same home runs to its end. + * + * Each CLI runs in its own process group, and the `omp` stub that it starts + * stays in that group, so the teardown ends the whole group by the CLI pid. */ import { spawn, type ChildProcess } from "node:child_process"; import { existsSync, readFileSync } from "node:fs"; @@ -19,24 +22,24 @@ import { cleanupTemporaryDirs, makeStubDir, ompStubBody, - processIsAlive, temporaryDir, } from "../lib/goldenResources"; import { SPAWN_TIMEOUT_MS } from "../lib/spawnTimeout"; -/** The environment key that names the pid file of the waiting `omp` stub. */ -const PID_FILE = "SYNC_SIGNAL_STUB_PID"; +/** The environment key that names the marker file of the waiting `omp` stub. */ +const MARKER_FILE = "SYNC_SIGNAL_STUB_MARKER"; /** * The `omp` stub: `plugin list`, the first `omp` child of a sync pass, writes - * its pid and then waits until it is killed, so the bridged plugin pass of the - * sync never settles. Every other command answers as the golden stub does. + * its pid as a marker and then waits until it is killed, so the bridged + * plugin pass of the sync never settles. Every other command answers as the + * golden stub does. */ const WAITING_OMP = `if (args[0] === "plugin" && args[1] === "list") { // The body goes inside the switch of the generated runner, which takes no other static import. const { writeFileSync } = await import("node:fs") - writeFileSync(process.env["${PID_FILE}"], String(process.pid)) - // A keep-alive, not a test delay: the stub waits until the test kills it. + writeFileSync(process.env["${MARKER_FILE}"], String(process.pid)) + // A keep-alive, not a test delay: the stub waits until the teardown kills it. setInterval(() => {}, 1000) } else { ${ompStubBody()} @@ -45,51 +48,39 @@ ${ompStubBody()} /** How long a signalled CLI may take to exit; a wait for the stub would never end. */ const EXIT_BOUND_MS = 10_000; -const stubPidFiles: Array = []; -const children: Array = []; +/** The way a launched CLI ended: its exit code or signal, or the spawn error. */ +type Ending = + | { readonly kind: "exit"; readonly code: number | null; readonly signal: string | null } + | { readonly kind: "error"; readonly error: Error }; + +interface Launched { + readonly child: ChildProcess; + /** Settles once, from launch, with the first `exit` or `error` of the child. */ + readonly ended: Promise; +} + +/** The CLI process groups that a case started; the teardown ends each one. */ +const groups: Array = []; afterEach(() => { - for (const child of children.splice(0)) child.kill("SIGKILL"); - for (const pidFile of stubPidFiles.splice(0)) { - if (!existsSync(pidFile)) continue; - const pid = Number(readFileSync(pidFile, "utf8")); - if (processIsAlive(pid)) process.kill(pid, "SIGKILL"); + for (const pid of groups.splice(0)) { + try { + // The negative pid names the group that the CLI leads, the `omp` stub included. + process.kill(-pid, "SIGKILL"); + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== "ESRCH") throw error; + } } }); afterAll(cleanupTemporaryDirs); -/** Wait until `path` exists; fail after the spawn bound. The child gives no other signal. */ -async function waitForFile(path: string): Promise { - const deadline = Date.now() + SPAWN_TIMEOUT_MS; - while (!existsSync(path)) { - if (Date.now() > deadline) throw new Error(`${path} did not appear`); - await sleep(20); - } -} - -/** The exit code of `child`, or `timed out` when it runs past `boundMs`. */ -function exitWithin(child: ChildProcess, boundMs: number): Promise { - const { promise, resolve } = Promise.withResolvers(); - // The bound only caps a CLI that waits for the stub; a prompt exit resolves first. - const timer = setTimeout(() => resolve("timed out"), boundMs); - child.once("exit", (code, signal) => { - clearTimeout(timer); - resolve(code ?? `signal ${String(signal)}`); - }); - return promise; -} - -/** Start `docks-kit sync` on `channel` in a fresh home, with the waiting `omp` stub first on PATH. */ -function startSync(channel: "public" | "raw"): { - child: ChildProcess; - home: string; - pidFile: string; -} { - const nativeHost = { nativeHost: true } as const; - const stubs = makeStubDir({ omp: WAITING_OMP }, nativeHost); - const home = temporaryDir("sync-signals-home-"); - const pidFile = join(temporaryDir("sync-signals-pid-"), "omp.pid"); - stubPidFiles.push(pidFile); +/** Start `docks-kit sync` on `channel` for `home`, with the stubs of `stubs` first on PATH. */ +function launchSync( + channel: "public" | "raw", + home: string, + stubs: string, + marker: string, +): Launched { const child = spawn(BUN_RUNTIME, [cliEntry(), "sync"], { env: { HOME: home, @@ -99,13 +90,66 @@ function startSync(channel: "public" | "raw"): { TERM: "dumb", BUN_INSTALL_CACHE_DIR: temporaryDir("sync-signals-bun-cache-"), BUN_RUNTIME_TRANSPILER_CACHE_PATH: temporaryDir("sync-signals-bun-transpiler-"), - [PID_FILE]: pidFile, + [MARKER_FILE]: marker, ...(channel === "raw" ? { DOCKS_KIT_ENGINE: "native-raw" } : {}), }, stdio: ["ignore", "ignore", "ignore"], + // Its own process group, which the teardown can end as a whole. + detached: true, }); - children.push(child); - return { child, home, pidFile }; + if (child.pid !== undefined) groups.push(child.pid); + const { promise, resolve } = Promise.withResolvers(); + child.once("exit", (code, signal) => resolve({ kind: "exit", code, signal })); + child.once("error", (error) => resolve({ kind: "error", error })); + return { child, ended: promise }; +} + +/** A description of `ending` for a failure message. */ +function described(ending: Ending): string { + return ending.kind === "error" + ? `spawn error: ${ending.error.message}` + : `exit code ${String(ending.code)}, signal ${String(ending.signal)}`; +} + +/** The pid in `path` when it holds a positive integer, else undefined. */ +function markerPid(path: string): number | undefined { + if (!existsSync(path)) return undefined; + const text = readFileSync(path, "utf8").trim(); + if (!/^\d+$/.test(text)) return undefined; + const pid = Number(text); + return Number.isSafeInteger(pid) && pid > 0 ? pid : undefined; +} + +/** + * Wait until the stub writes a valid marker, so its sync waits in the plugin + * pass; fail at once when the CLI ends first, and after the spawn bound. The + * stub gives no other signal, so the wait polls the file. + */ +async function waitForStub(launched: Launched, marker: string): Promise { + let ending: Ending | undefined; + void launched.ended.then((value) => { + ending = value; + }); + const deadline = Date.now() + SPAWN_TIMEOUT_MS; + while (markerPid(marker) === undefined) { + if (ending !== undefined) { + throw new Error(`the sync ended before its omp stub ran: ${described(ending)}`); + } + if (Date.now() > deadline) throw new Error(`${marker} got no valid pid`); + await sleep(20); + } +} + +/** The ending of `launched`, or `timed out` when it runs past `boundMs`. */ +async function endingWithin(launched: Launched, boundMs: number): Promise { + const { promise, resolve } = Promise.withResolvers<"timed out">(); + // The bound only caps a CLI that waits for the stub; a prompt exit resolves first. + const timer = setTimeout(() => resolve("timed out"), boundMs); + try { + return await Promise.race([launched.ended, promise]); + } finally { + clearTimeout(timer); + } } /** True when a new run can take the sync lock of `home`; the probe gives it back at once. */ @@ -126,20 +170,38 @@ describe.skipIf(process.platform === "win32")( ["raw", "SIGINT", 130], ] as const) { it( - `exits ${code} on one ${signal} while an omp child of the ${channel} sync waits, and frees the sync lock`, + `exits ${code} on one ${signal} while an omp child of the ${channel} sync waits, and the next sync runs to its end`, async () => { - const { child, home, pidFile } = startSync(channel); - await waitForFile(pidFile); + const nativeHost = { nativeHost: true } as const; + const home = temporaryDir("sync-signals-home-"); + const marker = join(temporaryDir("sync-signals-marker-"), "omp.pid"); + const waiting = launchSync( + channel, + home, + makeStubDir({ omp: WAITING_OMP }, nativeHost), + marker, + ); + await waitForStub(waiting, marker); // The sync holds its lock while the plugin pass waits for the stub. expect(syncLockFree(home)).toBe(false); // The signal goes to the CLI process only, not to its process group. - child.kill(signal); + waiting.child.kill(signal); + + expect(await endingWithin(waiting, EXIT_BOUND_MS)).toEqual({ + kind: "exit", + code, + signal: null, + }); - expect(await exitWithin(child, EXIT_BOUND_MS)).toBe(code); - expect(syncLockFree(home)).toBe(true); + // The next sync of the same home takes the lock and runs to its end. + const next = launchSync(channel, home, makeStubDir({}, nativeHost), marker); + const ending = await endingWithin(next, SPAWN_TIMEOUT_MS); + expect(ending === "timed out" ? ending : described(ending)).toBe( + "exit code 0, signal null", + ); }, - SPAWN_TIMEOUT_MS, + SPAWN_TIMEOUT_MS * 2, ); } }, From 66f67205d756489e240c01d675266c4fb55f76ef Mon Sep 17 00:00:00 2001 From: Eduardo Marquez <55303379+DocksDocks@users.noreply.github.com> Date: Tue, 1 Dec 2026 21:00:01 -0300 Subject: [PATCH 06/11] Tie the signal test cleanup to live process groups Repairs of code-review round 3 of #294: - Teardown signals a saved group only while its leader CLI still runs, so a reused id is never hit. - The waiting stub omp exits when its parent is gone or after 90 s, so a cancelled worker leaves no stub that holds the CLI and its locks. - One case deadline; each phase gets only the time left. - The reentry fixture sets its one-shot guard before the nested acquire runs. Verified: bun x --no-install vitest run (unit, toggles, signals rows); bun run check:types; bun run check --- cli/test/unit/logger.test.ts | 17 +++--- cli/test/unit/syncSignals.test.ts | 87 ++++++++++++++++++++++--------- 2 files changed, 71 insertions(+), 33 deletions(-) diff --git a/cli/test/unit/logger.test.ts b/cli/test/unit/logger.test.ts index 06be8c35..e11e7ab4 100644 --- a/cli/test/unit/logger.test.ts +++ b/cli/test/unit/logger.test.ts @@ -326,22 +326,23 @@ describe("logger terminal lease", () => { }); it("refuses an acquire that a sink starts during the first draw with LeaseHeld", async () => { - const nested: Array> = []; + let reacquired = false; + let nested: Exit.Exit | undefined; const logger = makeLogger({ progress: () => { - if (nested.length === 0) { - nested.push(Effect.runSyncExit(Effect.scoped(logger.acquireTerminal("nested")))); - } + if (reacquired) return; + // Set before the nested acquire, so its own draw, if it got one, cannot recurse. + reacquired = true; + nested = Effect.runSyncExit(Effect.scoped(logger.acquireTerminal("nested"))); }, }); const outer = await Effect.runPromiseExit(Effect.scoped(logger.acquireTerminal("Syncing..."))); expect(Exit.isSuccess(outer)).toBe(true); - expect(nested).toHaveLength(1); - expect(Exit.isFailure(nested[0]!) && Cause.squash(nested[0]!.cause)).toMatchObject({ - _tag: "LeaseHeld", - }); + expect( + nested !== undefined && Exit.isFailure(nested) && Cause.squash(nested.cause), + ).toMatchObject({ _tag: "LeaseHeld" }); }); it("leaves no lease behind when its first draw throws", async () => { diff --git a/cli/test/unit/syncSignals.test.ts b/cli/test/unit/syncSignals.test.ts index 962d43be..c4618586 100644 --- a/cli/test/unit/syncSignals.test.ts +++ b/cli/test/unit/syncSignals.test.ts @@ -29,22 +29,45 @@ import { SPAWN_TIMEOUT_MS } from "../lib/spawnTimeout"; /** The environment key that names the marker file of the waiting `omp` stub. */ const MARKER_FILE = "SYNC_SIGNAL_STUB_MARKER"; +/** The hard maximum lifetime of the waiting stub, past the timeout of any case. */ +const STUB_MAX_LIFETIME_MS = 90_000; + /** * The `omp` stub: `plugin list`, the first `omp` child of a sync pass, writes - * its pid as a marker and then waits until it is killed, so the bridged - * plugin pass of the sync never settles. Every other command answers as the - * golden stub does. + * its pid as a marker and then waits, so the bridged plugin pass of the sync + * never settles. It exits by itself when the CLI that started it is gone and + * after a hard maximum lifetime, so a cancelled test run leaves no stub that + * keeps its CLI waiting. Every other command answers as the golden stub does. */ const WAITING_OMP = `if (args[0] === "plugin" && args[1] === "list") { // The body goes inside the switch of the generated runner, which takes no other static import. const { writeFileSync } = await import("node:fs") writeFileSync(process.env["${MARKER_FILE}"], String(process.pid)) - // A keep-alive, not a test delay: the stub waits until the teardown kills it. - setInterval(() => {}, 1000) + const parent = process.ppid + const started = Date.now() + const parentGone = () => { + if (process.ppid !== parent) return true + try { + process.kill(parent, 0) + return false + } catch { + return true + } + } + // A watch, not a test delay: the stub waits until its CLI ends or the lifetime passes. + setInterval(() => { + if (parentGone() || Date.now() - started > ${STUB_MAX_LIFETIME_MS}) process.exit(0) + }, 100) } else { ${ompStubBody()} }`; +/** The timeout of one case; its phases share one deadline inside it. */ +const CASE_TIMEOUT_MS = SPAWN_TIMEOUT_MS; + +/** The time a case keeps after its last phase, to report a phase that ran out. */ +const CASE_REPORT_MARGIN_MS = 1_000; + /** How long a signalled CLI may take to exit; a wait for the stub would never end. */ const EXIT_BOUND_MS = 10_000; @@ -59,14 +82,22 @@ interface Launched { readonly ended: Promise; } -/** The CLI process groups that a case started; the teardown ends each one. */ -const groups: Array = []; +/** A CLI process group that a case started, with whether its leader has ended. */ +interface Group { + readonly pid: number; + readonly leaderEnded: () => boolean; +} + +const groups: Array = []; afterEach(() => { - for (const pid of groups.splice(0)) { + for (const group of groups.splice(0)) { + // Only a live leader keeps its pid, and so the group id, from reuse. After + // it ends, the stub of its group exits by itself. + if (group.leaderEnded()) continue; try { // The negative pid names the group that the CLI leads, the `omp` stub included. - process.kill(-pid, "SIGKILL"); + process.kill(-group.pid, "SIGKILL"); } catch (error) { if ((error as NodeJS.ErrnoException).code !== "ESRCH") throw error; } @@ -97,10 +128,17 @@ function launchSync( // Its own process group, which the teardown can end as a whole. detached: true, }); - if (child.pid !== undefined) groups.push(child.pid); + let ended = false; const { promise, resolve } = Promise.withResolvers(); - child.once("exit", (code, signal) => resolve({ kind: "exit", code, signal })); - child.once("error", (error) => resolve({ kind: "error", error })); + child.once("exit", (code, signal) => { + ended = true; + resolve({ kind: "exit", code, signal }); + }); + child.once("error", (error) => { + ended = true; + resolve({ kind: "error", error }); + }); + if (child.pid !== undefined) groups.push({ pid: child.pid, leaderEnded: () => ended }); return { child, ended: promise }; } @@ -122,15 +160,14 @@ function markerPid(path: string): number | undefined { /** * Wait until the stub writes a valid marker, so its sync waits in the plugin - * pass; fail at once when the CLI ends first, and after the spawn bound. The - * stub gives no other signal, so the wait polls the file. + * pass; fail at once when the CLI ends first, and at `deadline`. The stub + * gives no other signal, so the wait polls the file. */ -async function waitForStub(launched: Launched, marker: string): Promise { +async function waitForStub(launched: Launched, marker: string, deadline: number): Promise { let ending: Ending | undefined; void launched.ended.then((value) => { ending = value; }); - const deadline = Date.now() + SPAWN_TIMEOUT_MS; while (markerPid(marker) === undefined) { if (ending !== undefined) { throw new Error(`the sync ended before its omp stub ran: ${described(ending)}`); @@ -144,7 +181,7 @@ async function waitForStub(launched: Launched, marker: string): Promise { async function endingWithin(launched: Launched, boundMs: number): Promise { const { promise, resolve } = Promise.withResolvers<"timed out">(); // The bound only caps a CLI that waits for the stub; a prompt exit resolves first. - const timer = setTimeout(() => resolve("timed out"), boundMs); + const timer = setTimeout(() => resolve("timed out"), Math.max(0, boundMs)); try { return await Promise.race([launched.ended, promise]); } finally { @@ -172,6 +209,8 @@ describe.skipIf(process.platform === "win32")( it( `exits ${code} on one ${signal} while an omp child of the ${channel} sync waits, and the next sync runs to its end`, async () => { + // One deadline for every phase of the case, inside the case timeout. + const deadline = Date.now() + CASE_TIMEOUT_MS - CASE_REPORT_MARGIN_MS; const nativeHost = { nativeHost: true } as const; const home = temporaryDir("sync-signals-home-"); const marker = join(temporaryDir("sync-signals-marker-"), "omp.pid"); @@ -181,27 +220,25 @@ describe.skipIf(process.platform === "win32")( makeStubDir({ omp: WAITING_OMP }, nativeHost), marker, ); - await waitForStub(waiting, marker); + await waitForStub(waiting, marker, deadline); // The sync holds its lock while the plugin pass waits for the stub. expect(syncLockFree(home)).toBe(false); // The signal goes to the CLI process only, not to its process group. waiting.child.kill(signal); - expect(await endingWithin(waiting, EXIT_BOUND_MS)).toEqual({ - kind: "exit", - code, - signal: null, - }); + expect( + await endingWithin(waiting, Math.min(EXIT_BOUND_MS, deadline - Date.now())), + ).toEqual({ kind: "exit", code, signal: null }); // The next sync of the same home takes the lock and runs to its end. const next = launchSync(channel, home, makeStubDir({}, nativeHost), marker); - const ending = await endingWithin(next, SPAWN_TIMEOUT_MS); + const ending = await endingWithin(next, deadline - Date.now()); expect(ending === "timed out" ? ending : described(ending)).toBe( "exit code 0, signal null", ); }, - SPAWN_TIMEOUT_MS * 2, + CASE_TIMEOUT_MS, ); } }, From 4109f2528173a5f6dd33bca8d0541b75ec14b92a Mon Sep 17 00:00:00 2001 From: Eduardo Marquez <55303379+DocksDocks@users.noreply.github.com> Date: Tue, 1 Dec 2026 21:12:25 -0300 Subject: [PATCH 07/11] Supervise the signal test CLI and cover the listener order Repairs of code-review round 4 of #294: - A fixture supervisor leads its own process group, runs the CLI as its child, relays its pid and exit, and on control-pipe close stops the CLI and then its group; the worker signals no saved id. - The stub captures its parent and arms its timers before readiness; a relative 90 s limit exits 1. - One performance.now() case deadline. - A spawned public run under BunRuntime.runMain with a failing logger finalizer, waiting at an interruptible lock sleep, exits 130 on one signal; it exits 1 when the listeners are appended. - engineFailureDetail prints the message that LegacyStepFailed and KitHomeInvalid captured. Verified: bun x --no-install vitest run (unit, toggles, signals rows, skillMetadata.test.ts); bun run check:types; bun run check --- .agents/skills/engine-native-context/SKILL.md | 4 +- .../sync-orchestration-context/SKILL.md | 2 +- cli/src/engine.ts | 15 +- cli/test/lib/signalEngineEntry.ts | 53 ++++ cli/test/lib/signalSupervisor.ts | 52 ++++ cli/test/unit/engine.test.ts | 23 +- cli/test/unit/syncSignals.test.ts | 246 ++++++++++++------ 7 files changed, 301 insertions(+), 94 deletions(-) create mode 100644 cli/test/lib/signalEngineEntry.ts create mode 100644 cli/test/lib/signalSupervisor.ts diff --git a/.agents/skills/engine-native-context/SKILL.md b/.agents/skills/engine-native-context/SKILL.md index fe4180a8..30c6191a 100644 --- a/.agents/skills/engine-native-context/SKILL.md +++ b/.agents/skills/engine-native-context/SKILL.md @@ -8,7 +8,7 @@ metadata: - path: cli/src/engine-native/index.ts lines: "1-82" - path: cli/src/engine.ts - lines: "1-98" + lines: "1-103" - path: cli/src/main.ts lines: "1-78" - path: cli/src/engine-native/exec.ts @@ -20,7 +20,7 @@ metadata: - path: cli/src/engine-native/os/targets.ts lines: "1-64" - path: cli/test/unit/engine.test.ts - lines: "1-183" + lines: "1-204" - path: cli/test/golden-dryrun.ts lines: "1-199" - path: cli/test/golden-mutation.ts diff --git a/.agents/skills/sync-orchestration-context/SKILL.md b/.agents/skills/sync-orchestration-context/SKILL.md index 80da617e..aab8060d 100644 --- a/.agents/skills/sync-orchestration-context/SKILL.md +++ b/.agents/skills/sync-orchestration-context/SKILL.md @@ -18,7 +18,7 @@ metadata: - path: cli/src/argvSurface.ts lines: "1-351" - path: cli/src/engine.ts - lines: "1-98" + lines: "1-103" - path: cli/src/kitHome.ts lines: "1-99" - path: cli/src/payload.ts diff --git a/cli/src/engine.ts b/cli/src/engine.ts index 112db743..a46ab374 100644 --- a/cli/src/engine.ts +++ b/cli/src/engine.ts @@ -21,15 +21,20 @@ const requireSupportedHost = () => { ); }; -/** The value that a failed run threw or rejected with, which its message comes from. */ -const originalFailure = (error: EngineFailure): unknown => { +/** + * The text of a failed run. A bridged step and the kit home keep the message + * that they captured when they failed, so the cause is not read again; a lock + * failure gives the message of its Node error, and a held lease its own. + */ +const failureDetail = (error: EngineFailure): string => { switch (error._tag) { case "LegacyStepFailed": case "KitHomeInvalid": + return error.message; case "LockAcquireError": - return error.cause; + return failureText(error.cause); case "LeaseHeld": - return error; + return failureText(error); } }; @@ -43,7 +48,7 @@ const originalFailure = (error: EngineFailure): unknown => { export const engineFailureDetail = (cause: Cause.Cause): string => { const last = cause.reasons.filter((reason) => !Cause.isInterruptReason(reason)).at(-1); if (last === undefined) return failureText(undefined); - return failureText(Cause.isFailReason(last) ? originalFailure(last.error) : last.defect); + return Cause.isFailReason(last) ? failureDetail(last.error) : failureText(last.defect); }; /** diff --git a/cli/test/lib/signalEngineEntry.ts b/cli/test/lib/signalEngineEntry.ts new file mode 100644 index 00000000..f42f1271 --- /dev/null +++ b/cli/test/lib/signalEngineEntry.ts @@ -0,0 +1,53 @@ +/** + * Test entry for the listener-order signal case: it runs the public engine + * seam `engine.ts engine` with the arguments of the process under + * `BunRuntime.runMain`, as `main.ts` does, with two test layers: + * + * - a `LoggerService` layer whose scoped finalizer fails, so an interrupt + * that ends the run in-process exits 1, not 130; + * - a `Clock` whose first sleep writes the file that + * `SIGNAL_ENTRY_SLEEP_MARKER` names, so the test knows that the run waits + * at an interruptible point (the poll sleep of a held lock). + */ +import { writeFileSync } from "node:fs"; +import { BunRuntime, BunServices } from "@effect/platform-bun"; +import { Clock, Effect, Layer } from "effect"; + +import { engine } from "../../src/engine"; +import { makeEngineServices } from "../../src/engine-native/services"; +import { DependencyManagerService, LoggerService, PlatformService } from "../../src/services"; + +const services = makeEngineServices(); +const marker = process.env["SIGNAL_ENTRY_SLEEP_MARKER"] ?? ""; +let marked = false; + +const liveClock = Clock.Clock.defaultValue(); +const markingClock: Clock.Clock = Object.assign(Object.create(liveClock) as Clock.Clock, { + sleep: (duration: Parameters[0]) => { + if (!marked && marker !== "") { + marked = true; + writeFileSync(marker, String(process.pid)); + } + return liveClock.sleep(duration); + }, +}); + +const failingLogger = Layer.effect( + LoggerService, + Effect.acquireRelease(Effect.succeed(services.logger), () => + Effect.die(new Error("test logger finalizer failed")), + ), +); + +engine(process.argv.slice(2)).pipe( + Effect.provideService(Clock.Clock, markingClock), + Effect.provide( + Layer.mergeAll( + BunServices.layer, + failingLogger, + Layer.succeed(DependencyManagerService, services.deps), + Layer.succeed(PlatformService, services.platform), + ), + ), + BunRuntime.runMain, +); diff --git a/cli/test/lib/signalSupervisor.ts b/cli/test/lib/signalSupervisor.ts new file mode 100644 index 00000000..808d7e92 --- /dev/null +++ b/cli/test/lib/signalSupervisor.ts @@ -0,0 +1,52 @@ +/** + * Fixture supervisor for the spawned signal cases (POSIX only): run with Bun + * as `bun signalSupervisor.ts [args...]`, detached, so it leads its + * own process group, with a stdin pipe as its control channel. + * + * It starts `` as its child in that group with its own environment + * and writes one JSON line per event to stdout: `{"pid":}` once the child + * runs, then `{"exit":{"code":,"signal":}}` when it ends. The + * supervisor stays alive after that, so the group keeps its leader and its id. + * + * When stdin ends (the test closes the pipe, or the test worker dies for any + * reason), it stops the child with SIGKILL to the child pid, then ends its + * whole group, itself and every grandchild included, with SIGKILL to group 0. + * The test never signals a group id. + */ +import { spawn } from "node:child_process"; + +const [command, ...args] = process.argv.slice(2); +if (command === undefined) { + process.stderr.write("usage: bun signalSupervisor.ts [args...]\n"); + process.exit(2); +} + +const child = spawn(command, args, { env: process.env, stdio: "ignore" }); +let childEnded = false; + +child.once("spawn", () => { + process.stdout.write(`${JSON.stringify({ pid: child.pid })}\n`); +}); +child.once("exit", (code, signal) => { + childEnded = true; + process.stdout.write(`${JSON.stringify({ exit: { code, signal } })}\n`); +}); +child.once("error", (error) => { + childEnded = true; + process.stdout.write(`${JSON.stringify({ error: error.message })}\n`); +}); + +const stopAll = (): void => { + if (!childEnded && child.pid !== undefined) { + try { + child.kill("SIGKILL"); + } catch { + // The child ended between the check and the kill. + } + } + // Group 0 is the group of this supervisor: the child, its children, and itself. + process.kill(0, "SIGKILL"); +}; +process.stdin.once("end", stopAll); +process.stdin.once("close", stopAll); +process.stdin.resume(); diff --git a/cli/test/unit/engine.test.ts b/cli/test/unit/engine.test.ts index a420f989..5074a520 100644 --- a/cli/test/unit/engine.test.ts +++ b/cli/test/unit/engine.test.ts @@ -11,7 +11,7 @@ const mocks = vi.hoisted(() => ({ runEngineNative: vi.fn() })); vi.mock("../../src/engine-native", () => ({ runEngineNative: mocks.runEngineNative })); import { engine } from "../../src/engine"; -import { LegacyStepFailed } from "../../src/engine-native/bridge"; +import { bridgePromise, LegacyStepFailed } from "../../src/engine-native/bridge"; import { makeDependencyManager, makeEngineServices, @@ -113,6 +113,27 @@ describe("EngineNative Effect seam", () => { }); }); + it("prints the message that a bridged step captured, without reading its cause again", async () => { + // A message getter that answers once and then throws. + let reads = 0; + const cause = new Error("unused"); + Object.defineProperty(cause, "message", { + get: () => { + reads += 1; + if (reads > 1) throw new Error("message read twice"); + return "plugin pass failed"; + }, + }); + mocks.runEngineNative.mockReturnValue( + bridgePromise("syncPlugins", () => Promise.reject(cause)).pipe(Effect.as(0)), + ); + + await expect(runEngine(["sync"])).rejects.toMatchObject({ + _tag: "UserError", + message: "engine operation 'sync' failed: plugin pass failed", + }); + }); + it("maps a defect of the run, such as a stream write error, to the same CLI failure", async () => { mocks.runEngineNative.mockReturnValue(Effect.die(new Error("write EIO"))); diff --git a/cli/test/unit/syncSignals.test.ts b/cli/test/unit/syncSignals.test.ts index c4618586..51738967 100644 --- a/cli/test/unit/syncSignals.test.ts +++ b/cli/test/unit/syncSignals.test.ts @@ -6,8 +6,10 @@ * SIGINT on the raw channel. The OS releases the sync lock with the process, * so the next sync of the same home runs to its end. * - * Each CLI runs in its own process group, and the `omp` stub that it starts - * stays in that group, so the teardown ends the whole group by the CLI pid. + * Each CLI runs under `cli/test/lib/signalSupervisor.ts`, which leads the + * process group of the CLI and its children. The signal under test goes to + * the CLI pid only; the teardown closes the control pipe of the supervisor, + * which then ends its own group. The test never signals a group id. */ import { spawn, type ChildProcess } from "node:child_process"; import { existsSync, readFileSync } from "node:fs"; @@ -15,10 +17,11 @@ import { delimiter, join } from "node:path"; import { setTimeout as sleep } from "node:timers/promises"; import { afterAll, afterEach, describe, expect, it } from "vitest"; -import { releaseKitLock, tryAcquireKitLock } from "../../src/engine-native/kitLock"; +import { releaseKitLock, tryAcquireKitLock, type KitLock } from "../../src/engine-native/kitLock"; import { syncLockPath } from "../../src/engine-native/scratch"; import { BUN_RUNTIME, cliEntry } from "../lib/cliEntry"; import { + REPO_DIR, cleanupTemporaryDirs, makeStubDir, ompStubBody, @@ -26,6 +29,9 @@ import { } from "../lib/goldenResources"; import { SPAWN_TIMEOUT_MS } from "../lib/spawnTimeout"; +const SUPERVISOR = join(REPO_DIR, "cli", "test", "lib", "signalSupervisor.ts"); +const ENGINE_ENTRY = join(REPO_DIR, "cli", "test", "lib", "signalEngineEntry.ts"); + /** The environment key that names the marker file of the waiting `omp` stub. */ const MARKER_FILE = "SYNC_SIGNAL_STUB_MARKER"; @@ -33,18 +39,17 @@ const MARKER_FILE = "SYNC_SIGNAL_STUB_MARKER"; const STUB_MAX_LIFETIME_MS = 90_000; /** - * The `omp` stub: `plugin list`, the first `omp` child of a sync pass, writes - * its pid as a marker and then waits, so the bridged plugin pass of the sync - * never settles. It exits by itself when the CLI that started it is gone and - * after a hard maximum lifetime, so a cancelled test run leaves no stub that - * keeps its CLI waiting. Every other command answers as the golden stub does. + * The `omp` stub: `plugin list`, the first `omp` child of a sync pass, waits, + * so the bridged plugin pass of the sync never settles. It records its parent + * and arms its watch first, then writes its pid as the readiness marker. It + * exits when the CLI that started it is gone, and fails after a hard maximum + * lifetime, so the plugin pass then reads no inventory and only warns. Every + * other command answers as the golden stub does. */ const WAITING_OMP = `if (args[0] === "plugin" && args[1] === "list") { // The body goes inside the switch of the generated runner, which takes no other static import. const { writeFileSync } = await import("node:fs") - writeFileSync(process.env["${MARKER_FILE}"], String(process.pid)) const parent = process.ppid - const started = Date.now() const parentGone = () => { if (process.ppid !== parent) return true try { @@ -54,10 +59,12 @@ const WAITING_OMP = `if (args[0] === "plugin" && args[1] === "list") { return true } } - // A watch, not a test delay: the stub waits until its CLI ends or the lifetime passes. + // A watch, not a test delay: the stub waits until its CLI ends. setInterval(() => { - if (parentGone() || Date.now() - started > ${STUB_MAX_LIFETIME_MS}) process.exit(0) + if (parentGone()) process.exit(0) }, 100) + setTimeout(() => process.exit(1), ${STUB_MAX_LIFETIME_MS}) + writeFileSync(process.env["${MARKER_FILE}"], String(process.pid)) } else { ${ompStubBody()} }`; @@ -71,81 +78,111 @@ const CASE_REPORT_MARGIN_MS = 1_000; /** How long a signalled CLI may take to exit; a wait for the stub would never end. */ const EXIT_BOUND_MS = 10_000; -/** The way a launched CLI ended: its exit code or signal, or the spawn error. */ +/** The way a supervised CLI ended: its exit code or signal, or the error that ended its run. */ type Ending = | { readonly kind: "exit"; readonly code: number | null; readonly signal: string | null } - | { readonly kind: "error"; readonly error: Error }; + | { readonly kind: "error"; readonly error: string }; -interface Launched { - readonly child: ChildProcess; - /** Settles once, from launch, with the first `exit` or `error` of the child. */ +interface Supervised { + /** The pid of the CLI, once the supervisor started it. */ + readonly cliPid: Promise; + /** Settles once, from launch, with the end of the CLI or of its supervisor. */ readonly ended: Promise; } -/** A CLI process group that a case started, with whether its leader has ended. */ -interface Group { - readonly pid: number; - readonly leaderEnded: () => boolean; -} - -const groups: Array = []; +/** The supervisors that a case started; the teardown closes their control pipes. */ +const supervisors: Array = []; -afterEach(() => { - for (const group of groups.splice(0)) { - // Only a live leader keeps its pid, and so the group id, from reuse. After - // it ends, the stub of its group exits by itself. - if (group.leaderEnded()) continue; - try { - // The negative pid names the group that the CLI leads, the `omp` stub included. - process.kill(-group.pid, "SIGKILL"); - } catch (error) { - if ((error as NodeJS.ErrnoException).code !== "ESRCH") throw error; - } - } +afterEach(async () => { + const closing = supervisors.splice(0).map((supervisor) => { + const { promise, resolve } = Promise.withResolvers(); + if (supervisor.exitCode !== null || supervisor.signalCode !== null) resolve(); + else supervisor.once("exit", () => resolve()); + // End of input tells the supervisor to stop the CLI and end its group. + supervisor.stdin?.end(); + return promise; + }); + await Promise.all(closing); }); afterAll(cleanupTemporaryDirs); -/** Start `docks-kit sync` on `channel` for `home`, with the stubs of `stubs` first on PATH. */ +/** Run `command` under a new supervisor with `env`, and follow the events that it relays. */ +function supervise(command: ReadonlyArray, env: Record): Supervised { + const supervisor = spawn(BUN_RUNTIME, [SUPERVISOR, ...command], { + env, + stdio: ["pipe", "pipe", "ignore"], + // The supervisor leads its own process group, which holds the CLI and its children. + detached: true, + }); + supervisors.push(supervisor); + const pid = Promise.withResolvers(); + const ended = Promise.withResolvers(); + let buffered = ""; + supervisor.stdout?.setEncoding("utf8"); + supervisor.stdout?.on("data", (chunk: string) => { + buffered += chunk; + for (let newline = buffered.indexOf("\n"); newline >= 0; newline = buffered.indexOf("\n")) { + const event = JSON.parse(buffered.slice(0, newline)) as { + pid?: number; + exit?: { code: number | null; signal: string | null }; + error?: string; + }; + buffered = buffered.slice(newline + 1); + if (event.pid !== undefined) pid.resolve(event.pid); + if (event.exit !== undefined) ended.resolve({ kind: "exit", ...event.exit }); + if (event.error !== undefined) ended.resolve({ kind: "error", error: event.error }); + } + }); + supervisor.once("error", (error) => ended.resolve({ kind: "error", error: error.message })); + supervisor.once("exit", (code, signal) => { + const error = `the supervisor ended (code ${String(code)}, signal ${String(signal)})`; + ended.resolve({ kind: "error", error }); + pid.reject(new Error(error)); + }); + // A case that never reads the pid must not report its rejection as unhandled. + pid.promise.catch(() => {}); + return { cliPid: pid.promise, ended: ended.promise }; +} + +/** The environment of a sync in `home` with `stubs` first on PATH. */ +function syncEnv( + home: string, + stubs: string, + extra: Record, +): Record { + return { + HOME: home, + USERPROFILE: home, + PATH: `${stubs}${delimiter}${process.env["PATH"] ?? ""}`, + LC_ALL: "C", + TERM: "dumb", + BUN_INSTALL_CACHE_DIR: temporaryDir("sync-signals-bun-cache-"), + BUN_RUNTIME_TRANSPILER_CACHE_PATH: temporaryDir("sync-signals-bun-transpiler-"), + ...extra, + }; +} + +/** Start `docks-kit sync` on `channel` for `home` under a supervisor. */ function launchSync( channel: "public" | "raw", home: string, stubs: string, marker: string, -): Launched { - const child = spawn(BUN_RUNTIME, [cliEntry(), "sync"], { - env: { - HOME: home, - USERPROFILE: home, - PATH: `${stubs}${delimiter}${process.env["PATH"] ?? ""}`, - LC_ALL: "C", - TERM: "dumb", - BUN_INSTALL_CACHE_DIR: temporaryDir("sync-signals-bun-cache-"), - BUN_RUNTIME_TRANSPILER_CACHE_PATH: temporaryDir("sync-signals-bun-transpiler-"), +): Supervised { + return supervise( + [BUN_RUNTIME, cliEntry(), "sync"], + syncEnv(home, stubs, { [MARKER_FILE]: marker, ...(channel === "raw" ? { DOCKS_KIT_ENGINE: "native-raw" } : {}), - }, - stdio: ["ignore", "ignore", "ignore"], - // Its own process group, which the teardown can end as a whole. - detached: true, - }); - let ended = false; - const { promise, resolve } = Promise.withResolvers(); - child.once("exit", (code, signal) => { - ended = true; - resolve({ kind: "exit", code, signal }); - }); - child.once("error", (error) => { - ended = true; - resolve({ kind: "error", error }); - }); - if (child.pid !== undefined) groups.push({ pid: child.pid, leaderEnded: () => ended }); - return { child, ended: promise }; + }), + ); } /** A description of `ending` for a failure message. */ -function described(ending: Ending): string { +function described(ending: Ending | "timed out"): string { + if (ending === "timed out") return ending; return ending.kind === "error" - ? `spawn error: ${ending.error.message}` + ? `error: ${ending.error}` : `exit code ${String(ending.code)}, signal ${String(ending.signal)}`; } @@ -159,31 +196,31 @@ function markerPid(path: string): number | undefined { } /** - * Wait until the stub writes a valid marker, so its sync waits in the plugin - * pass; fail at once when the CLI ends first, and at `deadline`. The stub - * gives no other signal, so the wait polls the file. + * Wait until `marker` holds a valid pid; fail at once when the CLI ends + * first, and at `deadline` (`performance.now()` time). The marker is the only + * readiness signal, so the wait polls the file. */ -async function waitForStub(launched: Launched, marker: string, deadline: number): Promise { +async function waitForMarker(run: Supervised, marker: string, deadline: number): Promise { let ending: Ending | undefined; - void launched.ended.then((value) => { + void run.ended.then((value) => { ending = value; }); while (markerPid(marker) === undefined) { if (ending !== undefined) { - throw new Error(`the sync ended before its omp stub ran: ${described(ending)}`); + throw new Error(`the run ended before ${marker} appeared: ${described(ending)}`); } - if (Date.now() > deadline) throw new Error(`${marker} got no valid pid`); + if (performance.now() > deadline) throw new Error(`${marker} got no valid pid`); await sleep(20); } } -/** The ending of `launched`, or `timed out` when it runs past `boundMs`. */ -async function endingWithin(launched: Launched, boundMs: number): Promise { +/** The ending of `run`, or `timed out` when it runs past `boundMs`. */ +async function endingWithin(run: Supervised, boundMs: number): Promise { const { promise, resolve } = Promise.withResolvers<"timed out">(); - // The bound only caps a CLI that waits for the stub; a prompt exit resolves first. + // The bound only caps a CLI that waits; a prompt exit resolves first. const timer = setTimeout(() => resolve("timed out"), Math.max(0, boundMs)); try { - return await Promise.race([launched.ended, promise]); + return await Promise.race([run.ended, promise]); } finally { clearTimeout(timer); } @@ -210,7 +247,7 @@ describe.skipIf(process.platform === "win32")( `exits ${code} on one ${signal} while an omp child of the ${channel} sync waits, and the next sync runs to its end`, async () => { // One deadline for every phase of the case, inside the case timeout. - const deadline = Date.now() + CASE_TIMEOUT_MS - CASE_REPORT_MARGIN_MS; + const deadline = performance.now() + CASE_TIMEOUT_MS - CASE_REPORT_MARGIN_MS; const nativeHost = { nativeHost: true } as const; const home = temporaryDir("sync-signals-home-"); const marker = join(temporaryDir("sync-signals-marker-"), "omp.pid"); @@ -220,26 +257,65 @@ describe.skipIf(process.platform === "win32")( makeStubDir({ omp: WAITING_OMP }, nativeHost), marker, ); - await waitForStub(waiting, marker, deadline); + await waitForMarker(waiting, marker, deadline); // The sync holds its lock while the plugin pass waits for the stub. expect(syncLockFree(home)).toBe(false); - // The signal goes to the CLI process only, not to its process group. - waiting.child.kill(signal); + // The signal goes to the CLI pid only, while the CLI runs. + process.kill(await waiting.cliPid, signal); expect( - await endingWithin(waiting, Math.min(EXIT_BOUND_MS, deadline - Date.now())), - ).toEqual({ kind: "exit", code, signal: null }); + described( + await endingWithin(waiting, Math.min(EXIT_BOUND_MS, deadline - performance.now())), + ), + ).toBe(`exit code ${code}, signal null`); // The next sync of the same home takes the lock and runs to its end. const next = launchSync(channel, home, makeStubDir({}, nativeHost), marker); - const ending = await endingWithin(next, deadline - Date.now()); - expect(ending === "timed out" ? ending : described(ending)).toBe( + expect(described(await endingWithin(next, deadline - performance.now()))).toBe( "exit code 0, signal null", ); }, CASE_TIMEOUT_MS, ); } + + for (const signal of ["SIGTERM", "SIGINT"] as const) { + it( + `exits 130 on one ${signal} before runMain interrupts a public run whose logger finalizer fails`, + async () => { + const deadline = performance.now() + CASE_TIMEOUT_MS - CASE_REPORT_MARGIN_MS; + const home = temporaryDir("sync-signals-home-"); + const marker = join(temporaryDir("sync-signals-marker-"), "sleep.pid"); + // A held sync lock keeps the run at the interruptible poll sleep. + const held: KitLock | undefined = tryAcquireKitLock(syncLockPath(home), { + privateDirectory: true, + }); + if (held === undefined) throw new Error(`expected a free lock in ${home}`); + try { + const run = supervise( + [BUN_RUNTIME, ENGINE_ENTRY, "sync"], + syncEnv(home, makeStubDir({}, { nativeHost: true }), { + DOCKS_KIT_SYNC_LOCK_WAIT_MS: String(CASE_TIMEOUT_MS), + SIGNAL_ENTRY_SLEEP_MARKER: marker, + }), + ); + await waitForMarker(run, marker, deadline); + + process.kill(await run.cliPid, signal); + + // An interrupt first would end the run through the failing finalizer, with exit 1. + expect( + described( + await endingWithin(run, Math.min(EXIT_BOUND_MS, deadline - performance.now())), + ), + ).toBe("exit code 130, signal null"); + } finally { + releaseKitLock(held); + } + }, + CASE_TIMEOUT_MS, + ); + } }, ); From c5819f57d935396c483fc32eb117740cf04f5142 Mon Sep 17 00:00:00 2001 From: Eduardo Marquez <55303379+DocksDocks@users.noreply.github.com> Date: Tue, 1 Dec 2026 21:30:16 -0300 Subject: [PATCH 08/11] Raise the test signal from inside the process tree under test Repairs of code-review round 5 of #294 (stall rule: new approach for process identity): - The waiting stub signals its own verified parent CLI, and the listener-order entry signals itself, on a request file; the worker and the supervisor send no signal to any pid. - The supervisor checks that it leads its group, kills only that group, and ends it on a failed report write or a stdout error as on stdin EOF. - Fixture PATH holds only the stubs and Bun; graceful worker cancellation stops the supervisors before the temporary folders go (goldenResources registerBeforeTemporaryDirRemoval). - Supervisor completion comes from close, which also follows a failed spawn. Verified: bun x --no-install vitest run (unit, toggles, signals rows, skillMetadata.test.ts); bun run check:types; bun run lint; bun run check --- cli/test/lib/goldenResources.ts | 55 ++++++-- cli/test/lib/signalEngineEntry.ts | 35 +++-- cli/test/lib/signalSupervisor.ts | 82 ++++++------ cli/test/unit/syncSignals.test.ts | 207 ++++++++++++++++++------------ 4 files changed, 242 insertions(+), 137 deletions(-) diff --git a/cli/test/lib/goldenResources.ts b/cli/test/lib/goldenResources.ts index 4d98962f..4d7fcb66 100644 --- a/cli/test/lib/goldenResources.ts +++ b/cli/test/lib/goldenResources.ts @@ -255,22 +255,53 @@ function reportTemporaryDirCleanup(): void { for (const problem of removeTemporaryDirs()) console.error(problem); } -function handleSigint(): void { - try { - reportTemporaryDirCleanup(); - } finally { - process.off("SIGINT", handleSigint); - process.kill(process.pid, "SIGINT"); +/** + * Work that a test file registers to run on the signal path before the + * temporary folders go, such as stopping the processes that still use them. + */ +const BEFORE_REMOVAL = new Set<() => Promise>(); + +/** How long the signal path waits for the registered work before it removes the folders. */ +const BEFORE_REMOVAL_BOUND_MS = 2_000; + +/** + * Register `stop` to run, and be awaited for up to two seconds, when a + * SIGINT or SIGTERM ends the worker, before its temporary folders are removed. + */ +export function registerBeforeTemporaryDirRemoval(stop: () => Promise): void { + BEFORE_REMOVAL.add(stop); +} + +/** Remove the temporary folders, then raise `signal` again without this handler. */ +function endOnSignal(signal: "SIGINT" | "SIGTERM", handler: () => void): void { + const finish = (): void => { + try { + reportTemporaryDirCleanup(); + } finally { + process.off(signal, handler); + process.kill(process.pid, signal); + } + }; + if (BEFORE_REMOVAL.size === 0) { + finish(); + return; } + const { promise: bound, resolve: endWait } = Promise.withResolvers(); + const timer = setTimeout(endWait, BEFORE_REMOVAL_BOUND_MS); + void Promise.race([Promise.allSettled([...BEFORE_REMOVAL].map((stop) => stop())), bound]).then( + () => { + clearTimeout(timer); + finish(); + }, + ); +} + +function handleSigint(): void { + endOnSignal("SIGINT", handleSigint); } function handleSigterm(): void { - try { - reportTemporaryDirCleanup(); - } finally { - process.off("SIGTERM", handleSigterm); - process.kill(process.pid, "SIGTERM"); - } + endOnSignal("SIGTERM", handleSigterm); } sweepStaleTemporaryDirs(); diff --git a/cli/test/lib/signalEngineEntry.ts b/cli/test/lib/signalEngineEntry.ts index f42f1271..285d70f8 100644 --- a/cli/test/lib/signalEngineEntry.ts +++ b/cli/test/lib/signalEngineEntry.ts @@ -5,11 +5,15 @@ * * - a `LoggerService` layer whose scoped finalizer fails, so an interrupt * that ends the run in-process exits 1, not 130; - * - a `Clock` whose first sleep writes the file that - * `SIGNAL_ENTRY_SLEEP_MARKER` names, so the test knows that the run waits - * at an interruptible point (the poll sleep of a held lock). + * - a `Clock` whose sleeps drive the case: the first sleep (the poll sleep + * of a held lock, an interruptible point) writes the file that + * `SIGNAL_ENTRY_SLEEP_MARKER` names; a later sleep, once the file that + * `SIGNAL_REQUEST_FILE` names holds `SIGTERM` or `SIGINT`, raises that + * signal on this process once. + * + * The process signals only itself, so no pid can name another process. */ -import { writeFileSync } from "node:fs"; +import { existsSync, readFileSync, writeFileSync } from "node:fs"; import { BunRuntime, BunServices } from "@effect/platform-bun"; import { Clock, Effect, Layer } from "effect"; @@ -19,14 +23,29 @@ import { DependencyManagerService, LoggerService, PlatformService } from "../../ const services = makeEngineServices(); const marker = process.env["SIGNAL_ENTRY_SLEEP_MARKER"] ?? ""; +const request = process.env["SIGNAL_REQUEST_FILE"] ?? ""; let marked = false; +let raised = false; + +/** The signal that the request file asks for, if it holds one. */ +const requestedSignal = (): "SIGTERM" | "SIGINT" | undefined => { + if (request === "" || !existsSync(request)) return undefined; + const signal = readFileSync(request, "utf8").trim(); + return signal === "SIGTERM" || signal === "SIGINT" ? signal : undefined; +}; const liveClock = Clock.Clock.defaultValue(); -const markingClock: Clock.Clock = Object.assign(Object.create(liveClock) as Clock.Clock, { +const signallingClock: Clock.Clock = Object.assign(Object.create(liveClock) as Clock.Clock, { sleep: (duration: Parameters[0]) => { - if (!marked && marker !== "") { + if (!marked) { marked = true; - writeFileSync(marker, String(process.pid)); + if (marker !== "") writeFileSync(marker, String(process.pid)); + } else if (!raised) { + const signal = requestedSignal(); + if (signal !== undefined) { + raised = true; + process.kill(process.pid, signal); + } } return liveClock.sleep(duration); }, @@ -40,7 +59,7 @@ const failingLogger = Layer.effect( ); engine(process.argv.slice(2)).pipe( - Effect.provideService(Clock.Clock, markingClock), + Effect.provideService(Clock.Clock, signallingClock), Effect.provide( Layer.mergeAll( BunServices.layer, diff --git a/cli/test/lib/signalSupervisor.ts b/cli/test/lib/signalSupervisor.ts index 808d7e92..c6d8fec2 100644 --- a/cli/test/lib/signalSupervisor.ts +++ b/cli/test/lib/signalSupervisor.ts @@ -1,52 +1,62 @@ /** - * Fixture supervisor for the spawned signal cases (POSIX only): run with Bun - * as `bun signalSupervisor.ts [args...]`, detached, so it leads its - * own process group, with a stdin pipe as its control channel. + * Fixture supervisor for the spawned signal cases (POSIX only). Run it with + * Bun as `bun signalSupervisor.ts [args...]`, spawned with + * `detached: true` so that it leads a new process group, and with a stdin + * pipe as its control channel. It refuses to run when it does not lead its + * own group, so its cleanup can never reach another group. * - * It starts `` as its child in that group with its own environment - * and writes one JSON line per event to stdout: `{"pid":}` once the child - * runs, then `{"exit":{"code":,"signal":}}` when it ends. The - * supervisor stays alive after that, so the group keeps its leader and its id. + * It starts `` as its child in that group, with its own environment, + * and writes one JSON line to stdout when the child ends: + * `{"exit":{"code":,"signal":}}`, or `{"error":""}` + * when the child cannot start. It stays alive after that, so its group keeps + * its leader. * * When stdin ends (the test closes the pipe, or the test worker dies for any - * reason), it stops the child with SIGKILL to the child pid, then ends its - * whole group, itself and every grandchild included, with SIGKILL to group 0. - * The test never signals a group id. + * reason), and when it cannot write a report to stdout, it ends its whole + * group, the child, the grandchildren, and itself, with SIGKILL to group 0. + * It signals no single pid. */ -import { spawn } from "node:child_process"; +import { spawn, spawnSync } from "node:child_process"; + +const USAGE = + "usage: bun signalSupervisor.ts [args...]; spawn it detached (its own process group) with a stdin pipe\n"; const [command, ...args] = process.argv.slice(2); if (command === undefined) { - process.stderr.write("usage: bun signalSupervisor.ts [args...]\n"); + process.stderr.write(USAGE); process.exit(2); } -const child = spawn(command, args, { env: process.env, stdio: "ignore" }); -let childEnded = false; +// The supervisor must lead its group: group 0 is then this private group. +const pgid = spawnSync("/bin/ps", ["-o", "pgid=", "-p", String(process.pid)], { + encoding: "utf8", +}).stdout?.trim(); +if (pgid !== String(process.pid)) { + process.stderr.write( + `signalSupervisor: process group ${String(pgid)} is not led by pid ${process.pid}\n${USAGE}`, + ); + process.exit(2); +} -child.once("spawn", () => { - process.stdout.write(`${JSON.stringify({ pid: child.pid })}\n`); -}); -child.once("exit", (code, signal) => { - childEnded = true; - process.stdout.write(`${JSON.stringify({ exit: { code, signal } })}\n`); -}); -child.once("error", (error) => { - childEnded = true; - process.stdout.write(`${JSON.stringify({ error: error.message })}\n`); -}); +/** End the private group of this supervisor: its child, their children, and itself. */ +const stopGroup = (): void => { + process.kill(0, "SIGKILL"); +}; -const stopAll = (): void => { - if (!childEnded && child.pid !== undefined) { - try { - child.kill("SIGKILL"); - } catch { - // The child ended between the check and the kill. - } +/** Write one event line; a supervisor that cannot report ends its group. */ +const report = (event: object): void => { + try { + process.stdout.write(`${JSON.stringify(event)}\n`); + } catch { + stopGroup(); } - // Group 0 is the group of this supervisor: the child, its children, and itself. - process.kill(0, "SIGKILL"); }; -process.stdin.once("end", stopAll); -process.stdin.once("close", stopAll); + +process.stdout.on("error", stopGroup); +process.stdin.once("end", stopGroup); +process.stdin.once("close", stopGroup); process.stdin.resume(); + +const child = spawn(command, args, { env: process.env, stdio: "ignore" }); +child.once("exit", (code, signal) => report({ exit: { code, signal } })); +child.once("error", (error) => report({ error: error.message })); diff --git a/cli/test/unit/syncSignals.test.ts b/cli/test/unit/syncSignals.test.ts index 51738967..8d7131b1 100644 --- a/cli/test/unit/syncSignals.test.ts +++ b/cli/test/unit/syncSignals.test.ts @@ -6,14 +6,16 @@ * SIGINT on the raw channel. The OS releases the sync lock with the process, * so the next sync of the same home runs to its end. * - * Each CLI runs under `cli/test/lib/signalSupervisor.ts`, which leads the - * process group of the CLI and its children. The signal under test goes to - * the CLI pid only; the teardown closes the control pipe of the supervisor, - * which then ends its own group. The test never signals a group id. + * The test sends no signal to any pid. It writes the signal that it wants + * into a request file of the fixture folder; the waiting `omp` stub, a child + * of the blocked CLI, sends it to its own parent, and the listener-order + * entry raises it on itself. Each CLI runs under + * `cli/test/lib/signalSupervisor.ts`, which leads a private process group; + * the teardown closes the control pipe, and the supervisor ends its group. */ -import { spawn, type ChildProcess } from "node:child_process"; -import { existsSync, readFileSync } from "node:fs"; -import { delimiter, join } from "node:path"; +import { spawn } from "node:child_process"; +import { existsSync, readFileSync, renameSync, writeFileSync } from "node:fs"; +import { delimiter, dirname, join } from "node:path"; import { setTimeout as sleep } from "node:timers/promises"; import { afterAll, afterEach, describe, expect, it } from "vitest"; @@ -25,6 +27,7 @@ import { cleanupTemporaryDirs, makeStubDir, ompStubBody, + registerBeforeTemporaryDirRemoval, temporaryDir, } from "../lib/goldenResources"; import { SPAWN_TIMEOUT_MS } from "../lib/spawnTimeout"; @@ -32,8 +35,9 @@ import { SPAWN_TIMEOUT_MS } from "../lib/spawnTimeout"; const SUPERVISOR = join(REPO_DIR, "cli", "test", "lib", "signalSupervisor.ts"); const ENGINE_ENTRY = join(REPO_DIR, "cli", "test", "lib", "signalEngineEntry.ts"); -/** The environment key that names the marker file of the waiting `omp` stub. */ +/** The environment keys of the stub marker file and of the signal request file. */ const MARKER_FILE = "SYNC_SIGNAL_STUB_MARKER"; +const REQUEST_FILE = "SIGNAL_REQUEST_FILE"; /** The hard maximum lifetime of the waiting stub, past the timeout of any case. */ const STUB_MAX_LIFETIME_MS = 90_000; @@ -41,15 +45,24 @@ const STUB_MAX_LIFETIME_MS = 90_000; /** * The `omp` stub: `plugin list`, the first `omp` child of a sync pass, waits, * so the bridged plugin pass of the sync never settles. It records its parent - * and arms its watch first, then writes its pid as the readiness marker. It - * exits when the CLI that started it is gone, and fails after a hard maximum - * lifetime, so the plugin pass then reads no inventory and only warns. Every - * other command answers as the golden stub does. + * and arms its watch first, then writes its pid as the readiness marker. + * + * - When the request file holds `SIGTERM` or `SIGINT` and its parent is still + * the CLI that it recorded, it sends that signal to that parent, once. The + * CLI waits for this stub, so it cannot have exited and left its pid. + * - It exits when its CLI is gone. + * - It fails after a hard maximum lifetime. After the inventory stub fails, + * the plugin pass warns that the inventory is unavailable, and it can still + * run `omp plugin link`. + * + * Every other command answers as the golden stub does. */ const WAITING_OMP = `if (args[0] === "plugin" && args[1] === "list") { // The body goes inside the switch of the generated runner, which takes no other static import. - const { writeFileSync } = await import("node:fs") + const { existsSync, readFileSync, writeFileSync } = await import("node:fs") const parent = process.ppid + const request = process.env["${REQUEST_FILE}"] ?? "" + let signalled = false const parentGone = () => { if (process.ppid !== parent) return true try { @@ -59,10 +72,16 @@ const WAITING_OMP = `if (args[0] === "plugin" && args[1] === "list") { return true } } - // A watch, not a test delay: the stub waits until its CLI ends. + // A watch, not a test delay: it answers a signal request and ends with its CLI. setInterval(() => { if (parentGone()) process.exit(0) - }, 100) + if (signalled || request === "" || !existsSync(request)) return + const signal = readFileSync(request, "utf8").trim() + if ((signal === "SIGTERM" || signal === "SIGINT") && process.ppid === parent) { + signalled = true + process.kill(parent, signal) + } + }, 20) setTimeout(() => process.exit(1), ${STUB_MAX_LIFETIME_MS}) writeFileSync(process.env["${MARKER_FILE}"], String(process.pid)) } else { @@ -84,29 +103,30 @@ type Ending = | { readonly kind: "error"; readonly error: string }; interface Supervised { - /** The pid of the CLI, once the supervisor started it. */ - readonly cliPid: Promise; /** Settles once, from launch, with the end of the CLI or of its supervisor. */ readonly ended: Promise; + /** Settles when the supervisor closes, also after a failed spawn. */ + readonly closed: Promise; + /** End the control input; the supervisor then ends its group. */ + readonly stop: () => void; } -/** The supervisors that a case started; the teardown closes their control pipes. */ -const supervisors: Array = []; +/** The supervisors that still run; the teardown and the signal path stop them. */ +const supervisors = new Set(); -afterEach(async () => { - const closing = supervisors.splice(0).map((supervisor) => { - const { promise, resolve } = Promise.withResolvers(); - if (supervisor.exitCode !== null || supervisor.signalCode !== null) resolve(); - else supervisor.once("exit", () => resolve()); - // End of input tells the supervisor to stop the CLI and end its group. - supervisor.stdin?.end(); - return promise; - }); - await Promise.all(closing); -}); +/** Close the control pipe of each running supervisor and wait until each one closes. */ +async function stopSupervisors(): Promise { + const running = [...supervisors]; + for (const supervised of running) supervised.stop(); + await Promise.all(running.map((supervised) => supervised.closed)); +} + +// A cancelled worker stops the supervisors before it removes their folders. +registerBeforeTemporaryDirRemoval(stopSupervisors); +afterEach(stopSupervisors); afterAll(cleanupTemporaryDirs); -/** Run `command` under a new supervisor with `env`, and follow the events that it relays. */ +/** Run `command` under a new supervisor with `env`, and follow what it reports. */ function supervise(command: ReadonlyArray, env: Record): Supervised { const supervisor = spawn(BUN_RUNTIME, [SUPERVISOR, ...command], { env, @@ -114,38 +134,47 @@ function supervise(command: ReadonlyArray, env: Record): // The supervisor leads its own process group, which holds the CLI and its children. detached: true, }); - supervisors.push(supervisor); - const pid = Promise.withResolvers(); const ended = Promise.withResolvers(); + const closed = Promise.withResolvers(); let buffered = ""; supervisor.stdout?.setEncoding("utf8"); supervisor.stdout?.on("data", (chunk: string) => { buffered += chunk; for (let newline = buffered.indexOf("\n"); newline >= 0; newline = buffered.indexOf("\n")) { const event = JSON.parse(buffered.slice(0, newline)) as { - pid?: number; exit?: { code: number | null; signal: string | null }; error?: string; }; buffered = buffered.slice(newline + 1); - if (event.pid !== undefined) pid.resolve(event.pid); if (event.exit !== undefined) ended.resolve({ kind: "exit", ...event.exit }); if (event.error !== undefined) ended.resolve({ kind: "error", error: event.error }); } }); - supervisor.once("error", (error) => ended.resolve({ kind: "error", error: error.message })); - supervisor.once("exit", (code, signal) => { - const error = `the supervisor ended (code ${String(code)}, signal ${String(signal)})`; - ended.resolve({ kind: "error", error }); - pid.reject(new Error(error)); + supervisor.once("error", (error) => { + ended.resolve({ kind: "error", error: `the supervisor did not start: ${error.message}` }); + }); + const supervised: Supervised = { + ended: ended.promise, + closed: closed.promise, + stop: () => supervisor.stdin?.end(), + }; + supervisor.once("close", (code, signal) => { + supervisors.delete(supervised); + ended.resolve({ + kind: "error", + error: `the supervisor closed (code ${String(code)}, signal ${String(signal)})`, + }); + closed.resolve(); }); - // A case that never reads the pid must not report its rejection as unhandled. - pid.promise.catch(() => {}); - return { cliPid: pid.promise, ended: ended.promise }; + supervisors.add(supervised); + return supervised; } -/** The environment of a sync in `home` with `stubs` first on PATH. */ -function syncEnv( +/** + * The environment of a run in `home`: PATH holds only the stub folder and the + * folder of the Bun binary, so no real `omp` can run. + */ +function runEnv( home: string, stubs: string, extra: Record, @@ -153,7 +182,7 @@ function syncEnv( return { HOME: home, USERPROFILE: home, - PATH: `${stubs}${delimiter}${process.env["PATH"] ?? ""}`, + PATH: `${stubs}${delimiter}${dirname(BUN_RUNTIME)}`, LC_ALL: "C", TERM: "dumb", BUN_INSTALL_CACHE_DIR: temporaryDir("sync-signals-bun-cache-"), @@ -162,17 +191,36 @@ function syncEnv( }; } -/** Start `docks-kit sync` on `channel` for `home` under a supervisor. */ -function launchSync( - channel: "public" | "raw", - home: string, - stubs: string, - marker: string, -): Supervised { +/** The files of one case: the readiness marker and the signal request. */ +interface Fixture { + readonly home: string; + readonly marker: string; + readonly request: string; +} + +function makeFixture(markerName: string): Fixture { + const folder = temporaryDir("sync-signals-fixture-"); + return { + home: temporaryDir("sync-signals-home-"), + marker: join(folder, markerName), + request: join(folder, "signal-request"), + }; +} + +/** Ask the fixture process for `signal`: the request file appears whole, by rename. */ +function requestSignal(fixture: Fixture, signal: "SIGTERM" | "SIGINT"): void { + const pending = `${fixture.request}.pending`; + writeFileSync(pending, signal); + renameSync(pending, fixture.request); +} + +/** Start `docks-kit sync` on `channel` for the home of `fixture` under a supervisor. */ +function launchSync(channel: "public" | "raw", fixture: Fixture, stubs: string): Supervised { return supervise( [BUN_RUNTIME, cliEntry(), "sync"], - syncEnv(home, stubs, { - [MARKER_FILE]: marker, + runEnv(fixture.home, stubs, { + [MARKER_FILE]: fixture.marker, + [REQUEST_FILE]: fixture.request, ...(channel === "raw" ? { DOCKS_KIT_ENGINE: "native-raw" } : {}), }), ); @@ -186,17 +234,15 @@ function described(ending: Ending | "timed out"): string { : `exit code ${String(ending.code)}, signal ${String(ending.signal)}`; } -/** The pid in `path` when it holds a positive integer, else undefined. */ -function markerPid(path: string): number | undefined { - if (!existsSync(path)) return undefined; +/** True when `path` holds a positive integer, the pid that a ready process writes. */ +function markerReady(path: string): boolean { + if (!existsSync(path)) return false; const text = readFileSync(path, "utf8").trim(); - if (!/^\d+$/.test(text)) return undefined; - const pid = Number(text); - return Number.isSafeInteger(pid) && pid > 0 ? pid : undefined; + return /^\d+$/.test(text) && Number.isSafeInteger(Number(text)) && Number(text) > 0; } /** - * Wait until `marker` holds a valid pid; fail at once when the CLI ends + * Wait until `marker` holds a valid pid; fail at once when the run ends * first, and at `deadline` (`performance.now()` time). The marker is the only * readiness signal, so the wait polls the file. */ @@ -205,7 +251,7 @@ async function waitForMarker(run: Supervised, marker: string, deadline: number): void run.ended.then((value) => { ending = value; }); - while (markerPid(marker) === undefined) { + while (!markerReady(marker)) { if (ending !== undefined) { throw new Error(`the run ended before ${marker} appeared: ${described(ending)}`); } @@ -235,7 +281,7 @@ function syncLockFree(home: string): boolean { } describe.skipIf(process.platform === "win32")( - "signals during a sync (skipped on Windows: Bun's ChildProcess.kill force-terminates the process there instead of delivering the signal)", + "signals during a sync (skipped on Windows: process.kill force-terminates the process there instead of delivering the signal, and the supervisor needs POSIX process groups)", () => { for (const [channel, signal, code] of [ ["public", "SIGTERM", 130], @@ -249,20 +295,18 @@ describe.skipIf(process.platform === "win32")( // One deadline for every phase of the case, inside the case timeout. const deadline = performance.now() + CASE_TIMEOUT_MS - CASE_REPORT_MARGIN_MS; const nativeHost = { nativeHost: true } as const; - const home = temporaryDir("sync-signals-home-"); - const marker = join(temporaryDir("sync-signals-marker-"), "omp.pid"); + const fixture = makeFixture("omp.pid"); const waiting = launchSync( channel, - home, + fixture, makeStubDir({ omp: WAITING_OMP }, nativeHost), - marker, ); - await waitForMarker(waiting, marker, deadline); + await waitForMarker(waiting, fixture.marker, deadline); // The sync holds its lock while the plugin pass waits for the stub. - expect(syncLockFree(home)).toBe(false); + expect(syncLockFree(fixture.home)).toBe(false); - // The signal goes to the CLI pid only, while the CLI runs. - process.kill(await waiting.cliPid, signal); + // The stub sends the signal to its parent CLI, and to nothing else. + requestSignal(fixture, signal); expect( described( @@ -271,7 +315,7 @@ describe.skipIf(process.platform === "win32")( ).toBe(`exit code ${code}, signal null`); // The next sync of the same home takes the lock and runs to its end. - const next = launchSync(channel, home, makeStubDir({}, nativeHost), marker); + const next = launchSync(channel, fixture, makeStubDir({}, nativeHost)); expect(described(await endingWithin(next, deadline - performance.now()))).toBe( "exit code 0, signal null", ); @@ -285,24 +329,25 @@ describe.skipIf(process.platform === "win32")( `exits 130 on one ${signal} before runMain interrupts a public run whose logger finalizer fails`, async () => { const deadline = performance.now() + CASE_TIMEOUT_MS - CASE_REPORT_MARGIN_MS; - const home = temporaryDir("sync-signals-home-"); - const marker = join(temporaryDir("sync-signals-marker-"), "sleep.pid"); + const fixture = makeFixture("sleep.pid"); // A held sync lock keeps the run at the interruptible poll sleep. - const held: KitLock | undefined = tryAcquireKitLock(syncLockPath(home), { + const held: KitLock | undefined = tryAcquireKitLock(syncLockPath(fixture.home), { privateDirectory: true, }); - if (held === undefined) throw new Error(`expected a free lock in ${home}`); + if (held === undefined) throw new Error(`expected a free lock in ${fixture.home}`); try { const run = supervise( [BUN_RUNTIME, ENGINE_ENTRY, "sync"], - syncEnv(home, makeStubDir({}, { nativeHost: true }), { + runEnv(fixture.home, makeStubDir({}, { nativeHost: true }), { DOCKS_KIT_SYNC_LOCK_WAIT_MS: String(CASE_TIMEOUT_MS), - SIGNAL_ENTRY_SLEEP_MARKER: marker, + SIGNAL_ENTRY_SLEEP_MARKER: fixture.marker, + [REQUEST_FILE]: fixture.request, }), ); - await waitForMarker(run, marker, deadline); + await waitForMarker(run, fixture.marker, deadline); - process.kill(await run.cliPid, signal); + // The entry raises the signal on itself at its next poll sleep. + requestSignal(fixture, signal); // An interrupt first would end the run through the failing finalizer, with exit 1. expect( From 69746c371ebc96ece1b4e2ff033bc0b624a7bedc Mon Sep 17 00:00:00 2001 From: Eduardo Marquez <55303379+DocksDocks@users.noreply.github.com> Date: Tue, 1 Dec 2026 21:58:41 -0300 Subject: [PATCH 09/11] Make the signal test fixture signal-free outside the process under test Repairs of code-review round 6 of #294, after the second stall (user: Continue yolo): - A test-only preload in the CLI raises the requested signal on its own process; no fixture process signals another pid or group. Cleanup asks the CLI the same way. - One fixture root per case (docks-kit-signal-fixture-, matched by no sweep) with its home, caches, stubs, launch folders, and a working folder with no .env; bun runs with --no-env-file; the CLI PATH holds only stubs. - Stubs take a ticket in active/ and drop it as their last act; teardown removes the root only after every launch is confirmed and a non-recursive rmdir of active/ succeeds. - goldenResources: stop callbacks run inside the promise boundary; stub folders can be placed. Verified: bun x --no-install vitest run (unit, toggles, signals rows, skillMetadata.test.ts); bun run check:types; bun run lint; bun run check --- cli/test/lib/goldenResources.ts | 38 ++- cli/test/lib/signalSelfPreload.ts | 23 ++ cli/test/lib/signalSupervisor.ts | 135 ++++++---- cli/test/lib/supervisedRun.ts | 56 +++++ cli/test/unit/syncSignals.test.ts | 399 +++++++++++++++++++----------- 5 files changed, 448 insertions(+), 203 deletions(-) create mode 100644 cli/test/lib/signalSelfPreload.ts create mode 100644 cli/test/lib/supervisedRun.ts diff --git a/cli/test/lib/goldenResources.ts b/cli/test/lib/goldenResources.ts index 4d7fcb66..c8c5fae0 100644 --- a/cli/test/lib/goldenResources.ts +++ b/cli/test/lib/goldenResources.ts @@ -288,12 +288,12 @@ function endOnSignal(signal: "SIGINT" | "SIGTERM", handler: () => void): void { } const { promise: bound, resolve: endWait } = Promise.withResolvers(); const timer = setTimeout(endWait, BEFORE_REMOVAL_BOUND_MS); - void Promise.race([Promise.allSettled([...BEFORE_REMOVAL].map((stop) => stop())), bound]).then( - () => { - clearTimeout(timer); - finish(); - }, - ); + // Each call starts inside the promise, so a synchronous throw cannot skip the removal. + const stopping = [...BEFORE_REMOVAL].map((stop) => Promise.resolve().then(stop)); + void Promise.race([Promise.allSettled(stopping), bound]).then(() => { + clearTimeout(timer); + finish(); + }); } function handleSigint(): void { @@ -400,10 +400,12 @@ export function readStubHost(stubDir: string): string { * stub entirely (tool missing). `opts.nativeHost` must match the run helper the * stubs are handed to: the launcher form is the host's, so a Linux-preloaded * child needs extensionless launchers even when recording on Windows. + * `opts.dir` plants the stubs in an existing folder that the caller owns; + * else they go to a new registered temporary folder. */ export function makeStubDir( overrides: Record = {}, - opts: { readonly nativeHost?: boolean } = {}, + opts: { readonly nativeHost?: boolean; readonly dir?: string } = {}, ): string { const unknownNames = Object.keys(overrides) .filter((name) => !Object.hasOwn(STUB_BODIES, name)) @@ -412,7 +414,7 @@ export function makeStubDir( throw new Error(`Unknown golden stub override(s): ${unknownNames.join(", ")}`); } const hostId = childHostId(opts.nativeHost === true); - const dir = temporaryDir("golden-stubs-"); + const dir = opts.dir ?? temporaryDir("golden-stubs-"); writeFileSync(join(dir, STUB_HOST_MARKER), `${hostId}\n`); const runnerPath = join(dir, "golden-stub-runner.mjs"); const cases: Array = []; @@ -423,8 +425,26 @@ export function makeStubDir( } writeFileSync( runnerPath, - `import { appendFileSync } from "node:fs" + `import { randomUUID } from "node:crypto" +import { appendFileSync, closeSync, openSync, unlinkSync, writeFileSync } from "node:fs" +import { join } from "node:path" const [name, ...args] = process.argv.slice(2) +// A supervised fixture counts its running stubs by tickets (supervisedRun.ts). A stub that +// cannot create its ticket, because the teardown closed the folder, ends at once without its +// body; one that holds a ticket removes it as its last act, on every exit path. +const tickets = process.env["GOLDEN_STUB_TICKETS"] +if (tickets !== undefined) { + const ticket = join(tickets, randomUUID()) + let held + try { + held = openSync(ticket, "wx") + } catch { + process.exit(0) + } + writeFileSync(held, \`\${process.pid}\\n\`) + closeSync(held) + process.on("exit", () => unlinkSync(ticket)) +} const argvLog = process.env["GOLDEN_ARGV_LOG"] if (argvLog !== undefined) appendFileSync(argvLog, \`\${name}\\t\${args.join(" ")}\\n\`) switch (name) { diff --git a/cli/test/lib/signalSelfPreload.ts b/cli/test/lib/signalSelfPreload.ts new file mode 100644 index 00000000..a997b58f --- /dev/null +++ b/cli/test/lib/signalSelfPreload.ts @@ -0,0 +1,23 @@ +/** + * Test-only Bun preload for the spawned signal cases (`bun --preload + * signalSelfPreload.ts ...`). It polls the file that + * `SIGNAL_REQUEST_FILE` names and, once that file holds `SIGTERM` or + * `SIGINT`, raises that signal on this process, once. The process signals + * only itself, so no pid can name another process. Its timer does not keep + * the process alive. + */ +import { existsSync, readFileSync } from "node:fs"; + +const request = process.env["SIGNAL_REQUEST_FILE"] ?? ""; + +if (request !== "") { + // A request watch, not a delay: the test writes the file when the run waits. + const watch = setInterval(() => { + if (!existsSync(request)) return; + const signal = readFileSync(request, "utf8").trim(); + if (signal !== "SIGTERM" && signal !== "SIGINT") return; + clearInterval(watch); + process.kill(process.pid, signal); + }, 20); + watch.unref(); +} diff --git a/cli/test/lib/signalSupervisor.ts b/cli/test/lib/signalSupervisor.ts index c6d8fec2..c79405e6 100644 --- a/cli/test/lib/signalSupervisor.ts +++ b/cli/test/lib/signalSupervisor.ts @@ -1,62 +1,109 @@ /** * Fixture supervisor for the spawned signal cases (POSIX only). Run it with - * Bun as `bun signalSupervisor.ts [args...]`, spawned with - * `detached: true` so that it leads a new process group, and with a stdin - * pipe as its control channel. It refuses to run when it does not lead its - * own group, so its cleanup can never reach another group. + * Bun as `bun --no-env-file signalSupervisor.ts`, in a fixture-owned working + * folder, spawned detached (so that a signal to the group of the test worker + * does not reach it) and with a stdin pipe as its control channel, with these + * environment entries: * - * It starts `` as its child in that group, with its own environment, - * and writes one JSON line to stdout when the child ends: + * - `SIGNAL_SUPERVISOR_ROOT`: the fixture root, with the stub tickets; + * - `SIGNAL_SUPERVISOR_LAUNCH`: the record folder of this launch + * (`supervisedRun.ts`), which the test created; + * - `SIGNAL_SUPERVISOR_COMMAND`: the JSON argv of the CLI; + * - `SIGNAL_SUPERVISOR_ENV`: the JSON environment of the CLI. + * + * It records its pid, starts the CLI, records the CLI pid, and writes one + * JSON line to stdout when the CLI ends: * `{"exit":{"code":,"signal":}}`, or `{"error":""}` - * when the child cannot start. It stays alive after that, so its group keeps - * its leader. + * when the CLI cannot start. * - * When stdin ends (the test closes the pipe, or the test worker dies for any - * reason), and when it cannot write a report to stdout, it ends its whole - * group, the child, the grandchildren, and itself, with SIGKILL to group 0. - * It signals no single pid. + * It sends no signal. When stdin ends (the test closes the pipe, or the test + * worker dies for any reason), or when it cannot write a report, it writes + * `SIGTERM` into the signal request file of the launch, which the preload of + * the CLI reads to signal its own process. It then waits for the CLI to end + * and until no stub of the root holds a ticket, writes `shutdown-confirmed`, + * and exits. A wait past the bound ends it without the confirmation. */ -import { spawn, spawnSync } from "node:child_process"; - -const USAGE = - "usage: bun signalSupervisor.ts [args...]; spawn it detached (its own process group) with a stdin pipe\n"; +import { spawn } from "node:child_process"; +import { renameSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; -const [command, ...args] = process.argv.slice(2); -if (command === undefined) { - process.stderr.write(USAGE); - process.exit(2); -} +import { + CLI_PID, + SHUTDOWN_CONFIRMED, + SIGNAL_REQUEST, + SUPERVISOR_PID, + ticketsReleased, +} from "./supervisedRun"; -// The supervisor must lead its group: group 0 is then this private group. -const pgid = spawnSync("/bin/ps", ["-o", "pgid=", "-p", String(process.pid)], { - encoding: "utf8", -}).stdout?.trim(); -if (pgid !== String(process.pid)) { - process.stderr.write( - `signalSupervisor: process group ${String(pgid)} is not led by pid ${process.pid}\n${USAGE}`, - ); - process.exit(2); -} +/** How long the shutdown waits for the CLI and its stubs; past it, no confirmation. */ +const SHUTDOWN_BOUND_MS = 120_000; +const SHUTDOWN_POLL_MS = 20; -/** End the private group of this supervisor: its child, their children, and itself. */ -const stopGroup = (): void => { - process.kill(0, "SIGKILL"); -}; +const root = process.env["SIGNAL_SUPERVISOR_ROOT"] ?? ""; +const launch = process.env["SIGNAL_SUPERVISOR_LAUNCH"] ?? ""; +const [command, ...args] = JSON.parse( + process.env["SIGNAL_SUPERVISOR_COMMAND"] ?? "[]", +) as Array; +const env = JSON.parse(process.env["SIGNAL_SUPERVISOR_ENV"] ?? "{}") as Record; -/** Write one event line; a supervisor that cannot report ends its group. */ -const report = (event: object): void => { +/** Write one event line; true when it was written. */ +const report = (event: object): boolean => { try { process.stdout.write(`${JSON.stringify(event)}\n`); + return true; } catch { - stopGroup(); + return false; + } +}; + +if (root === "" || launch === "" || command === undefined) { + report({ + error: + "SIGNAL_SUPERVISOR_ROOT, SIGNAL_SUPERVISOR_LAUNCH, or SIGNAL_SUPERVISOR_COMMAND is missing", + }); + process.exit(2); +} + +writeFileSync(join(launch, SUPERVISOR_PID), String(process.pid)); + +let cliEnded = false; +let shuttingDown = false; + +/** Ask the CLI to end itself, wait for it and its stubs, confirm, and exit. */ +const shutDown = (): void => { + if (shuttingDown) return; + shuttingDown = true; + if (!cliEnded) { + // The request appears whole, by rename; the preload of the CLI raises it on its own process. + const request = join(launch, SIGNAL_REQUEST); + writeFileSync(`${request}.pending`, "SIGTERM"); + renameSync(`${request}.pending`, request); } + const deadline = performance.now() + SHUTDOWN_BOUND_MS; + const confirm = (): void => { + if (cliEnded && ticketsReleased(root)) { + writeFileSync(join(launch, SHUTDOWN_CONFIRMED), ""); + process.exit(0); + } + // Without the confirmation, the teardown of the test keeps the fixture root. + if (performance.now() > deadline) process.exit(1); + setTimeout(confirm, SHUTDOWN_POLL_MS); + }; + confirm(); }; -process.stdout.on("error", stopGroup); -process.stdin.once("end", stopGroup); -process.stdin.once("close", stopGroup); +process.stdout.on("error", shutDown); +process.stdin.once("end", shutDown); +process.stdin.once("close", shutDown); process.stdin.resume(); -const child = spawn(command, args, { env: process.env, stdio: "ignore" }); -child.once("exit", (code, signal) => report({ exit: { code, signal } })); -child.once("error", (error) => report({ error: error.message })); +const cli = spawn(command, args, { env, stdio: "ignore" }); +if (cli.pid !== undefined) writeFileSync(join(launch, CLI_PID), String(cli.pid)); +cli.once("exit", (code, signal) => { + cliEnded = true; + if (!report({ exit: { code, signal } })) shutDown(); +}); +cli.once("error", (error) => { + cliEnded = true; + if (!report({ error: error.message })) shutDown(); +}); diff --git a/cli/test/lib/supervisedRun.ts b/cli/test/lib/supervisedRun.ts new file mode 100644 index 00000000..f8a89187 --- /dev/null +++ b/cli/test/lib/supervisedRun.ts @@ -0,0 +1,56 @@ +/** + * The records of a fixture root of the spawned signal cases. Each supervised + * launch has a folder below `/launches/`, which the test creates before + * it starts `signalSupervisor.ts`; the supervisor records its pid and the pid + * of the CLI, and writes `shutdown-confirmed` once the CLI has ended and no + * stub holds a ticket. + * + * Stubs hold tickets in `/active/` (`goldenResources.ts makeStubDir`, + * `GOLDEN_STUB_TICKETS`): each invocation first creates its ticket + * `` exclusively, and exits at once without its body when it cannot; it + * removes the ticket as its last act, on every exit path. The teardown closes + * the registration with a non-recursive `rmdir` of `active/`: it succeeds only + * while the folder is empty, and no entry can be created in it afterwards, + * also through a path that was resolved before. A root goes only when every + * launch is confirmed and that `rmdir` succeeded; no sweep removes it. + * + * Only `node:` imports, so the supervisor can load this module alone. + */ +import { existsSync, readdirSync } from "node:fs"; +import { join } from "node:path"; + +/** The folder of a fixture root that holds one record folder per supervised launch. */ +export const LAUNCHES_DIR = "launches"; +/** Written by the supervisor once the CLI has ended and no stub holds a ticket. */ +export const SHUTDOWN_CONFIRMED = "shutdown-confirmed"; +/** The pid of the supervisor of the launch. */ +export const SUPERVISOR_PID = "supervisor.pid"; +/** The pid of the CLI of the launch. */ +export const CLI_PID = "cli.pid"; +/** The file that the CLI preload reads: `SIGTERM` or `SIGINT` asks the CLI to signal itself. */ +export const SIGNAL_REQUEST = "signal-request"; +/** The ticket folder of a root: one entry per running stub. */ +export const TICKETS_DIR = "active"; + +/** True when no stub of `root` holds a ticket: the ticket folder is empty, or closed. */ +export function ticketsReleased(root: string): boolean { + const tickets = join(root, TICKETS_DIR); + return !existsSync(tickets) || readdirSync(tickets).length === 0; +} + +/** The launch folders of the fixture root `root`. */ +export function launches(root: string): Array { + const folder = join(root, LAUNCHES_DIR); + if (!existsSync(folder)) return []; + return readdirSync(folder).map((name) => join(folder, name)); +} + +/** + * True when `launch` recorded its supervisor and its CLI and confirmed its + * shutdown. A launch that lacks one of these counts as unconfirmed. + */ +export function launchConfirmed(launch: string): boolean { + return [SUPERVISOR_PID, CLI_PID, SHUTDOWN_CONFIRMED].every((record) => + existsSync(join(launch, record)), + ); +} diff --git a/cli/test/unit/syncSignals.test.ts b/cli/test/unit/syncSignals.test.ts index 8d7131b1..82152064 100644 --- a/cli/test/unit/syncSignals.test.ts +++ b/cli/test/unit/syncSignals.test.ts @@ -6,82 +6,100 @@ * SIGINT on the raw channel. The OS releases the sync lock with the process, * so the next sync of the same home runs to its end. * - * The test sends no signal to any pid. It writes the signal that it wants - * into a request file of the fixture folder; the waiting `omp` stub, a child - * of the blocked CLI, sends it to its own parent, and the listener-order - * entry raises it on itself. Each CLI runs under - * `cli/test/lib/signalSupervisor.ts`, which leads a private process group; - * the teardown closes the control pipe, and the supervisor ends its group. + * No process of these cases signals another process. The test writes the + * signal that it wants into the request file of a launch; the CLI raises it + * on itself through `cli/test/lib/signalSelfPreload.ts`, and the + * listener-order entry `cli/test/lib/signalEngineEntry.ts` raises it on + * itself at its poll sleep. Each CLI runs under + * `cli/test/lib/signalSupervisor.ts`, which on teardown asks the CLI the same + * way to end, waits for it and its stubs, and confirms the shutdown. + * + * One fixture root per case, directly in the system temporary folder, holds + * everything that its processes use. The teardown removes it only when every + * launch of the case confirmed its shutdown and the ticket folder of the + * stubs could be closed (`supervisedRun.ts`); otherwise it keeps the root and + * reports why. No sweep of `goldenResources.ts` matches its name. The stubs + * get a PATH with only their own folder, HOME is inside the root, and every + * process works in a root folder without a `.env` file. */ import { spawn } from "node:child_process"; -import { existsSync, readFileSync, renameSync, writeFileSync } from "node:fs"; -import { delimiter, dirname, join } from "node:path"; +import { + existsSync, + mkdirSync, + mkdtempSync, + readFileSync, + renameSync, + rmSync, + rmdirSync, + writeFileSync, +} from "node:fs"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; import { setTimeout as sleep } from "node:timers/promises"; -import { afterAll, afterEach, describe, expect, it } from "vitest"; +import { afterEach, describe, expect, it } from "vitest"; -import { releaseKitLock, tryAcquireKitLock, type KitLock } from "../../src/engine-native/kitLock"; +import { releaseKitLock, tryAcquireKitLock } from "../../src/engine-native/kitLock"; import { syncLockPath } from "../../src/engine-native/scratch"; import { BUN_RUNTIME, cliEntry } from "../lib/cliEntry"; import { REPO_DIR, - cleanupTemporaryDirs, makeStubDir, ompStubBody, registerBeforeTemporaryDirRemoval, - temporaryDir, } from "../lib/goldenResources"; import { SPAWN_TIMEOUT_MS } from "../lib/spawnTimeout"; +import { + LAUNCHES_DIR, + SIGNAL_REQUEST, + CLI_PID, + TICKETS_DIR, + launchConfirmed, + launches, +} from "../lib/supervisedRun"; -const SUPERVISOR = join(REPO_DIR, "cli", "test", "lib", "signalSupervisor.ts"); -const ENGINE_ENTRY = join(REPO_DIR, "cli", "test", "lib", "signalEngineEntry.ts"); +const LIB = join(REPO_DIR, "cli", "test", "lib"); +const SUPERVISOR = join(LIB, "signalSupervisor.ts"); +const PRELOAD = join(LIB, "signalSelfPreload.ts"); +const ENGINE_ENTRY = join(LIB, "signalEngineEntry.ts"); -/** The environment keys of the stub marker file and of the signal request file. */ +/** The environment key of the readiness marker of the waiting `omp` stub. */ const MARKER_FILE = "SYNC_SIGNAL_STUB_MARKER"; -const REQUEST_FILE = "SIGNAL_REQUEST_FILE"; /** The hard maximum lifetime of the waiting stub, past the timeout of any case. */ const STUB_MAX_LIFETIME_MS = 90_000; +/** The environment key of the CLI pid record of the launch, which the waiting stub watches. */ +const CLI_PID_FILE = "SYNC_SIGNAL_CLI_PID_FILE"; + /** * The `omp` stub: `plugin list`, the first `omp` child of a sync pass, waits, - * so the bridged plugin pass of the sync never settles. It records its parent - * and arms its watch first, then writes its pid as the readiness marker. - * - * - When the request file holds `SIGTERM` or `SIGINT` and its parent is still - * the CLI that it recorded, it sends that signal to that parent, once. The - * CLI waits for this stub, so it cannot have exited and left its pid. - * - It exits when its CLI is gone. - * - It fails after a hard maximum lifetime. After the inventory stub fails, - * the plugin pass warns that the inventory is unavailable, and it can still - * run `omp plugin link`. - * - * Every other command answers as the golden stub does. + * so the bridged plugin pass of the sync never settles. It reads the CLI pid + * that the supervisor recorded and arms its watch first, then writes its pid + * as the readiness marker. It exits when that CLI is gone or is no longer its + * parent, also when the CLI ended before the stub ran, and fails after a hard + * maximum lifetime: the plugin pass then warns that the inventory is + * unavailable, and it can still run `omp plugin link`. It signals nothing; a + * liveness check only reads. Every other command answers as the golden stub + * does. */ const WAITING_OMP = `if (args[0] === "plugin" && args[1] === "list") { // The body goes inside the switch of the generated runner, which takes no other static import. - const { existsSync, readFileSync, writeFileSync } = await import("node:fs") - const parent = process.ppid - const request = process.env["${REQUEST_FILE}"] ?? "" - let signalled = false + const { readFileSync, writeFileSync } = await import("node:fs") + const cli = Number(readFileSync(process.env["${CLI_PID_FILE}"], "utf8").trim()) const parentGone = () => { - if (process.ppid !== parent) return true + if (process.ppid !== cli) return true try { - process.kill(parent, 0) + process.kill(cli, 0) return false } catch { return true } } - // A watch, not a test delay: it answers a signal request and ends with its CLI. + if (parentGone()) process.exit(0) + // A watch, not a test delay: the stub waits until its CLI ends. setInterval(() => { if (parentGone()) process.exit(0) - if (signalled || request === "" || !existsSync(request)) return - const signal = readFileSync(request, "utf8").trim() - if ((signal === "SIGTERM" || signal === "SIGINT") && process.ppid === parent) { - signalled = true - process.kill(parent, signal) - } - }, 20) + }, 100) setTimeout(() => process.exit(1), ${STUB_MAX_LIFETIME_MS}) writeFileSync(process.env["${MARKER_FILE}"], String(process.pid)) } else { @@ -90,52 +108,168 @@ ${ompStubBody()} /** The timeout of one case; its phases share one deadline inside it. */ const CASE_TIMEOUT_MS = SPAWN_TIMEOUT_MS; - /** The time a case keeps after its last phase, to report a phase that ran out. */ const CASE_REPORT_MARGIN_MS = 1_000; - /** How long a signalled CLI may take to exit; a wait for the stub would never end. */ const EXIT_BOUND_MS = 10_000; +/** How long the teardown waits for every shutdown confirmation, within its hook timeout. */ +const TEARDOWN_BUDGET_MS = 10_000; +const TEARDOWN_HOOK_TIMEOUT_MS = TEARDOWN_BUDGET_MS + 5_000; +/** How long the signal path of a cancelled worker waits, within its own two-second bound. */ +const SIGNAL_PATH_BUDGET_MS = 1_500; /** The way a supervised CLI ended: its exit code or signal, or the error that ended its run. */ type Ending = | { readonly kind: "exit"; readonly code: number | null; readonly signal: string | null } | { readonly kind: "error"; readonly error: string }; -interface Supervised { +/** One fixture root: the working folder, the home, the caches, the stubs, and the launches. */ +interface Fixture { + readonly root: string; + readonly work: string; + readonly home: string; + readonly bunCache: string; + readonly transpilerCache: string; + launchCount: number; +} + +interface Launch { + /** The record folder of this launch, with its empty request file. */ + readonly folder: string; + readonly request: string; /** Settles once, from launch, with the end of the CLI or of its supervisor. */ readonly ended: Promise; - /** Settles when the supervisor closes, also after a failed spawn. */ - readonly closed: Promise; - /** End the control input; the supervisor then ends its group. */ + /** End the control input; the supervisor then asks the CLI to end. */ readonly stop: () => void; } -/** The supervisors that still run; the teardown and the signal path stop them. */ -const supervisors = new Set(); +const fixtures = new Set(); +const running = new Set(); -/** Close the control pipe of each running supervisor and wait until each one closes. */ -async function stopSupervisors(): Promise { - const running = [...supervisors]; - for (const supervised of running) supervised.stop(); - await Promise.all(running.map((supervised) => supervised.closed)); +/** + * Stop every supervisor and wait within `budgetMs` until each launch + * confirmed its shutdown. Then close the ticket folder of the root with a + * non-recursive `rmdir`, retried while a stub still holds a ticket; once it + * succeeds, no stub can start its body in the root. A root goes only then. + * Return one line for each root that does not get there; it stays, and no + * sweep removes it. It sends no signal. + */ +async function stopAndRemove(budgetMs: number): Promise> { + const deadline = performance.now() + budgetMs; + for (const run of running) run.stop(); + const unconfirmed = (fixture: Fixture): Array => + launches(fixture.root).filter((folder) => !launchConfirmed(folder)); + const closed = new Set(); + for (;;) { + for (const fixture of fixtures) { + if (closed.has(fixture) || unconfirmed(fixture).length > 0) continue; + try { + // It fails while a stub holds a ticket; after it, no ticket can be created. + rmdirSync(join(fixture.root, TICKETS_DIR)); + closed.add(fixture); + } catch { + // A stub still holds a ticket: retry within the budget. + } + } + if (closed.size === fixtures.size || performance.now() >= deadline) break; + await sleep(20); + } + const problems: Array = []; + for (const fixture of [...fixtures]) { + if (!closed.has(fixture)) { + const open = unconfirmed(fixture); + problems.push( + ...(open.length > 0 + ? open.map((folder) => `launch ${folder} has no shutdown confirmation; its root stays`) + : [`a stub of ${fixture.root} still holds a ticket; the root stays`]), + ); + continue; + } + fixtures.delete(fixture); + try { + rmSync(fixture.root, { recursive: true, force: true }); + } catch (error) { + problems.push(`fixture root ${fixture.root} cannot be removed: ${String(error)}`); + } + } + return problems; } -// A cancelled worker stops the supervisors before it removes their folders. -registerBeforeTemporaryDirRemoval(stopSupervisors); -afterEach(stopSupervisors); -afterAll(cleanupTemporaryDirs); +// A cancelled worker stops the supervisors before its sweep, within its bound. +registerBeforeTemporaryDirRemoval(async () => { + await stopAndRemove(SIGNAL_PATH_BUDGET_MS); +}); +afterEach(async () => { + const problems = await stopAndRemove(TEARDOWN_BUDGET_MS); + if (problems.length > 0) throw new Error(`teardown:\n${problems.join("\n")}`); +}, TEARDOWN_HOOK_TIMEOUT_MS); + +function makeFixture(): Fixture { + const root = mkdtempSync(join(tmpdir(), "docks-kit-signal-fixture-")); + const fixture: Fixture = { + root, + // The working folder of every process: it holds no `.env` file. + work: join(root, "work"), + home: join(root, "home"), + bunCache: join(root, "bun-cache"), + transpilerCache: join(root, "bun-transpiler"), + launchCount: 0, + }; + for (const folder of [fixture.work, fixture.home, fixture.bunCache, fixture.transpilerCache]) { + mkdirSync(folder); + } + mkdirSync(join(root, TICKETS_DIR)); + fixtures.add(fixture); + return fixture; +} -/** Run `command` under a new supervisor with `env`, and follow what it reports. */ -function supervise(command: ReadonlyArray, env: Record): Supervised { - const supervisor = spawn(BUN_RUNTIME, [SUPERVISOR, ...command], { - env, +/** + * Start `command` under a new supervisor, in its own launch folder of + * `fixture`, which it records before the CLI starts. The CLI gets a PATH with + * only its stub folder, and the stubs take their tickets in the root. + */ +function launch( + fixture: Fixture, + command: ReadonlyArray, + stubOverrides: Record, + extraEnv: (folder: string) => Record, +): Launch { + fixture.launchCount += 1; + const folder = join(fixture.root, LAUNCHES_DIR, String(fixture.launchCount)); + mkdirSync(folder, { recursive: true }); + const request = join(folder, SIGNAL_REQUEST); + writeFileSync(request, ""); + const stubs = join(fixture.root, `stubs-${fixture.launchCount}`); + mkdirSync(stubs); + makeStubDir(stubOverrides, { nativeHost: true, dir: stubs }); + const cliEnv: Record = { + HOME: fixture.home, + USERPROFILE: fixture.home, + PATH: stubs, + LC_ALL: "C", + TERM: "dumb", + BUN_INSTALL_CACHE_DIR: fixture.bunCache, + BUN_RUNTIME_TRANSPILER_CACHE_PATH: fixture.transpilerCache, + SIGNAL_REQUEST_FILE: request, + GOLDEN_STUB_TICKETS: join(fixture.root, TICKETS_DIR), + ...extraEnv(folder), + }; + const supervisor = spawn(BUN_RUNTIME, ["--no-env-file", SUPERVISOR], { + cwd: fixture.work, + env: { + HOME: fixture.home, + // The supervisor starts the CLI by its absolute path and runs no tool. + PATH: stubs, + SIGNAL_SUPERVISOR_ROOT: fixture.root, + SIGNAL_SUPERVISOR_LAUNCH: folder, + SIGNAL_SUPERVISOR_COMMAND: JSON.stringify(command), + SIGNAL_SUPERVISOR_ENV: JSON.stringify(cliEnv), + }, stdio: ["pipe", "pipe", "ignore"], - // The supervisor leads its own process group, which holds the CLI and its children. + // Outside the process group of the worker, so a signal to that group leaves its shutdown to run. detached: true, }); const ended = Promise.withResolvers(); - const closed = Promise.withResolvers(); let buffered = ""; supervisor.stdout?.setEncoding("utf8"); supervisor.stdout?.on("data", (chunk: string) => { @@ -153,79 +287,50 @@ function supervise(command: ReadonlyArray, env: Record): supervisor.once("error", (error) => { ended.resolve({ kind: "error", error: `the supervisor did not start: ${error.message}` }); }); - const supervised: Supervised = { + const started: Launch = { + folder, + request, ended: ended.promise, - closed: closed.promise, stop: () => supervisor.stdin?.end(), }; supervisor.once("close", (code, signal) => { - supervisors.delete(supervised); + running.delete(started); ended.resolve({ kind: "error", error: `the supervisor closed (code ${String(code)}, signal ${String(signal)})`, }); - closed.resolve(); }); - supervisors.add(supervised); - return supervised; -} - -/** - * The environment of a run in `home`: PATH holds only the stub folder and the - * folder of the Bun binary, so no real `omp` can run. - */ -function runEnv( - home: string, - stubs: string, - extra: Record, -): Record { - return { - HOME: home, - USERPROFILE: home, - PATH: `${stubs}${delimiter}${dirname(BUN_RUNTIME)}`, - LC_ALL: "C", - TERM: "dumb", - BUN_INSTALL_CACHE_DIR: temporaryDir("sync-signals-bun-cache-"), - BUN_RUNTIME_TRANSPILER_CACHE_PATH: temporaryDir("sync-signals-bun-transpiler-"), - ...extra, - }; + running.add(started); + return started; } -/** The files of one case: the readiness marker and the signal request. */ -interface Fixture { - readonly home: string; - readonly marker: string; - readonly request: string; -} - -function makeFixture(markerName: string): Fixture { - const folder = temporaryDir("sync-signals-fixture-"); - return { - home: temporaryDir("sync-signals-home-"), - marker: join(folder, markerName), - request: join(folder, "signal-request"), - }; -} - -/** Ask the fixture process for `signal`: the request file appears whole, by rename. */ -function requestSignal(fixture: Fixture, signal: "SIGTERM" | "SIGINT"): void { - const pending = `${fixture.request}.pending`; - writeFileSync(pending, signal); - renameSync(pending, fixture.request); -} - -/** Start `docks-kit sync` on `channel` for the home of `fixture` under a supervisor. */ -function launchSync(channel: "public" | "raw", fixture: Fixture, stubs: string): Supervised { - return supervise( - [BUN_RUNTIME, cliEntry(), "sync"], - runEnv(fixture.home, stubs, { - [MARKER_FILE]: fixture.marker, - [REQUEST_FILE]: fixture.request, +/** Start `docks-kit sync` on `channel` in the home of `fixture`, with the self-signal preload. */ +function launchSync( + channel: "public" | "raw", + fixture: Fixture, + stubOverrides: Record, +): Launch { + // The entry may come relative from DOCKS_KIT_TEST_CLI_ENTRY; the CLI runs in the fixture folder. + const entry = resolve(cliEntry()); + return launch( + fixture, + [BUN_RUNTIME, "--no-env-file", "--preload", PRELOAD, entry, "sync"], + stubOverrides, + (folder) => ({ + [MARKER_FILE]: join(folder, "ready"), + [CLI_PID_FILE]: join(folder, CLI_PID), ...(channel === "raw" ? { DOCKS_KIT_ENGINE: "native-raw" } : {}), }), ); } +/** Ask the CLI of `run` for `signal`: the request file gets it whole, by rename. */ +function requestSignal(run: Launch, signal: "SIGTERM" | "SIGINT"): void { + const pending = `${run.request}.pending`; + writeFileSync(pending, signal); + renameSync(pending, run.request); +} + /** A description of `ending` for a failure message. */ function described(ending: Ending | "timed out"): string { if (ending === "timed out") return ending; @@ -246,7 +351,7 @@ function markerReady(path: string): boolean { * first, and at `deadline` (`performance.now()` time). The marker is the only * readiness signal, so the wait polls the file. */ -async function waitForMarker(run: Supervised, marker: string, deadline: number): Promise { +async function waitForMarker(run: Launch, marker: string, deadline: number): Promise { let ending: Ending | undefined; void run.ended.then((value) => { ending = value; @@ -261,10 +366,10 @@ async function waitForMarker(run: Supervised, marker: string, deadline: number): } /** The ending of `run`, or `timed out` when it runs past `boundMs`. */ -async function endingWithin(run: Supervised, boundMs: number): Promise { - const { promise, resolve } = Promise.withResolvers<"timed out">(); +async function endingWithin(run: Launch, boundMs: number): Promise { + const { promise, resolve: timeOut } = Promise.withResolvers<"timed out">(); // The bound only caps a CLI that waits; a prompt exit resolves first. - const timer = setTimeout(() => resolve("timed out"), Math.max(0, boundMs)); + const timer = setTimeout(() => timeOut("timed out"), Math.max(0, boundMs)); try { return await Promise.race([run.ended, promise]); } finally { @@ -281,7 +386,7 @@ function syncLockFree(home: string): boolean { } describe.skipIf(process.platform === "win32")( - "signals during a sync (skipped on Windows: process.kill force-terminates the process there instead of delivering the signal, and the supervisor needs POSIX process groups)", + "signals during a sync (skipped on Windows: process.kill force-terminates the process there instead of delivering the signal)", () => { for (const [channel, signal, code] of [ ["public", "SIGTERM", 130], @@ -294,19 +399,14 @@ describe.skipIf(process.platform === "win32")( async () => { // One deadline for every phase of the case, inside the case timeout. const deadline = performance.now() + CASE_TIMEOUT_MS - CASE_REPORT_MARGIN_MS; - const nativeHost = { nativeHost: true } as const; - const fixture = makeFixture("omp.pid"); - const waiting = launchSync( - channel, - fixture, - makeStubDir({ omp: WAITING_OMP }, nativeHost), - ); - await waitForMarker(waiting, fixture.marker, deadline); + const fixture = makeFixture(); + const waiting = launchSync(channel, fixture, { omp: WAITING_OMP }); + await waitForMarker(waiting, join(waiting.folder, "ready"), deadline); // The sync holds its lock while the plugin pass waits for the stub. expect(syncLockFree(fixture.home)).toBe(false); - // The stub sends the signal to its parent CLI, and to nothing else. - requestSignal(fixture, signal); + // The CLI raises the signal on itself. + requestSignal(waiting, signal); expect( described( @@ -314,8 +414,8 @@ describe.skipIf(process.platform === "win32")( ), ).toBe(`exit code ${code}, signal null`); - // The next sync of the same home takes the lock and runs to its end. - const next = launchSync(channel, fixture, makeStubDir({}, nativeHost)); + // The next sync of the same home, with its own launch and request file, runs to its end. + const next = launchSync(channel, fixture, {}); expect(described(await endingWithin(next, deadline - performance.now()))).toBe( "exit code 0, signal null", ); @@ -329,25 +429,24 @@ describe.skipIf(process.platform === "win32")( `exits 130 on one ${signal} before runMain interrupts a public run whose logger finalizer fails`, async () => { const deadline = performance.now() + CASE_TIMEOUT_MS - CASE_REPORT_MARGIN_MS; - const fixture = makeFixture("sleep.pid"); + const fixture = makeFixture(); // A held sync lock keeps the run at the interruptible poll sleep. - const held: KitLock | undefined = tryAcquireKitLock(syncLockPath(fixture.home), { - privateDirectory: true, - }); + const held = tryAcquireKitLock(syncLockPath(fixture.home), { privateDirectory: true }); if (held === undefined) throw new Error(`expected a free lock in ${fixture.home}`); try { - const run = supervise( - [BUN_RUNTIME, ENGINE_ENTRY, "sync"], - runEnv(fixture.home, makeStubDir({}, { nativeHost: true }), { + const run = launch( + fixture, + [BUN_RUNTIME, "--no-env-file", ENGINE_ENTRY, "sync"], + {}, + (folder) => ({ DOCKS_KIT_SYNC_LOCK_WAIT_MS: String(CASE_TIMEOUT_MS), - SIGNAL_ENTRY_SLEEP_MARKER: fixture.marker, - [REQUEST_FILE]: fixture.request, + SIGNAL_ENTRY_SLEEP_MARKER: join(folder, "ready"), }), ); - await waitForMarker(run, fixture.marker, deadline); + await waitForMarker(run, join(run.folder, "ready"), deadline); // The entry raises the signal on itself at its next poll sleep. - requestSignal(fixture, signal); + requestSignal(run, signal); // An interrupt first would end the run through the failing finalizer, with exit 1. expect( From 6017de700dfafd8b2497fa26653c539bc3718de9 Mon Sep 17 00:00:00 2001 From: Eduardo Marquez <55303379+DocksDocks@users.noreply.github.com> Date: Tue, 1 Dec 2026 22:10:09 -0300 Subject: [PATCH 10/11] Harden the signal fixture records and per-case teardown Repairs of code-review round 7 of #294: - The supervisor publishes cli.pid atomically; the waiting stub waits for a valid record. - Teardown handles only the fixtures of the current case; a kept root leaves tracking. - A stub whose ticket create fails exits 1; ticket release is armed right after the create. - Stubs write started and stub-exited records by invocation id; confirmation needs both. - Ticket code is generated only for supervised stub folders (no ambient variable). - A partial fixture root is removed on setup failure; cancellation prints its diagnostics. Verified: bun x --no-install vitest run (unit, toggles, signals rows, skillMetadata.test.ts); bun run check:types; bun run lint; bun run check --- cli/test/lib/goldenResources.ts | 68 +++++++++++++++------- cli/test/lib/signalSupervisor.ts | 13 +++-- cli/test/lib/supervisedRun.ts | 59 ++++++++++++++------ cli/test/unit/syncSignals.test.ts | 93 ++++++++++++++++++++++--------- 4 files changed, 167 insertions(+), 66 deletions(-) diff --git a/cli/test/lib/goldenResources.ts b/cli/test/lib/goldenResources.ts index c8c5fae0..3581de96 100644 --- a/cli/test/lib/goldenResources.ts +++ b/cli/test/lib/goldenResources.ts @@ -15,6 +15,7 @@ import { dirname, join, resolve } from "node:path"; import { fileURLToPath } from "node:url"; import { hostOs, type PlatformName } from "../../src/engine-native/os"; +import { STUB_EXITED_SUFFIX, STUB_STARTED_SUFFIX } from "./supervisedRun"; export const REPO_DIR = resolve(dirname(fileURLToPath(import.meta.url)), "..", "..", ".."); export const FIXTURES_DIR = join(REPO_DIR, "cli", "test", "fixtures"); @@ -395,17 +396,59 @@ export function readStubHost(stubDir: string): string { } } +/** + * The ticket code of a stub of a supervised fixture (`supervisedRun.ts`). The + * stub creates its ticket exclusively and ends nonzero, without its body, when + * it cannot, so the engine sees a failed tool. Right after the create it arms + * its release for every exit path: it records its exit, then removes its + * ticket. Only then it writes its pid into the ticket and records its start. + */ +function supervisedStubPrelude(folders: { + readonly tickets: string; + readonly records: string; +}): string { + return `import { randomUUID } from "node:crypto" +import { closeSync, openSync, unlinkSync, writeFileSync } from "node:fs" +import { join } from "node:path" +const stubId = randomUUID() +const ticket = join(${JSON.stringify(folders.tickets)}, stubId) +const records = ${JSON.stringify(folders.records)} +let held +try { + held = openSync(ticket, "wx") +} catch (error) { + process.stderr.write(\`golden stub: no ticket in a closed or failed fixture: \${String(error)}\\n\`) + process.exit(1) +} +process.on("exit", () => { + try { + writeFileSync(join(records, \`\${stubId}${STUB_EXITED_SUFFIX}\`), "") + } finally { + unlinkSync(ticket) + } +}) +writeFileSync(held, \`\${process.pid}\\n\`) +closeSync(held) +writeFileSync(join(records, \`\${stubId}${STUB_STARTED_SUFFIX}\`), \`\${process.pid}\\n\`)`; +} + /** * `overrides` replaces a stub's JavaScript body per test row; `null` omits the * stub entirely (tool missing). `opts.nativeHost` must match the run helper the * stubs are handed to: the launcher form is the host's, so a Linux-preloaded * child needs extensionless launchers even when recording on Windows. * `opts.dir` plants the stubs in an existing folder that the caller owns; - * else they go to a new registered temporary folder. + * else they go to a new registered temporary folder. `opts.supervised` makes + * each stub hold a ticket in the folders of a supervised fixture root + * (`supervisedRun.ts`); other stubs carry no ticket code. */ export function makeStubDir( overrides: Record = {}, - opts: { readonly nativeHost?: boolean; readonly dir?: string } = {}, + opts: { + readonly nativeHost?: boolean; + readonly dir?: string; + readonly supervised?: { readonly tickets: string; readonly records: string }; + } = {}, ): string { const unknownNames = Object.keys(overrides) .filter((name) => !Object.hasOwn(STUB_BODIES, name)) @@ -425,26 +468,9 @@ export function makeStubDir( } writeFileSync( runnerPath, - `import { randomUUID } from "node:crypto" -import { appendFileSync, closeSync, openSync, unlinkSync, writeFileSync } from "node:fs" -import { join } from "node:path" + `import { appendFileSync } from "node:fs" +${opts.supervised === undefined ? "" : supervisedStubPrelude(opts.supervised)} const [name, ...args] = process.argv.slice(2) -// A supervised fixture counts its running stubs by tickets (supervisedRun.ts). A stub that -// cannot create its ticket, because the teardown closed the folder, ends at once without its -// body; one that holds a ticket removes it as its last act, on every exit path. -const tickets = process.env["GOLDEN_STUB_TICKETS"] -if (tickets !== undefined) { - const ticket = join(tickets, randomUUID()) - let held - try { - held = openSync(ticket, "wx") - } catch { - process.exit(0) - } - writeFileSync(held, \`\${process.pid}\\n\`) - closeSync(held) - process.on("exit", () => unlinkSync(ticket)) -} const argvLog = process.env["GOLDEN_ARGV_LOG"] if (argvLog !== undefined) appendFileSync(argvLog, \`\${name}\\t\${args.join(" ")}\\n\`) switch (name) { diff --git a/cli/test/lib/signalSupervisor.ts b/cli/test/lib/signalSupervisor.ts index c79405e6..81fe4a63 100644 --- a/cli/test/lib/signalSupervisor.ts +++ b/cli/test/lib/signalSupervisor.ts @@ -20,7 +20,7 @@ * worker dies for any reason), or when it cannot write a report, it writes * `SIGTERM` into the signal request file of the launch, which the preload of * the CLI reads to signal its own process. It then waits for the CLI to end - * and until no stub of the root holds a ticket, writes `shutdown-confirmed`, + * and until every stub of the root has ended (`stubsEnded`), writes `shutdown-confirmed`, * and exits. A wait past the bound ends it without the confirmation. */ import { spawn } from "node:child_process"; @@ -32,7 +32,7 @@ import { SHUTDOWN_CONFIRMED, SIGNAL_REQUEST, SUPERVISOR_PID, - ticketsReleased, + stubsEnded, } from "./supervisedRun"; /** How long the shutdown waits for the CLI and its stubs; past it, no confirmation. */ @@ -81,7 +81,7 @@ const shutDown = (): void => { } const deadline = performance.now() + SHUTDOWN_BOUND_MS; const confirm = (): void => { - if (cliEnded && ticketsReleased(root)) { + if (cliEnded && stubsEnded(root)) { writeFileSync(join(launch, SHUTDOWN_CONFIRMED), ""); process.exit(0); } @@ -98,7 +98,12 @@ process.stdin.once("close", shutDown); process.stdin.resume(); const cli = spawn(command, args, { env, stdio: "ignore" }); -if (cli.pid !== undefined) writeFileSync(join(launch, CLI_PID), String(cli.pid)); +if (cli.pid !== undefined) { + // A reader sees the whole record or none: the waiting stub may read it before this line runs. + const record = join(launch, CLI_PID); + writeFileSync(`${record}.pending`, String(cli.pid)); + renameSync(`${record}.pending`, record); +} cli.once("exit", (code, signal) => { cliEnded = true; if (!report({ exit: { code, signal } })) shutDown(); diff --git a/cli/test/lib/supervisedRun.ts b/cli/test/lib/supervisedRun.ts index f8a89187..4244c00d 100644 --- a/cli/test/lib/supervisedRun.ts +++ b/cli/test/lib/supervisedRun.ts @@ -2,17 +2,20 @@ * The records of a fixture root of the spawned signal cases. Each supervised * launch has a folder below `/launches/`, which the test creates before * it starts `signalSupervisor.ts`; the supervisor records its pid and the pid - * of the CLI, and writes `shutdown-confirmed` once the CLI has ended and no - * stub holds a ticket. + * of the CLI, and writes `shutdown-confirmed` once the CLI has ended, no stub + * holds a ticket, and each stub that took one recorded its exit. * - * Stubs hold tickets in `/active/` (`goldenResources.ts makeStubDir`, - * `GOLDEN_STUB_TICKETS`): each invocation first creates its ticket - * `` exclusively, and exits at once without its body when it cannot; it - * removes the ticket as its last act, on every exit path. The teardown closes - * the registration with a non-recursive `rmdir` of `active/`: it succeeds only - * while the folder is empty, and no entry can be created in it afterwards, - * also through a path that was resolved before. A root goes only when every - * launch is confirmed and that `rmdir` succeeded; no sweep removes it. + * Stubs generated for the root (`goldenResources.ts makeStubDir`, + * `opts.supervised`) hold tickets in `/active/`: each invocation first + * creates its ticket `` exclusively, and exits nonzero without its body + * when it cannot. Right after the create it arms its release, which runs on + * every exit path: it writes `/stub-records/.stub-exited`, then + * removes its ticket. Then it writes `.started` there. The teardown + * closes the registration with a non-recursive `rmdir` of `active/`: it + * succeeds only while the folder is empty, and no entry can be created in it + * afterwards, also through a path that was resolved before. A root goes only + * when every launch is confirmed and that `rmdir` succeeded; no sweep + * removes it. * * Only `node:` imports, so the supervisor can load this module alone. */ @@ -21,21 +24,45 @@ import { join } from "node:path"; /** The folder of a fixture root that holds one record folder per supervised launch. */ export const LAUNCHES_DIR = "launches"; -/** Written by the supervisor once the CLI has ended and no stub holds a ticket. */ +/** Written by the supervisor once the CLI and every stub have ended. */ export const SHUTDOWN_CONFIRMED = "shutdown-confirmed"; /** The pid of the supervisor of the launch. */ export const SUPERVISOR_PID = "supervisor.pid"; -/** The pid of the CLI of the launch. */ +/** The pid of the CLI of the launch, published whole by rename. */ export const CLI_PID = "cli.pid"; /** The file that the CLI preload reads: `SIGTERM` or `SIGINT` asks the CLI to signal itself. */ export const SIGNAL_REQUEST = "signal-request"; /** The ticket folder of a root: one entry per running stub. */ export const TICKETS_DIR = "active"; +/** The folder of the start and exit records of the stubs of a root, named by invocation id. */ +export const STUB_RECORDS_DIR = "stub-records"; +export const STUB_STARTED_SUFFIX = ".started"; +export const STUB_EXITED_SUFFIX = ".stub-exited"; -/** True when no stub of `root` holds a ticket: the ticket folder is empty, or closed. */ -export function ticketsReleased(root: string): boolean { - const tickets = join(root, TICKETS_DIR); - return !existsSync(tickets) || readdirSync(tickets).length === 0; +/** The ticket and record folders that the stubs of `root` use. */ +export function supervisedStubFolders(root: string): { + readonly tickets: string; + readonly records: string; +} { + return { tickets: join(root, TICKETS_DIR), records: join(root, STUB_RECORDS_DIR) }; +} + +/** + * True when every stub of `root` has ended: no stub holds a ticket (the + * ticket folder is empty, or closed), and each stub that recorded its start + * also recorded its exit. + */ +export function stubsEnded(root: string): boolean { + const { tickets, records } = supervisedStubFolders(root); + if (existsSync(tickets) && readdirSync(tickets).length > 0) return false; + if (!existsSync(records)) return true; + const names = new Set(readdirSync(records)); + for (const name of names) { + if (!name.endsWith(STUB_STARTED_SUFFIX)) continue; + const id = name.slice(0, -STUB_STARTED_SUFFIX.length); + if (!names.has(`${id}${STUB_EXITED_SUFFIX}`)) return false; + } + return true; } /** The launch folders of the fixture root `root`. */ diff --git a/cli/test/unit/syncSignals.test.ts b/cli/test/unit/syncSignals.test.ts index 82152064..9e815013 100644 --- a/cli/test/unit/syncSignals.test.ts +++ b/cli/test/unit/syncSignals.test.ts @@ -55,6 +55,7 @@ import { TICKETS_DIR, launchConfirmed, launches, + supervisedStubFolders, } from "../lib/supervisedRun"; const LIB = join(REPO_DIR, "cli", "test", "lib"); @@ -85,7 +86,21 @@ const CLI_PID_FILE = "SYNC_SIGNAL_CLI_PID_FILE"; const WAITING_OMP = `if (args[0] === "plugin" && args[1] === "list") { // The body goes inside the switch of the generated runner, which takes no other static import. const { readFileSync, writeFileSync } = await import("node:fs") - const cli = Number(readFileSync(process.env["${CLI_PID_FILE}"], "utf8").trim()) + setTimeout(() => process.exit(1), ${STUB_MAX_LIFETIME_MS}) + // The supervisor publishes the record by rename, possibly after the CLI started this stub. + const recordedCli = () => { + try { + const text = readFileSync(process.env["${CLI_PID_FILE}"], "utf8").trim() + return /^\\d+$/.test(text) && Number(text) > 0 ? Number(text) : undefined + } catch { + return undefined + } + } + let cli = recordedCli() + while (cli === undefined) { + await new Promise((settle) => setTimeout(settle, 20)) + cli = recordedCli() + } const parentGone = () => { if (process.ppid !== cli) return true try { @@ -100,7 +115,6 @@ const WAITING_OMP = `if (args[0] === "plugin" && args[1] === "list") { setInterval(() => { if (parentGone()) process.exit(0) }, 100) - setTimeout(() => process.exit(1), ${STUB_MAX_LIFETIME_MS}) writeFileSync(process.env["${MARKER_FILE}"], String(process.pid)) } else { ${ompStubBody()} @@ -130,6 +144,8 @@ interface Fixture { readonly home: string; readonly bunCache: string; readonly transpilerCache: string; + /** The launches of this root whose supervisor has not closed. */ + readonly running: Set; launchCount: number; } @@ -143,25 +159,31 @@ interface Launch { readonly stop: () => void; } +/** Every root that is still tracked: not removed, and not reported as kept. */ const fixtures = new Set(); -const running = new Set(); +/** The roots of the current case. */ +const caseFixtures = new Set(); /** - * Stop every supervisor and wait within `budgetMs` until each launch - * confirmed its shutdown. Then close the ticket folder of the root with a - * non-recursive `rmdir`, retried while a stub still holds a ticket; once it - * succeeds, no stub can start its body in the root. A root goes only then. - * Return one line for each root that does not get there; it stays, and no - * sweep removes it. It sends no signal. + * Stop the supervisors of `scope` and wait within `budgetMs` until each + * launch confirmed its shutdown. Then close the ticket folder of the root + * with a non-recursive `rmdir`, retried while a stub still holds a ticket; + * once it succeeds, no stub can start its body in the root. A root goes only + * then. Return one line for each root that does not get there: it stays on + * disk, leaves the tracking, and no sweep removes it. It sends no signal. */ -async function stopAndRemove(budgetMs: number): Promise> { +async function stopAndRemove( + scope: ReadonlySet, + budgetMs: number, +): Promise> { const deadline = performance.now() + budgetMs; - for (const run of running) run.stop(); + const pending = [...scope].filter((fixture) => fixtures.has(fixture)); + for (const fixture of pending) for (const run of fixture.running) run.stop(); const unconfirmed = (fixture: Fixture): Array => launches(fixture.root).filter((folder) => !launchConfirmed(folder)); const closed = new Set(); for (;;) { - for (const fixture of fixtures) { + for (const fixture of pending) { if (closed.has(fixture) || unconfirmed(fixture).length > 0) continue; try { // It fails while a stub holds a ticket; after it, no ticket can be created. @@ -171,11 +193,12 @@ async function stopAndRemove(budgetMs: number): Promise> { // A stub still holds a ticket: retry within the budget. } } - if (closed.size === fixtures.size || performance.now() >= deadline) break; + if (closed.size === pending.length || performance.now() >= deadline) break; await sleep(20); } const problems: Array = []; - for (const fixture of [...fixtures]) { + for (const fixture of pending) { + fixtures.delete(fixture); if (!closed.has(fixture)) { const open = unconfirmed(fixture); problems.push( @@ -185,7 +208,6 @@ async function stopAndRemove(budgetMs: number): Promise> { ); continue; } - fixtures.delete(fixture); try { rmSync(fixture.root, { recursive: true, force: true }); } catch (error) { @@ -195,12 +217,15 @@ async function stopAndRemove(budgetMs: number): Promise> { return problems; } -// A cancelled worker stops the supervisors before its sweep, within its bound. +// A cancelled worker stops the supervisors of every tracked root before its sweep, within its bound. registerBeforeTemporaryDirRemoval(async () => { - await stopAndRemove(SIGNAL_PATH_BUDGET_MS); + const problems = await stopAndRemove(fixtures, SIGNAL_PATH_BUDGET_MS); + if (problems.length > 0) process.stderr.write(`syncSignals teardown:\n${problems.join("\n")}\n`); }); afterEach(async () => { - const problems = await stopAndRemove(TEARDOWN_BUDGET_MS); + const scope = new Set(caseFixtures); + caseFixtures.clear(); + const problems = await stopAndRemove(scope, TEARDOWN_BUDGET_MS); if (problems.length > 0) throw new Error(`teardown:\n${problems.join("\n")}`); }, TEARDOWN_HOOK_TIMEOUT_MS); @@ -213,13 +238,28 @@ function makeFixture(): Fixture { home: join(root, "home"), bunCache: join(root, "bun-cache"), transpilerCache: join(root, "bun-transpiler"), + running: new Set(), launchCount: 0, }; - for (const folder of [fixture.work, fixture.home, fixture.bunCache, fixture.transpilerCache]) { - mkdirSync(folder); + const { tickets, records } = supervisedStubFolders(root); + try { + for (const folder of [ + fixture.work, + fixture.home, + fixture.bunCache, + fixture.transpilerCache, + tickets, + records, + ]) { + mkdirSync(folder); + } + } catch (error) { + // No process has started in it yet, so the partial root goes at once. + rmSync(root, { recursive: true, force: true }); + throw error; } - mkdirSync(join(root, TICKETS_DIR)); fixtures.add(fixture); + caseFixtures.add(fixture); return fixture; } @@ -241,7 +281,11 @@ function launch( writeFileSync(request, ""); const stubs = join(fixture.root, `stubs-${fixture.launchCount}`); mkdirSync(stubs); - makeStubDir(stubOverrides, { nativeHost: true, dir: stubs }); + makeStubDir(stubOverrides, { + nativeHost: true, + dir: stubs, + supervised: supervisedStubFolders(fixture.root), + }); const cliEnv: Record = { HOME: fixture.home, USERPROFILE: fixture.home, @@ -251,7 +295,6 @@ function launch( BUN_INSTALL_CACHE_DIR: fixture.bunCache, BUN_RUNTIME_TRANSPILER_CACHE_PATH: fixture.transpilerCache, SIGNAL_REQUEST_FILE: request, - GOLDEN_STUB_TICKETS: join(fixture.root, TICKETS_DIR), ...extraEnv(folder), }; const supervisor = spawn(BUN_RUNTIME, ["--no-env-file", SUPERVISOR], { @@ -294,13 +337,13 @@ function launch( stop: () => supervisor.stdin?.end(), }; supervisor.once("close", (code, signal) => { - running.delete(started); + fixture.running.delete(started); ended.resolve({ kind: "error", error: `the supervisor closed (code ${String(code)}, signal ${String(signal)})`, }); }); - running.add(started); + fixture.running.add(started); return started; } From fe26962c635ccd6ce5a9b605df434c4218b49060 Mon Sep 17 00:00:00 2001 From: Eduardo Marquez <55303379+DocksDocks@users.noreply.github.com> Date: Tue, 1 Dec 2026 22:23:30 -0300 Subject: [PATCH 11/11] Publish stub exit records atomically in the signal fixture Repairs of code-review round 8 of #294: - A stub releases its ticket by renaming it to its stub-exited record; a failed rename keeps it. - A failed cli.pid publication asks the CLI to end and blocks confirmation; the waiting stub also stops when its parent changes. - Overlapping teardown paths recheck tracking before retries and reports. - Lifecycle comments list startup and exit actions in their real order. Verified: bun x --no-install vitest run (unit, toggles, signals rows, skillMetadata.test.ts); bun run check:types; bun run lint; bun run check --- cli/test/lib/goldenResources.ts | 24 ++++++++++++------- cli/test/lib/signalSupervisor.ts | 40 +++++++++++++++++++++---------- cli/test/lib/supervisedRun.ts | 31 +++++++++++++----------- cli/test/unit/syncSignals.test.ts | 22 +++++++++++++---- 4 files changed, 76 insertions(+), 41 deletions(-) diff --git a/cli/test/lib/goldenResources.ts b/cli/test/lib/goldenResources.ts index 3581de96..2cfc8882 100644 --- a/cli/test/lib/goldenResources.ts +++ b/cli/test/lib/goldenResources.ts @@ -397,18 +397,24 @@ export function readStubHost(stubDir: string): string { } /** - * The ticket code of a stub of a supervised fixture (`supervisedRun.ts`). The - * stub creates its ticket exclusively and ends nonzero, without its body, when - * it cannot, so the engine sees a failed tool. Right after the create it arms - * its release for every exit path: it records its exit, then removes its - * ticket. Only then it writes its pid into the ticket and records its start. + * The ticket code of a stub of a supervised fixture (`supervisedRun.ts`). + * + * At startup, in this order: the stub creates its ticket exclusively, and + * ends nonzero without its body when it cannot, so the engine sees a failed + * tool; it arms its exit action; it writes its pid into the ticket and closes + * it; it records its start as `.started`. Then its body runs. + * + * On every exit path, its one exit action renames the ticket to its exit + * record `.stub-exited`, which releases the ticket and publishes the + * record in one step. When that rename fails, the ticket stays and keeps the + * root from removal. */ function supervisedStubPrelude(folders: { readonly tickets: string; readonly records: string; }): string { return `import { randomUUID } from "node:crypto" -import { closeSync, openSync, unlinkSync, writeFileSync } from "node:fs" +import { closeSync, openSync, renameSync, writeFileSync } from "node:fs" import { join } from "node:path" const stubId = randomUUID() const ticket = join(${JSON.stringify(folders.tickets)}, stubId) @@ -422,9 +428,9 @@ try { } process.on("exit", () => { try { - writeFileSync(join(records, \`\${stubId}${STUB_EXITED_SUFFIX}\`), "") - } finally { - unlinkSync(ticket) + renameSync(ticket, join(records, \`\${stubId}${STUB_EXITED_SUFFIX}\`)) + } catch (error) { + process.stderr.write(\`golden stub: the ticket \${ticket} stays: \${String(error)}\\n\`) } }) writeFileSync(held, \`\${process.pid}\\n\`) diff --git a/cli/test/lib/signalSupervisor.ts b/cli/test/lib/signalSupervisor.ts index 81fe4a63..15c106f8 100644 --- a/cli/test/lib/signalSupervisor.ts +++ b/cli/test/lib/signalSupervisor.ts @@ -68,20 +68,27 @@ writeFileSync(join(launch, SUPERVISOR_PID), String(process.pid)); let cliEnded = false; let shuttingDown = false; +/** False until `cli.pid` is published; without it the launch gets no confirmation. */ +let pidPublished = false; +let terminationRequested = false; + +/** Ask the CLI to end itself: the request appears whole, by rename, and its preload raises it. */ +const requestTermination = (): void => { + if (terminationRequested || cliEnded) return; + terminationRequested = true; + const request = join(launch, SIGNAL_REQUEST); + writeFileSync(`${request}.pending`, "SIGTERM"); + renameSync(`${request}.pending`, request); +}; /** Ask the CLI to end itself, wait for it and its stubs, confirm, and exit. */ const shutDown = (): void => { if (shuttingDown) return; shuttingDown = true; - if (!cliEnded) { - // The request appears whole, by rename; the preload of the CLI raises it on its own process. - const request = join(launch, SIGNAL_REQUEST); - writeFileSync(`${request}.pending`, "SIGTERM"); - renameSync(`${request}.pending`, request); - } + requestTermination(); const deadline = performance.now() + SHUTDOWN_BOUND_MS; const confirm = (): void => { - if (cliEnded && stubsEnded(root)) { + if (pidPublished && cliEnded && stubsEnded(root)) { writeFileSync(join(launch, SHUTDOWN_CONFIRMED), ""); process.exit(0); } @@ -98,12 +105,6 @@ process.stdin.once("close", shutDown); process.stdin.resume(); const cli = spawn(command, args, { env, stdio: "ignore" }); -if (cli.pid !== undefined) { - // A reader sees the whole record or none: the waiting stub may read it before this line runs. - const record = join(launch, CLI_PID); - writeFileSync(`${record}.pending`, String(cli.pid)); - renameSync(`${record}.pending`, record); -} cli.once("exit", (code, signal) => { cliEnded = true; if (!report({ exit: { code, signal } })) shutDown(); @@ -112,3 +113,16 @@ cli.once("error", (error) => { cliEnded = true; if (!report({ error: error.message })) shutDown(); }); +if (cli.pid !== undefined) { + // A reader sees the whole record or none: the waiting stub may read it before this line runs. + const record = join(launch, CLI_PID); + try { + writeFileSync(`${record}.pending`, String(cli.pid)); + renameSync(`${record}.pending`, record); + pidPublished = true; + } catch (error) { + // The CLI still runs; it ends through its request file, and its exit report follows as usual. + process.stderr.write(`signal supervisor: cannot publish ${record}: ${String(error)}\n`); + requestTermination(); + } +} diff --git a/cli/test/lib/supervisedRun.ts b/cli/test/lib/supervisedRun.ts index 4244c00d..00b076c7 100644 --- a/cli/test/lib/supervisedRun.ts +++ b/cli/test/lib/supervisedRun.ts @@ -6,16 +6,18 @@ * holds a ticket, and each stub that took one recorded its exit. * * Stubs generated for the root (`goldenResources.ts makeStubDir`, - * `opts.supervised`) hold tickets in `/active/`: each invocation first - * creates its ticket `` exclusively, and exits nonzero without its body - * when it cannot. Right after the create it arms its release, which runs on - * every exit path: it writes `/stub-records/.stub-exited`, then - * removes its ticket. Then it writes `.started` there. The teardown - * closes the registration with a non-recursive `rmdir` of `active/`: it - * succeeds only while the folder is empty, and no entry can be created in it - * afterwards, also through a path that was resolved before. A root goes only - * when every launch is confirmed and that `rmdir` succeeded; no sweep - * removes it. + * `opts.supervised`) hold tickets in `/active/`. At startup, in this + * order, each invocation creates its ticket `` exclusively (it exits + * nonzero without its body when it cannot), arms its exit action, writes its + * pid into the ticket, and writes `/stub-records/.started`. On + * every exit path, its exit action renames the ticket to + * `/stub-records/.stub-exited`: one step releases the ticket and + * publishes the exit record; a failed rename leaves the ticket in place. The + * teardown closes the registration with a non-recursive `rmdir` of + * `active/`: it succeeds only while the folder is empty, and no entry can be + * created in it afterwards, also through a path that was resolved before. A + * root goes only when every launch is confirmed and that `rmdir` succeeded; + * no sweep removes it. * * Only `node:` imports, so the supervisor can load this module alone. */ @@ -48,14 +50,15 @@ export function supervisedStubFolders(root: string): { } /** - * True when every stub of `root` has ended: no stub holds a ticket (the - * ticket folder is empty, or closed), and each stub that recorded its start - * also recorded its exit. + * True when every stub of `root` has ended: no ticket is left (the ticket + * folder is empty, or closed), and each stub that recorded its start has its + * exit record, which is its renamed ticket. A missing record folder counts as + * not ended. */ export function stubsEnded(root: string): boolean { const { tickets, records } = supervisedStubFolders(root); if (existsSync(tickets) && readdirSync(tickets).length > 0) return false; - if (!existsSync(records)) return true; + if (!existsSync(records)) return false; const names = new Set(readdirSync(records)); for (const name of names) { if (!name.endsWith(STUB_STARTED_SUFFIX)) continue; diff --git a/cli/test/unit/syncSignals.test.ts b/cli/test/unit/syncSignals.test.ts index 9e815013..9cecd7f6 100644 --- a/cli/test/unit/syncSignals.test.ts +++ b/cli/test/unit/syncSignals.test.ts @@ -88,6 +88,7 @@ const WAITING_OMP = `if (args[0] === "plugin" && args[1] === "list") { const { readFileSync, writeFileSync } = await import("node:fs") setTimeout(() => process.exit(1), ${STUB_MAX_LIFETIME_MS}) // The supervisor publishes the record by rename, possibly after the CLI started this stub. + const startParent = process.ppid const recordedCli = () => { try { const text = readFileSync(process.env["${CLI_PID_FILE}"], "utf8").trim() @@ -98,6 +99,8 @@ const WAITING_OMP = `if (args[0] === "plugin" && args[1] === "list") { } let cli = recordedCli() while (cli === undefined) { + // A record that never comes must not keep a stub whose CLI has ended. + if (process.ppid !== startParent) process.exit(0) await new Promise((settle) => setTimeout(settle, 20)) cli = recordedCli() } @@ -170,7 +173,9 @@ const caseFixtures = new Set(); * with a non-recursive `rmdir`, retried while a stub still holds a ticket; * once it succeeds, no stub can start its body in the root. A root goes only * then. Return one line for each root that does not get there: it stays on - * disk, leaves the tracking, and no sweep removes it. It sends no signal. + * disk, leaves the tracking, and no sweep removes it. A root that the other + * teardown path has taken over meanwhile (it left the tracking) is done here, + * with no line. It sends no signal. */ async function stopAndRemove( scope: ReadonlySet, @@ -182,22 +187,29 @@ async function stopAndRemove( const unconfirmed = (fixture: Fixture): Array => launches(fixture.root).filter((folder) => !launchConfirmed(folder)); const closed = new Set(); + const settled = (): boolean => + pending.every((fixture) => closed.has(fixture) || !fixtures.has(fixture)); for (;;) { for (const fixture of pending) { - if (closed.has(fixture) || unconfirmed(fixture).length > 0) continue; + if (closed.has(fixture) || !fixtures.has(fixture) || unconfirmed(fixture).length > 0) { + continue; + } try { // It fails while a stub holds a ticket; after it, no ticket can be created. rmdirSync(join(fixture.root, TICKETS_DIR)); closed.add(fixture); - } catch { - // A stub still holds a ticket: retry within the budget. + } catch (error) { + // The other teardown path closed it already; otherwise a stub still holds a ticket. + if ((error as NodeJS.ErrnoException).code === "ENOENT") closed.add(fixture); } } - if (closed.size === pending.length || performance.now() >= deadline) break; + if (settled() || performance.now() >= deadline) break; await sleep(20); } const problems: Array = []; for (const fixture of pending) { + // The other teardown path removed or reported it already. + if (!fixtures.has(fixture)) continue; fixtures.delete(fixture); if (!closed.has(fixture)) { const open = unconfirmed(fixture);