diff --git a/.agents/skills/engine-native-context/SKILL.md b/.agents/skills/engine-native-context/SKILL.md
index 30c6191a..c0754499 100644
--- a/.agents/skills/engine-native-context/SKILL.md
+++ b/.agents/skills/engine-native-context/SKILL.md
@@ -6,11 +6,11 @@ metadata:
pattern: tool-wrapper
source_files:
- path: cli/src/engine-native/index.ts
- lines: "1-82"
+ lines: "1-98"
- path: cli/src/engine.ts
- lines: "1-103"
+ lines: "1-92"
- path: cli/src/main.ts
- lines: "1-78"
+ lines: "1-84"
- path: cli/src/engine-native/exec.ts
lines: "1-346"
- path: cli/src/engine-native/jq.ts
@@ -39,7 +39,7 @@ metadata:
lines: "1-18"
- path: cli/test/lib/goldenProveRed.ts
lines: "1-63"
- updated: "2026-12-01"
+ updated: "2026-12-02"
---
# EngineNative Golden Contract
diff --git a/.agents/skills/omp-sync-context/SKILL.md b/.agents/skills/omp-sync-context/SKILL.md
index 7e41b515..2fec0128 100644
--- a/.agents/skills/omp-sync-context/SKILL.md
+++ b/.agents/skills/omp-sync-context/SKILL.md
@@ -6,27 +6,27 @@ metadata:
pattern: tool-wrapper
source_files:
- path: cli/src/engine-native/ompSync.ts
- lines: "1-122"
+ lines: "1-151"
- path: cli/src/engine-native/ompFileDeploy.ts
- lines: "1-116"
+ lines: "1-131"
- path: cli/src/engine-native/ompPlugins.ts
- lines: "1-374"
+ lines: "1-436"
- path: cli/src/engine-native/ompKitPlugin.ts
- lines: "1-99"
+ lines: "1-164"
- path: cli/src/engine-native/ompRemovals.ts
- lines: "1-385"
+ lines: "1-466"
- path: cli/src/engine-native/failures.ts
lines: "1-16"
- path: cli/src/engine-native/ompPaths.ts
- lines: "1-123"
+ lines: "1-128"
- path: cli/src/engine-native/ompYaml.ts
- lines: "1-213"
+ lines: "1-255"
- path: cli/src/engine-native/home.ts
lines: "1-15"
- path: cli/src/engine-native/kitDb.ts
lines: "1-177"
- path: cli/src/commands/root.ts
- lines: "1-133"
+ lines: "1-150"
- path: cli/src/engine-native/syncDispatch.ts
lines: "1-215"
- path: cli/src/engine-native/atomicWrite.ts
@@ -34,8 +34,10 @@ metadata:
- path: cli/src/engine-native/ompFastMode.ts
lines: "1-63"
- path: cli/src/engine-native/ompChild.ts
- lines: "1-26"
- updated: "2026-12-01"
+ lines: "1-32"
+ - path: cli/src/engine-native/fileText.ts
+ lines: "1-65"
+ updated: "2026-12-02"
---
# omp Sync Context
@@ -56,9 +58,47 @@ Preserve the two deployment roots and all private modes.
Create directories with mode `0700`.
Write files with mode `0600`.
Run `chmod` after each creation or write.
-`mkdirSync` and `writeFileSync` apply `mode` only when they create a path.
+`FileSystem.makeDirectory` and `writeFileString` apply `mode` only when they
+create a path.
+Run each write or copy with its chmod, each directory creation with its
+chmod, each removal, and each `replaceFile` call as one started mutation
+(`signalGuard.ts mutationRegion`), so neither an interrupt nor a handled signal
+ends the run between the write and its chmod.
+The omp passes (`ompFileDeploy.ts`, `ompKitPlugin.ts`, `ompPlugins.ts`,
+`ompRemovals.ts`, `ompChild.ts`, `ompPaths.ts`) are Effect code on the
+`FileSystem` service, with typed failures. A failed `FileSystem` read, write,
+copy, chmod, directory creation, listing, or `lstat` of a pass fails the run
+with its `PlatformError`, and a YAML merge or prune fails with
+`OmpYamlInvalid`. These failures do not fail the run:
+
+- An existence probe counts every failure as absent.
+- A failed read of the marketplace registry: `ENOENT` and `ENOTDIR` mean that
+ the registry is missing, and any other error only warns.
+- A failed removal of the retired upgrade log, or a failure of its status
+ line, only warns (`ompPlugins.ts removeUpgradeLog`).
+
+The kit plugin prune removes a stale file with `unlinkSync` and an empty
+folder with `rmdirSync`, each inside `Effect.try`. A failed file removal fails
+the run with `PluginFileRemoveFailed`, and a failed folder removal with
+`PluginFolderRemoveFailed`; each keeps the Node error and its message.
+`FileSystem` has no removal of an empty folder alone, and the
+`FileSystem.remove` adapter of Bun 1.4.5 reports `EPERM` as `EFAULT`.
+
+The calls of the passes into `atomicWrite.ts`, `exec.ts` (through
+`ompChild.ts spawnOmp`), the dependency probes, and the logger (also through
+`recordFailure` and `deps.warnMissing`) stay behind `bridge.ts bridgeSync` or
+`bridgePromise` until #297 and #298.
+Every text read that a comparison or a parser uses goes through
+`fileText.ts readTextKeepingBom`, which keeps a leading byte order mark, as
+`readFileSync(path, "utf8")` did; `FileSystem.readFileString` drops it.
+Every existence probe goes through `fileText.ts pathExists`, which follows a
+symlink on every platform (`FileSystem.stat`), so a link to a missing target
+is absent, and counts every failure as absent, as the synchronous `node:fs`
+probe did. Do not use `FileSystem.exists`: on Windows it sees the link and
+not its target.
+
Resolve every omp path through `ompPaths.ts ompPaths`, which mirrors upstream
`dirs.ts` `DirResolver`. Never join `ctx.home` with `.omp`.
@@ -74,7 +114,12 @@ The agent directory never moves under XDG; only `dataRoot` does, on Linux and
macOS, and only when the probed omp directory already exists.
Deploy `AGENTS.md`, `config.yml`, `models.yml`, and `mcp.json` to `agentDir`, and read
the active `marketplaces.json` from `dataRoot`.
-Resolution stays env plus `existsSync` so a dry run runs no omp subcommand.
+Resolution stays env plus an existence probe of the final candidate
+(`fileText.ts pathExists`), so a dry run runs no omp subcommand. The probe
+checks existence only, not the type: when a folder above the candidate is a
+file, the candidate is absent and `dataRoot` falls back to the config root,
+but when the candidate itself is a file, `dataRoot` is that path.
+`ompPaths` is an Effect; the path math stays plain.
Plugin identity, the marketplace registry states of the retirement, the probe
@@ -256,20 +301,27 @@ and `bunx vitest run cli/test/unit/ompFastMode.test.ts -t "--fast under the fold
### Private Mode Pattern
```ts
-// BAD — mode does not repair an existing permissive path.
-mkdirSync(directory, { recursive: true, mode: 0o700 })
-writeFileSync(target, content, { mode: 0o600 })
-
-// GOOD — chmod enforces the private mode after each operation.
-mkdirSync(directory, { recursive: true, mode: 0o700 })
-chmodSync(directory, 0o700)
-writeFileSync(target, content, { mode: 0o600 })
-chmodSync(target, 0o600)
+// BAD — mode does not repair an existing permissive path, and an interrupt
+// or a signal can end the run between the write and the chmod.
+yield* fs.makeDirectory(directory, { recursive: true, mode: 0o700 })
+yield* fs.writeFileString(target, content, { mode: 0o600 })
+yield* fs.chmod(target, 0o600)
+
+// GOOD — chmod enforces the private mode, and each pair is one started mutation.
+yield* mutationRegion(
+ Effect.andThen(fs.makeDirectory(directory, { recursive: true, mode: 0o700 }), fs.chmod(directory, 0o700)),
+)
+yield* mutationRegion(
+ Effect.andThen(fs.writeFileString(target, content, { mode: 0o600 }), fs.chmod(target, 0o600)),
+)
```
Verify the private modes and the kit plugin rules:
`bunx vitest run cli/test/unit/ompKitPlugin.test.ts -t "writes the plugin package with the kit version and private modes"`
and `bunx vitest run cli/test/unit/ompKitPlugin.test.ts -t "removes stale files and empty directories from the plugin directory"`.
+Verify the mutation region:
+`bunx vitest run cli/test/unit/syncLock.test.ts -t "finishes a started deploy write with its chmod"`
+and `bunx vitest run cli/test/unit/syncSignals.test.ts -t "between a deploy write and its chmod"`.
## References
diff --git a/.agents/skills/omp-sync-context/references/yaml-merge.md b/.agents/skills/omp-sync-context/references/yaml-merge.md
index eeb6c179..25324abe 100644
--- a/.agents/skills/omp-sync-context/references/yaml-merge.md
+++ b/.agents/skills/omp-sync-context/references/yaml-merge.md
@@ -36,6 +36,15 @@ Validate both YAML roots as mappings when the deployed document is non-empty.
Return Source of Truth text when the deployed document is empty.
Reject invalid deployed YAML without writing the target.
+`mergeOmpConfig` and `mergeOmpModels` stay plain functions and return an
+`effect/Result`: the merged text, or an `OmpYamlInvalid` failure that keeps
+the message of each refusal (`Invalid deployed omp YAML: ...`,
+`Deployed omp YAML root must be a mapping`, and the SoT forms). A
+merged document that the `yaml` library cannot write, such as an alias that
+comes before its anchor, is also `OmpYamlInvalid`, with the message of the
+library (`ompYaml.ts yamlText`). `syncMergedYaml` yields the `Result`
+through `Effect.fromResult`, so the run fails with that message.
+
| Node relationship | Result |
|---|---|
| Both nodes are mappings | Merge recursively. |
@@ -51,7 +60,8 @@ Do not replace this parser with a line-based YAML merge.
Verify the merge:
`bunx vitest run cli/test/unit/ompYamlMerge.test.ts -t "drops deployed-only slash keys under retry.fallbackChains while keeping role siblings"`,
`bunx vitest run cli/test/unit/ompYamlMerge.test.ts -t "keeps a deployed-only slash key outside retry.fallbackChains"`,
-`bunx vitest run cli/test/unit/ompYamlMerge.test.ts -t "throws for invalid deployed YAML"`,
+`bunx vitest run cli/test/unit/ompYamlMerge.test.ts -t "fails with OmpYamlInvalid for invalid deployed YAML"`,
+`bunx vitest run cli/test/unit/contract-omp-yaml.test.ts -t "alias before its anchor"`,
and `bunx vitest run cli/test/unit/ompBashPatterns.test.ts -t "puts user denies and prompts ahead of every kit allow"`.
## Retired-Entry Prune
@@ -75,6 +85,8 @@ It keeps a section-header comment above the deleted key. The header moves onto
the next key, or becomes the mapping's trailing comment when no key follows.
A dry run prints `[dry-run] prune` with the entry names and writes nothing.
An unparseable file gets a warning and stays untouched.
+A pruned document that the `yaml` library cannot write fails the run with
+`OmpYamlInvalid` and the message of the library, after the backup.
`ompRemovals.ts pruneRetired` follows the deployment rules in SKILL.md. It
writes through `atomicWrite.ts replaceFile` with mode `0600`, so a symlinked
diff --git a/.agents/skills/sync-orchestration-context/SKILL.md b/.agents/skills/sync-orchestration-context/SKILL.md
index aab8060d..db832744 100644
--- a/.agents/skills/sync-orchestration-context/SKILL.md
+++ b/.agents/skills/sync-orchestration-context/SKILL.md
@@ -8,9 +8,9 @@ metadata:
- path: docks-kit
lines: "1-100"
- path: cli/src/main.ts
- lines: "1-78"
+ lines: "1-84"
- path: cli/src/commands/root.ts
- lines: "1-133"
+ lines: "1-150"
- path: cli/src/argv.ts
lines: "1-59"
- path: cli/src/argvValidate.ts
@@ -18,7 +18,9 @@ metadata:
- path: cli/src/argvSurface.ts
lines: "1-351"
- path: cli/src/engine.ts
- lines: "1-103"
+ lines: "1-92"
+ - path: cli/src/engine-native/signalGuard.ts
+ lines: "1-113"
- path: cli/src/kitHome.ts
lines: "1-99"
- path: cli/src/payload.ts
@@ -30,7 +32,7 @@ metadata:
- path: cli/src/commands/update.ts
lines: "1-282"
- path: cli/src/engine-native/index.ts
- lines: "1-82"
+ lines: "1-98"
- path: cli/src/engine-native/engineCtx.ts
lines: "1-86"
- path: cli/src/engine-native/syncDispatch.ts
@@ -50,14 +52,14 @@ metadata:
- path: cli/src/engine-native/modes.ts
lines: "1-69"
- path: cli/src/engine-native/ompSync.ts
- lines: "1-155"
+ lines: "1-151"
- path: cli/src/engine-native/ompPlugins.ts
- lines: "1-374"
+ lines: "1-436"
- path: cli/src/engine-native/bun.ts
lines: "1-120"
- path: cli/src/engine-native/toolchain.ts
lines: "1-237"
- updated: "2026-12-01"
+ updated: "2026-12-02"
---
# Sync Engine Orchestration
@@ -138,7 +140,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; 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/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` inside `signalGuard.ts exitOnSignal(RAW_SIGNAL_EXIT_CODES)`, and exits with its code; a SIGINT exits 130 and a SIGTERM 143 at once, except inside a started mutation, which `deferSignalExit` lets settle first. 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 }`. |
@@ -219,16 +221,31 @@ writing sync runs `lockedSync` in one lock scope (see § Sync Lock):
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 bridge text of a failure is
+step settles (`references/dispatch-flow.md`). The omp passes are Effect code
+(#296): only their calls into the logger, `atomicWrite.ts`, `exec.ts`, and
+the dependency probes are bridged. 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.
+A failed `FileSystem` operation of a pass fails the run with its
+`PlatformError`, a YAML merge or prune with `OmpYamlInvalid`, and a removal of
+the kit plugin prune with `PluginFileRemoveFailed` or
+`PluginFolderRemoveFailed`; `engine.ts engineFailureDetail` prints the
+message of the Node error or of the YAML failure, as the bridge did. An
+existence probe, the marketplace registry read, and the removal of the retired
+upgrade log do not fail the run (`omp-sync-context`).
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.
+installer child until #297: exit 130 on the public channel (`signalGuard.ts
+exitOnSignal(PUBLIC_SIGNAL_EXIT_CODES)` in `engine.ts`, installed only for the
+run) and 130 or 143 on the raw channel (`exitOnSignal(RAW_SIGNAL_EXIT_CODES)`
+in `main.ts`). The exception is a started mutation of a pass (a write or copy
+with its chmod, a directory creation with its chmod, a removal, or a
+`replaceFile` call): it runs in `signalGuard.ts mutationRegion`, which is
+uninterruptible and inside `deferSignalExit`, so a signal during it is
+recorded and the process exits with that code once the mutation settled. 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.
@@ -265,10 +282,12 @@ 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
- 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"`)
+ in-process interrupt during a bridged pass or a started mutation waits until
+ it settles, and the locks stay held until then. A SIGINT or SIGTERM ends the
+ process at once, except inside a started mutation, which `deferSignalExit`
+ lets settle first (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"`, `bunx vitest run cli/test/unit/syncLock.test.ts -t "finishes a started deploy write with its chmod"`, 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 eaf9810e..1ee2c99e 100644
--- a/.agents/skills/sync-orchestration-context/references/dispatch-flow.md
+++ b/.agents/skills/sync-orchestration-context/references/dispatch-flow.md
@@ -93,14 +93,23 @@ 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`, `../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
-rejection is `LegacyStepFailed`. The ledger stays a plain append
-(`failures.ts recordFailure`), which the Effect code calls through
-`Effect.sync`.
+#290 moves (`bun.ts`, `toolchain.ts`, `home.ts`, `../kitHome.ts`, and the
+logger, the atomic writer, the `exec.ts` spawns, and the dependency probes
+that the omp passes call) goes through `bridge.ts bridgeSync` or
+`bridgePromise`. A bridged step runs without interruption, so an interrupt
+of a sync waits until it settles, and the scope keeps the sync lock and the
+folder locks until then; a throw or a rejection is `LegacyStepFailed`.
+The omp passes themselves are Effect code since #296 and are not bridged:
+`ompFileDeploy.ts`, `ompKitPlugin.ts`, `ompPlugins.ts`, `ompRemovals.ts`,
+`ompPaths.ts`, and `ompChild.ts`. The YAML merges `ompYaml.ts
+mergeOmpConfig` and `mergeOmpModels` are not Effect passes: they are plain
+functions that return an `effect/Result` with an `OmpYamlInvalid` failure,
+and `ompFileDeploy.ts syncMergedYaml` converts that result with
+`Effect.fromResult`. Each started mutation of a pass runs in
+`signalGuard.ts mutationRegion`, uninterruptible and inside
+`deferSignalExit`. The ledger stays a plain append (`failures.ts
+recordFailure`); the plugin pass and `ompSync` call it through `bridgeSync`
+until #297, because its warning goes through the logger.
(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
diff --git a/.agents/skills/tidy-context/SKILL.md b/.agents/skills/tidy-context/SKILL.md
index 011e7e0e..6af19bdc 100644
--- a/.agents/skills/tidy-context/SKILL.md
+++ b/.agents/skills/tidy-context/SKILL.md
@@ -6,7 +6,7 @@ metadata:
pattern: tool-wrapper
source_files:
- path: cli/src/engine-native/tidy.ts
- lines: "1-1487"
+ lines: "1-1464"
- path: cli/src/engine-native/tidyReport.ts
lines: "1-586"
- path: cli/src/engine-native/kitLock.ts
@@ -16,7 +16,7 @@ metadata:
- path: cli/src/engine-native/scratch.ts
lines: "1-206"
- path: cli/src/commands/tidy.ts
- lines: "1-193"
+ lines: "1-199"
- path: cli/src/commands/scratch.ts
lines: "1-75"
- path: SoT/.omp/plugin/extensions/hygiene.ts
@@ -144,7 +144,7 @@ Probe: `bunx vitest run cli/test/unit/tidy.test.ts -t "removes the merged idle w
Probes: `bunx vitest run cli/test/unit/tidy.test.ts -t "containers first, then the worktree"` asserts the order, the `--host` prefix, and no git `--force`. `bunx vitest run cli/test/unit/tidy.test.ts -t "prints the held line and plans nothing while another run holds the lock"` asserts step 1. `bunx vitest run cli/test/unit/tidy.test.ts -t "releases the lock before the report runs"` asserts step 6.
-Signals: `tidyCommand` runs inside `exitOnSignal` (`cli/src/engine.ts`), so SIGINT or SIGTERM exits 130 at once, as the base `BunRuntime.runMain` interrupt did. `applyTidy` takes `deferSignalExit` in a scope that closes after its result is printed and before `--report`; each `git` and `docker` call of the apply runs in `signalExitPoint`. A signal that arrives during a waiting `git` or `docker` call exits 130 at once. A signal recorded during a plain apply step has one of two outcomes: when a later `git` or `docker` call of the apply remains, the CLI exits 130 before it starts the next `git` or `docker` call, and the lines of the apply are not printed; when no such call remains, the apply prints its lines and writes the log, and the CLI then exits 130. Probes: `bunx vitest run cli/test/unit/tidy.test.ts -t "defers a SIGTERM at the"`; `bunx vitest run cli/test/unit/tidy.test.ts -t "while docker rm of --apply waits"`.
+Signals: `tidyCommand` runs inside `exitOnSignal` (`cli/src/engine-native/signalGuard.ts`), so SIGINT or SIGTERM exits 130 at once, as the base `BunRuntime.runMain` interrupt did. `applyTidy` takes `deferSignalExit` in a scope that closes after its result is printed and before `--report`; each `git` and `docker` call of the apply runs in `signalExitPoint`. A signal that arrives during a waiting `git` or `docker` call exits 130 at once. A signal recorded during a plain apply step has one of two outcomes: when a later `git` or `docker` call of the apply remains, the CLI exits 130 before it starts the next `git` or `docker` call, and the lines of the apply are not printed; when no such call remains, the apply prints its lines and writes the log, and the CLI then exits 130. Probes: `bunx vitest run cli/test/unit/tidy.test.ts -t "defers a SIGTERM at the"`; `bunx vitest run cli/test/unit/tidy.test.ts -t "while docker rm of --apply waits"`.
### Temporary-path removal
diff --git a/.agents/skills/verify/scripts/omp-smoke.ts b/.agents/skills/verify/scripts/omp-smoke.ts
index 1fc24cf8..386dd670 100755
--- a/.agents/skills/verify/scripts/omp-smoke.ts
+++ b/.agents/skills/verify/scripts/omp-smoke.ts
@@ -48,6 +48,7 @@ import { dirname, isAbsolute, join, resolve, sep } from "node:path";
import { createInterface } from "node:readline";
import { fileURLToPath } from "node:url";
import { parseArgs } from "node:util";
+import { BunServices } from "@effect/platform-bun";
import { Effect, Option, Result } from "effect";
import { ompPaths } from "../../../../cli/src/engine-native/ompPaths.ts";
import { endpointKindFor } from "../../../../cli/talk/transport/endpoint.ts";
@@ -572,11 +573,15 @@ function mtimeOf(file: string): number | null {
* The real omp roots that can hold the registry: the base config root, the XDG data root when one is set,
* and the config and data roots of the active omp profile, which the kit resolves the same way (`ompPaths`).
*/
-function realRegistryRoots(): string[] {
+async function realRegistryRoots(): Promise {
const roots = [join(homedir(), process.env["PI_CONFIG_DIR"] || ".omp")];
const dataHome = process.env["XDG_DATA_HOME"];
if (dataHome) roots.push(join(dataHome, "omp"));
- const active = ompPaths({ home: homedir(), env: process.env, platform: process.platform });
+ const active = await Effect.runPromise(
+ ompPaths({ home: homedir(), env: process.env, platform: process.platform }).pipe(
+ Effect.provide(BunServices.layer),
+ ),
+ );
roots.push(active.configRoot, active.dataRoot);
return [...new Set(roots)];
}
@@ -590,8 +595,8 @@ interface RealState {
* A snapshot of the real state: the modification times of the real omp registry files, and the size of the
* real verify-gate log, so that the check reads only the lines that come after it.
*/
-function realStateSnapshot(): RealState {
- const files = realRegistryRoots().flatMap((root) =>
+async function realStateSnapshot(): Promise {
+ const files = (await realRegistryRoots()).flatMap((root) =>
REAL_REGISTRY_FILES.map((file) => join(root, file)),
);
return {
@@ -1486,7 +1491,7 @@ async function smoke(): Promise<{ lines: string[]; registry: string | null }> {
return { lines: [`FAIL plugin folder ${pluginDir} does not exist`], registry: null };
const failures: string[] = [];
const name = manifestName(failures);
- const realBefore = realStateSnapshot();
+ const realBefore = await realStateSnapshot();
const run = await install(failures);
const skillList = parseJson(
(await run.omp(["skill", "list", "--json"])).stdout,
@@ -1692,7 +1697,7 @@ async function hooks(): Promise<{ lines: string[]; registry: string | null }> {
check("install", `plugin folder ${pluginDir} does not exist`);
return { lines: checks, registry: null };
}
- const realBefore = realStateSnapshot();
+ const realBefore = await realStateSnapshot();
const installFailures: string[] = [];
const run = await install(installFailures);
check("install", installFailures.join("; "));
@@ -2362,7 +2367,7 @@ async function talkMode(): Promise<{ lines: string[]; registry: string | null }>
results.set("install", `plugin folder ${pluginDir} does not exist`);
return { lines: lines(), registry: null };
}
- const realBefore = realStateSnapshot();
+ const realBefore = await realStateSnapshot();
const installFailures: string[] = [];
const run = await install(installFailures, {
modelIds: [PEER_MODEL_ID, SENDER_MODEL_ID],
@@ -3317,7 +3322,7 @@ async function talkUiMode(): Promise<{ lines: string[]; registry: string | null
results.set("install", `plugin folder ${pluginDir} does not exist`);
return { lines: lines(), registry: null };
}
- const realBefore = realStateSnapshot();
+ const realBefore = await realStateSnapshot();
const installFailures: string[] = [];
const run = await install(installFailures, {
modelIds: [PEER_MODEL_ID, UI_MODEL_ID],
diff --git a/cli/src/commands/root.ts b/cli/src/commands/root.ts
index 8695cb98..2f7ec272 100644
--- a/cli/src/commands/root.ts
+++ b/cli/src/commands/root.ts
@@ -120,7 +120,8 @@ export const rootCommand = Command.make("docks-kit", { fast, ultrafast }, (confi
}
const onTier = config.ultrafast ? ULTRAFAST_ON_TIER : FAST_ON_TIER;
const home = engineHome(process.env);
- const agentDir = ompPaths({ home, env: process.env, platform: process.platform }).agentDir;
+ const agentDir = (yield* ompPaths({ home, env: process.env, platform: process.platform }))
+ .agentDir;
// A refusal leaves config.yml unchanged and exits 2; a held lock, a lock
// that cannot be opened, or a failed read or write exits 1, as a sync does.
// Each line passes through `printable`: it can quote config.yml or a path.
diff --git a/cli/src/commands/tidy.ts b/cli/src/commands/tidy.ts
index 0edd62f5..ac62d56d 100644
--- a/cli/src/commands/tidy.ts
+++ b/cli/src/commands/tidy.ts
@@ -2,13 +2,15 @@ import { resolve } from "node:path";
import { Command, Flag } from "effect/cli";
import { Console, Effect, type FileSystem, Option, Schema } from "effect";
+import type { PlatformError } from "effect/PlatformError";
-import { bail, exitOnSignal } from "../engine";
+import { bail } from "../engine";
import { bridgeSync, type LegacyStepFailed } from "../engine-native/bridge";
import { errorMessage } from "../engine-native/errorText";
import { engineHome } from "../engine-native/home";
import { releaseKitLock, tryAcquireKitLock } from "../engine-native/kitLock";
import { scratchRoot, tidyApplyLockPath } from "../engine-native/scratch";
+import { exitOnSignal, PUBLIC_SIGNAL_EXIT_CODES } from "../engine-native/signalGuard";
import {
actionSubject,
actionVerb,
@@ -60,7 +62,7 @@ const planAndApply = Effect.fnUntraced(function* (
perform: boolean,
inputs: TidyInputs,
host: TidyHost,
-): Effect.fn.Return {
+): Effect.fn.Return {
const plan = yield* planTidy(inputs, host);
for (const action of plan.actions) {
yield* Console.log(`${actionVerb(action)} ${actionSubject(action)}: ${action.reason}`);
@@ -109,7 +111,7 @@ const planAndApplyUnderLock = Effect.fnUntraced(function* (
host: TidyHost,
): Effect.fn.Return<
TidyPlan | undefined,
- LegacyStepFailed | TidyLockFailed,
+ LegacyStepFailed | PlatformError | TidyLockFailed,
FileSystem.FileSystem
> {
const path = tidyApplyLockPath(inputs.home);
@@ -143,7 +145,11 @@ export const runTidy = Effect.fn("runTidy")(function* (
options: TidyOptions,
inputs: TidyInputs,
host: TidyHost,
-): Effect.fn.Return {
+): Effect.fn.Return<
+ void,
+ LegacyStepFailed | PlatformError | TidyLockFailed,
+ FileSystem.FileSystem
+> {
const plan = options.apply
? yield* planAndApplyUnderLock(inputs, host)
: yield* planAndApply(false, inputs, host);
@@ -158,13 +164,13 @@ export const runTidy = Effect.fn("runTidy")(function* (
/**
* Resolve the inputs and run tidy inside `exitOnSignal`: a SIGINT or SIGTERM
* exits with 130 at once, except inside the apply, which defers it. A typed
- * failure ends the command as a defect of its original cause, so the runtime
- * prints it and exits 1.
+ * failure ends the command as a defect of its original cause (the Node error
+ * of a failed file operation), so the runtime prints it and exits 1.
*/
export const tidyCommand = Command.make("tidy", { apply, repo, report }, (config) =>
Effect.scoped(
Effect.gen(function* () {
- yield* exitOnSignal;
+ yield* exitOnSignal(PUBLIC_SIGNAL_EXIT_CODES);
const host = defaultTidyHost();
const home = yield* bridgeSync("engineHome", () => engineHome());
let repository: string | undefined;
diff --git a/cli/src/engine-native/fileText.ts b/cli/src/engine-native/fileText.ts
new file mode 100644
index 00000000..48ecbd37
--- /dev/null
+++ b/cli/src/engine-native/fileText.ts
@@ -0,0 +1,65 @@
+/**
+ * File reads, existence probes, and errno rules of the engine code on the
+ * Effect `FileSystem`, with the outcomes of the synchronous `node:fs` calls
+ * that they replace: a leading byte order mark stays in a read text, a probe
+ * counts every failure as absent, and a failed operation keeps the Node error
+ * as the cause of its `PlatformError`.
+ */
+import { Effect, FileSystem } from "effect";
+import type { PlatformError } from "effect/PlatformError";
+
+const UTF8_KEEPING_BOM = new TextDecoder("utf-8", { ignoreBOM: true });
+
+/**
+ * The UTF-8 text of `path`. A leading byte order mark stays in the text, as
+ * the synchronous `node:fs` UTF-8 read kept it, so a comparison sees each byte of the
+ * file and a parser that expects a prefix rejects such a file, as before;
+ * `FileSystem.readFileString` drops the mark. A failed read fails with its
+ * `PlatformError`.
+ */
+export const readTextKeepingBom = Effect.fnUntraced(function* (path: string) {
+ const fs = yield* FileSystem.FileSystem;
+ return UTF8_KEEPING_BOM.decode(yield* fs.readFile(path));
+});
+
+/**
+ * Whether `path` exists, as `existsSync` answers: the probe follows a
+ * symlink, so a link to a missing target is absent, and every failure of the
+ * probe, such as a folder of the path that is a file, counts as absent.
+ * `FileSystem.stat` follows the link on every platform. Do not use
+ * `FileSystem.exists`: it fails on an error other than a missing path, and on
+ * Windows its access call sees the link and not the target.
+ */
+export const pathExists = Effect.fnUntraced(function* (path: string) {
+ const fs = yield* FileSystem.FileSystem;
+ return yield* fs.stat(path).pipe(
+ Effect.as(true),
+ Effect.orElseSucceed(() => false),
+ );
+});
+
+/**
+ * The Node error of a failed file operation: the cause that the
+ * `PlatformError` keeps, else the `PlatformError`. Its errno code and its
+ * message are the ones that the synchronous `node:fs` call threw.
+ */
+export function nodeError(error: PlatformError): unknown {
+ return error.cause ?? error;
+}
+
+/**
+ * True when a failed file operation found no file at its path: the path is
+ * missing (`ENOENT`), or a folder of it is not a folder (`ENOTDIR`, which the
+ * Effect file system reports as `BadResource`).
+ */
+export function pathMissing(error: PlatformError): boolean {
+ if (error.reason._tag === "NotFound") return true;
+ const cause = nodeError(error);
+ return (
+ error.reason._tag === "BadResource" &&
+ typeof cause === "object" &&
+ cause !== null &&
+ "code" in cause &&
+ cause.code === "ENOTDIR"
+ );
+}
diff --git a/cli/src/engine-native/index.ts b/cli/src/engine-native/index.ts
index a8860922..2dbe19ba 100644
--- a/cli/src/engine-native/index.ts
+++ b/cli/src/engine-native/index.ts
@@ -11,12 +11,15 @@
* existing import paths keep working.
*/
import { Effect, type FileSystem } from "effect";
+import type { PlatformError } from "effect/PlatformError";
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 type { PluginFileRemoveFailed, PluginFolderRemoveFailed } from "./ompKitPlugin";
+import type { OmpYamlInvalid } from "./ompYaml";
import type { Logger } from "./services";
import { engineSync, type LockAcquireError } from "./syncDispatch";
@@ -24,8 +27,22 @@ 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;
+/**
+ * A run that failed: each failure keeps the original value that the seam
+ * prints. An unrecovered file operation of an omp pass fails with its
+ * `PlatformError` (a failed upgrade-log removal only warns), a YAML merge or
+ * prune with `OmpYamlInvalid`, and a kit plugin prune removal with
+ * `PluginFolderRemoveFailed` or `PluginFileRemoveFailed`.
+ */
+export type EngineFailure =
+ | LegacyStepFailed
+ | LockAcquireError
+ | KitHomeInvalid
+ | LeaseHeld
+ | PlatformError
+ | OmpYamlInvalid
+ | PluginFolderRemoveFailed
+ | PluginFileRemoveFailed;
/**
* Run one engine operation and succeed with its exit code. Help, a refused
diff --git a/cli/src/engine-native/ompChild.ts b/cli/src/engine-native/ompChild.ts
index 5b7beba7..a0d768ab 100644
--- a/cli/src/engine-native/ompChild.ts
+++ b/cli/src/engine-native/ompChild.ts
@@ -3,6 +3,9 @@
* plugin pass runs starts through `spawnOmp`, so each child
* writes into the data root that the sync locked.
*/
+import type { Effect } from "effect";
+
+import { bridgePromise, type LegacyStepFailed } from "./bridge";
import { spawnProcess, type AsyncProcessOptions, type AsyncProcessResult } from "./exec";
import type { OmpPaths } from "./ompPaths";
@@ -13,14 +16,17 @@ import type { OmpPaths } from "./ompPaths";
* When the locked data root is the config root, the child gets no
* `XDG_DATA_HOME`, so its resolver keeps the config root. When the locked
* data root is the XDG root, the child gets the environment of this process.
+ * The spawn of `exec.ts` moves with #297; until then it is bridged, so an
+ * interrupt waits until the child settles.
*/
-export function spawnOmp(
+export const spawnOmp = (
paths: OmpPaths,
args: ReadonlyArray,
stdio: AsyncProcessOptions["stdio"],
-): Promise {
- if (paths.dataRoot !== paths.configRoot) return spawnProcess("omp", args, { stdio });
- const env = { ...process.env };
- delete env["XDG_DATA_HOME"];
- return spawnProcess("omp", args, { stdio, env });
-}
+): Effect.Effect =>
+ bridgePromise(`omp ${args.join(" ")}`, () => {
+ if (paths.dataRoot !== paths.configRoot) return spawnProcess("omp", args, { stdio });
+ const env = { ...process.env };
+ delete env["XDG_DATA_HOME"];
+ return spawnProcess("omp", args, { stdio, env });
+ });
diff --git a/cli/src/engine-native/ompFastMode.ts b/cli/src/engine-native/ompFastMode.ts
index 2c3b4c17..19388baa 100644
--- a/cli/src/engine-native/ompFastMode.ts
+++ b/cli/src/engine-native/ompFastMode.ts
@@ -11,6 +11,7 @@ import { isAlias, isMap, isScalar, parseDocument, type Document } from "yaml";
import { replaceFile } from "./atomicWrite";
import { errorMessage } from "./errorText";
+import { pathMissing } from "./fileText";
export const FAST_ON_TIER = "priority";
export const ULTRAFAST_ON_TIER = "ultrafast";
@@ -287,26 +288,6 @@ const missingConfig = (configPath: string) =>
new ConfigMissing({ message: `${configPath} does not exist; run 'docks-kit sync' first` }),
);
-/**
- * True when a folder of the path is not a folder (`ENOTDIR`). The Effect file
- * system reports that as `BadResource`, with the system error as its cause.
- */
-function notADirectory(error: PlatformError): boolean {
- const cause = error.reason.cause;
- return (
- error.reason._tag === "BadResource" &&
- typeof cause === "object" &&
- cause !== null &&
- "code" in cause &&
- cause.code === "ENOTDIR"
- );
-}
-
-/** True when the path names no file now: it is missing, or a folder of it is not a folder. */
-function pathMissing(error: PlatformError): boolean {
- return error.reason._tag === "NotFound" || notADirectory(error);
-}
-
/** Refuse the toggle when the deployed config.yml is missing. */
export const requireDeployedConfig = Effect.fn("requireDeployedConfig")(function* (
configPath: string,
@@ -317,7 +298,7 @@ export const requireDeployedConfig = Effect.fn("requireDeployedConfig")(function
.exists(configPath)
.pipe(
Effect.catchTag("PlatformError", (error) =>
- notADirectory(error) ? Effect.succeed(false) : Effect.fail(error),
+ pathMissing(error) ? Effect.succeed(false) : Effect.fail(error),
),
);
if (!present) return yield* missingConfig(configPath);
diff --git a/cli/src/engine-native/ompFileDeploy.ts b/cli/src/engine-native/ompFileDeploy.ts
index 82914fb7..fa57ec94 100644
--- a/cli/src/engine-native/ompFileDeploy.ts
+++ b/cli/src/engine-native/ompFileDeploy.ts
@@ -2,115 +2,130 @@
* EngineNative omp file deploy: private file modes, whole-file sync, and
* merged-YAML sync for the agent directory. Split from ompSync.ts; the
* orchestration still lives there.
+ *
+ * Each write or copy with its chmod and each directory creation with its
+ * chmod is one started mutation (`signalGuard.ts mutationRegion`): neither an
+ * interrupt nor a handled signal ends the run between the two calls.
*/
-import {
- chmodSync,
- copyFileSync,
- existsSync,
- mkdirSync,
- readFileSync,
- writeFileSync,
-} from "node:fs";
import { basename } from "node:path";
+import { Effect, FileSystem, type Result } from "effect";
import { payloadDisplayPath, payloadText, type PayloadPath } from "../payload";
import { replaceFile } from "./atomicWrite";
+import { bridgeSync } from "./bridge";
+import { pathExists, readTextKeepingBom } from "./fileText";
import type { Ctx } from "./index";
+import type { OmpYamlInvalid } from "./ompYaml";
+import { mutationRegion } from "./signalGuard";
export type OmpTextPayloadPath = Extract;
// ------------------------------------------------------------ file modes ----
/**
- * `mkdirSync` and `writeFileSync` apply their `mode` only when they create the
- * path, so an existing world-readable directory or file would keep its mode.
- * The explicit chmod reproduces `install -d -m 0700` / `install -m 0600`.
+ * `makeDirectory` and `writeFileString` apply their `mode` only when they
+ * create the path, so an existing world-readable directory or file would keep
+ * its mode. The explicit chmod reproduces `install -d -m 0700` /
+ * `install -m 0600`.
*/
-export function ensureDirectory(directory: string): void {
- mkdirSync(directory, { recursive: true, mode: 0o700 });
- chmodSync(directory, 0o700);
-}
+export const ensureDirectory = Effect.fn("ensureDirectory")(function* (directory: string) {
+ const fs = yield* FileSystem.FileSystem;
+ yield* mutationRegion(
+ Effect.andThen(
+ fs.makeDirectory(directory, { recursive: true, mode: 0o700 }),
+ fs.chmod(directory, 0o700),
+ ),
+ );
+});
-function writePrivateFile(target: string, content: string): void {
- writeFileSync(target, content, { mode: 0o600 });
- chmodSync(target, 0o600);
-}
+const writePrivateFile = Effect.fnUntraced(function* (target: string, content: string) {
+ const fs = yield* FileSystem.FileSystem;
+ yield* mutationRegion(
+ Effect.andThen(fs.writeFileString(target, content, { mode: 0o600 }), fs.chmod(target, 0o600)),
+ );
+});
-export function backupPrivateFile(target: string): void {
- copyFileSync(target, `${target}.bak`);
- chmodSync(`${target}.bak`, 0o600);
-}
+export const backupPrivateFile = Effect.fn("backupPrivateFile")(function* (target: string) {
+ const fs = yield* FileSystem.FileSystem;
+ const backup = `${target}.bak`;
+ yield* mutationRegion(Effect.andThen(fs.copyFile(target, backup), fs.chmod(backup, 0o600)));
+});
// --------------------------------------------------------------- config ----
-export function syncWholeFile(
+export const syncWholeFile = Effect.fn("syncWholeFile")(function* (
ctx: Ctx,
sourcePath: OmpTextPayloadPath,
target: string,
alreadyMessage: string,
syncedMessage: string,
-): void {
+) {
const { change, echo, verbose } = ctx.services.logger;
const source = payloadDisplayPath(sourcePath);
const content = payloadText(sourcePath);
if (ctx.dryRun) {
- echo(`[dry-run] cp ${source} -> ${target}`);
+ yield* bridgeSync("logger", () => echo(`[dry-run] cp ${source} -> ${target}`));
return;
}
- if (existsSync(target) && readFileSync(target, "utf8") === content) {
- verbose(alreadyMessage);
+ if ((yield* pathExists(target)) && (yield* readTextKeepingBom(target)) === content) {
+ yield* bridgeSync("logger", () => verbose(alreadyMessage));
return;
}
- if (existsSync(target)) backupPrivateFile(target);
- writePrivateFile(target, content);
- change(syncedMessage);
+ // Probe again: another writer can create or remove the file after the comparison probe.
+ if (yield* pathExists(target)) yield* backupPrivateFile(target);
+ yield* writePrivateFile(target, content);
+ yield* bridgeSync("logger", () => change(syncedMessage));
ctx.nextStepTriggers.ompRestart = true;
-}
+});
/**
- * Merges the SoT YAML into the deployed file. Returns true when this call wrote
- * `.bak`, so a later pass on the same file in this sync keeps that
- * pre-sync backup instead of replacing it with the merged bytes.
+ * Merges the SoT YAML into the deployed file. Succeeds with true when this
+ * call wrote `.bak`, so a later pass on the same file in this sync
+ * keeps that pre-sync backup instead of replacing it with the merged bytes.
*/
-export function syncMergedYaml(
+export const syncMergedYaml = Effect.fn("syncMergedYaml")(function* (
ctx: Ctx,
sourcePath: OmpTextPayloadPath,
target: string,
- merge: (sotText: string, deployedText: string) => string,
-): boolean {
+ merge: (sotText: string, deployedText: string) => Result.Result,
+) {
const { change, echo, verbose } = ctx.services.logger;
const source = payloadDisplayPath(sourcePath);
const sotText = payloadText(sourcePath);
const name = basename(sourcePath);
- if (!existsSync(target)) {
+ if (!(yield* pathExists(target))) {
if (ctx.dryRun) {
- echo(`[dry-run] cp ${source} -> ${target}`);
+ yield* bridgeSync("logger", () => echo(`[dry-run] cp ${source} -> ${target}`));
return false;
}
- writePrivateFile(target, sotText);
- change(`omp ${name} installed`);
+ yield* writePrivateFile(target, sotText);
+ yield* bridgeSync("logger", () => change(`omp ${name} installed`));
ctx.nextStepTriggers.ompRestart = true;
return false;
}
- const deployedText = readFileSync(target, "utf8");
- const merged = merge(sotText, deployedText);
+ const deployedText = yield* readTextKeepingBom(target);
+ const merged = yield* Effect.fromResult(merge(sotText, deployedText));
if (merged === deployedText) {
- verbose(`omp ${name} already in sync`);
+ yield* bridgeSync("logger", () => verbose(`omp ${name} already in sync`));
return false;
}
if (ctx.dryRun) {
- echo(`[dry-run] merge ${source} -> ${target} (backup at ${target}.bak)`);
+ yield* bridgeSync("logger", () =>
+ echo(`[dry-run] merge ${source} -> ${target} (backup at ${target}.bak)`),
+ );
return false;
}
- backupPrivateFile(target);
+ yield* backupPrivateFile(target);
// replaceFile writes through a symlinked config.yml or models.yml, so the link stays.
- replaceFile(target, merged, { mode: 0o600 });
- change(`omp ${name} merged (backup at ${name}.bak)`);
+ yield* mutationRegion(
+ bridgeSync("replaceFile", () => replaceFile(target, merged, { mode: 0o600 })),
+ );
+ yield* bridgeSync("logger", () => change(`omp ${name} merged (backup at ${name}.bak)`));
ctx.nextStepTriggers.ompRestart = true;
return true;
-}
+});
diff --git a/cli/src/engine-native/ompKitPlugin.ts b/cli/src/engine-native/ompKitPlugin.ts
index 17d5fe6b..0689aa51 100644
--- a/cli/src/engine-native/ompKitPlugin.ts
+++ b/cli/src/engine-native/ompKitPlugin.ts
@@ -6,54 +6,113 @@
* the payload no longer lists. Split from ompSync.ts; the orchestration still
* lives there.
*/
-import { existsSync, lstatSync, readFileSync, readdirSync, rmdirSync, unlinkSync } from "node:fs";
+import { rmdirSync, unlinkSync } from "node:fs";
+import { Effect, FileSystem, Schema } from "effect";
+import type { PlatformError } from "effect/PlatformError";
import { GENERATED_PACKAGE_VERSION } from "../generated/sotPayload";
import { payloadBytes, payloadPaths } from "../payload";
import { replaceFile } from "./atomicWrite";
+import { bridgeSync, failureText } from "./bridge";
import { p } from "./exec";
+import { pathExists, readTextKeepingBom } from "./fileText";
import type { Ctx } from "./index";
import { isObject, parseJson } from "./jq";
import { ensureDirectory } from "./ompFileDeploy";
+import { mutationRegion } from "./signalGuard";
export const KIT_PLUGIN_NAME = "docks-kit-omp";
const SOURCE_PREFIX = "SoT/.omp/plugin/";
+/**
+ * The prune could not remove an empty folder of the kit plugin; `message` is
+ * the message of the Node error, which `cause` keeps.
+ */
+export class PluginFolderRemoveFailed extends Schema.TaggedError<
+ PluginFolderRemoveFailed,
+ { readonly brand: unique symbol }
+>()("PluginFolderRemoveFailed", {
+ path: Schema.String,
+ message: Schema.String,
+ cause: Schema.Defect(),
+}) {}
+
+/**
+ * The prune could not remove a stale file of the kit plugin; `message` is the
+ * message of the Node error, which `cause` keeps, with its errno code.
+ */
+export class PluginFileRemoveFailed extends Schema.TaggedError<
+ PluginFileRemoveFailed,
+ { readonly brand: unique symbol }
+>()("PluginFileRemoveFailed", {
+ path: Schema.String,
+ message: Schema.String,
+ cause: Schema.Defect(),
+}) {}
+
export function kitPluginDir(home: string): string {
return p(home, ".docks-kit", "omp-plugin");
}
-/** Removes every entry under `directory` that is not a target, then empty directories. */
-function pruneStale(directory: string, targets: ReadonlySet): boolean {
- let changed = false;
- for (const name of readdirSync(directory)) {
- const entry = p(directory, name);
- const stat = lstatSync(entry);
- if (stat.isDirectory()) {
- changed = pruneStale(entry, targets) || changed;
- if (readdirSync(entry).length === 0) {
- rmdirSync(entry);
+/**
+ * Removes every entry under `directory` that is not a target, then empty
+ * directories. Each removal is one started mutation. `FileSystem` has no
+ * removal of an empty folder alone, so that removal stays `rmdirSync`. A file
+ * removal stays `unlinkSync`, because the `FileSystem.remove` adapter of Bun
+ * 1.4.5 reports `EPERM` as `EFAULT`.
+ */
+const pruneStale = (
+ directory: string,
+ targets: ReadonlySet,
+): Effect.Effect<
+ boolean,
+ PlatformError | PluginFolderRemoveFailed | PluginFileRemoveFailed,
+ FileSystem.FileSystem
+> =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ let changed = false;
+ for (const name of yield* fs.readDirectory(directory)) {
+ const entry = p(directory, name);
+ const info = yield* fs.lstat(entry);
+ if (info.type === "Directory") {
+ changed = (yield* pruneStale(entry, targets)) || changed;
+ if ((yield* fs.readDirectory(entry)).length === 0) {
+ yield* mutationRegion(
+ Effect.try({
+ try: () => rmdirSync(entry),
+ catch: (cause) =>
+ new PluginFolderRemoveFailed({ path: entry, message: failureText(cause), cause }),
+ }),
+ );
+ changed = true;
+ }
+ } else if (!targets.has(entry)) {
+ yield* mutationRegion(
+ Effect.try({
+ try: () => unlinkSync(entry),
+ catch: (cause) =>
+ new PluginFileRemoveFailed({ path: entry, message: failureText(cause), cause }),
+ }),
+ );
changed = true;
}
- } else if (!targets.has(entry)) {
- unlinkSync(entry);
- changed = true;
}
- }
- return changed;
-}
+ return changed;
+ });
/** The `version` of the deployed manifest, or undefined when it is absent or does not parse. */
-function deployedVersion(manifestPath: string): string | undefined {
- if (!existsSync(manifestPath)) return undefined;
- const manifest = parseJson(readFileSync(manifestPath, "utf8"));
+const deployedVersion = Effect.fnUntraced(function* (manifestPath: string) {
+ if (!(yield* pathExists(manifestPath))) return undefined;
+ const manifest = parseJson(yield* readTextKeepingBom(manifestPath));
if (manifest === undefined || !isObject(manifest)) return undefined;
return typeof manifest["version"] === "string" ? manifest["version"] : undefined;
-}
+});
-export function syncKitPlugin(ctx: Ctx): void {
+export const syncKitPlugin = Effect.fn("syncKitPlugin")(function* (ctx: Ctx) {
const { change, echo, verbose } = ctx.services.logger;
+ const fs = yield* FileSystem.FileSystem;
const pluginDir = kitPluginDir(ctx.home);
const files = payloadPaths(SOURCE_PREFIX).map((source) => ({
source,
@@ -62,11 +121,13 @@ export function syncKitPlugin(ctx: Ctx): void {
if (ctx.dryRun) {
// One line for the folder: a line per file would grow with each plugin file.
- echo(`[dry-run] sync embedded:${SOURCE_PREFIX} -> ${pluginDir}`);
+ yield* bridgeSync("logger", () =>
+ echo(`[dry-run] sync embedded:${SOURCE_PREFIX} -> ${pluginDir}`),
+ );
return;
}
- const before = deployedVersion(p(pluginDir, "package.json"));
+ const before = yield* deployedVersion(p(pluginDir, "package.json"));
let changed = false;
for (const { source, target } of files) {
let content = payloadBytes(source);
@@ -76,24 +137,28 @@ export function syncKitPlugin(ctx: Ctx): void {
manifest["version"] = GENERATED_PACKAGE_VERSION;
content = Buffer.from(`${JSON.stringify(manifest, null, 2)}\n`);
}
- ensureDirectory(target.slice(0, target.lastIndexOf("/")));
- if (existsSync(target) && readFileSync(target).equals(content)) continue;
+ yield* ensureDirectory(target.slice(0, target.lastIndexOf("/")));
+ if ((yield* pathExists(target)) && content.equals(yield* fs.readFile(target))) continue;
// A rename, so a session that reads the file during a sync sees the old or the new file.
- replaceFile(target, content, { mode: 0o600 });
+ yield* mutationRegion(
+ bridgeSync("replaceFile", () => replaceFile(target, content, { mode: 0o600 })),
+ );
changed = true;
}
- if (existsSync(pluginDir)) {
- changed = pruneStale(pluginDir, new Set(files.map(({ target }) => target))) || changed;
+ if (yield* pathExists(pluginDir)) {
+ changed = (yield* pruneStale(pluginDir, new Set(files.map(({ target }) => target)))) || changed;
}
if (changed) {
- change(
- before === undefined || before === GENERATED_PACKAGE_VERSION
- ? "omp kit plugin files synced"
- : `omp kit plugin files synced (${KIT_PLUGIN_NAME} ${before} -> ${GENERATED_PACKAGE_VERSION})`,
+ yield* bridgeSync("logger", () =>
+ change(
+ before === undefined || before === GENERATED_PACKAGE_VERSION
+ ? "omp kit plugin files synced"
+ : `omp kit plugin files synced (${KIT_PLUGIN_NAME} ${before} -> ${GENERATED_PACKAGE_VERSION})`,
+ ),
);
ctx.nextStepTriggers.ompRestart = true;
} else {
- verbose("omp kit plugin files already in sync");
+ yield* bridgeSync("logger", () => verbose("omp kit plugin files already in sync"));
}
-}
+});
diff --git a/cli/src/engine-native/ompPaths.ts b/cli/src/engine-native/ompPaths.ts
index b7733be4..3b16a2df 100644
--- a/cli/src/engine-native/ompPaths.ts
+++ b/cli/src/engine-native/ompPaths.ts
@@ -4,13 +4,17 @@
* either one: the agent directory holds `AGENTS.md`, `config.yml`, and
* `mcp.json`; the data root holds `marketplaces.json` and `plugins/`.
*
- * Resolution reads the environment and probes directory existence only, so a
- * dry run stays free of omp subcommands.
+ * Resolution reads the environment and probes only whether the final XDG
+ * candidate exists (`fileText.ts pathExists`, which follows a symlink and
+ * counts every failure as absent). The probe does not check the type of the
+ * candidate. A dry run thus stays free of omp subcommands. The path math
+ * stays plain.
*/
-import { existsSync } from "node:fs";
import { resolve } from "node:path";
+import { Effect } from "effect";
import { p } from "./exec";
+import { pathExists } from "./fileText";
/** Upstream CONFIG_DIR_NAME; PI_CONFIG_DIR renames this directory under home. */
const DEFAULT_CONFIG_DIR_NAME = ".omp";
@@ -51,7 +55,12 @@ function normalizeProfile(value: string | undefined): string | undefined {
return name;
}
-export function ompPaths({ home, env, platform }: OmpPathInputs): OmpPaths {
+/**
+ * The omp paths of `inputs`. The XDG data root counts only once its final
+ * candidate exists (`pathExists`, which follows a symlink); a candidate that
+ * is a file also counts, because the probe does not check the type.
+ */
+export const ompPaths = Effect.fn("ompPaths")(function* ({ home, env, platform }: OmpPathInputs) {
// OMP_PROFILE wins whenever it is defined, including when explicitly empty;
// PI_PROFILE is only the legacy fallback.
const profile = normalizeProfile(
@@ -89,23 +98,27 @@ export function ompPaths({ home, env, platform }: OmpPathInputs): OmpPaths {
resolvedOverride === undefined || resolvedOverride === resolve(defaultAgentDir)
? defaultAgentDir
: resolvedOverride;
+ const candidate = xdgDataCandidate(env, platform, profile, agentDir === defaultAgentDir);
- return {
+ const paths: OmpPaths = {
profile,
configRoot,
agentDir,
- dataRoot: xdgDataRoot(env, platform, profile, agentDir === defaultAgentDir) ?? configRoot,
+ // An existence probe of the final candidate only; a failed probe falls back to the config root.
+ dataRoot: candidate !== undefined && (yield* pathExists(candidate)) ? candidate : configRoot,
};
-}
+ return paths;
+});
/**
+ * The XDG data root candidate, which the data root becomes once it exists.
* XDG is a Linux and macOS convention upstream disables whenever an agent-dir
* override is active, and adopts a category only once its omp directory
* exists - `omp config init-xdg` creates it without moving existing data. A
* named profile keys on its own `profiles/` path and adopts that path,
* so a profile stays where it was first activated.
*/
-function xdgDataRoot(
+function xdgDataCandidate(
env: Record,
platform: NodeJS.Platform,
profile: string | undefined,
@@ -118,6 +131,5 @@ function xdgDataRoot(
if (dataHome === undefined || dataHome === "") return undefined;
const appRoot = p(dataHome, APP_NAME);
- const candidate = profile === undefined ? appRoot : p(appRoot, "profiles", profile);
- return existsSync(candidate) ? candidate : undefined;
+ return profile === undefined ? appRoot : p(appRoot, "profiles", profile);
}
diff --git a/cli/src/engine-native/ompPlugins.ts b/cli/src/engine-native/ompPlugins.ts
index 586d8e5e..a1debd88 100644
--- a/cli/src/engine-native/ompPlugins.ts
+++ b/cli/src/engine-native/ompPlugins.ts
@@ -14,16 +14,20 @@
* tool of the kit plugin replaces it. While the inventory of the store lists
* pi-intercom, each real sync prints one notice and changes nothing for it.
*/
-import { existsSync, readFileSync, realpathSync, rmSync } from "node:fs";
+import { Effect, FileSystem, Option, Result } from "effect";
+import { bridgeSync } from "./bridge";
+import { errorMessage } from "./errorText";
import { p, processFailureSummary } from "./exec";
import { recordFailure } from "./failures";
+import { nodeError, pathExists, pathMissing, readTextKeepingBom } from "./fileText";
import type { Ctx } from "./index";
import { isObject, parseJson } from "./jq";
import { spawnOmp } from "./ompChild";
import { KIT_PLUGIN_NAME, kitPluginDir } from "./ompKitPlugin";
import type { OmpPaths } from "./ompPaths";
import { kitCacheDir } from "./scratch";
+import { mutationRegion } from "./signalGuard";
/** The marketplace plugins whose content the kit plugin now ships. */
const RETIRED_PLUGIN_IDS = ["docks@docks", "plan-lifecycle@docks"] as const;
@@ -62,8 +66,9 @@ type PluginOperation =
| { readonly kind: "uninstall"; readonly id: string }
| { readonly kind: "marketplaceRemove" };
-async function installedPluginsFromCli(paths: OmpPaths): Promise {
- const result = await spawnOmp(paths, ["plugin", "list", "--json"], ["ignore", "pipe", "ignore"]);
+/** The inventory of `omp plugin list --json`, or undefined when omp gives none that parses. */
+const installedPluginsFromCli = Effect.fnUntraced(function* (paths: OmpPaths) {
+ const result = yield* spawnOmp(paths, ["plugin", "list", "--json"], ["ignore", "pipe", "ignore"]);
if (result.error !== undefined || result.exitCode !== 0) return undefined;
const value = parseJson(result.stdout);
@@ -96,7 +101,7 @@ async function installedPluginsFromCli(paths: OmpPaths): Promise,
-): Promise {
+) {
const { clearProgress, progress } = ctx.services.logger;
- progress(`Updating omp plugin ${plugin}...`);
- const result = await spawnOmp(paths, args, ["ignore", "pipe", "pipe"]);
- clearProgress();
+ yield* bridgeSync("logger", () => progress(`Updating omp plugin ${plugin}...`));
+ const result = yield* spawnOmp(paths, args, ["ignore", "pipe", "pipe"]);
+ yield* bridgeSync("logger", () => clearProgress());
if (result.error === undefined && result.exitCode === 0) return true;
- recordFailure(
- ctx,
- `omp plugin operation failed for ${plugin}: ${processFailureSummary(result)}; run manually: omp ${args.join(" ")}`,
+ yield* bridgeSync("recordFailure", () =>
+ recordFailure(
+ ctx,
+ `omp plugin operation failed for ${plugin}: ${processFailureSummary(result)}; run manually: omp ${args.join(" ")}`,
+ ),
);
return false;
-}
+});
-function realPath(path: string): string | undefined {
- try {
- return realpathSync(path);
- } catch {
- return undefined;
- }
-}
+/** The real path of `path`, or undefined when it cannot be resolved. */
+const realPath = (path: string) =>
+ Effect.flatMap(FileSystem.FileSystem, (fs) =>
+ fs.realPath(path).pipe(Effect.option, Effect.map(Option.getOrUndefined)),
+ );
// ----------------------------------------------------------- retirement ----
@@ -172,17 +182,20 @@ type RegistryState =
| { readonly kind: "listed" | "absent" }
| { readonly kind: "unreadable"; readonly file: string };
-function registryState(registryFile: string): RegistryState | { readonly kind: "missing" } {
- let registryText: string;
- try {
- registryText = readFileSync(registryFile, "utf8");
- } catch (error) {
+/** A registry state, or `missing` when no registry file exists at the path. */
+type RegistryFile = RegistryState | { readonly kind: "missing" };
+
+const registryState = Effect.fnUntraced(function* (
+ registryFile: string,
+): Effect.fn.Return {
+ const read = yield* Effect.result(readTextKeepingBom(registryFile));
+ if (Result.isFailure(read)) {
// Only a missing path is no registry; a denied or failed read can hide the entry.
- const code = typeof error === "object" && error !== null && "code" in error ? error.code : "";
- if (code === "ENOENT" || code === "ENOTDIR") return { kind: "missing" };
- return { kind: "unreadable", file: registryFile };
+ return pathMissing(read.failure)
+ ? { kind: "missing" }
+ : { kind: "unreadable", file: registryFile };
}
- const registry = parseJson(registryText);
+ const registry = parseJson(read.success);
if (registry === undefined) return { kind: "unreadable", file: registryFile };
if (isObject(registry) && Object.hasOwn(registry, RETIRED_MARKETPLACE)) return { kind: "listed" };
@@ -194,7 +207,7 @@ function registryState(registryFile: string): RegistryState | { readonly kind: "
return entries.some((entry) => isObject(entry) && entry["name"] === RETIRED_MARKETPLACE)
? { kind: "listed" }
: { kind: "absent" };
-}
+});
/**
* Whether omp knows the `docks` marketplace. omp reads the active registry
@@ -204,13 +217,15 @@ function registryState(registryFile: string): RegistryState | { readonly kind: "
* entry counts only when no active registry exists; beside an active
* registry it is stale.
*/
-function docksRegistryState(paths: OmpPaths): RegistryState {
- const active = registryState(p(paths.dataRoot, "marketplaces.json"));
+const docksRegistryState = Effect.fnUntraced(function* (
+ paths: OmpPaths,
+): Effect.fn.Return {
+ const active = yield* registryState(p(paths.dataRoot, "marketplaces.json"));
if (active.kind !== "missing") return active;
if (paths.dataRoot === paths.configRoot) return { kind: "absent" };
- const legacy = registryState(p(paths.configRoot, "marketplaces.json"));
+ const legacy = yield* registryState(p(paths.configRoot, "marketplaces.json"));
return legacy.kind === "missing" ? { kind: "absent" } : legacy;
-}
+});
/** The warning for a registry that can hold the `docks` entry but cannot be read. */
function unreadableRegistryWarning(file: string): string {
@@ -219,31 +234,43 @@ function unreadableRegistryWarning(file: string): string {
/**
* Removes the folder of the retired plugin upgrade log, which only the
- * marketplace plugin upgrades wrote. The kit owns the folder.
+ * marketplace plugin upgrades wrote. The kit owns the folder. The removal is
+ * one started mutation. When the removal or its status line fails, the pass
+ * only warns, as the base `catch` did; a failed warning fails the pass.
*/
-function removeUpgradeLog(ctx: Ctx): void {
+const removeUpgradeLog = Effect.fnUntraced(function* (ctx: Ctx) {
+ const { verbose, warn } = ctx.services.logger;
+ const fs = yield* FileSystem.FileSystem;
const dir = p(kitCacheDir(ctx.home), "omp-plugin-upgrades");
- if (!existsSync(dir)) return;
- try {
- rmSync(dir, { recursive: true, force: true });
- ctx.services.logger.verbose(`removed the retired omp plugin upgrade log ${dir}`);
- } catch (error) {
- const detail = error instanceof Error ? error.message : String(error);
- ctx.services.logger.warn(`retired omp plugin upgrade log not removed: ${detail}`);
+ if (!(yield* pathExists(dir))) return;
+ const removed = yield* Effect.result(
+ Effect.andThen(
+ mutationRegion(fs.remove(dir, { recursive: true, force: true })),
+ bridgeSync("logger", () => verbose(`removed the retired omp plugin upgrade log ${dir}`)),
+ ),
+ );
+ if (Result.isFailure(removed)) {
+ const { failure } = removed;
+ const detail = errorMessage(
+ failure._tag === "PlatformError" ? nodeError(failure) : failure.cause,
+ );
+ yield* bridgeSync("logger", () =>
+ warn(`retired omp plugin upgrade log not removed: ${detail}`),
+ );
}
-}
+});
/**
* Uninstalls each user-scope install of a retired plugin and warns about each
* project-scope install, which belongs to that project. Then removes the
* `docks` marketplace when no uninstall failed and omp knows the marketplace.
- * Returns the successful operations.
+ * Succeeds with the successful operations.
*/
-async function retireMarketplacePlugins(
+const retireMarketplacePlugins = Effect.fnUntraced(function* (
ctx: Ctx,
paths: OmpPaths,
installed: InstalledPlugins,
-): Promise> {
+) {
const { warn } = ctx.services.logger;
const operations: Array = [];
let uninstallFailed = false;
@@ -251,14 +278,16 @@ async function retireMarketplacePlugins(
for (const pluginId of RETIRED_PLUGIN_IDS) {
const rows = installed.marketplace.filter((row) => row.id === pluginId);
if (rows.some((row) => row.scope === "project")) {
- warn(
- `omp plugin ${pluginId} is installed at project scope and docks-kit no longer ships it; run from that project: omp plugin uninstall --scope project ${pluginId}`,
+ yield* bridgeSync("logger", () =>
+ warn(
+ `omp plugin ${pluginId} is installed at project scope and docks-kit no longer ships it; run from that project: omp plugin uninstall --scope project ${pluginId}`,
+ ),
);
}
if (!rows.some((row) => row.scope === "user")) continue;
const args = ["plugin", "uninstall", "--scope", "user", pluginId];
- if (await runPluginCommand(ctx, paths, pluginId, args)) {
+ if (yield* runPluginCommand(ctx, paths, pluginId, args)) {
operations.push({ kind: "uninstall", id: pluginId });
} else {
uninstallFailed = true;
@@ -267,17 +296,17 @@ async function retireMarketplacePlugins(
// A failed uninstall keeps the marketplace, so the manual command still resolves the id.
if (uninstallFailed) return operations;
- const registry = docksRegistryState(paths);
+ const registry = yield* docksRegistryState(paths);
if (registry.kind === "unreadable") {
- warn(unreadableRegistryWarning(registry.file));
+ yield* bridgeSync("logger", () => warn(unreadableRegistryWarning(registry.file)));
} else if (registry.kind === "listed") {
const args = ["plugin", "marketplace", "remove", RETIRED_MARKETPLACE];
- if (await runPluginCommand(ctx, paths, RETIRED_MARKETPLACE_LABEL, args)) {
+ if (yield* runPluginCommand(ctx, paths, RETIRED_MARKETPLACE_LABEL, args)) {
operations.push({ kind: "marketplaceRemove" });
}
}
return operations;
-}
+});
/**
* The warning of an unavailable inventory when git is present. The pass then
@@ -292,8 +321,8 @@ const INVENTORY_UNAVAILABLE_NO_GIT =
/**
* Run the plugin pass. `paths` are the omp paths that the sync locked.
- * Returns the number of installed kit plugins, or undefined when the pass
- * could not read the inventory and linked no kit plugin.
+ * Succeeds with the number of installed kit plugins, or undefined when the
+ * pass could not read the inventory and linked no kit plugin.
*
* Only the omp plugin commands (uninstall, marketplace removal, link) need
* git. Without git, a real run reads the inventory, warns when it is
@@ -303,25 +332,32 @@ const INVENTORY_UNAVAILABLE_NO_GIT =
* does on any plugin command. A dry run and a run without omp spawn no omp
* command and print no notice.
*/
-export async function syncPlugins(ctx: Ctx, paths: OmpPaths): Promise {
+export const syncPlugins = Effect.fn("syncPlugins")(function* (ctx: Ctx, paths: OmpPaths) {
const { change, clearProgress, echo, progress, verbose, warn } = ctx.services.logger;
-
- if (!ctx.dryRun) removeUpgradeLog(ctx);
-
- if (ctx.services.deps.probe("omp").state === "missing") {
- ctx.services.deps.warnMissing(
- "omp",
- ctx.services.logger,
- "deployed omp config only — plugin pass skipped; re-run sync after installing",
+ const { deps } = ctx.services;
+
+ if (!ctx.dryRun) yield* removeUpgradeLog(ctx);
+
+ // The dependency probes move with #298; until then they are bridged.
+ if ((yield* bridgeSync("deps.probe omp", () => deps.probe("omp"))).state === "missing") {
+ yield* bridgeSync("deps.warnMissing omp", () =>
+ deps.warnMissing(
+ "omp",
+ ctx.services.logger,
+ "deployed omp config only — plugin pass skipped; re-run sync after installing",
+ ),
);
return undefined;
}
- const gitMissing = ctx.services.deps.probe("git").state === "missing";
+ const gitMissing =
+ (yield* bridgeSync("deps.probe git", () => deps.probe("git"))).state === "missing";
if (gitMissing) {
- ctx.services.deps.warnMissing(
- "git",
- ctx.services.logger,
- "omp plugin changes skipped; re-run sync after installing",
+ yield* bridgeSync("deps.warnMissing git", () =>
+ deps.warnMissing(
+ "git",
+ ctx.services.logger,
+ "omp plugin changes skipped; re-run sync after installing",
+ ),
);
}
@@ -329,28 +365,36 @@ export async function syncPlugins(ctx: Ctx, paths: OmpPaths): Promise
+ echo(`[dry-run] omp plugin uninstall --scope user ${pluginId}`),
+ );
}
- const registry = docksRegistryState(paths);
+ const registry = yield* docksRegistryState(paths);
if (registry.kind === "unreadable") {
- warn(unreadableRegistryWarning(registry.file));
+ yield* bridgeSync("logger", () => warn(unreadableRegistryWarning(registry.file)));
} else if (registry.kind === "listed") {
- echo(`[dry-run] omp plugin marketplace remove ${RETIRED_MARKETPLACE}`);
+ yield* bridgeSync("logger", () =>
+ echo(`[dry-run] omp plugin marketplace remove ${RETIRED_MARKETPLACE}`),
+ );
}
- echo(`[dry-run] omp plugin link ${kitPluginDir(ctx.home)}`);
+ yield* bridgeSync("logger", () => echo(`[dry-run] omp plugin link ${kitPluginDir(ctx.home)}`));
return undefined;
}
- progress("Checking installed omp plugins...");
- const installed = await installedPluginsFromCli(paths);
- clearProgress();
+ yield* bridgeSync("logger", () => progress("Checking installed omp plugins..."));
+ const installed = yield* installedPluginsFromCli(paths);
+ yield* bridgeSync("logger", () => clearProgress());
if (installed === undefined) {
- warn(gitMissing ? INVENTORY_UNAVAILABLE_NO_GIT : INVENTORY_UNAVAILABLE);
+ yield* bridgeSync("logger", () =>
+ warn(gitMissing ? INVENTORY_UNAVAILABLE_NO_GIT : INVENTORY_UNAVAILABLE),
+ );
} else {
const piIntercom = installed.npm.get(PI_INTERCOM);
if (piIntercom !== undefined) {
- echo(piIntercomNotice(p(paths.dataRoot, "plugins"), piIntercom.version));
+ yield* bridgeSync("logger", () =>
+ echo(piIntercomNotice(p(paths.dataRoot, "plugins"), piIntercom.version)),
+ );
}
}
// The kit plugin count that the inventory shows: undefined when the inventory is unavailable.
@@ -360,31 +404,33 @@ export async function syncPlugins(ctx: Ctx, paths: OmpPaths): Promise = [];
if (installed !== undefined) {
- operations.push(...(await retireMarketplacePlugins(ctx, paths, installed)));
+ operations.push(...(yield* retireMarketplacePlugins(ctx, paths, installed)));
}
// The kit plugin is linked when omp's entry resolves to the kit directory.
// A refresh never applies: the link always points at the current files.
const kitDir = kitPluginDir(ctx.home);
const kitPluginPath = installed?.npm.get(KIT_PLUGIN_NAME)?.path;
- const linkedTarget = kitPluginPath === undefined ? undefined : realPath(kitPluginPath);
- if (linkedTarget !== undefined && linkedTarget === realPath(kitDir)) {
- verbose(`omp kit plugin ${KIT_PLUGIN_NAME} already linked`);
- } else if (await runPluginCommand(ctx, paths, KIT_PLUGIN_NAME, ["plugin", "link", kitDir])) {
+ const linkedTarget = kitPluginPath === undefined ? undefined : yield* realPath(kitPluginPath);
+ if (linkedTarget !== undefined && linkedTarget === (yield* realPath(kitDir))) {
+ yield* bridgeSync("logger", () => verbose(`omp kit plugin ${KIT_PLUGIN_NAME} already linked`));
+ } else if (yield* runPluginCommand(ctx, paths, KIT_PLUGIN_NAME, ["plugin", "link", kitDir])) {
operations.push({ kind: "link", id: KIT_PLUGIN_NAME });
pluginsInstalled = 1;
}
if (operations.length === 0) {
- verbose("omp plugins already in sync");
+ yield* bridgeSync("logger", () => verbose("omp plugins already in sync"));
return pluginsInstalled;
}
- change(`omp plugins synced: ${operations.map(describeOperation).join(", ")}`);
+ yield* bridgeSync("logger", () =>
+ change(`omp plugins synced: ${operations.map(describeOperation).join(", ")}`),
+ );
// A link or an uninstall changes the plugins that omp loads. A marketplace
// removal alone changes no loaded plugin.
if (operations.some((operation) => operation.kind !== "marketplaceRemove")) {
ctx.nextStepTriggers.ompRestart = true;
}
return pluginsInstalled;
-}
+});
diff --git a/cli/src/engine-native/ompRemovals.ts b/cli/src/engine-native/ompRemovals.ts
index aa03d645..1af6183a 100644
--- a/cli/src/engine-native/ompRemovals.ts
+++ b/cli/src/engine-native/ompRemovals.ts
@@ -9,13 +9,17 @@
* sync, without `--reconcile`. Message strings and prune semantics are part of
* the contract.
*/
-import { existsSync, readFileSync } from "node:fs";
import { isDeepStrictEqual } from "node:util";
+import { Effect } from "effect";
import { isMap, isScalar, isSeq, parseDocument, type YAMLMap } from "yaml";
+
import { replaceFile } from "./atomicWrite";
+import { bridgeSync } from "./bridge";
+import { pathExists, readTextKeepingBom } from "./fileText";
import type { Ctx } from "./index";
import { backupPrivateFile } from "./ompFileDeploy";
-import { bashPatternKey, bashRuleKey } from "./ompYaml";
+import { bashPatternKey, bashRuleKey, yamlText } from "./ompYaml";
+import { mutationRegion } from "./signalGuard";
/** A retired leaf value: a scalar, or a sequence the kit shipped as one value. */
type RetiredValue = string | number | boolean | ReadonlyArray;
@@ -371,24 +375,28 @@ const retiredBashRules: Pruner = (root) => {
};
/**
- * Applies each pruner to one deployed omp YAML file. `alreadyBackedUp` is true
- * when the merge of this sync already wrote `.bak`; a second backup would
- * replace those pre-sync bytes with the merged bytes.
+ * Applies each pruner to one deployed omp YAML file and succeeds with the
+ * number of pruned entries. `alreadyBackedUp` is true when the merge of this
+ * sync already wrote `.bak`; a second backup would replace those
+ * pre-sync bytes with the merged bytes. A pruned document that the YAML
+ * library cannot write fails with `OmpYamlInvalid`.
*/
-function pruneRetired(
+const pruneRetired = Effect.fnUntraced(function* (
ctx: Ctx,
file: string,
label: string,
pruners: ReadonlyArray,
alreadyBackedUp: boolean,
-): number {
+) {
const { change, echo, verbose, warn } = ctx.services.logger;
- if (!existsSync(file)) return 0;
+ if (!(yield* pathExists(file))) return 0;
- const doc = parseDocument(readFileSync(file, "utf8"));
+ const doc = parseDocument(yield* readTextKeepingBom(file));
const parseError = doc.errors[0];
if (parseError !== undefined) {
- warn(`omp ${label} unreadable, retired entries not pruned: ${parseError.message}`);
+ yield* bridgeSync("logger", () =>
+ warn(`omp ${label} unreadable, retired entries not pruned: ${parseError.message}`),
+ );
return 0;
}
const contents = doc.contents;
@@ -397,25 +405,28 @@ function pruneRetired(
const pruned = pruners.flatMap((prune) => prune(contents));
if (pruned.length === 0) {
- verbose(`omp ${label} carries no retired entries`);
+ yield* bridgeSync("logger", () => verbose(`omp ${label} carries no retired entries`));
return 0;
}
if (ctx.dryRun) {
- echo(`[dry-run] prune ${file}: ${pruned.join(", ")}`);
+ yield* bridgeSync("logger", () => echo(`[dry-run] prune ${file}: ${pruned.join(", ")}`));
return pruned.length;
}
- if (!alreadyBackedUp) backupPrivateFile(file);
+ if (!alreadyBackedUp) yield* backupPrivateFile(file);
+ const text = yield* Effect.fromResult(yamlText(doc));
// replaceFile writes through a symlinked file, so the link stays.
- replaceFile(file, String(doc), { mode: 0o600 });
+ yield* mutationRegion(bridgeSync("replaceFile", () => replaceFile(file, text, { mode: 0o600 })));
const backupNote = alreadyBackedUp ? "" : ` (backup at ${label}.bak)`;
- change(
- `omp ${label} pruned ${pruned.length} retired entr(ies): ${pruned.join(", ")}${backupNote}`,
+ yield* bridgeSync("logger", () =>
+ change(
+ `omp ${label} pruned ${pruned.length} retired entr(ies): ${pruned.join(", ")}${backupNote}`,
+ ),
);
return pruned.length;
-}
+});
-/** Prunes retired kit-owned keys and bash rules from a deployed omp config.yml. */
-export function syncOmpRemovals(ctx: Ctx, configFile: string, alreadyBackedUp: boolean): number {
+/** Prunes retired kit-owned keys and bash rules from a deployed omp config.yml; succeeds with the count. */
+export function syncOmpRemovals(ctx: Ctx, configFile: string, alreadyBackedUp: boolean) {
return pruneRetired(
ctx,
configFile,
@@ -436,12 +447,8 @@ export function syncOmpRemovals(ctx: Ctx, configFile: string, alreadyBackedUp: b
);
}
-/** Prunes retired kit-owned blocks from a deployed omp models.yml. */
-export function syncOmpModelRemovals(
- ctx: Ctx,
- modelsFile: string,
- alreadyBackedUp: boolean,
-): number {
+/** Prunes retired kit-owned blocks from a deployed omp models.yml; succeeds with the count. */
+export function syncOmpModelRemovals(ctx: Ctx, modelsFile: string, alreadyBackedUp: boolean) {
return pruneRetired(
ctx,
modelsFile,
diff --git a/cli/src/engine-native/ompSync.ts b/cli/src/engine-native/ompSync.ts
index b336dda4..cf9b723e 100644
--- a/cli/src/engine-native/ompSync.ts
+++ b/cli/src/engine-native/ompSync.ts
@@ -5,7 +5,7 @@
* 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
+ * Resolution stays within the environment and file system probes so no omp
* subcommand runs under ctx.dryRun.
*
* Split: file deploy lives in `ompFileDeploy.ts`, the kit plugin files in
@@ -43,13 +43,7 @@ export interface OmpWriteFolders {
/** 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(),
- }),
- );
+ ompPaths({ home: ctx.home, env: process.env, platform: ctx.services.platform.raw() });
/**
* Resolve the omp paths of this run. `engineSync` resolves them once, under
@@ -65,8 +59,10 @@ export const ompWriteFolders = Effect.fn("ompWriteFolders")(function* () {
/**
* 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.
+ * and locked. The passes are Effect code; only their calls into code that a
+ * later child of plan #290 moves run through the bridge (`bunBootstrap` here,
+ * the logger, the atomic writer, the dependency probes, and the omp
+ * children inside the passes), so an interrupt waits until that call settles.
*/
export const ompSync = Effect.fn("ompSync")(function* (folders: OmpWriteFolders) {
const ctx = yield* EngineContext;
@@ -74,45 +70,45 @@ export const ompSync = Effect.fn("ompSync")(function* (folders: OmpWriteFolders)
const { paths } = folders;
const agentDir = paths.agentDir;
- if (!ctx.dryRun) yield* bridgeSync("ensureDirectory", () => ensureDirectory(agentDir));
+ if (!ctx.dryRun) yield* ensureDirectory(agentDir);
- 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",
- ),
+ yield* syncWholeFile(
+ ctx,
+ "SoT/.omp/AGENTS.md",
+ p(agentDir, "AGENTS.md"),
+ "omp AGENTS.md already in sync",
+ "omp AGENTS.md 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",
- ),
+ yield* 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 = yield* bridgeSync("syncMergedYaml config.yml", () =>
- syncMergedYaml(ctx, "SoT/.omp/config.yml", configFile, mergeOmpConfig),
+ const configBackedUp = yield* syncMergedYaml(
+ ctx,
+ "SoT/.omp/config.yml",
+ configFile,
+ mergeOmpConfig,
);
// mergeOmpConfig is additive, so the prune must run on the merged result.
- yield* bridgeSync("syncOmpRemovals", () => syncOmpRemovals(ctx, configFile, configBackedUp));
+ yield* syncOmpRemovals(ctx, configFile, configBackedUp);
const modelsFile = p(agentDir, "models.yml");
- const modelsBackedUp = yield* bridgeSync("syncMergedYaml models.yml", () =>
- syncMergedYaml(ctx, "SoT/.omp/models.yml", modelsFile, mergeOmpModels),
- );
- yield* bridgeSync("syncOmpModelRemovals", () =>
- syncOmpModelRemovals(ctx, modelsFile, modelsBackedUp),
+ const modelsBackedUp = yield* syncMergedYaml(
+ ctx,
+ "SoT/.omp/models.yml",
+ modelsFile,
+ mergeOmpModels,
);
+ yield* 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.
- yield* bridgeSync("syncKitPlugin", () => syncKitPlugin(ctx));
+ yield* syncKitPlugin(ctx);
- const pluginsInstalled = yield* bridgePromise("syncPlugins", () => syncPlugins(ctx, paths));
+ const pluginsInstalled = yield* 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
@@ -120,7 +116,7 @@ export const ompSync = Effect.fn("ompSync")(function* (folders: OmpWriteFolders)
if (!ctx.dryRun) {
const currentRoot = (yield* currentOmpPaths(ctx)).dataRoot;
if (currentRoot !== paths.dataRoot) {
- yield* Effect.sync(() =>
+ yield* bridgeSync("recordFailure", () =>
recordFailure(
ctx,
`omp data root moved to ${currentRoot} during the sync; run docks-kit sync again`,
diff --git a/cli/src/engine-native/ompYaml.ts b/cli/src/engine-native/ompYaml.ts
index f5968ce5..c2d57729 100644
--- a/cli/src/engine-native/ompYaml.ts
+++ b/cli/src/engine-native/ompYaml.ts
@@ -11,8 +11,43 @@
* A SoT sequence replaces the deployed sequence, except `bash.patterns` in
* config.yml: `mergeBashPatterns` keeps the user's command rules and groups all
* rules by approval.
+ *
+ * The merges stay plain functions: each returns a `Result`, with the merged
+ * text or an `OmpYamlInvalid` failure.
*/
-import { isMap, isScalar, isSeq, parseDocument, type YAMLMap, type YAMLSeq } from "yaml";
+import { Result, Schema } from "effect";
+import {
+ isMap,
+ isScalar,
+ isSeq,
+ parseDocument,
+ type Document,
+ type YAMLMap,
+ type YAMLSeq,
+} from "yaml";
+
+import { failureText } from "./bridge";
+
+/**
+ * A YAML file of a merge or a prune cannot be read as a mapping, or the
+ * merged or pruned document cannot be written as YAML, for example an alias
+ * that comes before its anchor; `message` names the file or gives the message
+ * of the YAML library.
+ */
+export class OmpYamlInvalid extends Schema.TaggedError<
+ OmpYamlInvalid,
+ { readonly brand: unique symbol }
+>()("OmpYamlInvalid", {
+ message: Schema.String,
+}) {}
+
+/** The YAML text of `doc`, or an `OmpYamlInvalid` with the message of the library that refused it. */
+export function yamlText(doc: Document): Result.Result {
+ return Result.try({
+ try: () => doc.toString(),
+ catch: (cause) => new OmpYamlInvalid({ message: failureText(cause) }),
+ });
+}
/** Decides whether a deployed-only key at `path` is dropped instead of kept. */
type DropDeployedKey = (path: ReadonlyArray, key: string) => boolean;
@@ -161,11 +196,12 @@ function mergeYamlDocuments(
name: string,
drop: DropDeployedKey,
mergeSequence: MergeSequence,
-): string {
+): Result.Result {
+ const invalid = (message: string) => Result.fail(new OmpYamlInvalid({ message }));
const deployedDoc = parseDocument(deployedText);
const deployedError = deployedDoc.errors[0];
if (deployedError !== undefined) {
- throw new Error(`Invalid deployed omp ${name} YAML: ${deployedError.message}`);
+ return invalid(`Invalid deployed omp ${name} YAML: ${deployedError.message}`);
}
const deployedContents = deployedDoc.contents;
@@ -174,30 +210,33 @@ function mergeYamlDocuments(
deployedContents === undefined ||
(isScalar(deployedContents) && deployedContents.value === null)
) {
- return sotText;
+ return Result.succeed(sotText);
}
if (!isMap(deployedContents)) {
- throw new Error(`Deployed omp ${name} YAML root must be a mapping`);
+ return invalid(`Deployed omp ${name} YAML root must be a mapping`);
}
const sotDoc = parseDocument(sotText);
const sotError = sotDoc.errors[0];
if (sotError !== undefined) {
- throw new Error(`Invalid SoT omp ${name} YAML: ${sotError.message}`);
+ return invalid(`Invalid SoT omp ${name} YAML: ${sotError.message}`);
}
if (!isMap(sotDoc.contents)) {
- throw new Error(`SoT omp ${name} YAML root must be a mapping`);
+ return invalid(`SoT omp ${name} YAML root must be a mapping`);
}
mergeMappings(sotDoc.contents, deployedContents, [], drop, mergeSequence);
- return sotDoc.toString();
+ return yamlText(sotDoc);
}
/**
* config.yml merge: keeps user-only keys and user `bash.patterns` rules, drops
* stale fallback-chain wildcards.
*/
-export function mergeOmpConfig(sotText: string, deployedText: string): string {
+export function mergeOmpConfig(
+ sotText: string,
+ deployedText: string,
+): Result.Result {
return mergeYamlDocuments(
sotText,
deployedText,
@@ -208,6 +247,9 @@ export function mergeOmpConfig(sotText: string, deployedText: string): string {
}
/** models.yml merge: keeps every user-only key, including credentials and custom models. */
-export function mergeOmpModels(sotText: string, deployedText: string): string {
+export function mergeOmpModels(
+ sotText: string,
+ deployedText: string,
+): Result.Result {
return mergeYamlDocuments(sotText, deployedText, "models.yml", keepEveryKey, keepSotSequence);
}
diff --git a/cli/src/engine-native/signalGuard.ts b/cli/src/engine-native/signalGuard.ts
new file mode 100644
index 00000000..540a2055
--- /dev/null
+++ b/cli/src/engine-native/signalGuard.ts
@@ -0,0 +1,113 @@
+/**
+ * The signal guard of the engine runs: the exit codes per signal, the signal
+ * state, and the scopes that defer a signal exit during a started mutation.
+ * The CLI entry points (`engine.ts`, `main.ts`, `commands/tidy.ts`), the tidy
+ * apply, and the omp passes import it. It imports no pass and no CLI module,
+ * so a pass does not load the public CLI seam.
+ */
+import { Effect } from "effect";
+
+/** The exit code of each signal that `exitOnSignal` handles. */
+export interface SignalExitCodes {
+ readonly SIGINT: number;
+ readonly SIGTERM: number;
+}
+
+/** The public CLI exits 130 for SIGINT and SIGTERM, as the Promise seam did. */
+export const PUBLIC_SIGNAL_EXIT_CODES: SignalExitCodes = { SIGINT: 130, SIGTERM: 130 };
+
+/** The raw golden channel of main.ts exits 130 for SIGINT and 143 for SIGTERM. */
+export const RAW_SIGNAL_EXIT_CODES: SignalExitCodes = { SIGINT: 130, SIGTERM: 143 };
+
+/**
+ * The signal state of `exitOnSignal`: `deferred` counts the open
+ * `deferSignalExit` scopes, `exitPoints` the calls that `signalExitPoint`
+ * runs, and `recorded` is the exit code of the first signal that came while
+ * an exit was deferred.
+ */
+const signals: { deferred: number; exitPoints: number; recorded: number | undefined } = {
+ deferred: 0,
+ exitPoints: 0,
+ recorded: undefined,
+};
+
+/**
+ * While the engine runs, a SIGINT or SIGTERM ends the process at once with
+ * its code in `codes`, 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 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. Inside a `deferSignalExit` scope, a signal is recorded instead,
+ * unless a `signalExitPoint` call waits. `docks-kit tidy` and the raw channel
+ * of main.ts run inside it too.
+ */
+export const exitOnSignal = (codes: SignalExitCodes) =>
+ Effect.acquireRelease(
+ Effect.sync(() => {
+ const listener = (code: number) => (): void => {
+ if (signals.deferred > 0 && signals.exitPoints === 0) {
+ signals.recorded ??= code;
+ return;
+ }
+ process.exit(code);
+ };
+ const listeners = { SIGINT: listener(codes.SIGINT), SIGTERM: listener(codes.SIGTERM) };
+ process.prependListener("SIGINT", listeners.SIGINT);
+ process.prependListener("SIGTERM", listeners.SIGTERM);
+ return listeners;
+ }),
+ (listeners) =>
+ Effect.sync(() => {
+ process.off("SIGINT", listeners.SIGINT);
+ process.off("SIGTERM", listeners.SIGTERM);
+ }),
+ );
+
+/**
+ * For the rest of the scope, `exitOnSignal` records a SIGINT or SIGTERM
+ * instead of exiting, so the steps of the scope run to their end; when the
+ * last open scope closes after a recorded signal, the process exits with the
+ * code of that signal. The plain steps of `tidy --apply` and the printing of
+ * their result run in it, as they ran without a signal turn before, and so
+ * does each started mutation of a sync (`mutationRegion`); #297 replaces it
+ * with fiber interruption.
+ */
+export const deferSignalExit = Effect.acquireRelease(
+ Effect.sync(() => {
+ signals.deferred += 1;
+ }),
+ () =>
+ Effect.sync(() => {
+ signals.deferred -= 1;
+ if (signals.deferred === 0 && signals.recorded !== undefined) process.exit(signals.recorded);
+ }),
+);
+
+/**
+ * Run the started mutation `mutation`, such as a write with its chmod or a
+ * removal, to its end: an interrupt waits until it settles, and a signal that
+ * comes during it is recorded and ends the process once it settled
+ * (`deferSignalExit`). The locks of the run stay held until then; between two
+ * mutations, an interrupt and a signal exit still end the run.
+ */
+export const mutationRegion = (mutation: Effect.Effect) =>
+ Effect.uninterruptible(Effect.scoped(Effect.andThen(deferSignalExit, mutation)));
+
+/**
+ * Run `effect`, a call that can wait on a child process, as an exit point: a
+ * signal recorded before it, or one that comes while it waits, exits with the
+ * code of that signal at once, also inside a `deferSignalExit` scope.
+ */
+export const signalExitPoint = (effect: Effect.Effect): Effect.Effect =>
+ Effect.acquireUseRelease(
+ Effect.sync(() => {
+ if (signals.recorded !== undefined) process.exit(signals.recorded);
+ signals.exitPoints += 1;
+ }),
+ () => effect,
+ () =>
+ Effect.sync(() => {
+ signals.exitPoints -= 1;
+ }),
+ );
diff --git a/cli/src/engine-native/tidy.ts b/cli/src/engine-native/tidy.ts
index c0c851cb..06da6756 100644
--- a/cli/src/engine-native/tidy.ts
+++ b/cli/src/engine-native/tidy.ts
@@ -11,13 +11,14 @@ import { basename, dirname, isAbsolute, join, relative, resolve } from "node:pat
import { Cause, Effect, FileSystem, Option, Result, Schema, type Scope } from "effect";
import type { PlatformError } from "effect/PlatformError";
-import { deferSignalExit, signalExitPoint } from "../engine";
import { bridgePromise, bridgeSync, type LegacyStepFailed } from "./bridge";
import { errorMessage } from "./errorText";
import { spawnProcess, type AsyncProcessResult } from "./exec";
+import { nodeError, readTextKeepingBom } from "./fileText";
import { ensureDirectory } from "./ompFileDeploy";
import { processExited } from "./processes";
import { isSameOrInside, kitCacheDir, removeTemporaryPath } from "./scratch";
+import { deferSignalExit, signalExitPoint } from "./signalGuard";
import { runBounded } from "./syncConcurrency";
export const HOUR_MS = 3_600_000;
@@ -63,15 +64,6 @@ function errorCode(cause: unknown): string | undefined {
: undefined;
}
-/**
- * The Node error of a failed file operation: the cause that the
- * `PlatformError` keeps, else the `PlatformError`. Its errno code and its
- * message are the ones that the synchronous `node:fs` call threw.
- */
-export function nodeError(error: PlatformError): unknown {
- return error.cause ?? error;
-}
-
/** A typed failure of tidy or of its report: a check, a report section, or a bridged call. */
interface TaggedFailure {
readonly _tag: string;
@@ -125,21 +117,6 @@ export const normalizePath = Effect.fnUntraced(function* (path: string) {
return yield* fs.realPath(resolved).pipe(Effect.orElseSucceed(() => resolved));
});
-const UTF8_KEEPING_BOM = new TextDecoder("utf-8", { ignoreBOM: true });
-
-/**
- * The UTF-8 text of `path`; none when it cannot be read. A leading byte order
- * mark stays in the text, as `readFileSync(path, "utf8")` kept it, so a
- * parser that expects a prefix rejects such a file, as it did before.
- */
-export const readTextKeepingBom = Effect.fnUntraced(function* (path: string) {
- const fs = yield* FileSystem.FileSystem;
- return yield* fs.readFile(path).pipe(
- Effect.map((bytes) => UTF8_KEEPING_BOM.decode(bytes)),
- Effect.option,
- );
-});
-
// ------------------------------------------------------------------ host ----
export interface TidyProcess {
@@ -637,7 +614,7 @@ export const sortedEntries = Effect.fnUntraced(function* (directory: string) {
/** The admin directory from a `gitdir: ` file at `/.git`. */
const adminDirectory = Effect.fnUntraced(function* (worktree: string) {
- const text = yield* readTextKeepingBom(join(worktree, ".git"));
+ const text = yield* readTextKeepingBom(join(worktree, ".git")).pipe(Effect.option);
if (Option.isNone(text) || !text.value.startsWith("gitdir: ")) return undefined;
return yield* normalizePath(resolve(worktree, text.value.slice("gitdir: ".length).trim()));
});
@@ -1354,11 +1331,11 @@ export const applyTidy = Effect.fn("applyTidy")(function* (
host: TidyHost,
): Effect.fn.Return<
{ readonly failures: number; readonly lines: ReadonlyArray },
- LegacyStepFailed,
+ LegacyStepFailed | PlatformError,
FileSystem.FileSystem | Scope.Scope
> {
yield* deferSignalExit;
- yield* bridgeSync("ensureDirectory", () => ensureDirectory(kitCacheDir(inputs.home)));
+ yield* ensureDirectory(kitCacheDir(inputs.home));
const lines: Array = [];
let failures = 0;
const done = (outcome: "removed" | "stopped", subject: string): void => {
diff --git a/cli/src/engine-native/tidyReport.ts b/cli/src/engine-native/tidyReport.ts
index 30d711d5..724ede7c 100644
--- a/cli/src/engine-native/tidyReport.ts
+++ b/cli/src/engine-native/tidyReport.ts
@@ -9,6 +9,7 @@ import { join } from "node:path";
import { Cause, Effect, FileSystem, Option, Schema } from "effect";
import { errorMessage } from "./errorText";
+import { nodeError, readTextKeepingBom } from "./fileText";
import { parseJson } from "./jq";
import { isSameOrInside } from "./scratch";
import { runBounded } from "./syncConcurrency";
@@ -25,12 +26,10 @@ import {
lstatOrUndefined,
localDocker,
mainRepository,
- nodeError,
normalizePath,
notLocalMessage,
orphanParents,
PROCESS_LIST_UNAVAILABLE,
- readTextKeepingBom,
repositoryWorktrees,
shorten,
shortRef,
@@ -359,7 +358,7 @@ const trashSection = Effect.fnUntraced(function* (home: string, host: TidyHost)
for (const name of yield* sortedEntries(info)) {
if (!name.endsWith(".trashinfo")) continue;
// An unreadable entry does not change the oldest date.
- const text = yield* readTextKeepingBom(join(info, name));
+ const text = yield* readTextKeepingBom(join(info, name)).pipe(Effect.option);
if (Option.isNone(text)) continue;
const date = /^DeletionDate=(.+)$/m.exec(text.value)?.[1]?.trim();
if (date !== undefined && (oldest === undefined || date < oldest)) oldest = date;
@@ -485,7 +484,9 @@ const scheduledSection = Effect.fnUntraced(function* (home: string, host: TidyHo
* its global `package.json`; its `node_modules` also holds their dependencies.
*/
const bunGlobalPackages = Effect.fnUntraced(function* (home: string) {
- const text = yield* readTextKeepingBom(join(home, ".bun", "install", "global", "package.json"));
+ const text = yield* readTextKeepingBom(
+ join(home, ".bun", "install", "global", "package.json"),
+ ).pipe(Effect.option);
const manifest = Option.isNone(text) ? undefined : parseJson(text.value);
const dependencies =
typeof manifest === "object" && manifest !== null && "dependencies" in manifest
diff --git a/cli/src/engine.ts b/cli/src/engine.ts
index 2d230c9f..59102a98 100644
--- a/cli/src/engine.ts
+++ b/cli/src/engine.ts
@@ -2,7 +2,9 @@ import { CliError } from "effect/cli";
import { Cause, Console, Effect } from "effect";
import { runEngineNative, type EngineFailure } from "./engine-native";
import { failureText } from "./engine-native/bridge";
+import { nodeError } from "./engine-native/fileText";
import { targetForHost } from "./engine-native/os/targets";
+import { exitOnSignal, PUBLIC_SIGNAL_EXIT_CODES } from "./engine-native/signalGuard";
/**
* The single seam between the typed CLI and EngineNative. Engine execution
@@ -22,17 +24,23 @@ const requireSupportedHost = () => {
};
/**
- * 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.
+ * The text of a failed run. A bridged step, the kit home, a YAML failure, and
+ * a removal of the kit plugin prune keep the message that they captured when
+ * they failed, so the cause is not read again; a lock failure and a file
+ * operation give the message of their Node error, and a held lease its own.
*/
const failureDetail = (error: EngineFailure): string => {
switch (error._tag) {
case "LegacyStepFailed":
case "KitHomeInvalid":
+ case "OmpYamlInvalid":
+ case "PluginFolderRemoveFailed":
+ case "PluginFileRemoveFailed":
return error.message;
case "LockAcquireError":
return failureText(error.cause);
+ case "PlatformError":
+ return failureText(nodeError(error));
case "LeaseHeld":
return failureText(error);
}
@@ -51,83 +59,6 @@ export const engineFailureDetail = (cause: Cause.Cause): string =
return Cause.isFailReason(last) ? failureDetail(last.error) : failureText(last.defect);
};
-/**
- * The signal state of `exitOnSignal`: `deferred` counts the open
- * `deferSignalExit` scopes, `exitPoints` the calls that `signalExitPoint`
- * runs, and `recorded` is true once a signal came while an exit was deferred.
- */
-const signals = { deferred: 0, exitPoints: 0, recorded: false };
-
-/** The exit of a signal while `exitOnSignal` is active: 130 for SIGINT and SIGTERM. */
-const exitNow = (): never => process.exit(130);
-
-/**
- * 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 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. Inside a
- * `deferSignalExit` scope, a signal is recorded instead, unless a
- * `signalExitPoint` call waits. `docks-kit tidy` runs inside it too.
- */
-export const exitOnSignal = Effect.acquireRelease(
- Effect.sync(() => {
- const exit = (): void => {
- if (signals.deferred > 0 && signals.exitPoints === 0) {
- signals.recorded = true;
- return;
- }
- exitNow();
- };
- process.prependListener("SIGINT", exit);
- process.prependListener("SIGTERM", exit);
- return exit;
- }),
- (exit) =>
- Effect.sync(() => {
- process.off("SIGINT", exit);
- process.off("SIGTERM", exit);
- }),
-);
-
-/**
- * For the rest of the scope, `exitOnSignal` records a SIGINT or SIGTERM
- * instead of exiting, so the steps of the scope run to their end; when the
- * last open scope closes after a recorded signal, the process exits with 130.
- * The plain steps of `tidy --apply` and the printing of their result run in
- * it, as they ran without a signal turn before; #297 replaces it with fiber
- * interruption.
- */
-export const deferSignalExit = Effect.acquireRelease(
- Effect.sync(() => {
- signals.deferred += 1;
- }),
- () =>
- Effect.sync(() => {
- signals.deferred -= 1;
- if (signals.deferred === 0 && signals.recorded) exitNow();
- }),
-);
-
-/**
- * Run `effect`, a call that can wait on a child process, as an exit point: a
- * signal recorded before it, or one that comes while it waits, exits with 130
- * at once, also inside a `deferSignalExit` scope.
- */
-export const signalExitPoint = (effect: Effect.Effect): Effect.Effect =>
- Effect.acquireUseRelease(
- Effect.sync(() => {
- if (signals.recorded) exitNow();
- signals.exitPoints += 1;
- }),
- () => effect,
- () =>
- Effect.sync(() => {
- signals.exitPoints -= 1;
- }),
- );
-
export const engine = (args: ReadonlyArray) =>
Effect.gen(function* () {
yield* requireSupportedHost();
@@ -135,7 +66,10 @@ export const engine = (args: ReadonlyArray) =>
return yield* bail(bashRemovedMessage, 2);
}
const code = yield* Effect.scoped(
- Effect.andThen(exitOnSignal, runEngineNative(args, { envGlobals: false })),
+ Effect.andThen(
+ exitOnSignal(PUBLIC_SIGNAL_EXIT_CODES),
+ runEngineNative(args, { envGlobals: false }),
+ ),
).pipe(
Effect.catchCause((cause) =>
Cause.hasInterruptsOnly(cause)
diff --git a/cli/src/main.ts b/cli/src/main.ts
index 5f491b09..8a3048bf 100755
--- a/cli/src/main.ts
+++ b/cli/src/main.ts
@@ -9,6 +9,7 @@ import { rootCommand, TIER_USAGE } from "./commands/root";
import { engineFailureDetail } from "./engine";
import { runEngineNative } from "./engine-native";
import { OmpYamlReader } from "./engine-native/ompFastMode";
+import { exitOnSignal, RAW_SIGNAL_EXIT_CODES } from "./engine-native/signalGuard";
const root = rootCommand.pipe(Command.withSubcommands(COMMANDS));
@@ -41,12 +42,17 @@ if (process.env["DOCKS_KIT_ENGINE"] === "native-raw") {
const rawOperation = rawArgs.join(" ") || "default";
// The raw channel bypasses BunRuntime.runMain, which turns a signal into
// process.exit. Without a handler a signal ends the process without the
- // `exit` event, and exec.ts then cannot end its bounded probes.
- process.once("SIGINT", () => process.exit(130));
- process.once("SIGTERM", () => process.exit(143));
+ // `exit` event, and exec.ts then cannot end its bounded probes. The
+ // handlers of `exitOnSignal` go first, before the layers, and exit 130 on
+ // SIGINT and 143 on SIGTERM, after a started mutation settled.
const exit = await Effect.runPromiseExit(
- runEngineNative(rawArgs, { envGlobals: true }).pipe(
- Effect.provide(Layer.mergeAll(BunServices.layer, EngineServicesLive)),
+ Effect.scoped(
+ Effect.andThen(
+ exitOnSignal(RAW_SIGNAL_EXIT_CODES),
+ runEngineNative(rawArgs, { envGlobals: true }).pipe(
+ Effect.provide(Layer.mergeAll(BunServices.layer, EngineServicesLive)),
+ ),
+ ),
),
);
if (Exit.isSuccess(exit)) process.exit(exit.value);
diff --git a/cli/test/lib/signalSelfPreload.ts b/cli/test/lib/signalSelfPreload.ts
index 5af3178f..840d556c 100644
--- a/cli/test/lib/signalSelfPreload.ts
+++ b/cli/test/lib/signalSelfPreload.ts
@@ -12,11 +12,40 @@
* 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.
+ *
+ * When `SIGNAL_AT_CHMOD` holds `:`, the first `fs.chmod`
+ * of that path raises the signal on this process instead of running, and a
+ * listener of that signal runs the chmod. The listener comes after the
+ * listeners of the entry, so an entry that exits on the signal ends before the
+ * chmod, and an entry that defers the exit lets the chmod run first.
*/
-import { existsSync, readFileSync } from "node:fs";
+import type * as NodeFs from "node:fs";
+import type { Mode, NoParamCallback, PathLike } from "node:fs";
+import { createRequire } from "node:module";
+
+// The module object, not an ESM namespace: Bun fixes the exports of `node:fs`
+// in a namespace when a module first imports it, so the chmod hook goes in
+// before any static `node:fs` import of this preload and of the entry.
+const nodeFs: typeof NodeFs = createRequire(import.meta.url)("node:fs");
+
+const atChmod = /^(SIGTERM|SIGINT):(.+)$/.exec(process.env["SIGNAL_AT_CHMOD"] ?? "");
-import { publishPidRecordOrExit } from "./supervisedRun";
+if (atChmod !== null) {
+ const signal = atChmod[1] === "SIGTERM" ? "SIGTERM" : "SIGINT";
+ const target = atChmod[2];
+ const chmod = nodeFs.chmod;
+ let raised = false;
+ const chmodAfterSignal = (path: PathLike, mode: Mode, callback: NoParamCallback): void => {
+ if (raised || String(path) !== target) return chmod(path, mode, callback);
+ raised = true;
+ process.once(signal, () => chmod(path, mode, callback));
+ process.kill(process.pid, signal);
+ };
+ Object.assign(nodeFs, { chmod: chmodAfterSignal });
+}
+// `supervisedRun.ts` imports `node:fs`, so it loads after the hook.
+const { publishPidRecordOrExit } = await import("./supervisedRun");
publishPidRecordOrExit("signal preload");
const request = process.env["SIGNAL_REQUEST_FILE"] ?? "";
@@ -24,8 +53,8 @@ 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 (!nodeFs.existsSync(request)) return;
+ const signal = nodeFs.readFileSync(request, "utf8").trim();
if (signal !== "SIGTERM" && signal !== "SIGINT") return;
clearInterval(watch);
process.kill(process.pid, signal);
diff --git a/cli/test/unit/contract-omp-yaml.test.ts b/cli/test/unit/contract-omp-yaml.test.ts
index 6264f0f1..af942851 100644
--- a/cli/test/unit/contract-omp-yaml.test.ts
+++ b/cli/test/unit/contract-omp-yaml.test.ts
@@ -2,25 +2,40 @@ import { describe, expect, it } from "vitest";
import { mergeOmpConfig, mergeOmpModels } from "../../src/engine-native/ompYaml";
+/** The `Result` of a merge that fails with `OmpYamlInvalid` and `message`. */
+const refused = (message: unknown) => ({
+ _tag: "Failure",
+ failure: { _tag: "OmpYamlInvalid", message },
+});
+
describe("omp YAML document boundaries", () => {
it("names the file when models.yml or SoT config.yml is malformed", () => {
- expect(() => mergeOmpModels("value: 1\n", "[unterminated\n")).toThrow(
- /Invalid deployed omp models\.yml YAML:/,
+ expect(mergeOmpModels("value: 1\n", "[unterminated\n")).toMatchObject(
+ refused(expect.stringMatching(/^Invalid deployed omp models\.yml YAML:/)),
);
- expect(() => mergeOmpConfig("[unterminated\n", "value: 1\n")).toThrow(
- /Invalid SoT omp config\.yml YAML:/,
+ expect(mergeOmpConfig("[unterminated\n", "value: 1\n")).toMatchObject(
+ refused(expect.stringMatching(/^Invalid SoT omp config\.yml YAML:/)),
);
});
it("rejects a non-null deployed scalar instead of overwriting user config", () => {
- expect(() => mergeOmpConfig("managed: true\n", "invalid-root\n")).toThrow(
- "Deployed omp config.yml YAML root must be a mapping",
+ expect(mergeOmpConfig("managed: true\n", "invalid-root\n")).toMatchObject(
+ refused("Deployed omp config.yml YAML root must be a mapping"),
);
});
it("rejects a missing SoT document when the deployed file has data", () => {
- expect(() => mergeOmpConfig("", "value: 1\n")).toThrow(
- /SoT omp config\.yml YAML root must be a mapping/,
+ expect(mergeOmpConfig("", "value: 1\n")).toMatchObject(
+ refused("SoT omp config.yml YAML root must be a mapping"),
);
});
+
+ it("fails with the YAML library message when the merge leaves an alias before its anchor", () => {
+ // The deployed file is valid: its anchor comes first. The merge keeps both
+ // nodes but emits the SoT key order, so the managed mapping with the kept
+ // alias comes before the deployed-only anchored key.
+ expect(
+ mergeOmpConfig("managed:\n key: 1\n", "user: &x 1\nmanaged:\n ref: *x\n"),
+ ).toMatchObject(refused("Unresolved alias (the anchor must be set before the alias): x"));
+ });
});
diff --git a/cli/test/unit/engine.test.ts b/cli/test/unit/engine.test.ts
index 5074a520..7c32699e 100644
--- a/cli/test/unit/engine.test.ts
+++ b/cli/test/unit/engine.test.ts
@@ -2,7 +2,7 @@ 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 { Effect, FileSystem, Layer } from "effect";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type * as EngineNativeModule from "../../src/engine-native";
@@ -143,6 +143,23 @@ describe("EngineNative Effect seam", () => {
});
});
+ it("prints the Node error message of a failed file operation, as the bridged pass did", async () => {
+ const owned = mkdtempSync(join(tmpdir(), "docks-kit-engine-test-"));
+ try {
+ const missing = join(owned, "AGENTS.md");
+ mocks.runEngineNative.mockReturnValue(
+ Effect.flatMap(FileSystem.FileSystem, (fs) => fs.readFile(missing)).pipe(Effect.as(0)),
+ );
+
+ await expect(runEngine(["sync"])).rejects.toMatchObject({
+ _tag: "UserError",
+ message: `engine operation 'sync' failed: ENOENT: no such file or directory, open '${missing}'`,
+ });
+ } finally {
+ rmSync(owned, { recursive: true, force: true });
+ }
+ });
+
it("reports the default operation and unknown cause when the native engine fails silently", async () => {
mocks.runEngineNative.mockReturnValue(Effect.die(new Error("")));
diff --git a/cli/test/unit/ompBashPatterns.test.ts b/cli/test/unit/ompBashPatterns.test.ts
index f4849781..55bb1fb8 100644
--- a/cli/test/unit/ompBashPatterns.test.ts
+++ b/cli/test/unit/ompBashPatterns.test.ts
@@ -8,6 +8,7 @@
*/
import { readFileSync } from "node:fs";
import { join } from "node:path";
+import { Result } from "effect";
import { describe, expect, it } from "vitest";
import { parse } from "yaml";
@@ -446,12 +447,16 @@ describe("omp bash.patterns sync merge", () => {
const byApproval = (approval: OmpApproval): Array =>
KIT_RULES.filter((rule) => rule.approval === approval);
+ /** The merged config.yml text; a refused merge fails the case. */
+ const merge = (sot: string, deployed: string): string =>
+ Result.getOrThrow(mergeOmpConfig(sot, deployed));
+
it("deploys the kit rules unchanged into a config without bash.patterns", () => {
- expect(bashPatterns(mergeOmpConfig(SOT_TEXT, "userOnly: true\n"))).toEqual(KIT_RULES);
+ expect(bashPatterns(merge(SOT_TEXT, "userOnly: true\n"))).toEqual(KIT_RULES);
});
it("puts user denies and prompts ahead of every kit allow, and user allows ahead of kit allows", () => {
- const merged = mergeOmpConfig(SOT_TEXT, userRules);
+ const merged = merge(SOT_TEXT, userRules);
const rules = bashPatterns(merged);
expect(rules).toEqual([
@@ -483,7 +488,7 @@ describe("omp bash.patterns sync merge", () => {
].join("\n");
expect(ompApproval(bashPatterns(shadowed), "git clean -x -f")).toBe("prompt");
- const rules = bashPatterns(mergeOmpConfig(SOT_TEXT, shadowed));
+ const rules = bashPatterns(merge(SOT_TEXT, shadowed));
expect(ompYoloOutcome(rules, "git clean -x -f")).toBe("deny");
expect(rules.filter(({ match }) => match === "git clean -x *")).toEqual([
@@ -511,7 +516,7 @@ describe("omp bash.patterns sync merge", () => {
"",
].join("\n");
- expect(bashPatterns(mergeOmpConfig(sot, deployed)).map(({ match }) => match)).toEqual([
+ expect(bashPatterns(merge(sot, deployed)).map(({ match }) => match)).toEqual([
"kit-deny *",
"user-deny *",
"user-prompt *",
@@ -522,8 +527,8 @@ describe("omp bash.patterns sync merge", () => {
});
it("is idempotent and does not duplicate a deployed kit rule", () => {
- const once = mergeOmpConfig(SOT_TEXT, userRules);
- const twice = mergeOmpConfig(SOT_TEXT, once);
+ const once = merge(SOT_TEXT, userRules);
+ const twice = merge(SOT_TEXT, once);
expect(twice).toBe(once);
expect(bashPatterns(twice)).toHaveLength(KIT_RULES.length + 4);
@@ -532,6 +537,6 @@ describe("omp bash.patterns sync merge", () => {
it("treats a respaced or recased copy of a kit rule as the kit rule", () => {
const deployed = 'bash:\n patterns:\n - match: " rm * ~"\n approval: DENY\n';
- expect(bashPatterns(mergeOmpConfig(SOT_TEXT, deployed))).toEqual(KIT_RULES);
+ expect(bashPatterns(merge(SOT_TEXT, deployed))).toEqual(KIT_RULES);
});
});
diff --git a/cli/test/unit/ompFastMode.test.ts b/cli/test/unit/ompFastMode.test.ts
index 841cab01..498c2bf8 100644
--- a/cli/test/unit/ompFastMode.test.ts
+++ b/cli/test/unit/ompFastMode.test.ts
@@ -1,6 +1,6 @@
import { BunServices } from "@effect/platform-bun";
import { spawnSync } from "node:child_process";
-import { Effect, Exit, FileSystem, Layer } from "effect";
+import { Effect, Exit, FileSystem, Layer, Result } from "effect";
import { Command } from "effect/cli";
import { afterEach, describe, expect, it, vi } from "vitest";
import {
@@ -333,7 +333,9 @@ describe("toggleOpenAiTier with priority (--fast)", () => {
it("survives a sync merge with the shipped SoT config", () => {
const deployed = toggleFast(CONFIG).text;
- const merged = parse(mergeOmpConfig(payloadText("SoT/.omp/config.yml"), deployed));
+ const merged = parse(
+ Result.getOrThrow(mergeOmpConfig(payloadText("SoT/.omp/config.yml"), deployed)),
+ );
expect(merged.tier.openai).toBe("priority");
});
});
diff --git a/cli/test/unit/ompKitPlugin.test.ts b/cli/test/unit/ompKitPlugin.test.ts
index d0574642..176a1666 100644
--- a/cli/test/unit/ompKitPlugin.test.ts
+++ b/cli/test/unit/ompKitPlugin.test.ts
@@ -1,5 +1,6 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import {
+ chmodSync,
existsSync,
mkdirSync,
mkdtempSync,
@@ -10,6 +11,8 @@ import {
} from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
+import { BunServices } from "@effect/platform-bun";
+import { Effect } from "effect";
import type { Ctx } from "../../src/engine-native";
import { DEPENDENCIES } from "../../src/engine-native/deps";
@@ -61,10 +64,15 @@ afterEach(() => {
for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true });
});
+/** Run the kit plugin pass of `ctx` on the real file system. */
+function syncPluginFiles(ctx: Ctx): Promise {
+ return Effect.runPromise(syncKitPlugin(ctx).pipe(Effect.provide(BunServices.layer)));
+}
+
describe("omp kit plugin files", () => {
- it("writes the plugin package with the kit version and private modes", () => {
+ it("writes the plugin package with the kit version and private modes", async () => {
const ctx = testCtx();
- syncKitPlugin(ctx);
+ await syncPluginFiles(ctx);
const pluginDir = kitPluginDir(ctx.home);
const manifest = JSON.parse(readFileSync(join(pluginDir, "package.json"), "utf8")) as {
@@ -103,18 +111,21 @@ describe("omp kit plugin files", () => {
expect(ctx.nextStepTriggers.ompRestart).toBe(true);
});
- it.skipIf(process.platform === "win32")("keeps files at 0600 and directories at 0700", () => {
- const ctx = testCtx();
- syncKitPlugin(ctx);
+ it.skipIf(process.platform === "win32")(
+ "keeps files at 0600 and directories at 0700",
+ async () => {
+ const ctx = testCtx();
+ await syncPluginFiles(ctx);
- const pluginDir = kitPluginDir(ctx.home);
- expect(statSync(pluginDir).mode & 0o777).toBe(0o700);
- expect(statSync(join(pluginDir, "extensions")).mode & 0o777).toBe(0o700);
- expect(statSync(join(pluginDir, "package.json")).mode & 0o777).toBe(0o600);
- expect(statSync(join(pluginDir, "extensions", "hygiene.ts")).mode & 0o777).toBe(0o600);
- });
+ const pluginDir = kitPluginDir(ctx.home);
+ expect(statSync(pluginDir).mode & 0o777).toBe(0o700);
+ expect(statSync(join(pluginDir, "extensions")).mode & 0o777).toBe(0o700);
+ expect(statSync(join(pluginDir, "package.json")).mode & 0o777).toBe(0o600);
+ expect(statSync(join(pluginDir, "extensions", "hygiene.ts")).mode & 0o777).toBe(0o600);
+ },
+ );
- it("removes stale files and empty directories from the plugin directory", () => {
+ it("removes stale files and empty directories from the plugin directory", async () => {
const ctx = testCtx();
const pluginDir = kitPluginDir(ctx.home);
mkdirSync(join(pluginDir, "extensions"), { recursive: true });
@@ -122,31 +133,68 @@ describe("omp kit plugin files", () => {
mkdirSync(join(pluginDir, "retired", "nested"), { recursive: true });
writeFileSync(join(pluginDir, "retired", "nested", "file.md"), "old\n");
- syncKitPlugin(ctx);
+ await syncPluginFiles(ctx);
expect(existsSync(join(pluginDir, "extensions", "old.ts"))).toBe(false);
expect(existsSync(join(pluginDir, "retired"))).toBe(false);
expect(existsSync(join(pluginDir, "extensions", "hygiene.ts"))).toBe(true);
});
- it("changes nothing on a second run", () => {
+ // A read-only folder refuses the unlink; root and Windows ignore the mode.
+ it.skipIf(process.platform === "win32" || process.getuid?.() === 0)(
+ "fails with the Node error of a stale file that the prune cannot remove",
+ async () => {
+ const ctx = testCtx();
+ const retired = join(kitPluginDir(ctx.home), "retired");
+ mkdirSync(retired, { recursive: true });
+ const stale = join(retired, "old.md");
+ writeFileSync(stale, "old\n");
+ chmodSync(retired, 0o500);
+ try {
+ const exit = await Effect.runPromiseExit(
+ syncKitPlugin(ctx).pipe(Effect.provide(BunServices.layer)),
+ );
+
+ expect(exit).toMatchObject({
+ _tag: "Failure",
+ cause: {
+ reasons: [
+ {
+ _tag: "Fail",
+ error: {
+ _tag: "PluginFileRemoveFailed",
+ path: stale,
+ message: `EACCES: permission denied, unlink '${stale}'`,
+ },
+ },
+ ],
+ },
+ });
+ expect(existsSync(stale)).toBe(true);
+ } finally {
+ chmodSync(retired, 0o700);
+ }
+ },
+ );
+
+ it("changes nothing on a second run", async () => {
const ctx = testCtx();
- syncKitPlugin(ctx);
+ await syncPluginFiles(ctx);
ctx.nextStepTriggers.ompRestart = false;
- syncKitPlugin(ctx);
+ await syncPluginFiles(ctx);
expect(ctx.nextStepTriggers.ompRestart).toBe(false);
});
- it("names the kit plugin version change when the deployed version differs", () => {
+ it("names the kit plugin version change when the deployed version differs", async () => {
const stderr: Array = [];
const ctx = testCtx(false, [], stderr);
const pluginDir = kitPluginDir(ctx.home);
mkdirSync(pluginDir, { recursive: true });
writeFileSync(join(pluginDir, "package.json"), '{ "version": "0.0.1" }\n');
- syncKitPlugin(ctx);
+ await syncPluginFiles(ctx);
expect(stderr.join("")).toContain(
`omp kit plugin files synced (docks-kit-omp 0.0.1 -> ${GENERATED_PACKAGE_VERSION})`,
@@ -155,7 +203,7 @@ describe("omp kit plugin files", () => {
it.skipIf(process.platform === "win32")(
"replaces a changed file with a new file, not in place, and keeps mode 0600",
- () => {
+ async () => {
const ctx = testCtx();
const pluginDir = kitPluginDir(ctx.home);
const target = join(pluginDir, "extensions", "hygiene.ts");
@@ -163,7 +211,7 @@ describe("omp kit plugin files", () => {
writeFileSync(target, "old\n", { mode: 0o600 });
const before = statSync(target).ino;
- syncKitPlugin(ctx);
+ await syncPluginFiles(ctx);
expect(readFileSync(target, "utf8")).toBe(
payloadText("SoT/.omp/plugin/extensions/hygiene.ts"),
@@ -173,10 +221,10 @@ describe("omp kit plugin files", () => {
},
);
- it("previews the plugin folder in one dry-run line and writes nothing", () => {
+ it("previews the plugin folder in one dry-run line and writes nothing", async () => {
const stdout: Array = [];
const ctx = testCtx(true, stdout);
- syncKitPlugin(ctx);
+ await syncPluginFiles(ctx);
const pluginDir = kitPluginDir(ctx.home);
const lines = stdout.join("").split("\n");
diff --git a/cli/test/unit/ompPaths.test.ts b/cli/test/unit/ompPaths.test.ts
index a83bea04..b2d9c0cc 100644
--- a/cli/test/unit/ompPaths.test.ts
+++ b/cli/test/unit/ompPaths.test.ts
@@ -1,6 +1,8 @@
-import { mkdirSync, mkdtempSync, rmSync } from "node:fs";
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
+import { BunServices } from "@effect/platform-bun";
+import { Effect } from "effect";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { ompPaths, type OmpPaths } from "../../src/engine-native/ompPaths";
@@ -13,7 +15,8 @@ let home = "";
const paths = (
env: Record,
platform: NodeJS.Platform = "linux",
-): OmpPaths => ompPaths({ home, env, platform });
+): Promise =>
+ Effect.runPromise(ompPaths({ home, env, platform }).pipe(Effect.provide(BunServices.layer)));
const expectedDefault = (configRoot: string): OmpPaths => ({
profile: undefined,
@@ -32,17 +35,17 @@ describe("omp path resolution", () => {
rmSync(sandbox, { recursive: true, force: true });
});
- it("uses the home config root for the default profile with no overrides", () => {
- expect(paths({})).toEqual(expectedDefault(`${home}/.omp`));
+ it("uses the home config root for the default profile with no overrides", async () => {
+ expect(await paths({})).toEqual(expectedDefault(`${home}/.omp`));
});
- it("treats PI_CONFIG_DIR as a root dirname under home, never a working-directory path", () => {
- expect(paths({ PI_CONFIG_DIR: ".omp-alt" })).toEqual(expectedDefault(`${home}/.omp-alt`));
- expect(paths({ PI_CONFIG_DIR: "" })).toEqual(expectedDefault(`${home}/.omp`));
+ it("treats PI_CONFIG_DIR as a root dirname under home, never a working-directory path", async () => {
+ expect(await paths({ PI_CONFIG_DIR: ".omp-alt" })).toEqual(expectedDefault(`${home}/.omp-alt`));
+ expect(await paths({ PI_CONFIG_DIR: "" })).toEqual(expectedDefault(`${home}/.omp`));
});
- it("relocates the whole config root under a named profile", () => {
- expect(paths({ OMP_PROFILE: "work" })).toEqual({
+ it("relocates the whole config root under a named profile", async () => {
+ expect(await paths({ OMP_PROFILE: "work" })).toEqual({
profile: "work",
configRoot: `${home}/.omp/profiles/work`,
agentDir: `${home}/.omp/profiles/work/agent`,
@@ -50,27 +53,27 @@ describe("omp path resolution", () => {
});
});
- it("honors PI_CODING_AGENT_DIR for the default profile and ignores it under a named profile", () => {
+ it("honors PI_CODING_AGENT_DIR for the default profile and ignores it under a named profile", async () => {
const override = join(sandbox, "custom-agent");
- expect(paths({ PI_CODING_AGENT_DIR: override })).toEqual({
+ expect(await paths({ PI_CODING_AGENT_DIR: override })).toEqual({
...expectedDefault(`${home}/.omp`),
agentDir: override,
});
- expect(paths({ PI_CODING_AGENT_DIR: override, OMP_PROFILE: "work" }).agentDir).toBe(
+ expect((await paths({ PI_CODING_AGENT_DIR: override, OMP_PROFILE: "work" })).agentDir).toBe(
`${home}/.omp/profiles/work/agent`,
);
});
- it("resolves a relative PI_CODING_AGENT_DIR against the working directory", () => {
- expect(paths({ PI_CODING_AGENT_DIR: "rel-agent" }).agentDir).toBe(
+ it("resolves a relative PI_CODING_AGENT_DIR against the working directory", async () => {
+ expect((await paths({ PI_CODING_AGENT_DIR: "rel-agent" })).agentDir).toBe(
resolve(process.cwd(), "rel-agent"),
);
});
- it("ignores a default-profile override that equals the PI_PROFILE agent directory", () => {
+ it("ignores a default-profile override that equals the PI_PROFILE agent directory", async () => {
expect(
- paths({
+ await paths({
OMP_PROFILE: "",
PI_PROFILE: "work",
PI_CODING_AGENT_DIR: `${home}/.omp/profiles/work/agent`,
@@ -78,17 +81,17 @@ describe("omp path resolution", () => {
).toEqual(expectedDefault(`${home}/.omp`));
});
- it("prefers OMP_PROFILE even when empty, and otherwise falls back to PI_PROFILE", () => {
- expect(paths({ OMP_PROFILE: "", PI_PROFILE: "legacy" })).toEqual(
+ it("prefers OMP_PROFILE even when empty, and otherwise falls back to PI_PROFILE", async () => {
+ expect(await paths({ OMP_PROFILE: "", PI_PROFILE: "legacy" })).toEqual(
expectedDefault(`${home}/.omp`),
);
- expect(paths({ PI_PROFILE: "legacy" })).toEqual({
+ expect(await paths({ PI_PROFILE: "legacy" })).toEqual({
profile: "legacy",
configRoot: `${home}/.omp/profiles/legacy`,
agentDir: `${home}/.omp/profiles/legacy/agent`,
dataRoot: `${home}/.omp/profiles/legacy`,
});
- expect(paths({ OMP_PROFILE: "primary", PI_PROFILE: "legacy" })).toEqual({
+ expect(await paths({ OMP_PROFILE: "primary", PI_PROFILE: "legacy" })).toEqual({
profile: "primary",
configRoot: `${home}/.omp/profiles/primary`,
agentDir: `${home}/.omp/profiles/primary/agent`,
@@ -98,26 +101,34 @@ describe("omp path resolution", () => {
it.each([" ", "default", "..", "trailing.", "Upper", "has space", "CON", "nul.txt"])(
"degrades the invalid or reserved profile %j to the default paths",
- (profile) => {
- expect(paths({ OMP_PROFILE: profile })).toEqual(expectedDefault(`${home}/.omp`));
+ async (profile) => {
+ expect(await paths({ OMP_PROFILE: profile })).toEqual(expectedDefault(`${home}/.omp`));
},
);
- it("adopts the XDG data root for the default profile only after its omp directory exists", () => {
+ it("adopts the XDG data root for the default profile only after its omp directory exists", async () => {
const dataHome = join(sandbox, "xdg-data");
mkdirSync(dataHome);
- expect(paths({ XDG_DATA_HOME: dataHome }).dataRoot).toBe(`${home}/.omp`);
+ expect((await paths({ XDG_DATA_HOME: dataHome })).dataRoot).toBe(`${home}/.omp`);
mkdirSync(join(dataHome, "omp"));
- expect(paths({ XDG_DATA_HOME: dataHome }).dataRoot).toBe(`${dataHome}/omp`);
+ expect((await paths({ XDG_DATA_HOME: dataHome })).dataRoot).toBe(`${dataHome}/omp`);
});
- it("keeps the agent directory out of XDG even when the data root moves", () => {
+ // `fileText.ts pathExists` follows links and counts every failure, ENOTDIR included, as absent.
+ it("falls back to the config root when the XDG data home is a regular file", async () => {
+ const dataHome = join(sandbox, "xdg-data");
+ writeFileSync(dataHome, "");
+
+ expect((await paths({ XDG_DATA_HOME: dataHome })).dataRoot).toBe(`${home}/.omp`);
+ });
+
+ it("keeps the agent directory out of XDG even when the data root moves", async () => {
const dataHome = join(sandbox, "xdg-data");
mkdirSync(join(dataHome, "omp"), { recursive: true });
- expect(paths({ XDG_DATA_HOME: dataHome })).toEqual({
+ expect(await paths({ XDG_DATA_HOME: dataHome })).toEqual({
profile: undefined,
configRoot: `${home}/.omp`,
agentDir: `${home}/.omp/agent`,
@@ -125,34 +136,36 @@ describe("omp path resolution", () => {
});
});
- it("keys a named profile on its own XDG profile directory and adopts that path", () => {
+ it("keys a named profile on its own XDG profile directory and adopts that path", async () => {
const dataHome = join(sandbox, "xdg-data");
mkdirSync(join(dataHome, "omp"), { recursive: true });
const env = { XDG_DATA_HOME: dataHome, OMP_PROFILE: "work" };
// The base app root exists, but the profile path does not: the profile
// stays where it was first activated.
- expect(paths(env).dataRoot).toBe(`${home}/.omp/profiles/work`);
+ expect((await paths(env)).dataRoot).toBe(`${home}/.omp/profiles/work`);
mkdirSync(join(dataHome, "omp", "profiles", "work"), { recursive: true });
- expect(paths(env).dataRoot).toBe(`${dataHome}/omp/profiles/work`);
+ expect((await paths(env)).dataRoot).toBe(`${dataHome}/omp/profiles/work`);
});
- it("disables XDG while a PI_CODING_AGENT_DIR override is active", () => {
+ it("disables XDG while a PI_CODING_AGENT_DIR override is active", async () => {
const dataHome = join(sandbox, "xdg-data");
mkdirSync(join(dataHome, "omp"), { recursive: true });
const override = join(sandbox, "custom-agent");
- expect(paths({ XDG_DATA_HOME: dataHome, PI_CODING_AGENT_DIR: override }).dataRoot).toBe(
+ expect((await paths({ XDG_DATA_HOME: dataHome, PI_CODING_AGENT_DIR: override })).dataRoot).toBe(
`${home}/.omp`,
);
});
- it("normalizes an absolute override that names the default agent directory and keeps XDG", () => {
+ it("normalizes an absolute override that names the default agent directory and keeps XDG", async () => {
const dataHome = join(sandbox, "xdg-data");
mkdirSync(join(dataHome, "omp"), { recursive: true });
- expect(paths({ XDG_DATA_HOME: dataHome, PI_CODING_AGENT_DIR: `${home}/.omp/agent/` })).toEqual({
+ expect(
+ await paths({ XDG_DATA_HOME: dataHome, PI_CODING_AGENT_DIR: `${home}/.omp/agent/` }),
+ ).toEqual({
profile: undefined,
configRoot: `${home}/.omp`,
agentDir: `${home}/.omp/agent`,
@@ -160,11 +173,11 @@ describe("omp path resolution", () => {
});
});
- it("keeps XDG active when PI_CONFIG_DIR renames the config root", () => {
+ it("keeps XDG active when PI_CONFIG_DIR renames the config root", async () => {
const dataHome = join(sandbox, "xdg-data");
mkdirSync(join(dataHome, "omp"), { recursive: true });
- expect(paths({ XDG_DATA_HOME: dataHome, PI_CONFIG_DIR: ".omp-alt" })).toEqual({
+ expect(await paths({ XDG_DATA_HOME: dataHome, PI_CONFIG_DIR: ".omp-alt" })).toEqual({
profile: undefined,
configRoot: `${home}/.omp-alt`,
agentDir: `${home}/.omp-alt/agent`,
@@ -172,12 +185,12 @@ describe("omp path resolution", () => {
});
});
- it("ignores XDG outside Linux and macOS", () => {
+ it("ignores XDG outside Linux and macOS", async () => {
const dataHome = join(sandbox, "xdg-data");
mkdirSync(join(dataHome, "omp"), { recursive: true });
const env = { XDG_DATA_HOME: dataHome };
- expect(paths(env, "darwin").dataRoot).toBe(`${dataHome}/omp`);
- expect(paths(env, "win32").dataRoot).toBe(`${home}/.omp`);
+ expect((await paths(env, "darwin")).dataRoot).toBe(`${dataHome}/omp`);
+ expect((await paths(env, "win32")).dataRoot).toBe(`${home}/.omp`);
});
});
diff --git a/cli/test/unit/ompPluginInventory.test.ts b/cli/test/unit/ompPluginInventory.test.ts
index fb8cd62c..8f7c8156 100644
--- a/cli/test/unit/ompPluginInventory.test.ts
+++ b/cli/test/unit/ompPluginInventory.test.ts
@@ -12,11 +12,13 @@
import {
chmodSync,
existsSync,
+ lstatSync,
mkdirSync,
mkdtempSync,
readFileSync,
readdirSync,
rmSync,
+ symlinkSync,
writeFileSync,
} from "node:fs";
import { tmpdir } from "node:os";
@@ -43,6 +45,7 @@ vi.mock("../../src/engine-native/bun", () => ({
bunBootstrap: async () => ({ kind: "ready", executable: "bun" }),
}));
+import { BunServices } from "@effect/platform-bun";
import { Effect } from "effect";
import type { Ctx } from "../../src/engine-native";
import { EngineContext } from "../../src/engine-native/engineCtx";
@@ -185,14 +188,21 @@ function makeCtx(
/** Run the omp pipeline in the folders that a sync of `ctx` resolves, as `engineSync` does. */
function syncOmp(ctx: Ctx): Promise {
return Effect.runPromise(
- Effect.flatMap(ompWriteFolders(), ompSync).pipe(Effect.provideService(EngineContext, ctx)),
+ Effect.flatMap(ompWriteFolders(), ompSync).pipe(
+ Effect.provideService(EngineContext, ctx),
+ Effect.provide(BunServices.layer),
+ ),
);
}
/** Run the plugin pass on the omp paths that a sync of `ctx` resolves. */
function syncOmpPlugins(ctx: Ctx): Promise {
- const folders = Effect.runSync(ompWriteFolders().pipe(Effect.provideService(EngineContext, ctx)));
- return syncPlugins(ctx, folders.paths);
+ return Effect.runPromise(
+ Effect.flatMap(ompWriteFolders(), (folders) => syncPlugins(ctx, folders.paths)).pipe(
+ Effect.provideService(EngineContext, ctx),
+ Effect.provide(BunServices.layer),
+ ),
+ );
}
/** Every `omp` argv the pipeline spawned, as one joined string per call. */
@@ -576,6 +586,17 @@ describe("omp plugin inventory", () => {
expect(existsSync(upgradeLog(root))).toBe(true);
});
+ it("leaves a link at the retired upgrade log path alone when its target is missing", async () => {
+ const root = makeRoot();
+ mkdirSync(join(root, ".cache", "docks-kit"), { recursive: true });
+ symlinkSync(join(root, "missing-upgrades"), upgradeLog(root), "junction");
+ respondWithInventory(inventory(root));
+
+ await syncOmp(makeCtx(root));
+
+ expect(lstatSync(upgradeLog(root)).isSymbolicLink()).toBe(true);
+ });
+
it.each([
["lists docks", ["docks"], true],
["does not list docks", ["another-marketplace"], false],
diff --git a/cli/test/unit/ompRemovals.test.ts b/cli/test/unit/ompRemovals.test.ts
index 7842cee7..0b470218 100644
--- a/cli/test/unit/ompRemovals.test.ts
+++ b/cli/test/unit/ompRemovals.test.ts
@@ -1,6 +1,7 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import {
chmodSync,
+ existsSync,
lstatSync,
mkdirSync,
mkdtempSync,
@@ -34,6 +35,7 @@ vi.mock("../../src/engine-native/bun", () => ({
bunBootstrap: async () => ({ kind: "ready", executable: "bun" }),
}));
+import { BunServices } from "@effect/platform-bun";
import { Effect } from "effect";
import { EngineContext } from "../../src/engine-native/engineCtx";
import { syncOmpModelRemovals, syncOmpRemovals } from "../../src/engine-native/ompRemovals";
@@ -89,11 +91,12 @@ function deployConfig(content: string): { file: string; root: string } {
}
/**
- * Runs ompSync with home at `root` and the omp env keys cleared.
- * PI_CODING_AGENT_DIR relocates the whole agent directory, so an ambient
- * value would send these writes outside the temporary root.
+ * Runs ompSync with home at `root` and the omp env keys cleared; resolves
+ * with the stdout chunks of the run. PI_CODING_AGENT_DIR relocates the whole
+ * agent directory, so an ambient value would send these writes outside the
+ * temporary root.
*/
-async function runOmpSync(root: string): Promise {
+async function runOmpSync(root: string, dryRun = false): Promise> {
const ompEnvKeys = [
"XDG_DATA_HOME",
"OMP_PROFILE",
@@ -120,10 +123,15 @@ async function runOmpSync(root: string): Promise {
});
try {
- const ctx = { ...testCtx(root), home: root };
+ const stdout: Array = [];
+ const ctx = { ...testCtx(root, dryRun, stdout), home: root };
await Effect.runPromise(
- Effect.flatMap(ompWriteFolders(), ompSync).pipe(Effect.provideService(EngineContext, ctx)),
+ Effect.flatMap(ompWriteFolders(), ompSync).pipe(
+ Effect.provideService(EngineContext, ctx),
+ Effect.provide(BunServices.layer),
+ ),
);
+ return stdout;
} finally {
for (const [key, value] of Object.entries(restore)) {
if (value === undefined) delete process.env[key];
@@ -132,42 +140,56 @@ async function runOmpSync(root: string): Promise {
}
}
+/** Run the config.yml prune on the real file system; resolves with the pruned count. */
+function prune(ctx: Ctx, file: string, alreadyBackedUp: boolean): Promise {
+ return Effect.runPromise(
+ syncOmpRemovals(ctx, file, alreadyBackedUp).pipe(Effect.provide(BunServices.layer)),
+ );
+}
+
+/** Run the models.yml prune on the real file system; resolves with the pruned count. */
+function pruneModels(ctx: Ctx, file: string, alreadyBackedUp: boolean): Promise {
+ return Effect.runPromise(
+ syncOmpModelRemovals(ctx, file, alreadyBackedUp).pipe(Effect.provide(BunServices.layer)),
+ );
+}
+
afterEach(() => {
for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true });
});
describe("retired omp config keys", () => {
- it("prunes a key whose deployed value still matches the value the kit shipped", () => {
+ it("prunes a key whose deployed value still matches the value the kit shipped", async () => {
const { file, root } = deployConfig("symbolPreset: unicode\nuserOnly: 1\n");
- expect(syncOmpRemovals(testCtx(root), file, false)).toBe(1);
+ expect(await prune(testCtx(root), file, false)).toBe(1);
expect(parse(readFileSync(file, "utf8"))).toEqual({ userOnly: 1 });
});
- it("keeps a retired key the user changed away from the shipped value", () => {
+ it("keeps a retired key the user changed away from the shipped value", async () => {
const { file, root } = deployConfig("theme:\n dark: nord\n");
- expect(syncOmpRemovals(testCtx(root), file, false)).toBe(0);
+ expect(await prune(testCtx(root), file, false)).toBe(0);
expect(parse(readFileSync(file, "utf8"))).toEqual({ theme: { dark: "nord" } });
});
- it("prunes an outright-retired key at a value the kit never shipped", () => {
+ it("prunes an outright-retired key at a value the kit never shipped", async () => {
const { file, root } = deployConfig(
"providers:\n webSearchOrder:\n - brave\n webSearchTimeoutSeconds: 45\n",
);
- expect(syncOmpRemovals(testCtx(root), file, false)).toBe(1);
+ expect(await prune(testCtx(root), file, false)).toBe(1);
expect(parse(readFileSync(file, "utf8"))).toEqual({
providers: { webSearchTimeoutSeconds: 45 },
});
});
- it("removes a mapping emptied by pruning and keeps one that still holds a key", () => {
+ it("removes a mapping emptied by pruning and keeps one that still holds a key", async () => {
const { file, root } = deployConfig(
"tui:\n textSizing: false\n tight: false\nstatusLine:\n transparent: false\n compactThinkingLevel: true\n",
);
- expect(syncOmpRemovals(testCtx(root), file, false)).toBe(3);
+ expect(await prune(testCtx(root), file, false)).toBe(3);
expect(parse(readFileSync(file, "utf8"))).toEqual({
statusLine: { compactThinkingLevel: true },
});
@@ -175,22 +197,22 @@ describe("retired omp config keys", () => {
// An older kit wrote both OpenCode command switches as `false`. Sync prunes
// them at that value only; any other value stays, with the rest of the file.
- it("prunes both OpenCode command switches at the old kit value false", () => {
+ it("prunes both OpenCode command switches at the old kit value false", async () => {
const { file, root } = deployConfig(
"commands:\n enableOpencodeUser: false\n enableOpencodeProject: false\nuserOnly: 1\n",
);
- expect(syncOmpRemovals(testCtx(root), file, false)).toBe(2);
+ expect(await prune(testCtx(root), file, false)).toBe(2);
expect(parse(readFileSync(file, "utf8"))).toEqual({ userOnly: 1 });
});
it.each([["enableOpencodeUser"], ["enableOpencodeProject"]])(
"keeps commands.%s: true and leaves the file unchanged",
- (key) => {
+ async (key) => {
const text = `commands:\n ${key}: true\nuserOnly: 1\n`;
const { file, root } = deployConfig(text);
- expect(syncOmpRemovals(testCtx(root), file, false)).toBe(0);
+ expect(await prune(testCtx(root), file, false)).toBe(0);
expect(readFileSync(file, "utf8")).toBe(text);
},
);
@@ -200,7 +222,7 @@ describe("retired omp config keys", () => {
// edited `compaction.thresholdTokens`, which an earlier kit retired at -1
// and 231200, so sync keeps it. `task` keeps the reviewer override that the
// kit still ships.
- it("prunes all 18 returned overrides at their shipped values and keeps an edited retired value", () => {
+ it("prunes all 18 returned overrides at their shipped values and keeps an edited retired value", async () => {
const { file, root } = deployConfig(
[
"statusLine:",
@@ -237,14 +259,14 @@ describe("retired omp config keys", () => {
].join("\n"),
);
- expect(syncOmpRemovals(testCtx(root), file, false)).toBe(18);
+ expect(await prune(testCtx(root), file, false)).toBe(18);
expect(parse(readFileSync(file, "utf8"))).toEqual({
compaction: { thresholdTokens: 150000 },
task: { agentModelOverrides: { reviewer: "@reviewer" } },
});
});
- it("prunes the shipped advisor block, role, and empty retry chain", () => {
+ it("prunes the shipped advisor block, role, and empty retry chain", async () => {
const { file, root } = deployConfig(
[
"advisor:",
@@ -262,14 +284,14 @@ describe("retired omp config keys", () => {
].join("\n"),
);
- expect(syncOmpRemovals(testCtx(root), file, false)).toBe(4);
+ expect(await prune(testCtx(root), file, false)).toBe(4);
expect(parse(readFileSync(file, "utf8"))).toEqual({
modelRoles: { default: "anthropic/claude-opus-5-5:high" },
retry: { fallbackChains: { default: ["openai-codex/gpt-6.1-sol:high"] } },
});
});
- it("keeps advisor settings and a non-empty advisor chain the user changed", () => {
+ it("keeps advisor settings and a non-empty advisor chain the user changed", async () => {
const source = [
"advisor:",
' syncBacklog: "3"',
@@ -283,7 +305,7 @@ describe("retired omp config keys", () => {
].join("\n");
const { file, root } = deployConfig(source);
- expect(syncOmpRemovals(testCtx(root), file, false)).toBe(0);
+ expect(await prune(testCtx(root), file, false)).toBe(0);
expect(readFileSync(file, "utf8")).toBe(source);
});
@@ -291,12 +313,12 @@ describe("retired omp config keys", () => {
// survive. A comment written directly above a key belongs to that key, so it
// is correct for it to leave with the key rather than be orphaned onto the
// next one.
- it("keeps document and neighbour comments while a pruned key takes its own", () => {
+ it("keeps document and neighbour comments while a pruned key takes its own", async () => {
const { file, root } = deployConfig(
"# kit-owned omp configuration\n\n# no longer set by the kit\nautoResume: false\n\n# roles below\nmodelRoles:\n default: anthropic/claude-opus-5\n",
);
- expect(syncOmpRemovals(testCtx(root), file, false)).toBe(1);
+ expect(await prune(testCtx(root), file, false)).toBe(1);
const after = readFileSync(file, "utf8");
expect(after).toContain("# kit-owned omp configuration");
expect(after).toContain("# roles below");
@@ -305,30 +327,30 @@ describe("retired omp config keys", () => {
expect(after).not.toContain("# no longer set by the kit");
});
- it("reports the count under dry run and leaves the file byte-identical", () => {
+ it("reports the count under dry run and leaves the file byte-identical", async () => {
const source = "symbolPreset: unicode\nautoResume: false\n";
const { file, root } = deployConfig(source);
- expect(syncOmpRemovals(testCtx(root, true), file, false)).toBe(2);
+ expect(await prune(testCtx(root, true), file, false)).toBe(2);
expect(readFileSync(file, "utf8")).toBe(source);
});
- it("leaves an unparseable config untouched instead of throwing", () => {
+ it("leaves an unparseable config untouched instead of throwing", async () => {
const source = "symbolPreset: unicode\n : : broken\n - [\n";
const { file, root } = deployConfig(source);
- expect(syncOmpRemovals(testCtx(root), file, false)).toBe(0);
+ expect(await prune(testCtx(root), file, false)).toBe(0);
expect(readFileSync(file, "utf8")).toBe(source);
});
// With no later key to carry it, a header would otherwise vanish. This is the
// one position where the carry-over has nowhere obvious to go.
- it("keeps a carried header when the pruned key was last in its mapping", () => {
+ it("keeps a carried header when the pruned key was last in its mapping", async () => {
const { file, root } = deployConfig(
"userOnly: 1\n\n# kit-owned omp configuration\n\n# about autoResume\nautoResume: false\n",
);
- expect(syncOmpRemovals(testCtx(root), file, false)).toBe(1);
+ expect(await prune(testCtx(root), file, false)).toBe(1);
const after = readFileSync(file, "utf8");
expect(after).toContain("# kit-owned omp configuration");
expect(after).toContain("userOnly: 1");
@@ -339,12 +361,12 @@ describe("retired omp config keys", () => {
// A trailing comment belongs to the mapping that holds it, not to the
// document. Hoisting it to the document instead would drag a nested section
// header to the top of the file.
- it("keeps a carried header inside the mapping it came from", () => {
+ it("keeps a carried header inside the mapping it came from", async () => {
const { file, root } = deployConfig(
"tui:\n keepMe: 1\n\n # tui section header\n\n # about tight\n tight: false\nuserOnly: 1\n",
);
- expect(syncOmpRemovals(testCtx(root), file, false)).toBe(1);
+ expect(await prune(testCtx(root), file, false)).toBe(1);
const after = readFileSync(file, "utf8");
const header = after.indexOf("# tui section header");
expect(header).toBeGreaterThan(after.indexOf("keepMe: 1"));
@@ -388,7 +410,47 @@ describe("retired omp config keys", () => {
});
});
- it("backs up a pruned config.yml and keeps mode 0600", () => {
+ describe("a symlinked config.yml whose target is missing", () => {
+ /** A config.yml link in the agent folder of `root` to a missing file; returns both paths. */
+ const danglingConfig = (root: string) => {
+ mkdirSync(join(root, "dotfiles"));
+ const linkTarget = join(root, "dotfiles", "config.yml");
+ const agentDir = join(root, ".omp", "agent");
+ mkdirSync(agentDir, { recursive: true });
+ const file = join(agentDir, "config.yml");
+ symlinkSync(linkTarget, file);
+ return { file, linkTarget };
+ };
+
+ it("previews the installation in a dry run", async () => {
+ const root = mkdtempSync(join(tmpdir(), "omp-removals-dangling-"));
+ roots.push(root);
+ const { file, linkTarget } = danglingConfig(root);
+
+ const stdout = await runOmpSync(root, true);
+
+ // The engine joins its paths with `/` (`exec.ts p`); Windows paths of the host use `\`.
+ expect(stdout.join("").replaceAll("\\", "/")).toContain(
+ `[dry-run] cp embedded:SoT/.omp/config.yml -> ${file.replaceAll("\\", "/")}\n`,
+ );
+ expect(existsSync(linkTarget)).toBe(false);
+ expect(lstatSync(file).isSymbolicLink()).toBe(true);
+ });
+
+ it("installs the SoT file at the link target in a writing sync and keeps the link", async () => {
+ const root = mkdtempSync(join(tmpdir(), "omp-removals-dangling-"));
+ roots.push(root);
+ const { file, linkTarget } = danglingConfig(root);
+
+ await runOmpSync(root);
+
+ expect(lstatSync(file).isSymbolicLink()).toBe(true);
+ expect(readFileSync(linkTarget, "utf8")).toBe("startup:\n quiet: true\n");
+ expect(existsSync(`${file}.bak`)).toBe(false);
+ });
+ });
+
+ it("backs up a pruned config.yml and keeps mode 0600", async () => {
const source = "symbolPreset: unicode\nuserOnly: 1\n";
const { file, root } = deployConfig(source);
chmodSync(file, 0o644);
@@ -398,7 +460,7 @@ describe("retired omp config keys", () => {
const logger = makeLogger({ stderr: (chunk) => stderr.push(chunk), progress: () => {} });
const ctx: Ctx = { ...base, services: { ...base.services, logger } };
- expect(syncOmpRemovals(ctx, file, false)).toBe(1);
+ expect(await prune(ctx, file, false)).toBe(1);
expect(readFileSync(`${file}.bak`, "utf8")).toBe(source);
// Windows has no POSIX permission bits, so only POSIX hosts can check 0600.
@@ -425,6 +487,32 @@ describe("retired omp config keys", () => {
expect(parse(readFileSync(file, "utf8"))).toEqual({ userOnly: 1, startup: { quiet: true } });
expect(readFileSync(`${file}.bak`, "utf8")).toBe(source);
});
+
+ // `FileSystem.readFileString` drops a leading byte order mark; the deploy compares every byte.
+ it("rewrites a deployed AGENTS.md that differs from the SoT only by a byte order mark", async () => {
+ const root = mkdtempSync(join(tmpdir(), "omp-removals-bom-"));
+ roots.push(root);
+ const agentDir = join(root, ".omp", "agent");
+ mkdirSync(agentDir, { recursive: true });
+ const file = join(agentDir, "AGENTS.md");
+ writeFileSync(file, "\uFEFF# omp\n");
+
+ await runOmpSync(root);
+
+ expect(readFileSync(file, "utf8")).toBe("# omp\n");
+ expect(readFileSync(`${file}.bak`, "utf8")).toBe("\uFEFF# omp\n");
+ });
+
+ it("fails with the YAML library message when the prune leaves an alias before its anchor", async () => {
+ const source = "symbolPreset: &preset unicode\ntheme:\n name: *preset\n";
+ const { file, root } = deployConfig(source);
+
+ await expect(prune(testCtx(root), file, false)).rejects.toMatchObject({
+ _tag: "OmpYamlInvalid",
+ message: "Unresolved alias (the anchor must be set before the alias): preset",
+ });
+ expect(readFileSync(file, "utf8")).toBe(source);
+ });
});
/**
@@ -459,10 +547,10 @@ const KEPT_RULES = [
];
describe("retired omp bash.patterns rules", () => {
- it("prunes retired kit rules and keeps kit and user rules that differ", () => {
+ it("prunes retired kit rules and keeps kit and user rules that differ", async () => {
const { file, root } = deployConfig(DEPLOYED_RULES);
- expect(syncOmpRemovals(testCtx(root), file, false)).toBe(5);
+ expect(await prune(testCtx(root), file, false)).toBe(5);
const after = readFileSync(file, "utf8");
expect(parse(after)).toEqual({ bash: { patterns: KEPT_RULES } });
expect(after).not.toContain("# Allow, ahead of the prompts below.");
@@ -472,7 +560,7 @@ describe("retired omp bash.patterns rules", () => {
// One rule from each family of the 492 prompt rules that the kit shipped up
// to 0.22.7, beside a user prompt that resembles them and a user deny that
// reuses a retired match.
- it("prunes every family of the retired kit prompt rules", () => {
+ it("prunes every family of the retired kit prompt rules", async () => {
const retired = [
"git clean",
"git clean *",
@@ -508,35 +596,35 @@ describe("retired omp bash.patterns rules", () => {
].join("\n");
const { file, root } = deployConfig(deployed);
- expect(syncOmpRemovals(testCtx(root), file, false)).toBe(retired.length);
+ expect(await prune(testCtx(root), file, false)).toBe(retired.length);
expect(parse(readFileSync(file, "utf8"))).toEqual({ bash: { patterns: kept } });
});
- it("reports the retired rules under dry run and leaves the file byte-identical", () => {
+ it("reports the retired rules under dry run and leaves the file byte-identical", async () => {
const { file, root } = deployConfig(DEPLOYED_RULES);
const stdout: Array = [];
- expect(syncOmpRemovals(testCtx(root, true, stdout), file, false)).toBe(5);
+ expect(await prune(testCtx(root, true, stdout), file, false)).toBe(5);
expect(readFileSync(file, "utf8")).toBe(DEPLOYED_RULES);
expect(stdout.join("")).toContain(
`[dry-run] prune ${file}: bash.patterns "git rm -- *" (allow), bash.patterns "rm" (prompt)`,
);
});
- it("changes nothing on a second run", () => {
+ it("changes nothing on a second run", async () => {
const { file, root } = deployConfig(DEPLOYED_RULES);
- expect(syncOmpRemovals(testCtx(root), file, false)).toBe(5);
+ expect(await prune(testCtx(root), file, false)).toBe(5);
const once = readFileSync(file, "utf8");
- expect(syncOmpRemovals(testCtx(root), file, false)).toBe(0);
+ expect(await prune(testCtx(root), file, false)).toBe(0);
expect(readFileSync(file, "utf8")).toBe(once);
});
- it("retires no key or rule the SoT config still ships", () => {
+ it("retires no key or rule the SoT config still ships", async () => {
const source = readFileSync(join(kitHome(), "SoT", ".omp", "config.yml"), "utf8");
const { file, root } = deployConfig(source);
- expect(syncOmpRemovals(testCtx(root), file, false)).toBe(0);
+ expect(await prune(testCtx(root), file, false)).toBe(0);
expect(readFileSync(file, "utf8")).toBe(source);
});
@@ -603,36 +691,36 @@ function deployModels(content: string): { file: string; root: string } {
}
describe("retired omp models.yml blocks", () => {
- it("prunes the shipped Opus 5.5 override and the provider mapping it empties", () => {
+ it("prunes the shipped Opus 5.5 override and the provider mapping it empties", async () => {
const { file, root } = deployModels(
`providers:\n anthropic:\n modelOverrides:\n${SHIPPED_OPUS_BLOCK} openai-codex:\n baseUrl: https://example.test\n`,
);
- expect(syncOmpModelRemovals(testCtx(root), file, false)).toBe(1);
+ expect(await pruneModels(testCtx(root), file, false)).toBe(1);
expect(parse(readFileSync(file, "utf8"))).toEqual({
providers: { "openai-codex": { baseUrl: "https://example.test" } },
});
});
- it("keeps an Opus 5.5 override the user edited, and a provider key beside it", () => {
+ it("keeps an Opus 5.5 override the user edited, and a provider key beside it", async () => {
const edited = SHIPPED_OPUS_BLOCK.replace("defaultLevel: high", "defaultLevel: max");
const { file, root } = deployModels(
`providers:\n anthropic:\n apiKey: secret\n modelOverrides:\n${edited}`,
);
- expect(syncOmpModelRemovals(testCtx(root), file, false)).toBe(0);
+ expect(await pruneModels(testCtx(root), file, false)).toBe(0);
expect(parse(readFileSync(file, "utf8"))).toHaveProperty(
["providers", "anthropic", "modelOverrides", "claude-opus-5-5", "thinking", "defaultLevel"],
"max",
);
});
- it("prunes the shipped GPT-6 Astra ladder override and keeps the GPT-6.2 Astra override beside it", () => {
+ it("prunes the shipped GPT-6 Astra ladder override and keeps the GPT-6.2 Astra override beside it", async () => {
const { file, root } = deployModels(
`providers:\n openai-codex:\n modelOverrides:\n${SHIPPED_GPT_6_ASTRA_BLOCK}${SHIPPED_GPT_6_ASTRA_BLOCK.replace("gpt-6-astra:", "gpt-6.2-astra:")}`,
);
- expect(syncOmpModelRemovals(testCtx(root), file, false)).toBe(1);
+ expect(await pruneModels(testCtx(root), file, false)).toBe(1);
expect(parse(readFileSync(file, "utf8"))).toEqual({
providers: {
"openai-codex": {
@@ -650,13 +738,13 @@ describe("retired omp models.yml blocks", () => {
});
});
- it("keeps a GPT-6 Astra ladder override the user edited", () => {
+ it("keeps a GPT-6 Astra ladder override the user edited", async () => {
const edited = SHIPPED_GPT_6_ASTRA_BLOCK.replace("defaultLevel: xhigh", "defaultLevel: max");
const { file, root } = deployModels(
`providers:\n openai-codex:\n modelOverrides:\n${edited}`,
);
- expect(syncOmpModelRemovals(testCtx(root), file, false)).toBe(0);
+ expect(await pruneModels(testCtx(root), file, false)).toBe(0);
expect(parse(readFileSync(file, "utf8"))).toHaveProperty(
["providers", "openai-codex", "modelOverrides", "gpt-6-astra", "thinking", "defaultLevel"],
"max",
diff --git a/cli/test/unit/ompYamlMerge.test.ts b/cli/test/unit/ompYamlMerge.test.ts
index 6349c156..1d6c81a1 100644
--- a/cli/test/unit/ompYamlMerge.test.ts
+++ b/cli/test/unit/ompYamlMerge.test.ts
@@ -1,17 +1,22 @@
+import { Result } from "effect";
import { describe, expect, it } from "vitest";
import { parse } from "yaml";
import { mergeOmpConfig, mergeOmpModels } from "../../src/engine-native/ompYaml";
+/** The merged config.yml text; a refused merge fails the case. */
+const mergeConfig = (sot: string, deployed: string): string =>
+ Result.getOrThrow(mergeOmpConfig(sot, deployed));
+
describe("omp YAML merge", () => {
it("recurses into nested mappings", () => {
- const merged = mergeOmpConfig("a: { b: 1 }\n", "a: { c: 2 }\n");
+ const merged = mergeConfig("a: { b: 1 }\n", "a: { c: 2 }\n");
expect(parse(merged)).toEqual({ a: { b: 1, c: 2 } });
});
it("replaces a deployed sequence with the SoT sequence", () => {
- const merged = mergeOmpConfig(
+ const merged = mergeConfig(
"models:\n - kit/model\n",
"models:\n - user/first\n - user/second\n",
);
@@ -20,19 +25,19 @@ describe("omp YAML merge", () => {
});
it("replaces a deployed scalar with the SoT scalar", () => {
- const merged = mergeOmpConfig("theme: kit\n", "theme: user\n");
+ const merged = mergeConfig("theme: kit\n", "theme: user\n");
expect(parse(merged)).toEqual({ theme: "kit" });
});
it("keeps a deployed-only top-level key", () => {
- const merged = mergeOmpConfig("managed: true\n", "userOnly: preserved\n");
+ const merged = mergeConfig("managed: true\n", "userOnly: preserved\n");
expect(parse(merged)).toEqual({ managed: true, userOnly: "preserved" });
});
it("keeps an unknown deployed-only role under retry.fallbackChains", () => {
- const merged = mergeOmpConfig(
+ const merged = mergeConfig(
"retry:\n fallbackChains:\n coding:\n - kit/model\n",
"retry:\n fallbackChains:\n releaseManager:\n - user/model\n",
);
@@ -48,7 +53,7 @@ describe("omp YAML merge", () => {
});
it("drops deployed-only slash keys under retry.fallbackChains while keeping role siblings", () => {
- const merged = mergeOmpConfig(
+ const merged = mergeConfig(
"retry:\n fallbackChains:\n coding:\n - kit/model\n",
[
"retry:",
@@ -74,7 +79,7 @@ describe("omp YAML merge", () => {
});
it("keeps a deployed-only slash key outside retry.fallbackChains", () => {
- const merged = mergeOmpConfig(
+ const merged = mergeConfig(
"modelRoles:\n coding: kit/model\n",
'modelRoles:\n "provider/*": user/model\n',
);
@@ -94,26 +99,34 @@ describe("omp YAML merge", () => {
])("returns SoT bytes for a %s deployed file", (_case, deployed) => {
const sotText = "# managed\nvalue: 1\n";
- expect(mergeOmpConfig(sotText, deployed)).toBe(sotText);
+ expect(mergeConfig(sotText, deployed)).toBe(sotText);
});
it("preserves a SoT comment on its managed key while merging user settings", () => {
- const merged = mergeOmpConfig("# managed by docks-kit\nvalue: 1\n", "userOnly: true\n");
+ const merged = mergeConfig("# managed by docks-kit\nvalue: 1\n", "userOnly: true\n");
expect(merged).toContain("# managed by docks-kit\nvalue: 1");
expect(parse(merged)).toEqual({ value: 1, userOnly: true });
});
- it("throws for invalid deployed YAML", () => {
- expect(() => mergeOmpConfig("value: 1\n", "[unterminated\n")).toThrow(
- /Invalid deployed omp config\.yml YAML:/,
- );
+ it("fails with OmpYamlInvalid for invalid deployed YAML", () => {
+ expect(mergeOmpConfig("value: 1\n", "[unterminated\n")).toMatchObject({
+ _tag: "Failure",
+ failure: {
+ _tag: "OmpYamlInvalid",
+ message: expect.stringMatching(/^Invalid deployed omp config\.yml YAML:/),
+ },
+ });
});
- it("throws when the deployed root is a sequence", () => {
- expect(() => mergeOmpConfig("value: 1\n", "- first\n- second\n")).toThrow(
- /Deployed omp config\.yml YAML root must be a mapping/,
- );
+ it("fails with OmpYamlInvalid when the deployed root is a sequence", () => {
+ expect(mergeOmpConfig("value: 1\n", "- first\n- second\n")).toMatchObject({
+ _tag: "Failure",
+ failure: {
+ _tag: "OmpYamlInvalid",
+ message: "Deployed omp config.yml YAML root must be a mapping",
+ },
+ });
});
// models.yml is user territory for credentials and custom models, so the
@@ -123,15 +136,19 @@ describe("omp YAML merge", () => {
"retry:\n fallbackChains:\n openai/*: [b]\nproviders:\n mine:\n apiKey: secret\n";
const sot = "providers:\n openai-codex:\n modelOverrides: {}\n";
- expect(parse(mergeOmpModels(sot, deployed))).toEqual({
+ expect(parse(Result.getOrThrow(mergeOmpModels(sot, deployed)))).toEqual({
providers: { "openai-codex": { modelOverrides: {} }, mine: { apiKey: "secret" } },
retry: { fallbackChains: { "openai/*": ["b"] } },
});
});
it("names models.yml in its diagnostics", () => {
- expect(() => mergeOmpModels("value: 1\n", "- first\n")).toThrow(
- /Deployed omp models\.yml YAML root must be a mapping/,
- );
+ expect(mergeOmpModels("value: 1\n", "- first\n")).toMatchObject({
+ _tag: "Failure",
+ failure: {
+ _tag: "OmpYamlInvalid",
+ message: "Deployed omp models.yml YAML root must be a mapping",
+ },
+ });
});
});
diff --git a/cli/test/unit/syncLock.test.ts b/cli/test/unit/syncLock.test.ts
index 6aed36db..cc0ba8e6 100644
--- a/cli/test/unit/syncLock.test.ts
+++ b/cli/test/unit/syncLock.test.ts
@@ -32,12 +32,13 @@ import {
rmSync,
statSync,
symlinkSync,
+ writeFileSync,
} from "node:fs";
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 { Effect, Fiber, FileSystem } from "effect";
import { TestClock } from "effect/testing";
import { describe, expect, it, vi } from "vitest";
import type * as ExecModule from "../../src/engine-native/exec";
@@ -68,6 +69,7 @@ import {
type Logger,
} from "../../src/engine-native/services";
import { folderLockPaths, homeAndFolderLocks } from "../../src/engine-native/syncDispatch";
+import { payloadText } from "../../src/payload";
import { engineLayer, runEngine } from "../lib/engineRun";
const WAIT_MS = "100";
@@ -552,11 +554,13 @@ describe("omp children of a sync", () => {
expect(existsSync(join(configRoot, FOLDER_LOCK))).toBe(true);
expect(spawned.omp.length).toBeGreaterThan(0);
for (const { args, env } of spawned.omp) {
- const childRoot = ompPaths({
- home,
- env: env ?? process.env,
- platform: process.platform,
- }).dataRoot;
+ const childRoot = (
+ await Effect.runPromise(
+ ompPaths({ home, env: env ?? process.env, platform: process.platform }).pipe(
+ Effect.provide(BunServices.layer),
+ ),
+ )
+ ).dataRoot;
expect({ args, childRoot }).toEqual({ args, childRoot: configRoot });
}
// The kit wrote nothing into the unlocked candidate.
@@ -571,6 +575,40 @@ describe("omp children of a sync", () => {
}
});
+/**
+ * The longest wait for a sync to reach a checkpoint; below the test timeout.
+ * The wait is real time: the sync runs on the real file system and the
+ * default clock, so a test clock cannot end it.
+ */
+const CHECKPOINT_BOUND_MS = 5_000;
+
+/**
+ * Wait until the sync `fiber` reaches `checkpoint`. Fail when the sync ends
+ * first or the bound passes, so that the case unwinds through its cleanup and
+ * `withHome` restores the environment before the test timeout.
+ */
+async function reachCheckpoint(
+ checkpoint: Promise,
+ fiber: Fiber.Fiber,
+ name: string,
+): Promise {
+ const late = Promise.withResolvers<"late">();
+ const timer = setTimeout(() => late.resolve("late"), CHECKPOINT_BOUND_MS);
+ try {
+ const outcome = await Promise.race([
+ checkpoint.then(() => "reached" as const),
+ Effect.runPromise(Fiber.await(fiber)).then(() => "ended" as const),
+ late.promise,
+ ]);
+ if (outcome === "ended") throw new Error(`the sync ended before ${name}`);
+ if (outcome === "late") {
+ throw new Error(`the sync did not reach ${name} within ${CHECKPOINT_BOUND_MS} ms`);
+ }
+ } finally {
+ clearTimeout(timer);
+ }
+}
+
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) => {
@@ -595,13 +633,13 @@ describe("interrupt of a sync", () => {
runEngineNative(["sync"]).pipe(Effect.provide(engineLayer(services))),
);
try {
- await entered.promise;
+ await reachCheckpoint(entered.promise, fiber, "the Bun bootstrap");
// 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 { agentDir, dataRoot } = await Effect.runPromise(
+ ompPaths({ home, env: process.env, platform: process.platform }).pipe(
+ Effect.provide(BunServices.layer),
+ ),
+ );
const folderLocks = Effect.runSync(folderLockPaths([agentDir, dataRoot]));
expect(folderLocks).toHaveLength(2);
@@ -628,6 +666,65 @@ describe("interrupt of a sync", () => {
});
});
});
+
+ it.skipIf(process.platform === "win32")(
+ "finishes a started deploy write with its chmod before an interrupt ends the sync, under the locks",
+ async () => {
+ await withHome(async (home) => {
+ const agentDir = join(home, ".omp", "agent");
+ const target = join(agentDir, "AGENTS.md");
+ mkdirSync(agentDir, { recursive: true });
+ // A deployed file with other bytes and a wider mode: the sync rewrites it and sets 0600.
+ writeFileSync(target, "user text\n");
+ chmodSync(target, 0o644);
+ const entered = Promise.withResolvers();
+ const release = Promise.withResolvers();
+ const sync = Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ // The write of AGENTS.md waits for the test, inside its started mutation.
+ const gated = FileSystem.FileSystem.of({
+ ...fs,
+ writeFileString: (path, data, options) =>
+ path === target
+ ? Effect.andThen(
+ Effect.promise(() => {
+ entered.resolve();
+ return release.promise;
+ }),
+ fs.writeFileString(path, data, options),
+ )
+ : fs.writeFileString(path, data, options),
+ });
+ return yield* runEngineNative(["sync"]).pipe(
+ Effect.provideService(FileSystem.FileSystem, gated),
+ );
+ });
+ const fiber = Effect.runFork(sync.pipe(Effect.provide(engineLayer(recordingServices([])))));
+ try {
+ await reachCheckpoint(entered.promise, fiber, "the AGENTS.md write");
+ 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");
+
+ release.resolve();
+ await interrupted;
+ expect(probe(home)).toBe("acquired");
+ expect(readFileSync(target, "utf8")).toBe(payloadText("SoT/.omp/AGENTS.md"));
+ expect(statSync(target).mode & 0o777).toBe(0o600);
+ // The interrupt ended the run after the started write, before the next file.
+ expect(existsSync(join(agentDir, "mcp.json"))).toBe(false);
+ } finally {
+ // A failed assertion must not leave the sync holding its locks during cleanup.
+ release.resolve();
+ await Effect.runPromise(Fiber.interrupt(fiber));
+ }
+ });
+ },
+ );
});
describe("lock wait deadline", () => {
diff --git a/cli/test/unit/syncPipelineFailure.test.ts b/cli/test/unit/syncPipelineFailure.test.ts
index 81e0fdf7..ac452794 100644
--- a/cli/test/unit/syncPipelineFailure.test.ts
+++ b/cli/test/unit/syncPipelineFailure.test.ts
@@ -3,6 +3,9 @@
* 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.
+ * The test injects a typed failure of the plugin pass: a mock of
+ * `syncPlugins` fails with `LegacyStepFailed`. The ledger, the summary, and
+ * the cleanup are those of the real pipeline.
*/
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
@@ -10,10 +13,11 @@ 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 { LegacyStepFailed } from "../../src/engine-native/bridge";
import type * as OmpPluginsModule from "../../src/engine-native/ompPlugins";
const mocks = vi.hoisted(() => ({
- syncPlugins: vi.fn<(ctx: Ctx) => Promise>(),
+ syncPlugins: vi.fn<(ctx: Ctx) => Effect.Effect>(),
}));
vi.mock("../../src/engine-native/ompPlugins", async (importOriginal) => ({
@@ -26,6 +30,7 @@ vi.mock("../../src/engine-native/bun", () => ({
import { engineFailureDetail } from "../../src/engine";
import { runEngineNative } from "../../src/engine-native";
+import { bridgePromise } from "../../src/engine-native/bridge";
import { recordFailure } from "../../src/engine-native/failures";
import { makeEngineServices } from "../../src/engine-native/services";
import { engineLayer } from "../lib/engineRun";
@@ -66,6 +71,15 @@ afterEach(() => {
const LEDGER_ENTRY = "omp plugin link failed";
const PASS_FAILURE = new Error("plugin pass broke");
+/** The step of the injected failure; the mock names it, so no assertion reads it. */
+const INJECTED_STEP = "injected plugin pass failure";
+
+/** The plugin pass after it recorded `ledger` (when given): it fails with a typed failure. */
+const failingPluginPass = (ctx: Ctx, ledger?: string) =>
+ Effect.suspend(() => {
+ if (ledger !== undefined) recordFailure(ctx, ledger);
+ return bridgePromise(INJECTED_STEP, () => Promise.reject(PASS_FAILURE));
+ });
/** Run a dry-run sync with the logger sinks of `options` and return its exit. */
function failedSync(options: Parameters[0]) {
@@ -79,10 +93,7 @@ function failedSync(options: Parameters[0]) {
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);
- });
+ mocks.syncPlugins.mockImplementation((ctx) => failingPluginPass(ctx, LEDGER_ENTRY));
const exit = await failedSync({
sinks: { stdout: (chunk) => void stdout.push(chunk), stderr: () => {} },
@@ -92,20 +103,14 @@ describe("a failed omp pipeline", () => {
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.objectContaining({ _tag: "Fail" }),
]);
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);
- });
+ mocks.syncPlugins.mockImplementation((ctx) => failingPluginPass(ctx, LEDGER_ENTRY));
const exit = await failedSync({
sinks: {
@@ -122,12 +127,14 @@ describe("a failed omp pipeline", () => {
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);
- });
+ mocks.syncPlugins.mockImplementation((ctx) =>
+ Effect.suspend(() => {
+ // Draw a progress line, so the release erases it, then fail the pass.
+ ctx.terminalLease?.update("Syncing omp plugins...");
+ failErase = true;
+ return failingPluginPass(ctx);
+ }),
+ );
const exit = await failedSync({
sinks: {
diff --git a/cli/test/unit/syncSignals.test.ts b/cli/test/unit/syncSignals.test.ts
index 5a2ac155..4d2aea87 100644
--- a/cli/test/unit/syncSignals.test.ts
+++ b/cli/test/unit/syncSignals.test.ts
@@ -4,13 +4,16 @@
* 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 of the same home runs to its end.
+ * so the next sync of the same home runs to its end. A signal that comes
+ * inside a started mutation, such as a deploy write and its chmod (plan
+ * #296), ends the process with the same code once the mutation settled.
*
* 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
+ * signal that it wants into the request file of a launch, or names the file
+ * whose chmod raises it; 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.
*
@@ -28,6 +31,7 @@
*/
import { spawn } from "node:child_process";
import {
+ chmodSync,
existsSync,
mkdirSync,
mkdtempSync,
@@ -40,12 +44,13 @@ import {
writeFileSync,
} from "node:fs";
import { tmpdir } from "node:os";
-import { join, resolve } from "node:path";
+import { dirname, join, resolve } from "node:path";
import { setTimeout as sleep } from "node:timers/promises";
import { afterEach, describe, expect, it } from "vitest";
import { releaseKitLock, tryAcquireKitLock } from "../../src/engine-native/kitLock";
import { syncLockPath } from "../../src/engine-native/scratch";
+import { payloadText } from "../../src/payload";
import { BUN_RUNTIME, cliEntry } from "../lib/cliEntry";
import {
REPO_DIR,
@@ -80,6 +85,9 @@ const SUPERVISED_RUN = join(LIB, "supervisedRun.ts");
/** The environment key of the readiness marker of the waiting `omp` stub. */
const MARKER_FILE = "SYNC_SIGNAL_STUB_MARKER";
+/** The environment key that `signalSelfPreload.ts` reads: `:` of the chmod that raises it. */
+const SIGNAL_AT_CHMOD = "SIGNAL_AT_CHMOD";
+
/** The hard maximum lifetime of the waiting stub, past the timeout of any case. */
const STUB_MAX_LIFETIME_MS = 90_000;
@@ -323,6 +331,8 @@ function makeFixture(tracking: "case" | "teardown" | "none" = "case"): Fixture {
/** The options of one supervised launch. */
interface LaunchOptions {
+ /** Extra environment of the CLI, such as the chmod that raises a signal. */
+ readonly cliEnv?: Record;
/** Extra environment of the supervisor, such as its shutdown bound. */
readonly supervisorEnv?: Record;
/** Runs on the new launch folder before the supervisor starts. */
@@ -364,6 +374,7 @@ function launch(
BUN_RUNTIME_TRANSPILER_CACHE_PATH: fixture.transpilerCache,
SIGNAL_REQUEST_FILE: request,
...extraEnv(folder),
+ ...options.cliEnv,
};
const supervisor = spawn(BUN_RUNTIME, ["--no-env-file", SUPERVISOR], {
cwd: fixture.work,
@@ -632,6 +643,43 @@ describe.skipIf(process.platform === "win32")(
);
}
+ for (const [channel, signal, code] of [
+ ["public", "SIGTERM", 130],
+ ["public", "SIGINT", 130],
+ ["raw", "SIGTERM", 143],
+ ["raw", "SIGINT", 130],
+ ] as const) {
+ it(
+ `exits ${code} on a ${signal} between a deploy write and its chmod of the ${channel} sync, after the chmod`,
+ async () => {
+ const deadline = performance.now() + CASE_TIMEOUT_MS - CASE_REPORT_MARGIN_MS;
+ const fixture = makeFixture();
+ const agents = join(fixture.home, ".omp", "agent", "AGENTS.md");
+ mkdirSync(dirname(agents), { recursive: true });
+ // Other bytes and a wider mode: the sync rewrites the file, then sets 0600.
+ writeFileSync(agents, "user text\n");
+ chmodSync(agents, 0o644);
+
+ // The chmod of the rewritten AGENTS.md raises the signal on the CLI, before it runs.
+ const run = launchSync(
+ channel,
+ fixture,
+ {},
+ { cliEnv: { [SIGNAL_AT_CHMOD]: `${signal}:${agents}` } },
+ );
+
+ expect(described(await endingWithin(run, deadline - performance.now()))).toBe(
+ `exit code ${code}, signal null`,
+ );
+ expect(readFileSync(agents, "utf8")).toBe(payloadText("SoT/.omp/AGENTS.md"));
+ expect(statSync(agents).mode & 0o777).toBe(0o600);
+ // The signal ended the run once the write settled, before the next file.
+ expect(existsSync(join(dirname(agents), "mcp.json"))).toBe(false);
+ },
+ 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`,
diff --git a/cli/test/unit/tidy.test.ts b/cli/test/unit/tidy.test.ts
index b36c6658..9342e5d5 100644
--- a/cli/test/unit/tidy.test.ts
+++ b/cli/test/unit/tidy.test.ts
@@ -729,7 +729,7 @@ describe("planTidy without a verified local Docker endpoint", () => {
* options: { readonly apply: boolean; readonly report: boolean },
* inputs: TidyInputs,
* host: TidyHost,
- * ): Effect.Effect
+ * ): Effect.Effect
*
* `tidyCommand` resolves `--repo` into `inputs.repo` and then runs
* `runTidy({ apply, report }, inputs, defaultTidyHost())`. With `apply`,