docks-kit 0.22.12 → 0.22.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/AGENTS.md +95 -81
  2. package/README.md +7 -7
  3. package/cli/docs/command-guards.md +7 -3
  4. package/cli/docs/flags.md +59 -9
  5. package/cli/docs/install.md +2 -2
  6. package/cli/docs/omp-context.md +14 -8
  7. package/cli/docs/omp-models.md +1 -1
  8. package/cli/docs/overview.md +1 -1
  9. package/cli/docs/platforms.md +4 -2
  10. package/cli/docs/plugins.md +8 -5
  11. package/cli/docs/sync-layers.md +29 -15
  12. package/cli/docs/toolchain.md +24 -14
  13. package/cli/src/argv.ts +7 -4
  14. package/cli/src/argvValidate.ts +2 -16
  15. package/cli/src/commands/docs.ts +1 -1
  16. package/cli/src/commands/omp.ts +56 -15
  17. package/cli/src/commands/sync.ts +6 -6
  18. package/cli/src/commands/tidy.ts +83 -26
  19. package/cli/src/engine-native/DESIGN.md +93 -56
  20. package/cli/src/engine-native/atomicWrite.ts +168 -8
  21. package/cli/src/engine-native/codexConfig.ts +2 -6
  22. package/cli/src/engine-native/codexPlugins.ts +1 -1
  23. package/cli/src/engine-native/codexSync.ts +137 -26
  24. package/cli/src/engine-native/codexToml.ts +4 -86
  25. package/cli/src/engine-native/deps.ts +51 -51
  26. package/cli/src/engine-native/exec.ts +3 -0
  27. package/cli/src/engine-native/index.ts +1 -1
  28. package/cli/src/engine-native/kitLock.ts +121 -0
  29. package/cli/src/engine-native/modes.ts +49 -31
  30. package/cli/src/engine-native/ompChild.ts +26 -0
  31. package/cli/src/engine-native/ompFastMode.ts +14 -7
  32. package/cli/src/engine-native/ompFileDeploy.ts +12 -6
  33. package/cli/src/engine-native/ompMarketplace.ts +25 -18
  34. package/cli/src/engine-native/ompPlugins.ts +39 -18
  35. package/cli/src/engine-native/ompRemovals.ts +51 -23
  36. package/cli/src/engine-native/ompSync.ts +78 -38
  37. package/cli/src/engine-native/os/targets.ts +16 -4
  38. package/cli/src/engine-native/os/types.ts +1 -1
  39. package/cli/src/engine-native/parseArgs.ts +27 -17
  40. package/cli/src/engine-native/processes.ts +16 -0
  41. package/cli/src/engine-native/scratch.ts +18 -0
  42. package/cli/src/engine-native/skillsInstall.ts +27 -2
  43. package/cli/src/engine-native/skillsPrune.ts +51 -49
  44. package/cli/src/engine-native/skillsRecords.ts +138 -0
  45. package/cli/src/engine-native/skillsSync.ts +16 -13
  46. package/cli/src/engine-native/syncDispatch.ts +186 -4
  47. package/cli/src/engine-native/tidy.ts +102 -119
  48. package/cli/src/engine-native/tomlLines.ts +92 -0
  49. package/cli/src/generated/sotPayload.ts +5 -5
  50. package/cli/src/main.ts +5 -30
  51. package/cli/src/manifests.ts +24 -4
  52. package/package.json +2 -2
  53. package/cli/src/engine-native/tidyLock.ts +0 -163
@@ -5,7 +5,8 @@ import { Console, Effect, Option } from "effect";
5
5
 
6
6
  import { bail } from "../engine";
7
7
  import { engineHome } from "../engine-native/harnesses";
