docks-kit 0.22.13 → 0.22.22

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 (57) hide show
  1. package/AGENTS.md +97 -83
  2. package/README.md +7 -7
  3. package/cli/docs/command-guards.md +12 -7
  4. package/cli/docs/flags.md +59 -9
  5. package/cli/docs/install.md +2 -2
  6. package/cli/docs/omp-context.md +27 -17
  7. package/cli/docs/omp-models.md +91 -70
  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 +6 -4
  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 +81 -88
  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/harnesses.ts +5 -11
  28. package/cli/src/engine-native/index.ts +1 -1
  29. package/cli/src/engine-native/kitDb.ts +7 -7
  30. package/cli/src/engine-native/kitLock.ts +121 -0
  31. package/cli/src/engine-native/modes.ts +49 -31
  32. package/cli/src/engine-native/ompChild.ts +26 -0
  33. package/cli/src/engine-native/ompFastMode.ts +14 -7
  34. package/cli/src/engine-native/ompFileDeploy.ts +12 -6
  35. package/cli/src/engine-native/ompMarketplace.ts +25 -18
  36. package/cli/src/engine-native/ompOverlay.ts +23 -69
  37. package/cli/src/engine-native/ompPlugins.ts +23 -14
  38. package/cli/src/engine-native/ompRemovals.ts +97 -30
  39. package/cli/src/engine-native/ompSync.ts +66 -32
  40. package/cli/src/engine-native/os/targets.ts +16 -4
  41. package/cli/src/engine-native/os/types.ts +1 -1
  42. package/cli/src/engine-native/parseArgs.ts +27 -17
  43. package/cli/src/engine-native/processes.ts +16 -0
  44. package/cli/src/engine-native/scratch.ts +18 -0
  45. package/cli/src/engine-native/sharedTypes.d.ts +0 -2
  46. package/cli/src/engine-native/skillsInstall.ts +27 -2
  47. package/cli/src/engine-native/skillsPrune.ts +51 -49
  48. package/cli/src/engine-native/skillsRecords.ts +138 -0
  49. package/cli/src/engine-native/skillsSync.ts +16 -13
  50. package/cli/src/engine-native/syncDispatch.ts +186 -4
  51. package/cli/src/engine-native/tidy.ts +102 -119
  52. package/cli/src/engine-native/tomlLines.ts +92 -0
  53. package/cli/src/generated/sotPayload.ts +5 -5
  54. package/cli/src/main.ts +5 -30
  55. package/cli/src/manifests.ts +24 -4
  56. package/package.json +2 -2
  57. package/cli/src/engine-native/tidyLock.ts +0 -163
@@ -4,7 +4,7 @@
4
4
 
5
5
  | Field | Meaning |
6
6
  |-------|---------|
7
- | `kind` | `check` (doctor visibility) / `managed` (kit-managed install) / `pin` (no binary — a version pin for npx-invoked tools, e.g. `skills-cli`) |
7
+ | `kind` | `check` (doctor visibility) / `managed` (kit-managed install) / `pin` (no binary — a version pin for a package that the kit installs through another tool: `npx` for `skills-cli`, `omp install` for `pi-intercom`; the optional `via` field names that tool in the doctor table, and the default is `npx`) |
8
8
  | `policy` | Installation policy; `present` installs when missing and never upgrades |
9
9
  | `floor` | Minimum acceptable version shown in the doctor table |
10
10
  | `verified` | Last kit-tested version and the exact pin for kit-driven installs |
@@ -37,8 +37,10 @@ server as an npm global for the `typescript-lsp` plugin, so an older Node runs
37
37
  a server its own manifest rejects. `docks-kit toolchain check` prints
38
38
  `below-floor` for a Node older than 22.22.2. The sync pass reads the same
39
39
  floor: it skips the `typescript-language-server` install on such a host, warns
40
- with the host Node version, and installs the other language servers. Nothing
41
- else consults the floor, so a host below it still runs every kit operation.
40
+ with the host Node version, and installs the other language servers.
41
+ `docks-kit toolchain upgrade` also reads the floor: it skips the
42
+ `typescript-language-server` upgrade on such a host and warns. Nothing else
43
+ consults the floor, so a host below it still runs every other kit operation.
42
44
 
