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