8
- import { scratchRoot } from "../engine-native/scratch";
8
+ import { acquireKitLock, releaseKitLock } from "../engine-native/kitLock";
9
+ import { scratchRoot, tidyApplyLockPath } from "../engine-native/scratch";
9
10
  import {
10
11
  actionSubject,
11
12
  actionVerb,
@@ -14,7 +15,9 @@ import {
14
15
  defaultTidyHost,
15
16
  mainRepository,
16
17
  planTidy,
18
+ type TidyHost,
17
19
  type TidyInputs,
20
+ type TidyPlan,
18
21
  } from "../engine-native/tidy";
19
22
  import { buildTidyReport } from "../engine-native/tidyReport";
20
23
 
@@ -31,23 +34,18 @@ const report = Flag.Boolean("report").pipe(
31
34
  Flag.withDefault(false),
32
35
  );
33
36
 
34
- export const tidyCommand = Command.make("tidy", { apply, repo, report }, (config) =>
35
- Effect.gen(function* () {
36
- const host = defaultTidyHost();
37
- const home = engineHome();
38
- let repository: string | undefined;
39
- if (Option.isSome(config.repo)) {
40
- const typed = config.repo.value;
41
- repository = yield* Effect.promise(() => mainRepository(resolve(process.cwd(), typed), host));
42
- if (repository === undefined) return yield* bail(`--repo ${typed} is not a git repository`);
43
- }
44
- const inputs: TidyInputs = {
45
- home,
46
- worktreeRoot: agentWorktreeRoot(home, process.env),
47
- scratchRoot: scratchRoot(home),
48
- ...(repository === undefined ? {} : { repo: repository }),
49
- };
37
+ export interface TidyOptions {
38
+ readonly apply: boolean;
39
+ readonly report: boolean;
40
+ }
50
41
 
42
+ /** Print the plan, then perform it when `perform` is true or print the dry-run line. Return the plan. */
43
+ function planAndApply(
44
+ perform: boolean,
45
+ inputs: TidyInputs,
46
+ host: TidyHost,
47
+ ): Effect.Effect<TidyPlan> {
48
+ return Effect.gen(function* () {
51
49
  const plan = yield* Effect.promise(() => planTidy(inputs, host));
52
50
  for (const action of plan.actions) {
53
51
  yield* Console.log(`${actionVerb(action)} ${actionSubject(action)}: ${action.reason}`);
@@ -57,7 +55,7 @@ export const tidyCommand = Command.make("tidy", { apply, repo, report }, (config
57
55
 
58
56
  if (plan.actions.length === 0) {
59
57
  yield* Console.log("Nothing to tidy.");
60
- } else if (config.apply) {
58
+ } else if (perform) {
61
59
  const outcome = yield* Effect.promise(() => applyTidy(plan, inputs, host));
62
60
  for (const line of outcome.lines) yield* Console.log(line);
63
61
  if (outcome.failures > 0) {
@@ -68,21 +66,80 @@ export const tidyCommand = Command.make("tidy", { apply, repo, report }, (config
68
66
  } else {
69
67
  // In --repo mode a bare `tidy --apply` would perform a different plan.
70
68
  const applyCommand =
71
- repository === undefined
69
+ inputs.repo === undefined
72
70
  ? "docks-kit tidy --apply"
73
- : `docks-kit tidy --repo ${repository} --apply`;
71
+ : `docks-kit tidy --repo ${inputs.repo} --apply`;
74
72
  yield* Console.log(
75
73
  `Dry run: ${plan.actions.length} actions. Run '${applyCommand}' to perform them.`,
76
74
  );
77
75
  }
76
+ return plan;
77
+ });
78
+ }
78
79
 
79
- if (config.report) {
80
- const sections = yield* Effect.promise(() => buildTidyReport(inputs, host, plan.docker));
81
- for (const section of sections) {
82
- yield* Console.log(`== ${section.title}`);
83
- for (const line of section.lines) yield* Console.log(line);
84
- }
80
+ /**
81
+ * Plan and apply under the tidy lock, so that a second run cannot act on a
82
+ * plan that the first run makes stale. When another run holds the lock, print
83
+ * only the held line, with no plan, and return `undefined`. The exit code
84
+ * stays unset.
85
+ */
86
+ function planAndApplyUnderLock(
87
+ inputs: TidyInputs,
88
+ host: TidyHost,
89
+ ): Effect.Effect<TidyPlan | undefined> {
90
+ const path = tidyApplyLockPath(inputs.home);
91
+ return Effect.acquireUseRelease(
92
+ Effect.promise(() => acquireKitLock(path, { waitMs: 0 })),
93
+ (result) =>
94
+ result.kind === "acquired"
95
+ ? planAndApply(true, inputs, host)
96
+ : Console.log(`another docks-kit tidy run holds ${path}`).pipe(Effect.as(undefined)),
97
+ (result) =>
98
+ Effect.sync(() => {
99
+ if (result.kind === "acquired") releaseKitLock(result.lock);
100
+ }),
101
+ );
102
+ }
103
+
104
+ /**
105
+ * Run `docks-kit tidy` with resolved inputs. `apply` takes the tidy lock
106
+ * before `planTidy`; a dry run and `--report` take no lock.
107
+ */
108
+ export function runTidy(
109
+ options: TidyOptions,
110
+ inputs: TidyInputs,
111
+ host: TidyHost,
112
+ ): Effect.Effect<void> {
113
+ return Effect.gen(function* () {
114
+ const plan = options.apply
115
+ ? yield* planAndApplyUnderLock(inputs, host)
116
+ : yield* planAndApply(false, inputs, host);
117
+ if (plan === undefined || !options.report) return;
118
+ const sections = yield* Effect.promise(() => buildTidyReport(inputs, host, plan.docker));
119
+ for (const section of sections) {
120
+ yield* Console.log(`== ${section.title}`);
121
+ for (const line of section.lines) yield* Console.log(line);
85
122
  }
123
+ });
124
+ }
125
+
126
+ export const tidyCommand = Command.make("tidy", { apply, repo, report }, (config) =>
127
+ Effect.gen(function* () {
128
+ const host = defaultTidyHost();
129
+ const home = engineHome();
130
+ let repository: string | undefined;
131
+ if (Option.isSome(config.repo)) {
132
+ const typed = config.repo.value;
133
+ repository = yield* Effect.promise(() => mainRepository(resolve(process.cwd(), typed), host));
134
+ if (repository === undefined) return yield* bail(`--repo ${typed} is not a git repository`);
135
+ }
136
+ const inputs: TidyInputs = {
137
+ home,
138
+ worktreeRoot: agentWorktreeRoot(home, process.env),
139
+ scratchRoot: scratchRoot(home),
140
+ ...(repository === undefined ? {} : { repo: repository }),
141
+ };
142
+ yield* runTidy({ apply: config.apply, report: config.report }, inputs, host);
86
143
  }),
87
144
  ).pipe(
88
145
  Command.withDescription(
@@ -1,20 +1,30 @@
1
1
  # EngineNative Design
2
2
 
3
3
  EngineNative is the only supported sync engine. It lives in
4
- `cli/src/engine-native/` and is invoked through `cli/src/engine.ts`; the rest
5
- of the CLI passes normalized argv to that seam. The former shell engine was
6
- removed after the `bash-engine-final` tag. `DOCKS_KIT_ENGINE=bash` is now an
7
- explicit removed-engine diagnostic and exits 2 with the recovery tag message.
4
+ `cli/src/engine-native/`. The `sync`, `model`, `toolchain`, and `status`
5
+ commands invoke it through `cli/src/engine.ts` and pass normalized argv to
6
+ that seam. Other commands, such as `omp`, `harnesses`, `models`, `update`,
7
+ `scratch`, and `tidy`, import engine-native modules directly. The former
8
+ shell engine was removed after the `bash-engine-final` tag.
9
+ `DOCKS_KIT_ENGINE=bash` is now an explicit removed-engine diagnostic and exits
10
+ 2 with the recovery tag message.
8
11
 
9
12
  ## Selection Contract
10
13
 
11
- - Public CLI commands route through `engine(args)` after @effect/cli parses
14
+ - The public `sync`, `model`, and `toolchain` commands route through
15
+ `engine(args)` after `effect/cli` (the CLI module inside `effect` 4) parses
12
16
  pickers, target words, and flag spellings.
13
- - `engineCapture(args)` re-spawns the raw channel to capture stdout for
14
- commands such as `status --json`.
15
- - `DOCKS_KIT_ENGINE=native-raw` is harness-private: it bypasses @effect/cli
17
+ - `engineCapture(args)` re-spawns the CLI on the `native-capture` channel to
18
+ capture stdout. `status` uses it to read the `toolchain check` report.
19
+ - Other public commands call engine-native modules directly, for example
20
+ `tidy.ts` `planTidy` and `applyTidy`, `scratch.ts` `createScratchDir`, and
21
+ `harnesses.ts` `readHarnessSelection`.
22
+ - `DOCKS_KIT_ENGINE=native-raw` is harness-private: it bypasses `effect/cli`
16
23
  and hands argv directly to EngineNative so tests can exercise the internal
17
24
  engine vocabulary.
25
+ - `DOCKS_KIT_ENGINE=native-capture` is the `engineCapture` child channel. It
26
+ also takes raw argv, but `main.ts` runs it with `{ envGlobals: false }`, so
27
+ it ignores the env globals.
18
28
 
19
29
  ## Behavior Contract
20
30
 
@@ -62,17 +72,17 @@ warnings, and the summary. Status-quo confirmations exist but are opt-in.
62
72
 
63
73
  | Emitter | Channel | Default | `--verbose` | Prefix / form |
64
74
  | --------------- | ------- | ---------------- | ---------------- | ---------------------------------------------------------------------------------------------- |
65
- | `error(msg)` | stderr | shown | shown | `[err]` red (`\x1b[1;31m`) |
75
+ | `err(msg)` | stderr | shown | shown | `[err]` red (`\x1b[1;31m`) |
66
76
  | `warn(msg)` | stderr | shown | shown | `[warn]` yellow (`\x1b[1;33m`) |
67
77
  | `change(msg)` | stderr | shown | shown | `[ok]` green (`\x1b[1;32m`) — ONLY after an operation actually mutated |
68
78
  | `verbose(msg)` | stderr | hidden | shown | `[ok]` green — no-op confirmations ("already …", "present", "up to date", "left as-is"), skips |
69
79
  | `progress(msg)` | stderr | interactive only | interactive only | dim, transient single-line status with no newline |
70
- | `data(line)` | stdout | shown | shown | bare — dry-run report lines, `status --json`, summary block, usage text |
80
+ | `echo(line)` | stdout | shown | shown | bare — dry-run report lines, `status --json`, summary block, usage text |
71
81
 
72
- - stdout is data, stderr is logs — the logger NEVER writes to stdout
73
- (`engineCapture` depends on it).
74
- - **Dry-run is a complete inspection report**: `[dry-run]` lines are `data`,
75
- printed unfiltered at every verbosity.
82
+ - stdout is data, stderr is logs — only `echo` writes to stdout, and every
83
+ log emitter writes to stderr (`engineCapture` depends on it).
84
+ - **Dry-run is a complete inspection report**: `[dry-run]` lines use `echo`
85
+ and print unfiltered at every verbosity.
76
86
  - Prefixes and ANSI codes are stable golden surface; the level controls
77
87
  visibility, not the prefix.
78
88
  - `logger.ts` `makeLogger`, at progress sink selection, enables transient
@@ -114,19 +124,42 @@ their stdout IS the deliverable (`deployed:`/`SoT:` + catalog lines for
114
124
  `model`; the report table for `toolchain check`), so nothing prints after
115
125
  it. The schema below applies to `sync` only.
116
126
 
117
- The `--- Sync complete ---` block (stdout, `data`) prints on every run,
118
- including dry-run, with the per-target inventory lines (`Claude:`/`Hooks:`/
119
- `Plugins:`/`Codex:`/`Skills:`). Next-step advice lines print only when their
120
- trigger changed this run (plugins changed → `/reload-plugins` line; hooks/env
121
- changed → restart line; skills changed → discovery line) or under `--verbose`.
127
+ The `--- Sync complete ---` block (stdout, `echo`) prints after the selected
128
+ pipelines settle, also on dry-run. When a pipeline rejects, `syncDispatch.ts`
129
+ `engineSync` skips the block and prints only the `--- Failures ---` ledger.
130
+ The block starts with a `Repo:` line and adds the inventory lines of each
131
+ selected target: `Claude:`/`Hooks:`/`Plugins:`, `Codex:`/`Codex plugins:`,
132
+ `Skills:`, and `omp:`/`omp plugins:`. Dry-run leaves out the `Hooks:`,
133
+ `Plugins:`, `Codex plugins:`, and `omp plugins:` lines. Next-step advice
134
+ lines print only when their trigger changed this run (plugins changed →
135
+ `/reload-plugins` line; hooks/env changed → restart line; skills changed →
136
+ discovery line) or under `--verbose`.
122
137
 
123
138
  ### Platform seam
124
139
 
125
- All host detection routes through `os/index.ts`. Its `rawPlatform` function
140
+ Engine host detection routes through `os/index.ts`. Its `rawPlatform` function
126
141
  holds the engine's host-detection `process.platform` read and keeps platform
127
- normalization injectable for tests. Two direct reads remain: the POSIX-only
128
- `chmod` guard in `kitDb.ts` and the default `platform` argument of
129
- `harnesses.ts` `engineHome`.
142
+ normalization injectable for tests. These direct reads remain:
143
+
144
+ - the POSIX-only `chmod` guard in `kitDb.ts`;
145
+ - the default `platform` argument of `harnesses.ts` `engineHome`;
146
+ - `exec.ts` `WINDOWS_PROCESS`;
147
+ - `tidy.ts` `listProcesses`;
148
+ - `tidyReport.ts` `memorySection`, `processSection`, `trashSection`,
149
+ `scheduledSection`, and `buildTidyReport`;
150
+ - `scratch.ts` `removeTemporaryPath`.
151
+
152
+ Two cross-platform primitives need no platform branch:
153
+
154
+ - `kitLock.ts` `acquireKitLock`: an SQLite `BEGIN IMMEDIATE` lock. The OS
155
+ releases it when the holder process ends, on POSIX and on Windows.
156
+ - `processes.ts` `processExited`: `process.kill(pid, 0)` throws ESRCH for an
157
+ exited PID on every host (`kill(2)` on POSIX, libuv `uv_kill` on Windows).
158
+
159
+ The omp extension `SoT/.omp/plugin/extensions/hygiene.ts` is outside the
160
+ engine. Its `isWindowsContention` reads `process.platform` and runs an EPERM
161
+ probe on win32 only.
162
+
130
163
  Per-OS facts live in `os/linux.ts`, `os/darwin.ts`, and `os/windows.ts` behind
131
164
  `HostOs`; consumers select those facts through the package rather than branching
132
165
  on the host directly.
@@ -148,35 +181,36 @@ active logger binding.
148
181
 
149
182
  ## Module Map
150
183
 
151
- | Module | Owns |
152
- | ---------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
153
- | `parseArgs.ts` | engine usage, target selection, argv dispatch loop, legacy rename hints; re-exports the `parseHelp.ts` help text and early-exit error |
154
- | `parseModifiers.ts` | deploy-time modifier metadata, scalar modifier setters, compact-window and opt-in plugin parsing, modifier and model flag validation |
155
- | `index.ts` | entry routing (`model`/`toolchain`/`sync`) and the run-scoped verbosity gate |
156
- | `engineCtx.ts` | `Ctx` shape and `makeCtx`; the unprefixed env globals (`ENV_GLOBAL_KEYS`) apply only on the native-raw channel |
157
- | `syncDispatch.ts` | pipeline selection, pool dispatch, run summary, next-step blocks, and the `--- Failures ---` ledger |
158
- | `syncConcurrency.ts` | input-ordered bounded pool (`runBounded`) and the manifest-driven serial rule (`syncConcurrencyForManifest`) |
159
- | `../payload.ts` | generated text/byte payload reads and presentation-only source labels |
160
- | `claudeSync.ts` | Claude pipeline: Bun bootstrap, prepared settings transaction, runtime assets, deploy-time modifiers, `~/.claude.json`, readiness-gated removed artifacts, plugins, optional plugins, LSP binaries |
161
- | `bun.ts` | per-run memoized Bun resolution/bootstrap shared by the Claude runtime and direct toolchain ensure |
162
- | `claudeRuntime.ts` | sentinel validation, absolute runtime paths, no-cutover settings projection, and per-host statusline and failure-hook command materialization |
163
- | `settings.ts` | pure Claude settings merge/reconcile semantics and permission-array union |
164
- | `claudeSettings.ts` | Claude settings preflight, prepare/commit transaction, dry-run description, and the compact-window and permissive modifiers |
165
- | `claudeSettingsModifiers.ts` | atomic top-level Claude settings modifiers (model, effort, advisor) and the direct `model claude` write path |
166
- | `claudeRemovals.ts` | force-prune of retired Claude artifacts and the `claudeRetired.ts` permission inventory without `--reconcile` |
167
- | `codexSync.ts` | Codex pipeline: bubblewrap check, config merge, rules, AGENTS.md, personal marketplace, plugin refresh |
168
- | `codexToml.ts` | line-based top-level TOML replacement and deployed Codex model modifier |
169
- | `skillsSync.ts` | universal skill install/prune, ordered symlink/junction/copy fallback, Claude entry healing, managed-skill snapshot |
170
- | `ompSync.ts` | omp pipeline orchestration and summary; `ompFileDeploy.ts`, `ompMarketplace.ts`, `ompPlugins.ts`, and `ompRemovals.ts` own the file, marketplace, plugin, and retired-key passes; `ompPaths.ts` resolves roots; `ompYaml.ts` merges YAML |
171
- | `toolchain.ts` | tool presence/version probes, verified-version floor reporting, report table |
172
- | `modes.ts` | direct `model` and `toolchain` modes |
173
- | `models.ts` | model catalog listing and validation |
174
- | `jq.ts` | JSON helpers that preserve jq-style merge/order/stringify behavior where the deployed file contract needs it |
175
- | `exec.ts` | slash-stable path helpers, host-aware PATH probes and invocation, capture/spawn wrappers, and change-detecting write/copy helpers |
176
- | `logger.ts` | Logger shape + stable raw stdout/stderr sink factory; the run-scoped verbosity gate lives in `index.ts` |
177
- | `deps.ts` | external-tool registry: identity, requirement class, presence probe, supported-host install hints, per-manager missing-tool dedup; callers supply the current run Logger to `warnMissing` |
178
- | `os/` | host reader, injected platform normalization, and per-OS `HostOs` fact modules |
179
- | `services.ts` | shared raw-Logger + DependencyManager + Platform factory; wrapped in Effect Layers at `cli/src/services.ts`, with the run-scoped Logger gate applied only by `runEngineNative` |
184
+ | Module | Owns |
185
+ | ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
186
+ | `parseArgs.ts` | engine usage, target selection, argv dispatch loop, legacy rename hints; re-exports the `parseHelp.ts` help text and early-exit error |
187
+ | `parseModifiers.ts` | deploy-time modifier metadata, scalar modifier setters, compact-window and opt-in plugin parsing, modifier and model flag validation |
188
+ | `index.ts` | entry routing (`model`/`toolchain`/`sync`) and the run-scoped verbosity gate |
189
+ | `engineCtx.ts` | `Ctx` shape and `makeCtx`; the unprefixed env globals (`ENV_GLOBAL_KEYS`) apply only on the native-raw channel |
190
+ | `syncDispatch.ts` | pipeline selection, pool dispatch, run summary, next-step blocks, and the `--- Failures ---` ledger |
191
+ | `syncConcurrency.ts` | input-ordered bounded pool (`runBounded`) and the manifest-driven serial rule (`syncConcurrencyForManifest`) |
192
+ | `../payload.ts` | generated text/byte payload reads and presentation-only source labels |
193
+ | `claudeSync.ts` | Claude pipeline orchestration and summary: Bun bootstrap, prepared settings transaction, runtime assets, deploy-time modifiers, `~/.claude.json`, readiness-gated removed artifacts; `claudePluginPasses.ts`, `claudeOptionalPlugins.ts`, and `claudeLsp.ts` own the plugin, optional-plugin, and LSP binary passes |
194
+ | `bun.ts` | per-run memoized Bun resolution/bootstrap shared by the Claude runtime and direct toolchain ensure |
195
+ | `claudeRuntime.ts` | sentinel validation, absolute runtime paths, no-cutover settings projection, and per-host statusline and failure-hook command materialization |
196
+ | `settings.ts` | pure Claude settings merge/reconcile semantics and permission-array union |
197
+ | `claudeSettings.ts` | Claude settings preflight, prepare/commit transaction, dry-run description, and the compact-window and permissive modifiers |
198
+ | `claudeSettingsModifiers.ts` | atomic top-level Claude settings modifiers (model, effort, advisor) and the direct `model claude` write path |
199
+ | `claudeRemovals.ts` | force-prune of retired Claude artifacts and the `claudeRetired.ts` permission inventory without `--reconcile` |
200
+ | `codexSync.ts` | Codex pipeline orchestration: bubblewrap check, rules, AGENTS.md; `codexConfig.ts` `syncConfig` owns the config merge, `codexHooks.ts` the retired-hook prune, `codexPlugins.ts` the personal marketplace and plugin refresh, and `codexStatus.ts` the summary |
201
+ | `codexToml.ts` | line-based top-level TOML replacement and deployed Codex model modifier |
202
+ | `tomlLines.ts` | import-free TOML line grammar (header lines, key separators, value continuation lines) shared by `codexToml.ts`, `codexConfig.ts`, `codexPlugins.ts`, and `../manifests.ts` |
203
+ | `skillsSync.ts` | universal-skill pipeline orchestration; `skillsManifest.ts` parses the manifest, `skillsInstall.ts` owns the install pass, `skillsLinks.ts` the ordered symlink/junction/copy fallback and Claude entry healing, and `skillsPrune.ts` the prune and managed-skill snapshot |
204
+ | `ompSync.ts` | omp pipeline orchestration and summary; `ompFileDeploy.ts`, `ompMarketplace.ts`, `ompPlugins.ts`, and `ompRemovals.ts` own the file, marketplace, plugin, and retired-key passes; `ompPaths.ts` resolves roots; `ompYaml.ts` merges YAML |
205
+ | `toolchain.ts` | tool presence/version probes, verified-version floor reporting, report table |
206
+ | `modes.ts` | direct `model` and `toolchain` modes |
207
+ | `models.ts` | model catalog listing and validation |
208
+ | `jq.ts` | JSON helpers that preserve jq-style merge/order/stringify behavior where the deployed file contract needs it |
209
+ | `exec.ts` | slash-stable path helpers, host-aware PATH probes and invocation, capture/spawn wrappers, and change-detecting write/copy helpers |
210
+ | `logger.ts` | Logger shape + stable raw stdout/stderr sink factory; the run-scoped verbosity gate lives in `index.ts` |
211
+ | `deps.ts` | external-tool registry: identity, presence probe, supported-host install hints; the Bun hint renders the pinned download-then-run installer of the host (`HostOs.bunInstaller`) |
212
+ | `os/` | host reader, injected platform normalization, and per-OS `HostOs` fact modules |
213
+ | `services.ts` | shared raw-Logger + DependencyManager + Platform factory; `makeDependencyManager` owns the per-manager missing-tool dedup, and callers supply the current run Logger to `warnMissing`; wrapped in Effect Layers at `cli/src/services.ts`, with the run-scoped Logger gate applied only by `runEngineNative` |
180
214
 
181
215
  ## Platform Support
182
216
 
@@ -200,10 +234,13 @@ active logger binding.
200
234
  `cli/test/goldens/dryrun.json`.
201
235
  - `bun run golden:mutation` compares live native mutation snapshots, argv logs,
202
236
  output, and TOML invariants to `cli/test/goldens/mutation.json`.
203
- - `.github/workflows/parity.yml` runs its portable lane on `ubuntu-24.04`,
204
- `macos-26`, and `windows-2025`: typecheck, unit tests, host-specific runtime
205
- command checks, and compilation and execution of the native host artifact.
206
- The Linux-canonical snapshot lane stays on Ubuntu and runs both golden suites
237
+ - `.github/workflows/parity.yml` runs its portable lane on `ubuntu-24.04` and
238
+ `macos-26`: typecheck, unit tests, host-specific runtime command checks, and
239
+ compilation and execution of the native host artifact. On `windows-2025`,
240
+ two unit-test shards and a runtime job (generated-payload check, typecheck,
241
+ runtime commands, native artifact) run in parallel. The check
242
+ `portable (windows-2025)` passes only when all three pass. The
243
+ Linux-canonical snapshot lane stays on Ubuntu and runs both golden suites
207
244
  plus their prove-red checks.
208
245
  - `.github/workflows/release-cli.yml` publishes four binaries (Linux x64 and
209
246
  arm64, macOS arm64, Windows x64), plus `SHA256SUMS` and the npm package.
@@ -1,20 +1,43 @@
1
1
  /**
2
2
  * File replacement through a temporary sibling and a rename, so a reader never
3
- * sees a partial write. Every kit writer that rewrites a user file uses it,
4
- * because two properties must hold for all of them:
3
+ * sees a partial write. Kit writers that replace a user file through this
4
+ * helper get these properties:
5
5
  * - A symlinked target stays a symlink; the file it points to is replaced.
6
6
  * - The replaced file keeps its permission bits unless the caller sets them.
7
+ * - Each write uses its own temporary name, so two writers never write into
8
+ * the same temporary file.
9
+ * - A write that throws tries to remove its temporary file. A failed removal,
10
+ * or a process that is killed during a write, can leave one. The temporary
11
+ * name holds the PID of its writer, so the next write of the same target
12
+ * removes such a file when its writer exited (`removeStaleTemporaries`).
7
13
  */
14
+ import { createHash, randomBytes } from "node:crypto";
8
15
  import {
9
16
  chmodSync,
17
+ existsSync,
10
18
  lstatSync,
19
+ readdirSync,
20
+ readFileSync,
11
21
  readlinkSync,
12
22
  realpathSync,
13
23
  renameSync,
14
24
  statSync,
25
+ unlinkSync,
15
26
  writeFileSync,
16
27
  } from "node:fs";
17
- import { dirname, resolve } from "node:path";
28
+ import { basename, dirname, join, resolve } from "node:path";
29
+ import { processExited } from "./processes";
30
+
31
+ /** The longest file name that common filesystems accept, in UTF-8 bytes. */
32
+ const MAX_NAME_BYTES = 255;
33
+
34
+ /**
35
+ * A temporary name, parsed from the right: `<target>.<pid>.<16 hex>.tmp`. The
36
+ * PID has no leading zero, so it is 1 or more.
37
+ */
38
+ const TEMPORARY_NAME = /^(.+)\.([1-9][0-9]*)\.[0-9a-f]{16}\.tmp$/;
39
+ /** The `<target>` part of a short temporary name: `.<tag>`. */
40
+ const SHORT_TARGET = /^\.([0-9a-f]{16})$/;
18
41
 
19
42
  export interface ReplaceFileOptions {
20
43
  /**
@@ -49,6 +72,119 @@ function permissionBits(file: string): number | undefined {
49
72
  }
50
73
  }
51
74
 
75
+ /** The tag of a short temporary name: the first 16 hex of sha256(`name`). */
76
+ function nameTag(name: string): string {
77
+ return createHash("sha256").update(name).digest("hex").slice(0, 16);
78
+ }
79
+
80
+ /**
81
+ * A temporary sibling name unique to this write: `<file>.<pid>.<16 hex>.tmp`.
82
+ * When that name is longer than the filesystem accepts, use the short
83
+ * `.<tag>.<pid>.<16 hex>.tmp` in the same directory, where `tag` is
84
+ * `nameTag(basename(file))`.
85
+ */
86
+ function temporaryPath(file: string): string {
87
+ const unique = randomBytes(8).toString("hex");
88
+ const long = `${file}.${process.pid}.${unique}.tmp`;
89
+ if (Buffer.byteLength(basename(long)) <= MAX_NAME_BYTES) return long;
90
+ return join(dirname(file), `.${nameTag(basename(file))}.${process.pid}.${unique}.tmp`);
91
+ }
92
+
93
+ /**
94
+ * The target that a temporary name records: the base name of the target, or,
95
+ * for a short name, the tag of that base name.
96
+ */
97
+ export type TemporaryTarget =
98
+ | { readonly kind: "name"; readonly name: string }
99
+ | { readonly kind: "tag"; readonly tag: string };
100
+
101
+ interface TemporaryName {
102
+ readonly target: TemporaryTarget;
103
+ readonly pid: number;
104
+ }
105
+
106
+ function parseTemporaryName(entry: string): TemporaryName | undefined {
107
+ const match = TEMPORARY_NAME.exec(entry);
108
+ if (match === null) return undefined;
109
+ const [, target = "", digits = ""] = match;
110
+ const pid = Number(digits);
111
+ if (!Number.isSafeInteger(pid)) return undefined;
112
+ const short = SHORT_TARGET.exec(target);
113
+ return {
114
+ target: short === null ? { kind: "name", name: target } : { kind: "tag", tag: short[1] ?? "" },
115
+ pid,
116
+ };
117
+ }
118
+
119
+ function isRegularFile(path: string): boolean {
120
+ try {
121
+ return lstatSync(path).isFile();
122
+ } catch {
123
+ return false;
124
+ }
125
+ }
126
+
127
+ /**
128
+ * Remove each temporary file in `dir` that a killed write left. An entry is
129
+ * removed only when all of these are true:
130
+ * - Its name parses from the right as `<target>.<pid>.<16 hex>.tmp`, or as the
131
+ * short `.<tag>.<pid>.<16 hex>.tmp`, with a PID of 1 or more.
132
+ * - `owns` accepts its target, so the caller writes that target.
133
+ * - It is a regular file (not a directory or a symlink).
134
+ * - Its PID is not this process, and `processExited` is true for it.
135
+ * This cleanup is best effort: it ignores every error, so it never makes a
136
+ * write fail.
137
+ */
138
+ export function removeStaleTemporaries(
139
+ dir: string,
140
+ owns: (target: TemporaryTarget) => boolean,
141
+ ): void {
142
+ let entries: Array<string>;
143
+ try {
144
+ entries = readdirSync(dir);
145
+ } catch {
146
+ return;
147
+ }
148
+ for (const entry of entries) {
149
+ const parsed = parseTemporaryName(entry);
150
+ if (parsed === undefined || parsed.pid === process.pid || !owns(parsed.target)) continue;
151
+ const path = join(dir, entry);
152
+ if (!isRegularFile(path) || !processExited(parsed.pid)) continue;
153
+ try {
154
+ unlinkSync(path);
155
+ } catch {
156
+ // Ignore it: the next write of the target tries again.
157
+ }
158
+ }
159
+ }
160
+
161
+ /** Remove the temporary files that killed writes of `file` left. */
162
+ function removeStaleTemporariesOf(file: string): void {
163
+ const name = basename(file);
164
+ const tag = nameTag(name);
165
+ removeStaleTemporaries(dirname(file), (target) =>
166
+ target.kind === "name" ? target.name === name : target.tag === tag,
167
+ );
168
+ }
169
+
170
+ function errorSyscall(error: unknown): unknown {
171
+ return typeof error === "object" && error !== null && "syscall" in error
172
+ ? error.syscall
173
+ : undefined;
174
+ }
175
+
176
+ /**
177
+ * Remove the temporary file of a failed write. The caller rethrows the error of
178
+ * the failed write, so a removal error must not replace it.
179
+ */
180
+ function removeTemporary(path: string): void {
181
+ try {
182
+ unlinkSync(path);
183
+ } catch {
184
+ // Ignore it: the error of the failed write tells the user what went wrong.
185
+ }
186
+ }
187
+
52
188
  export function replaceFile(
53
189
  target: string,
54
190
  content: string | Uint8Array,
@@ -56,9 +192,33 @@ export function replaceFile(
56
192
  ): void {
57
193
  const file = writeTarget(target);
58
194
  const mode = options.mode ?? permissionBits(file);
59
- const temporary = `${file}.tmp`;
60
- writeFileSync(temporary, content, mode === undefined ? {} : { mode });
61
- // writeFileSync applies `mode` only when it creates the file, and through the umask.
62
- if (mode !== undefined) chmodSync(temporary, mode);
63
- renameSync(temporary, file);
195
+ const temporary = temporaryPath(file);
196
+ try {
197
+ // Flag `wx` creates the file or fails, so this write never uses a file of another writer.
198
+ writeFileSync(temporary, content, mode === undefined ? { flag: "wx" } : { flag: "wx", mode });
199
+ // writeFileSync applies `mode` only when it creates the file, and through the umask.
200
+ if (mode !== undefined) chmodSync(temporary, mode);
201
+ renameSync(temporary, file);
202
+ } catch (error) {
203
+ // A failed `open` is the exclusive create. This writer does not own the path,
204
+ // so it touches nothing.
205
+ if (errorSyscall(error) !== "open") removeTemporary(temporary);
206
+ throw error;
207
+ }
208
+ removeStaleTemporariesOf(file);
209
+ }
210
+
211
+ /**
212
+ * Replace `path` through `replaceFile` only when its content differs. Returns
213
+ * false when the file already holds `content`, else true. When it holds
214
+ * `content`, it still removes the temporary files that killed writes of
215
+ * `path` left, because no `replaceFile` call does it.
216
+ */
217
+ export function replaceTextIfChanged(path: string, content: string): boolean {
218
+ if (existsSync(path) && readFileSync(path, "utf8") === content) {
219
+ removeStaleTemporariesOf(writeTarget(path));
220
+ return false;
221
+ }
222
+ replaceFile(path, content);
223
+ return true;
64
224
  }
@@ -8,13 +8,9 @@ import { copyFileSync, existsSync, readFileSync, rmSync, writeFileSync } from "n
8
8
 
9
9
  import { payloadDisplayPath } from "../payload";
10
10
  import { replaceFile } from "./atomicWrite";
11
- import {
12
- isTomlHeaderLine,
13
- mergeTableSettings,
14
- mergeTopLevelSettings,
15
- tomlContinuationLines,
16
- } from "./codexToml";
11
+ import { mergeTableSettings, mergeTopLevelSettings } from "./codexToml";
17
12
  import type { Ctx } from "./index";
13
+ import { isTomlHeaderLine, tomlContinuationLines } from "./tomlLines";
18
14
 
19
15
  // --------------------------------------------------------------- config ----
20
16
 
@@ -8,12 +8,12 @@ import { copyFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from
8
8
  import { payloadDisplayPath } from "../payload";
9
9
  import { replaceFile } from "./atomicWrite";
10
10
  import { PLUGIN_TABLE_HEADER } from "./codexConfig";
11
- import { isTomlHeaderLine } from "./codexToml";
12
11
  import { p, processFailureSummary, spawnProcess } from "./exec";
13
12
  import { recordFailure } from "./failures";
14
13
  import type { Ctx } from "./index";
15
14
  import { compareCodepoints, isObject, jqStringify, parseJson, type Json } from "./jq";
16
15
  import type { JsonObject } from "./sharedTypes";
16
+ import { isTomlHeaderLine } from "./tomlLines";
17
17
 
18
18
  // ---------------------------------------------------------- marketplace ----
19
19