43
45
  ## rust-analyzer: no floor, no pin
44
46
 
@@ -62,8 +64,9 @@ the component is not installed. When `rust-analyzer --version` does not answer
62
64
  within 60 s, sync warns, stops the probe, and does not add the component on that
63
65
  run. `rustup update` is the user's remedy for an old component.
64
66
 
65
- A lagging server shows as `below-floor` in `docks-kit toolchain check`. To move
66
- the npm servers to their `verified` pins, run:
67
+ A server below its `floor` shows as `below-floor` in `docks-kit toolchain check`.
68
+ A server at or above its floor but below its `verified` pin shows as `ok`.
69
+ To move every npm server that is below its `verified` pin to that pin, run:
67
70
 
68
71
  ```bash
69
72
  docks-kit toolchain upgrade --dry-run # print the npm command
@@ -72,8 +75,9 @@ docks-kit toolchain upgrade # run it
72
75
 
73
76
  `toolchain upgrade` (`claudeLsp.ts upgradeLspServers`) reads `npm ls -g` to see
74
77
  which of `intelephense`, `typescript-language-server`, and `typescript` npm
75
- owns. It runs one `npm install -g <pkg>@<verified>` for each npm-owned package
76
- below its pin. A package already at or above its pin stays as it is. It leaves
78
+ owns. It runs one `npm install -g` command that names every npm-owned package
79
+ below its pin as `<pkg>@<verified>`. A package already at or above its pin
80
+ stays as it is. It leaves
77
81
  these alone and warns:
78
82
 
79
83
  - A binary on PATH that npm does not own. It came from another installer, so
@@ -92,13 +96,19 @@ package is not at its pin.
92
96
 
93
97
  ## Supply-chain stance
94
98
 
95
- Every kit-driven install of third-party software is pinned to a
96
- `SoT/toolchain.json` `verified` version — never floating `@latest` (the
97
- npm-worm / Shai-Hulud attack surface). That includes the
98
- `npx skills@<verified>` invocations on agents sync and the release workflow
99
- (actions pinned to commit SHAs, exact bun/npm versions).
100
-
101
- The kit's own package is the single exemption. `install.sh` and `install.ps1`
99
+ Every kit-driven package install from npm, npx, GitHub releases, or
100
+ `omp install` is pinned to a `SoT/toolchain.json` `verified` version — never
101
+ floating `@latest` (the npm-worm / Shai-Hulud attack surface). That includes
102
+ the `npx skills@<verified>` invocations on agents sync and the release workflow
103
+ (actions pinned to commit SHAs, exact bun/npm versions). Two installs follow
104
+ the host toolchain and have no pin: `rust-analyzer` (rustup) and `bubblewrap`
105
+ (distro package manager). The existing Claude Code, Codex, and omp marketplace
106
+ plugins have no manifest pin either: sync installs and refreshes them at the
107
+ version that their marketplace publishes (see `plugins`). Any new install
108
+ surface, a new marketplace or plugin source included, needs a manifest pin
109
+ first.
110
+
111
+ The kit's own package is the single exemption from the `@latest` ban. `install.sh` and `install.ps1`
102
112
  end with `bun add -g docks-kit@latest` because a global installer that pinned
103
113
  itself would install a fixed old kit forever. The exemption covers `docks-kit`
104
114
  alone; both installers still pin the Bun installer they download to the
package/cli/src/argv.ts CHANGED
@@ -19,7 +19,6 @@ import {
19
19
  spliceOmpBoundary,
20
20
  subcommandName as scanSubcommandName,
21
21
  type ArgvSurfaces,
22
- type CommandValue,
23
22
  } from "./argvSurface";
24
23
  import { validateScannedArgv } from "./argvValidate";
25
24
 
@@ -27,13 +26,17 @@ export type ArgvOutcome =
27
26
  | { readonly kind: "reject"; readonly message: string; readonly exitCode: number }
28
27
  | { readonly kind: "accept"; readonly args: ReadonlyArray<string> };
29
28
 
30
- const COMMANDS: ReadonlyArray<CommandValue> = [
29
+ /**
30
+ * The one subcommand list. `main.ts` registers it with Effect, and the argv
31
+ * surfaces below accept the same words. The order is the `--help` order.
32
+ */
33
+ export const COMMANDS = [
31
34
  syncCommand,
32
35
  harnessesCommand,
33
36
  updateCommand,
34
37
  modelCommand,
35
- toolchainCommand,
36
38
  modelsCommand,
39
+ toolchainCommand,
37
40
  statusCommand,
38
41
  pluginsCommand,
39
42
  skillsCommand,
@@ -41,7 +44,7 @@ const COMMANDS: ReadonlyArray<CommandValue> = [
41
44
  ompCommand,
42
45
  scratchCommand,
43
46
  tidyCommand,
44
- ];
47
+ ] as const;
45
48
 
46
49
  const SURFACES: ArgvSurfaces = buildSurfaces(COMMANDS, GlobalFlag.BuiltIns);
47
50
 
@@ -6,25 +6,12 @@
6
6
  */
7
7
 
8
8
  import { KNOWN_CLAUDE_OPTIN_PLUGINS } from "./engine-native/parseModifiers";
9
+ import { isLegacyFlag, LEGACY_FLAG_HINTS } from "./engine-native/parseArgs";
9
10
  import { modelCatalog } from "./engine-native/models";
10
11
  import { advisorCatalog, advisorFlagGrammar, effortCatalog, effortFlagGrammar } from "./efforts";
11
12
  import type { Tool } from "./manifests";
12
13
  import type { ArgvSurfaces, FlagSurface, ScannedFlag } from "./argvSurface";
13
14
 
14
- const LEGACY_HINTS: Readonly<Record<string, string>> = {
15
- "--force": "--force was renamed to --reconcile",
16
- "--remove-plugins":
17
- "--remove-plugins was renamed to --prune (it also removes marketplaces + kit-managed skills)",
18
- "--680k": "--680k was renamed to --claude-compact-window=680k",
19
- "--permissive": "--permissive was renamed to --claude-permissive",
20
- "--supabase": "--supabase was renamed to --claude-plugin=supabase",
21
- "--n8n": "--n8n was renamed to --claude-plugin=n8n",
22
- "--skip-rtk": "--skip-rtk was renamed to --skip-bubblewrap",
23
- "--claude": "--claude was renamed: pass the target as a word, e.g. 'sync claude'",
24
- "--codex": "--codex was renamed: pass the target as a word, e.g. 'sync codex'",
25
- "--agents": "--agents was renamed: pass the target as a word, e.g. 'sync agents'",
26
- };
27
-
28
15
  const modelCatalogHint = (tool: Tool): string => {
29
16
  const catalog = modelCatalog(tool);
30
17
  const list = catalog.models
@@ -76,8 +63,7 @@ export const validateScannedArgv = (
76
63
 
77
64
  if (subcommand === "sync") {
78
65
  for (const flag of flags) {
79
- const hint = LEGACY_HINTS[flag.name];
80
- if (hint !== undefined) return hint;
66
+ if (isLegacyFlag(flag.name)) return LEGACY_FLAG_HINTS[flag.name];
81
67
  }
82
68
  }
83
69
 
@@ -17,7 +17,7 @@ import commandGuards from "../../docs/command-guards.md" with { type: "text" };
17
17
  const TOPICS: Record<string, { summary: string; body: string }> = {
18
18
  overview: { summary: "What docks-kit is and how the pieces fit", body: overview },
19
19
  "sync-layers": {
20
- summary: "The three sync layers and additive-by-default semantics",
20
+ summary: "The four sync targets (claude, codex, agents, omp) and additive-by-default semantics",
21
21
  body: syncLayers,
22
22
  },
23
23
  flags: { summary: "Full flag reference incl. the old→new rename table", body: flags },
@@ -12,8 +12,6 @@ import {
12
12
  type OmpSessionModel,
13
13
  } from "../engine-native/harnesses";
14
14
  import {
15
- advisorLevelFor,
16
- advisorRecommendation,
17
15
  buildOmpArgs,
18
16
  ladderCeiling,
19
17
  ompChildEnvironment,
@@ -23,8 +21,15 @@ import {
23
21
  renderFreeOverlay,
24
22
  type CatalogModel,
25
23
  } from "../engine-native/ompOverlay";
26
- import { FAST_ON_TIER, toggleDeployedOpenAiFast } from "../engine-native/ompFastMode";
24
+ import {
25
+ FAST_ON_TIER,
26
+ requireDeployedConfig,
27
+ toggleDeployedOpenAiFast,
28
+ type FastToggle,
29
+ } from "../engine-native/ompFastMode";
27
30
  import { ompPaths } from "../engine-native/ompPaths";
31
+ import { ExitError } from "../engine-native/parseArgs";
32
+ import { withHomeAndFolderLocks } from "../engine-native/syncDispatch";
28
33
 
29
34
  const model = Flag.String("model").pipe(
30
35
  Flag.withDescription("Free model selector to use and remember for omp sessions"),
@@ -184,73 +189,84 @@ const loadFreeCatalog = (
184
189
  });
185
190
 
186
191
  /**
187
- * Ask for the thinking levels of one model. Every choice comes from that
192
+ * Ask for the thinking level of one model. Every choice comes from that
188
193
  * model own ladder, because omp rejects a `:level` suffix the model does not
189
194
  * publish. A model with no ladder and a model with one level are settled
190
- * without a question.
195
+ * without a question. Every role runs at the chosen level.
191
196
  */
192
- const pickLevels = (catalogModel: CatalogModel) =>
197
+ const pickLevel = (catalogModel: CatalogModel) =>
193
198
  Effect.gen(function* () {
194
199
  const plan = planEffortChoice(catalogModel.thinking);
195
200
  if (plan.kind === "none") {
196
201
  yield* Console.error(
197
202
  `${catalogModel.name} publishes no thinking levels; the model default applies`,
198
203
  );
199
- return { thinking: undefined, advisorThinking: undefined };
204
+ return undefined;
200
205
  }
201
206
  if (plan.kind === "fixed") {
202
207
  yield* Console.error(`${catalogModel.name} publishes one thinking level: ${plan.level}`);
203
- return { thinking: plan.level, advisorThinking: plan.level };
208
+ return plan.level;
204
209
  }
205
- const uniform = yield* Prompt.Select({
206
- message: "Use the same thinking level for every role?",
207
- choices: [
208
- {
209
- title: "Yes",
210
- value: true,
211
- description: `every role runs at ${plan.highest}, the highest this model offers`,
212
- },
213
- { title: "No", value: false, description: "set the advisor apart from the other roles" },
214
- ],
215
- });
216
- if (uniform) return { thinking: plan.highest, advisorThinking: plan.highest };
217
- const ladderChoices = plan.levels.map((level) => ({
218
- title: level,
219
- value: level,
220
- description:
221
- level === plan.highest
222
- ? "highest this model offers"
223
- : level === plan.levels[0]
224
- ? "lowest this model offers"
225
- : "",
226
- }));
227
- const thinking = yield* Prompt.Select({
228
- message: "Thinking level for all roles except the advisor",
229
- choices: ladderChoices,
210
+ // Prompt.Select always starts on the first entry and offers no initial
211
+ // index, so the list runs highest first and Enter keeps the ceiling.
212
+ return yield* Prompt.Select({
213
+ message: "Thinking level for every role",
214
+ choices: [...plan.levels].reverse().map((level) => ({
215
+ title: level,
216
+ value: level,
217
+ description:
218
+ level === plan.highest
219
+ ? "highest this model offers"
220
+ : level === plan.levels[0]
221
+ ? "lowest this model offers"
222
+ : "",
223
+ })),
230
224
  });
231
- const suggested = advisorRecommendation(plan.levels, thinking);
232
- // The list leads with the suggestion, because Prompt.Select always starts
233
- // on the first entry and offers no initial index. The full ladder follows
234
- // in ladder order, so a different level stays one keypress away. A
235
- // suggestion equal to the main level would only duplicate a row.
236
- const advisorChoices =
237
- suggested === undefined || suggested === thinking
238
- ? ladderChoices
239
- : [
240
- {
241
- title: suggested,
242
- value: suggested,
243
- description: `recommended, two levels below ${thinking}`,
244
- },
245
- ...ladderChoices,
246
- ];
247
- const advisorThinking = yield* Prompt.Select({
248
- message: "Thinking level for the advisor role",
249
- choices: advisorChoices,
250
- });
251
- return { thinking, advisorThinking };
252
225
  });
253
226
 
227
+ /**
228
+ * Toggle fast mode under the sync lock of `home` and the folder lock of the
229
+ * omp agent folder, with the wait and the held line of a sync. A sync also
230
+ * merges `config.yml` there. Return 0 after the toggle, 1 for a held lock,
231
+ * and 2 for a failed toggle or an invalid wait bound.
232
+ */
233
+ async function toggleFastUnderLocks(home: string, agentDir: string): Promise<number> {
234
+ const configPath = p(agentDir, "config.yml");
235
+ const err = (line: string) => console.error(line);
236
+ // Check config.yml before any lock. A missing file ends the run before the
237
+ // lock step can create the agent folder, and a folder that a sync creates
238
+ // during the home lock wait is never toggled without its folder lock.
239
+ try {
240
+ requireDeployedConfig(configPath);
241
+ } catch (error) {
242
+ err(error instanceof Error ? error.message : String(error));
243
+ return 2;
244
+ }
245
+ try {
246
+ return await withHomeAndFolderLocks(home, [agentDir], err, async () => {
247
+ let toggle: FastToggle;
248
+ try {
249
+ toggle = toggleDeployedOpenAiFast(configPath);
250
+ } catch (error) {
251
+ err(error instanceof Error ? error.message : String(error));
252
+ return 2;
253
+ }
254
+ const state = toggle.next === FAST_ON_TIER ? "ON" : "OFF";
255
+ console.log(
256
+ `omp fast mode ${state} for OpenAI/Codex models: tier.openai ${toggle.previous} -> ${toggle.next} in ${configPath}`,
257
+ );
258
+ console.log(
259
+ "New omp sessions use it; in a running session, use /fast on|off or restart omp.",
260
+ );
261
+ return 0;
262
+ });
263
+ } catch (error) {
264
+ // An invalid DOCKS_KIT_SYNC_LOCK_WAIT_MS prints its error line, then throws ExitError(2).
265
+ if (error instanceof ExitError) return error.code;
266
+ throw error;
267
+ }
268
+ }
269
+
254
270
  export const ompCommand = Command.make("omp", { model, pick, fast, args }, (config) =>
255
271
  Effect.gen(function* () {
256
272
  // Check the forwarded arguments before omp, the catalog, or kit.db, so a
@@ -266,22 +282,13 @@ export const ompCommand = Command.make("omp", { model, pick, fast, args }, (conf
266
282
  if (Option.isSome(config.model) || config.pick || config.args.length > 0) {
267
283
  return yield* bail("--fast toggles fast mode and exits; pass it alone");
268
284
  }
269
- const configPath = p(
270
- ompPaths({ home: engineHome(process.env), env: process.env, platform: process.platform })
271
- .agentDir,
272
- "config.yml",
273
- );
274
- const toggle = yield* Effect.try({
275
- try: () => toggleDeployedOpenAiFast(configPath),
285
+ const home = engineHome(process.env);
286
+ const agentDir = ompPaths({ home, env: process.env, platform: process.platform }).agentDir;
287
+ const code = yield* Effect.tryPromise({
288
+ try: () => toggleFastUnderLocks(home, agentDir),
276
289
  catch: (error) => (error instanceof Error ? error.message : String(error)),
277
290
  }).pipe(Effect.catch((message) => bail(message)));
278
- const state = toggle.next === FAST_ON_TIER ? "ON" : "OFF";
279
- yield* Console.log(
280
- `omp fast mode ${state} for OpenAI/Codex models: tier.openai ${toggle.previous} -> ${toggle.next} in ${configPath}`,
281
- );
282
- yield* Console.log(
283
- "New omp sessions use it; in a running session, use /fast on|off or restart omp.",
284
- );
291
+ if (code !== 0) return yield* Effect.sync(() => process.exit(code));
285
292
  return;
286
293
  }
287
294
 
@@ -323,7 +330,6 @@ export const ompCommand = Command.make("omp", { model, pick, fast, args }, (conf
323
330
  chosen = {
324
331
  selector: resolved.model.selector,
325
332
  thinking: ladderCeiling(resolved.model.thinking),
326
- advisorThinking: advisorLevelFor(resolved.model.thinking),
327
333
  };
328
334
  }
329
335
 
@@ -346,12 +352,7 @@ export const ompCommand = Command.make("omp", { model, pick, fast, args }, (conf
346
352
  if (match === undefined) {
347
353
  return yield* bail(`Model '${pickedSelector}' is not in the free catalog`);
348
354
  }
349
- const chosenLevels = yield* pickLevels(match);
350
- chosen = {
351
- selector: match.selector,
352
- thinking: chosenLevels.thinking,
353
- advisorThinking: chosenLevels.advisorThinking,
354
- };
355
+ chosen = { selector: match.selector, thinking: yield* pickLevel(match) };
355
356
  }
356
357
 
357
358
  const session: OmpSessionModel =
@@ -386,21 +387,13 @@ export const ompCommand = Command.make("omp", { model, pick, fast, args }, (conf
386
387
  });
387
388
 
388
389
  // A level-free model states the model default so the line never shows
389
- // an undefined level. The advisor appears only when it differs, because
390
- // a uniform session has nothing extra to report.
391
- const level =
392
- typeof session.thinking === "string" && session.thinking.trim() !== ""
393
- ? session.thinking
394
- : undefined;
395
- const advisor =
396
- typeof session.advisorThinking === "string" && session.advisorThinking.trim() !== ""
397
- ? session.advisorThinking
398
- : undefined;
390
+ // an undefined level.
399
391
  const levelText =
400
- level === undefined ? "the model default thinking level" : `${level} thinking`;
401
- const advisorText = advisor !== undefined && advisor !== level ? `, advisor at ${advisor}` : "";
392
+ typeof session.thinking === "string" && session.thinking.trim() !== ""
393
+ ? `${session.thinking} thinking`
394
+ : "the model default thinking level";
402
395
  yield* Console.error(
403
- `Starting omp with ${session.selector} at ${levelText}${advisorText} (session only; deployed config unchanged)`,
396
+ `Starting omp with ${session.selector} at ${levelText} (session only; deployed config unchanged)`,
404
397
  );
405
398
 
406
399
  // An exported model variable would set its role above the overlay, so the
@@ -1,27 +1,27 @@
1
1
  import { Argument, Command, Flag } from "effect/cli";
2
2
  import { Effect, Option } from "effect";
3
- import { spawnSync } from "node:child_process";
4
3
  import { existsSync } from "node:fs";
5
4
  import { join } from "node:path";
6
5
  import { bail, engine } from "../engine";
6
+ import { spawnHost } from "../engine-native/exec";
7
7
  import type { Logger } from "../engine-native/logger";
8
8
  import { kitHome } from "../kitHome";
9
9
  import { LoggerService } from "../services";
10
10
 
11
11
  /** Best-effort update autodetection: nudge (never block, never fail) when
12
12
  * the kit checkout is behind its upstream. Silent on detached HEADs, no
13
- * upstream, no network, no git. */
14
- const updateNudge = (logger: Logger): void => {
13
+ * upstream, no network, no git. git starts through spawnHost, so a Windows
14
+ * host never runs a `git.exe` from the current directory. */
15
+ export const updateNudge = (logger: Logger): void => {
15
16
  try {
16
17
  const home = kitHome();
17
18
  if (!existsSync(join(home, ".git"))) return;
18
19
  if (
19
- spawnSync("git", ["-C", home, "fetch", "--quiet"], { stdio: "ignore", timeout: 4000 })
20
+ spawnHost("git", ["-C", home, "fetch", "--quiet"], { stdio: "ignore", timeout: 4000 })
20
21
  .status !== 0
21
22
  )
22
23
  return;
23
- const res = spawnSync("git", ["-C", home, "rev-list", "--count", "HEAD..@{u}"], {
24
- encoding: "utf8",
24
+ const res = spawnHost("git", ["-C", home, "rev-list", "--count", "HEAD..@{u}"], {
25
25
  stdio: ["ignore", "pipe", "ignore"],
26
26
  });
27
27
  const behind = (res.stdout ?? "").trim();
@@ -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(