@crewhaus/tool-fleet 0.7.0

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.
package/dist/index.js ADDED
@@ -0,0 +1,1449 @@
1
+ /**
2
+ * @crewhaus/tool-fleet — the harnesses on this machine, as deterministic
3
+ * tools: register them, ask what the queue did, recompile a stale bundle,
4
+ * see which CLI version each one is actually running, and manage the hooks
5
+ * that wrap a start.
6
+ *
7
+ * Five properties hold across the package.
8
+ *
9
+ * 1. THE REAL STORES. The registry file is written by
10
+ * `@crewhaus/harness-registry` and by nothing else here: its atomic
11
+ * tmp+rename, its 0600 mode and its fingerprint-checked
12
+ * read-merge-write retry are what keep two sessions and a running
13
+ * manager from losing each other's rows, and a read-modify-write of
14
+ * `harnesses.json` in this package would defeat all three. Bundle
15
+ * staleness is `@crewhaus/harness-supervisor`'s spec-hash comparison,
16
+ * the recompile is its `compileIfStale`, the hook grammar is its
17
+ * `parseManagerHook`, the job fold is its `createFileJobStore`. Nothing
18
+ * here is a second copy of any of them.
19
+ * 2. AN EMPTY STORE AND AN UNREADABLE ONE ARE DIFFERENT ANSWERS. Every
20
+ * store these tools read answers a file it could not open with an empty
21
+ * result, because each is read on a boot path that must not die on a
22
+ * typo. That is the right posture there and a lie in a report, so each
23
+ * file's CONDITION is probed before anything is concluded from an empty
24
+ * result — and a mutation against a registry or a settings file that
25
+ * could not be parsed is refused, because the next write would heal it
26
+ * wholesale and take every row, group, tag and note with it.
27
+ * 3. A BUNDLE THAT COULD NOT BE JUDGED IS NOT A FRESH BUNDLE. The
28
+ * supervisor recompiles on `stale`; `unknown` and `unstamped` it treats
29
+ * as "not stale" and carries on with `{ ok: true }`. Reported as
30
+ * success, that is how ten of eleven harnesses sat on last month's CLI
31
+ * with every status line green. Here those two states are a THIRD
32
+ * verdict — `undetermined` — and a real recompile on one is refused by
33
+ * name rather than reported as a no-op success.
34
+ * 4. THE IDENTITY KEY IS THE ID, NOT THE PATH. A relocate changes the
35
+ * directory and keeps the `hrn_` id, which inverts the key every other
36
+ * call uses. So an id is validated as an id before it is passed
37
+ * anywhere (the registry silently treats a non-`hrn_` string as a
38
+ * DIRECTORY and resolves it against the working directory), a relocate
39
+ * is looked up by id and verified afterwards to leave exactly one entry
40
+ * carrying it, and a register that finds a row under the other spelling
41
+ * of the same directory refreshes THAT row instead of adding a second
42
+ * one.
43
+ * 5. CONTAINMENT, AND ONE NAMED EXCEPTION. Every path a CALLER supplies
44
+ * goes through `resolveSafe` — the verbatim `@crewhaus/tool-pkg` copy —
45
+ * and so does every leaf underneath it that is actually OPENED, not
46
+ * only the ones a write lands on. The four that matter are named in no
47
+ * schema and are handed back by a library that finds them with
48
+ * `existsSync`, which follows a symlink: `crewhaus.yaml`, the bundle
49
+ * directory with its entry and manifest, `.crewhaus/settings.json` and
50
+ * `.crewhaus/run/hooks.json`. Reading one that leads out of the
51
+ * workspace reports another harness's identity as this one's; the
52
+ * bundle directory is worse, because the recompile WRITES into it.
53
+ * The exception is deliberate and cannot be moved by an input: the two
54
+ * machine-wide files (`<registryRoot>/harnesses.json`,
55
+ * `<hangarRoot>/jobs.jsonl`) are resolved from the environment, because
56
+ * a registry that only ever saw the current workspace would not be a
57
+ * registry. Each is reported, absolute, in every result that read it.
58
+ *
59
+ * WHAT THIS PACKAGE DOES NOT DO. It does not install or switch a CLI version
60
+ * (that is `@crewhaus/chvm` and the npm registry — see `CliVersionPin`), it
61
+ * never starts, stops or cancels anything (the job ledger is read-only here,
62
+ * and no cancel route exists in the store), and it does not execute a hook.
63
+ */
64
+ import { randomBytes } from "node:crypto";
65
+ import { unlinkSync } from "node:fs";
66
+ import * as path from "node:path";
67
+ import { HARNESS_ID_RE, openHangarRegistry, } from "@crewhaus/harness-registry";
68
+ import { MANAGER_HOOK_NAMES, compileIfStale, compileOutDir, createFileJobStore, createProcessOps, hookLogPath, readHookRunLog, readManagerSettings, runPrepareCommand, } from "@crewhaus/harness-supervisor";
69
+ import { buildTool } from "@crewhaus/tool-builder";
70
+ import { z } from "zod";
71
+ import { externalBinRefusal, freshnessOf, readSpecFacts, resolveCli, spawnEnv, } from "./lib/bundle";
72
+ import { countByState, filterJobs, jobView, ledgerBlockedBy, probeLedger, sortJobs, } from "./lib/jobs";
73
+ import { entryView, mutationBlockedBy, probeRegistryFile, sortEntries } from "./lib/registry";
74
+ import { compareStrings, contain, containExistingDir, containUnder, containWritePaths, isInside, json, refusal, renderPath, renderStorePath, renderText, sample, } from "./lib/result";
75
+ import { jobLedgerPath, registryFilePath } from "./lib/roots";
76
+ import { managerBlock, parseDeclaration, probeSettings, settingsAbsPath, settingsRelPath, splitWarning, timeoutView, viewHook, withHook, writeBlockedBy, writeSettingsFile, } from "./lib/settings";
77
+ import { workspaceRoot } from "./paths";
78
+ // ---------------------------------------------------------------------------
79
+ // shared plumbing
80
+ // ---------------------------------------------------------------------------
81
+ /**
82
+ * `dryRun` defaults to TRUE on every mutating action in this package.
83
+ *
84
+ * Uniform on purpose: these tools edit files a running manager also writes,
85
+ * and a caller who has to type `dryRun: false` has been told once, in the
86
+ * schema, what class of call they are making. The preview is produced by the
87
+ * same selection code the real call uses — the same registry lookup, the
88
+ * same staleness verdict, the same parsed hook — never by a parallel
89
+ * description of it.
90
+ */
91
+ const dryRunField = z
92
+ .boolean()
93
+ .optional()
94
+ .describe("report what WOULD happen and change nothing. Defaults to TRUE: a mutating action takes an explicit dryRun:false to act.");
95
+ /** How long a `--version` probe may run before it is killed. */
96
+ const VERSION_PROBE_TIMEOUT_MS = 15_000;
97
+ /** Longest job listing returned in one call, unless the caller lowers it. */
98
+ const DEFAULT_JOB_LIMIT = 100;
99
+ /** Cap on harnesses inspected by one CliVersionPin call. */
100
+ const MAX_FLEET = 500;
101
+ /** Resolve a harness directory that must exist, inside the workspace. */
102
+ function harnessDir(tool, rel) {
103
+ // `findHarnessRoot` is deliberately NOT used to walk up from the given
104
+ // directory: it climbs four levels looking for a spec and would happily
105
+ // land outside the workspace this tool is contained to, which is the one
106
+ // direction containment cannot follow. The directory the caller names IS
107
+ // the harness root, and a missing spec there is its own reported answer.
108
+ return containExistingDir(tool, rel);
109
+ }
110
+ /**
111
+ * Open the machine registry, capturing the warnings it would otherwise
112
+ * swallow.
113
+ *
114
+ * `list()` PERSISTS missing-directory stamps and pre-v2 lifts, and when that
115
+ * write fails (a root-owned `~/.crewhaus`, a read-only home, a full disk) it
116
+ * degrades to an un-persisted view and reports it through `onWarn` — whose
117
+ * default is silence, because the hook path must stay quiet. A tool that
118
+ * drops those warnings tells an operator the registry was updated when it
119
+ * was not.
120
+ */
121
+ function openRegistry(intent) {
122
+ const warnings = [];
123
+ const onWarn = (message) => {
124
+ warnings.push(message);
125
+ };
126
+ // Constructing a handle touches no file, so asking for two is free.
127
+ const live = openHangarRegistry({ onWarn });
128
+ if (intent === "mutate")
129
+ return { registry: live, warnings, writesDisabled: live.disabled };
130
+ // A READ MUST NOT WRITE. `list()` persists missing-directory stamps and a
131
+ // pre-v2 lift, so merely reporting the fleet edits a machine-wide file —
132
+ // and `CliVersionPin` declares `readOnly: true`, which a permission layer
133
+ // acts on. `CREWHAUS_NO_REGISTRY` is the library's OWN opt-out: every
134
+ // write becomes a no-op while the computed view (including the freshly
135
+ // stamped `missingSince`) is identical, so this is that switch rather
136
+ // than a second reader written here.
137
+ const reading = openHangarRegistry({
138
+ onWarn,
139
+ env: { ...process.env, CREWHAUS_NO_REGISTRY: "1" },
140
+ });
141
+ return { registry: reading, warnings, writesDisabled: live.disabled };
142
+ }
143
+ /**
144
+ * Perform a registry WRITE and report a write that could not land.
145
+ *
146
+ * `openHangarRegistry`'s setters THROW when the rename fails — a root-owned
147
+ * `~/.crewhaus`, a read-only home, a full disk — and only `list()` degrades
148
+ * instead (it passes `degradeOnWriteError`). An exception out of `execute`
149
+ * reaches the caller as a bare `EACCES: permission denied, open …` with no
150
+ * tool, no code and, for a multi-field `update`, no word about which of the
151
+ * several setters had already landed. The write itself is still atomic
152
+ * (tmp+rename), so a failure means the document on disk is the one that was
153
+ * there.
154
+ */
155
+ function attempt(fn) {
156
+ try {
157
+ return { ok: true, value: fn() };
158
+ }
159
+ catch (err) {
160
+ return { ok: false, reason: err instanceof Error ? err.message : String(err) };
161
+ }
162
+ }
163
+ /** Refuse a string that is not an `hrn_` id, rather than let it be a path. */
164
+ function idRefusal(tool, given) {
165
+ return refusal(tool, "bad-input", `"${renderPath(given)}" is not a harness id. An id is \`hrn_\` plus 16 hex characters; @crewhaus/harness-registry treats any other string as a DIRECTORY and resolves it against the working directory, so passing one here would quietly act on a different entry — or on none.`);
166
+ }
167
+ /**
168
+ * Both spellings of a contained directory.
169
+ *
170
+ * The registry keys on `resolve(dir)` — lexical, symlinks intact — while
171
+ * containment hands back the real path. On a machine where the workspace is
172
+ * reached through a symlink (macOS `/tmp` → `/private/tmp` is the everyday
173
+ * case) those differ, and a lookup with one spelling misses a row written
174
+ * with the other. Both are tried before concluding a directory is not
175
+ * registered, and both are checked before adding a row that would be the
176
+ * second one for the same directory.
177
+ */
178
+ function spellings(safe) {
179
+ return safe.abs === safe.real ? [safe.real] : [safe.real, safe.abs];
180
+ }
181
+ function findByDir(registry, safe) {
182
+ const found = [];
183
+ for (const spelling of spellings(safe)) {
184
+ const entry = registry.get(spelling);
185
+ if (entry !== undefined && !found.some((e) => e.id === entry.id))
186
+ found.push(entry);
187
+ }
188
+ return found;
189
+ }
190
+ // ---------------------------------------------------------------------------
191
+ // HarnessRegister
192
+ // ---------------------------------------------------------------------------
193
+ const updateFields = {
194
+ groups: z.array(z.string().min(1)).optional().describe("replace the entry's group membership"),
195
+ tags: z.array(z.string().min(1)).optional().describe("replace the entry's tags"),
196
+ pinned: z.boolean().optional().describe("pin the entry so a prune leaves it alone"),
197
+ hidden: z
198
+ .boolean()
199
+ .optional()
200
+ .describe("hide from the manager's default Library view (the entry stays registered)"),
201
+ notes: z.string().max(4000).optional().describe("replace the entry's free-text notes"),
202
+ group: z.string().min(1).optional().describe("with `order`: the group whose boot order to set"),
203
+ order: z
204
+ .number()
205
+ .int()
206
+ .positive()
207
+ .optional()
208
+ .describe("this member's 1-based boot order inside `group`; omit with `group` to clear it"),
209
+ };
210
+ export const harnessRegister = buildTool({
211
+ name: "HarnessRegister",
212
+ description: "Add, remove, relocate, list and annotate the harnesses in this machine's registry (<registryRoot>/harnesses.json, from CREWHAUS_REGISTRY_ROOT or ~/.crewhaus — never a caller-supplied path). Every write goes through @crewhaus/harness-registry's own atomic tmp+rename with its read-merge-write retry, so a concurrent session or a running manager cannot lose your edit or you theirs. A relocate keeps the hrn_ id and changes only the directory, and the result proves it: the tool re-reads the registry and reports how many entries carry that id. It REFUSES to mutate a registry file that exists but did not parse (the library reads it as empty and the next write replaces it), refuses when CREWHAUS_NO_REGISTRY has turned writes into silent no-ops, refuses an `id` that is not an hrn_ id, and refuses to add a second row for a directory already registered under its other spelling. A register reads the harness's crewhaus.yaml for its name and shape and refuses one that a symlink puts outside the workspace, rather than recording another harness's identity. A write that the filesystem refuses is REPORTED, and a multi-field update — which is one atomic write per field — names which fields landed and which did not. dryRun defaults to true.",
213
+ inputSchema: z.object({
214
+ action: z
215
+ .enum(["list", "register", "remove", "relocate", "update"])
216
+ .describe("what to do; `list` is the only one that never writes"),
217
+ dir: z
218
+ .string()
219
+ .optional()
220
+ .describe("for `register`, the harness directory; for `relocate`, the NEW directory. Inside the workspace, and it must exist."),
221
+ id: z.string().optional().describe("the hrn_ id of the entry to act on"),
222
+ from: z
223
+ .string()
224
+ .optional()
225
+ .describe("for `relocate`/`remove`/`update` without an id: the entry's CURRENT directory"),
226
+ specName: z
227
+ .string()
228
+ .min(1)
229
+ .optional()
230
+ .describe("recorded spec name (default: read from the harness's crewhaus.yaml)"),
231
+ target: z
232
+ .string()
233
+ .min(1)
234
+ .optional()
235
+ .describe("recorded shape (default: read from the harness's crewhaus.yaml)"),
236
+ filterGroup: z.string().min(1).optional().describe("`list`: only entries in this group"),
237
+ filterTag: z.string().min(1).optional().describe("`list`: only entries carrying this tag"),
238
+ includeHidden: z
239
+ .boolean()
240
+ .optional()
241
+ .describe("`list`: include entries hidden from the Library view (default true)"),
242
+ ...updateFields,
243
+ dryRun: dryRunField,
244
+ }),
245
+ destructive: true,
246
+ execute: async (input) => {
247
+ const tool = "HarnessRegister";
248
+ const action = input.action;
249
+ const dryRun = input.dryRun ?? true;
250
+ const root = workspaceRoot();
251
+ const file = probeRegistryFile(registryFilePath());
252
+ if (input.id !== undefined && !HARNESS_ID_RE.test(input.id))
253
+ return idRefusal(tool, input.id);
254
+ // `list` gets a handle whose writes are no-ops: the schema calls it "the
255
+ // only one that never writes", and `registry.list()` would otherwise
256
+ // persist missing-directory stamps and a pre-v2 lift on a reporting call.
257
+ const { registry, warnings, writesDisabled } = openRegistry(action === "list" ? "read" : "mutate");
258
+ const base = {
259
+ tool,
260
+ action,
261
+ registryFile: file.path,
262
+ registryFileState: file.state,
263
+ ...(file.detail !== undefined ? { registryFileDetail: file.detail } : {}),
264
+ ...(file.rawHarnessCount !== undefined ? { rawHarnessCount: file.rawHarnessCount } : {}),
265
+ writesDisabled,
266
+ };
267
+ const warned = () => warnings.length > 0 ? { registryWarnings: sample(warnings, 10) } : {};
268
+ if (action === "list") {
269
+ // An unreadable or unparseable registry is NOT an empty one: the
270
+ // library's reader returns an empty document either way, so the file's
271
+ // condition is what decides whether this listing means anything.
272
+ const readable = file.state === "ok" || file.state === "absent";
273
+ const entries = readable ? sortEntries(registry.list()) : [];
274
+ const filtered = entries.filter((entry) => {
275
+ if (input.filterGroup !== undefined && !entry.groups.includes(input.filterGroup)) {
276
+ return false;
277
+ }
278
+ if (input.filterTag !== undefined && !entry.tags.includes(input.filterTag))
279
+ return false;
280
+ if (input.includeHidden === false && entry.hidden)
281
+ return false;
282
+ return true;
283
+ });
284
+ return json({
285
+ ...base,
286
+ status: readable ? "ok" : "unreadable",
287
+ ...(readable
288
+ ? {}
289
+ : {
290
+ reason: `${file.detail ?? file.state} — this is NOT an empty registry, and no entry could be listed`,
291
+ }),
292
+ count: filtered.length,
293
+ entries: filtered.map((entry) => entryView(entry, root)),
294
+ // Groups come out of the same document. Reporting `[]` for a file
295
+ // that could not be read would be the same lie as `count: 0`.
296
+ ...(readable ? { groups: registry.listGroups() } : {}),
297
+ outsideWorkspace: filtered.filter((entry) => !isInside(root, entry.dir)).length,
298
+ ...warned(),
299
+ });
300
+ }
301
+ // Everything below writes. Two gates first, in this order: a registry
302
+ // whose file could not be read must not be "healed" into an empty one,
303
+ // and a disabled registry would compute a perfectly plausible answer and
304
+ // write nothing at all.
305
+ const blocked = mutationBlockedBy(file);
306
+ if (!blocked.ok)
307
+ return refusal(tool, blocked.code, blocked.reason, base);
308
+ if (writesDisabled) {
309
+ return refusal(tool, "unavailable", "CREWHAUS_NO_REGISTRY is set, which turns every registry write into a no-op while reads keep working. The call would have returned an entry that was never persisted.", base);
310
+ }
311
+ if (action === "register") {
312
+ if (input.dir === undefined) {
313
+ return refusal(tool, "bad-input", "`register` needs `dir`", base);
314
+ }
315
+ const safe = harnessDir(tool, input.dir);
316
+ if (!safe.ok)
317
+ return refusal(tool, safe.code, safe.reason, base);
318
+ const existing = findByDir(registry, safe.value);
319
+ if (existing.length > 1) {
320
+ return refusal(tool, "conflict", `this directory is already registered TWICE, under both of its spellings (${existing
321
+ .map((e) => `${e.id} at ${e.dir}`)
322
+ .join(", ")}). Remove one before registering.`, base);
323
+ }
324
+ // Identity facts come from the PARSED spec, not from the directory
325
+ // name: `upsert` defaults specName to `basename(dir)` and target to
326
+ // "unknown", and a fleet table full of those is how a registry stops
327
+ // being worth reading.
328
+ const facts = readSpecFacts(tool, safe.value);
329
+ // A spec that leads OUT of the workspace is refused on its own terms.
330
+ // "Pass specName and target explicitly" is the remedy for a spec that
331
+ // does not parse; it is not the remedy for a symlink, and appending it
332
+ // would read as an offer to register the row anyway.
333
+ if (!facts.ok && facts.code === "refused") {
334
+ return refusal(tool, facts.code, facts.reason, base);
335
+ }
336
+ const specName = input.specName ?? (facts.ok ? facts.value.name : undefined);
337
+ const target = input.target ?? (facts.ok ? facts.value.target : undefined);
338
+ if (specName === undefined || target === undefined) {
339
+ return refusal(tool, facts.ok ? "bad-input" : facts.code, facts.ok
340
+ ? "the spec parsed but carries no name — pass specName and target explicitly"
341
+ : `${facts.reason}. Pass specName and target explicitly to register it anyway.`, base);
342
+ }
343
+ const prior = existing[0];
344
+ // Register under the REAL path, so two spellings of one directory
345
+ // cannot become two rows — but refresh the row that is already there
346
+ // under its own spelling rather than adding a second.
347
+ const dir = prior?.dir ?? safe.value.real;
348
+ if (dryRun) {
349
+ return json({
350
+ ...base,
351
+ status: "preview",
352
+ dryRun: true,
353
+ would: prior === undefined ? "add a new entry" : `refresh ${prior.id}`,
354
+ dir,
355
+ specName,
356
+ target,
357
+ ...(prior !== undefined ? { entry: entryView(prior, root) } : {}),
358
+ nothingWasTouched: true,
359
+ ...warned(),
360
+ });
361
+ }
362
+ const written = attempt(() => registry.upsert({
363
+ dir,
364
+ specName,
365
+ target,
366
+ origin: "manual",
367
+ originDetail: "HarnessRegister",
368
+ }));
369
+ if (!written.ok) {
370
+ return refusal(tool, "unavailable", `the registry could not be written (${renderText(written.reason, 400)}). The write is atomic, so ${file.path} still holds exactly what it held before this call.`, { ...base, ...warned() });
371
+ }
372
+ const entry = written.value;
373
+ // Read back: `upsert` returns the entry it COMPUTED, which is not
374
+ // proof the document on disk carries it.
375
+ const stored = registry.get(entry.id);
376
+ return json({
377
+ ...base,
378
+ status: stored === undefined ? "failed" : "applied",
379
+ dryRun: false,
380
+ created: prior === undefined,
381
+ entry: entryView(stored ?? entry, root),
382
+ persisted: stored !== undefined,
383
+ ...warned(),
384
+ });
385
+ }
386
+ // The remaining three all act on ONE existing entry. Resolve it first —
387
+ // by id when given, else by directory — so the preview and the real call
388
+ // select the same row, and so a relocate acts on an id rather than on
389
+ // the path that is about to change.
390
+ let entry;
391
+ if (input.id !== undefined) {
392
+ entry = registry.get(input.id);
393
+ }
394
+ else if (input.from !== undefined) {
395
+ const safe = contain(tool, input.from);
396
+ if (!safe.ok)
397
+ return refusal(tool, safe.code, safe.reason, base);
398
+ const found = findByDir(registry, safe.value);
399
+ if (found.length > 1) {
400
+ return refusal(tool, "conflict", `two entries point at that directory (${found
401
+ .map((e) => e.id)
402
+ .join(", ")}) — name the one you mean with \`id\``, base);
403
+ }
404
+ entry = found[0];
405
+ }
406
+ else {
407
+ return refusal(tool, "bad-input", `\`${action}\` needs \`id\` or \`from\``, base);
408
+ }
409
+ if (entry === undefined) {
410
+ return refusal(tool, "missing", `no registry entry for ${input.id !== undefined
411
+ ? `id "${renderPath(input.id)}"`
412
+ : `directory "${renderPath(input.from ?? "")}"`}`, base);
413
+ }
414
+ const selectedId = entry.id;
415
+ const selectedDir = entry.dir;
416
+ const selected = entryView(entry, root);
417
+ if (action === "remove") {
418
+ if (dryRun) {
419
+ return json({
420
+ ...base,
421
+ status: "preview",
422
+ dryRun: true,
423
+ would: `remove the registry row ${selectedId} (the directory itself is never touched)`,
424
+ entry: selected,
425
+ nothingWasTouched: true,
426
+ ...warned(),
427
+ });
428
+ }
429
+ // BY ID: the row that was selected, not whatever now answers to the
430
+ // directory that was typed.
431
+ const outcome = attempt(() => registry.remove(selectedId));
432
+ if (!outcome.ok) {
433
+ return refusal(tool, "unavailable", `the registry could not be written (${renderText(outcome.reason, 400)}). The write is atomic, so the row is still there.`, { ...base, entry: selected, ...warned() });
434
+ }
435
+ const removed = outcome.value;
436
+ const after = registry.get(selectedId);
437
+ return json({
438
+ ...base,
439
+ status: removed && after === undefined ? "applied" : "failed",
440
+ dryRun: false,
441
+ removed,
442
+ entry: selected,
443
+ stillPresent: after !== undefined,
444
+ note: "only the registry row was removed; the harness directory and its state are untouched",
445
+ ...warned(),
446
+ });
447
+ }
448
+ if (action === "relocate") {
449
+ if (input.dir === undefined) {
450
+ return refusal(tool, "bad-input", "`relocate` needs `dir` (the new directory)", base);
451
+ }
452
+ const safe = harnessDir(tool, input.dir);
453
+ if (!safe.ok)
454
+ return refusal(tool, safe.code, safe.reason, base);
455
+ const conflicts = findByDir(registry, safe.value).filter((e) => e.id !== selectedId);
456
+ if (conflicts.length > 0) {
457
+ return refusal(tool, "conflict", `"${renderPath(input.dir)}" is already registered as ${conflicts
458
+ .map((e) => e.id)
459
+ .join(", ")} — relocating onto it would need that row removed first`, { ...base, entry: selected });
460
+ }
461
+ const to = safe.value.real;
462
+ if (dryRun) {
463
+ return json({
464
+ ...base,
465
+ status: "preview",
466
+ dryRun: true,
467
+ would: `point ${selectedId} at "${to}", keeping its id, groups, tags and notes`,
468
+ from: selectedDir,
469
+ to,
470
+ entry: selected,
471
+ nothingWasTouched: true,
472
+ ...warned(),
473
+ });
474
+ }
475
+ let moved;
476
+ try {
477
+ moved = registry.relocate(selectedId, to);
478
+ }
479
+ catch (err) {
480
+ return refusal(tool, "conflict", err instanceof Error ? err.message : String(err), {
481
+ ...base,
482
+ entry: selected,
483
+ });
484
+ }
485
+ // The claim this action exists to make, checked against the file: ONE
486
+ // row, still carrying the id, now pointing at the new directory. A
487
+ // registry keyed by path answers a relocate by adding a SECOND entry,
488
+ // and a result built from the return value alone would never see it.
489
+ const all = registry.list();
490
+ const withId = all.filter((e) => e.id === selectedId);
491
+ const atOldDir = all.filter((e) => e.dir === selectedDir && e.id !== selectedId);
492
+ const landed = withId[0];
493
+ return json({
494
+ ...base,
495
+ status: moved !== undefined && withId.length === 1 && landed?.dir === to ? "applied" : "failed",
496
+ dryRun: false,
497
+ from: selectedDir,
498
+ to,
499
+ idPreserved: landed?.id === selectedId,
500
+ entriesWithId: withId.length,
501
+ entriesLeftAtOldDir: atOldDir.length,
502
+ entry: landed !== undefined ? entryView(landed, root) : selected,
503
+ ...warned(),
504
+ });
505
+ }
506
+ // update
507
+ //
508
+ // ONE list, built once: the fields named in the preview, the setters the
509
+ // real call runs and the fields it reports as applied are the same
510
+ // array in the same order, so a preview cannot describe a write the
511
+ // real path does not perform.
512
+ const groups = input.groups;
513
+ const tags = input.tags;
514
+ const pinned = input.pinned;
515
+ const hidden = input.hidden;
516
+ const notes = input.notes;
517
+ const group = input.group;
518
+ const setters = [
519
+ ...(groups !== undefined
520
+ ? [{ field: "groups", run: () => void registry.setGroups(selectedId, groups) }]
521
+ : []),
522
+ ...(tags !== undefined
523
+ ? [{ field: "tags", run: () => void registry.setTags(selectedId, tags) }]
524
+ : []),
525
+ ...(pinned !== undefined
526
+ ? [{ field: "pinned", run: () => void registry.setPinned(selectedId, pinned) }]
527
+ : []),
528
+ ...(hidden !== undefined
529
+ ? [{ field: "hidden", run: () => void registry.setHidden(selectedId, hidden) }]
530
+ : []),
531
+ ...(notes !== undefined
532
+ ? [{ field: "notes", run: () => void registry.setNotes(selectedId, notes) }]
533
+ : []),
534
+ ...(group !== undefined
535
+ ? [
536
+ {
537
+ field: `groupOrder[${group}]`,
538
+ run: () => void registry.setGroupOrder(selectedId, group, input.order),
539
+ },
540
+ ]
541
+ : []),
542
+ ];
543
+ const planned = setters.map((setter) => setter.field);
544
+ if (planned.length === 0) {
545
+ return refusal(tool, "bad-input", "`update` was given nothing to change (groups, tags, pinned, hidden, notes, or group+order)", base);
546
+ }
547
+ if (input.order !== undefined && input.group === undefined) {
548
+ return refusal(tool, "bad-input", "`order` needs the `group` it applies to", base);
549
+ }
550
+ // A membership in a group nobody DEFINED is legal and nearly invisible:
551
+ // the row carries the name, `listGroups` does not, and the manager's
552
+ // Library has no column to show it in. Reported rather than rejected —
553
+ // defining groups is the manager's own verb, not this tool's.
554
+ const definedGroups = new Set(registry.listGroups().map((group) => group.name));
555
+ const undefinedGroups = [
556
+ ...new Set([...(groups ?? []), ...(group !== undefined ? [group] : [])].filter((name) => !definedGroups.has(name))),
557
+ ].sort(compareStrings);
558
+ const groupNote = undefinedGroups.length > 0
559
+ ? {
560
+ groupsNotDefined: undefinedGroups,
561
+ groupsNote: "these names are not defined in the registry's group list, so the entry carries a membership the manager's Library will not show a group for",
562
+ }
563
+ : {};
564
+ if (dryRun) {
565
+ return json({
566
+ ...base,
567
+ status: "preview",
568
+ dryRun: true,
569
+ would: `set ${planned.join(", ")} on ${selectedId}`,
570
+ entry: selected,
571
+ ...groupNote,
572
+ nothingWasTouched: true,
573
+ ...warned(),
574
+ });
575
+ }
576
+ // Each setter is its own atomic read-merge-write. A multi-field update is
577
+ // therefore SEVERAL writes and another writer can land between them —
578
+ // stated here rather than papered over, because the alternative is a
579
+ // second document-level mutation path in this package, which is exactly
580
+ // the thing the registry's own writer exists to prevent.
581
+ //
582
+ // It is also why a failure halfway through has to be REPORTED rather
583
+ // than thrown: with three setters and the second one refused by the
584
+ // filesystem, one field is on disk and two are not, and the caller is
585
+ // the only one who can put that right.
586
+ const appliedFields = [];
587
+ let writeFailure;
588
+ for (const setter of setters) {
589
+ const outcome = attempt(setter.run);
590
+ if (!outcome.ok) {
591
+ writeFailure = { field: setter.field, reason: outcome.reason };
592
+ break;
593
+ }
594
+ appliedFields.push(setter.field);
595
+ }
596
+ const after = registry.get(selectedId);
597
+ if (writeFailure !== undefined) {
598
+ return json({
599
+ ...base,
600
+ status: "failed",
601
+ dryRun: false,
602
+ applied: appliedFields,
603
+ notApplied: planned.slice(appliedFields.length),
604
+ failedAt: writeFailure.field,
605
+ reason: `the registry could not be written (${renderText(writeFailure.reason, 400)}). Each field is its own atomic write, so the ones listed in \`applied\` ARE on disk and the ones in \`notApplied\` are not.`,
606
+ entry: after === undefined ? selected : entryView(after, root),
607
+ ...groupNote,
608
+ ...warned(),
609
+ });
610
+ }
611
+ return json({
612
+ ...base,
613
+ status: after === undefined ? "failed" : "applied",
614
+ dryRun: false,
615
+ applied: appliedFields,
616
+ writes: appliedFields.length,
617
+ entry: after === undefined ? selected : entryView(after, root),
618
+ ...groupNote,
619
+ ...warned(),
620
+ });
621
+ },
622
+ });
623
+ // ---------------------------------------------------------------------------
624
+ // HarnessJobStatus
625
+ // ---------------------------------------------------------------------------
626
+ /**
627
+ * The job states the ledger can hold, so a caller can filter on one.
628
+ *
629
+ * The constant below fails to COMPILE if `JobState` ever gains a member this
630
+ * list does not carry — the only kind of drift guard worth having, one that
631
+ * cannot pass vacuously.
632
+ */
633
+ const JOB_STATES = [
634
+ "pending",
635
+ "running",
636
+ "done",
637
+ "failed",
638
+ "cancelled",
639
+ "interrupted",
640
+ ];
641
+ /** Compile-time proof that `JOB_STATES` covers every `JobState`. */
642
+ export const JOB_STATES_COVER_JOBSTATE = true;
643
+ export const harnessJobStatus = buildTool({
644
+ name: "HarnessJobStatus",
645
+ description: "Read the manager's durable job ledger (<hangarRoot>/jobs.jsonl, from CREWHAUS_HANGAR_ROOT or <registryRoot>/hangar): what was enqueued, what ran, what it exited with, and what is still open. Read-only — the store has no cancel route. The fold is @crewhaus/harness-supervisor's own, which skips a torn trailing line while the manager is appending to it. A ledger that exists but could not be opened is reported as unreadable, never as 'no jobs': the store answers both with an empty list, and that is how an operator concludes a queue is idle while it is running. `interrupted` is a FINAL state — a manager that died mid-job reopens the row as interrupted and never re-runs it — so a job sitting there is waiting for a person, not for the queue.",
646
+ inputSchema: z.object({
647
+ jobId: z.string().min(1).max(200).optional().describe("a single job"),
648
+ dir: z
649
+ .string()
650
+ .optional()
651
+ .describe("only jobs for this harness directory (inside the workspace)"),
652
+ harnessId: z.string().optional().describe("only jobs recorded with this hrn_ id"),
653
+ kind: z.string().min(1).max(100).optional().describe("only this job kind (eval, compile, …)"),
654
+ state: z.enum(JOB_STATES).optional().describe("only jobs in this state"),
655
+ since: z
656
+ .string()
657
+ .min(1)
658
+ .optional()
659
+ .describe("only jobs enqueued at or after this ISO 8601 instant"),
660
+ limit: z
661
+ .number()
662
+ .int()
663
+ .positive()
664
+ .max(1000)
665
+ .optional()
666
+ .describe(`most recent N jobs (default ${DEFAULT_JOB_LIMIT})`),
667
+ }),
668
+ readOnly: true,
669
+ concurrencySafe: true,
670
+ execute: async (input) => {
671
+ const tool = "HarnessJobStatus";
672
+ const ledger = jobLedgerPath();
673
+ const probe = probeLedger(ledger);
674
+ const base = {
675
+ tool,
676
+ ledger: probe.path,
677
+ ledgerState: probe.state,
678
+ ...(probe.bytes !== undefined ? { bytes: probe.bytes } : {}),
679
+ };
680
+ const blocked = ledgerBlockedBy(probe);
681
+ if (!blocked.ok)
682
+ return refusal(tool, blocked.code, blocked.reason, base);
683
+ let harnessDirs;
684
+ if (input.dir !== undefined) {
685
+ const safe = contain(tool, input.dir);
686
+ if (!safe.ok)
687
+ return refusal(tool, safe.code, safe.reason, base);
688
+ // Both spellings: the manager records whichever path it was handed.
689
+ harnessDirs = spellings(safe.value);
690
+ }
691
+ if (input.since !== undefined && Number.isNaN(Date.parse(input.since))) {
692
+ return refusal(tool, "bad-input", `"${renderPath(input.since)}" is not an ISO 8601 instant — filtering on it would have silently kept every record`, base);
693
+ }
694
+ const records = createFileJobStore(ledger).read();
695
+ const { kept, unparsedTimestamps } = filterJobs(records, {
696
+ ...(harnessDirs !== undefined ? { harnessDirs } : {}),
697
+ ...(input.harnessId !== undefined ? { harnessId: input.harnessId } : {}),
698
+ ...(input.jobId !== undefined ? { jobId: input.jobId } : {}),
699
+ ...(input.kind !== undefined ? { kind: input.kind } : {}),
700
+ ...(input.state !== undefined ? { state: input.state } : {}),
701
+ ...(input.since !== undefined ? { sinceIso: input.since } : {}),
702
+ });
703
+ const ordered = sortJobs(kept);
704
+ const limit = input.limit ?? DEFAULT_JOB_LIMIT;
705
+ return json({
706
+ ...base,
707
+ status: "ok",
708
+ // Three different questions: how many records the fold produced, how
709
+ // many survived the filter, how many are shown.
710
+ recordsInLedger: records.length,
711
+ matched: ordered.length,
712
+ shown: Math.min(ordered.length, limit),
713
+ countsByState: countByState(ordered),
714
+ ...(probe.state === "ok" && records.length === 0
715
+ ? {
716
+ note: "the ledger file is there but folded to NO records — every line was empty or unparseable, which is not the same as a manager that has run nothing",
717
+ }
718
+ : {}),
719
+ ...(unparsedTimestamps.length > 0
720
+ ? {
721
+ unparsedTimestamps: sample(unparsedTimestamps, 20),
722
+ timestampNote: "these records were KEPT despite an enqueuedAt that does not parse — a malformed field must not hide a job from a status listing",
723
+ }
724
+ : {}),
725
+ jobs: ordered.slice(0, limit).map(jobView),
726
+ });
727
+ },
728
+ });
729
+ // ---------------------------------------------------------------------------
730
+ // CompileBundle
731
+ // ---------------------------------------------------------------------------
732
+ export const compileBundle = buildTool({
733
+ name: "CompileBundle",
734
+ description: "Compare a harness's compiled bundle against its spec with @crewhaus/harness-supervisor's spec-hash stamp — the exact comparison the manager gates a start on — and recompile it when it is stale, by running the same `crewhaus compile` (plus `bun install` in the bundle) that `daemon start --compile` runs. THREE verdicts, not two: fresh, stale, and UNDETERMINED. A bundle with no stamp and no usable mtimes, or one whose spec cannot be read or parsed, is undetermined — the supervisor treats that as 'not stale' and carries on, so a tool that reported its success as 'the bundle is current' is exactly how a fleet ends up running last month's CLI with every line green. A real run on an undetermined verdict is refused, with the command that fixes it. The compile spawns with a minimal environment (no .env chain) and, afterwards, the freshness is re-read and reported: a compile that exited 0 and left the bundle stale says so. Every file it opens is contained, including the ones the supervisor's own locators hand back — a crewhaus.yaml or a bundle directory that a symlink puts outside the workspace is refused in the preview and in the real call alike, because the recompile writes into that directory. dryRun defaults to true.",
735
+ inputSchema: z.object({
736
+ dir: z
737
+ .string()
738
+ .optional()
739
+ .describe("the harness root — the directory holding crewhaus.yaml (default: .)"),
740
+ target: z
741
+ .string()
742
+ .min(1)
743
+ .optional()
744
+ .describe("the shape, when the spec cannot be parsed to supply it"),
745
+ allowExternalCli: z
746
+ .boolean()
747
+ .optional()
748
+ .describe("run a `crewhaus` binary that resolves outside the workspace (a globally installed CLI on PATH)"),
749
+ forwardEnv: z
750
+ .array(z.string().min(1).max(200))
751
+ .max(50)
752
+ .optional()
753
+ .describe("extra environment variable NAMES to forward to the compile (values come from this process; nothing else is forwarded)"),
754
+ dryRun: dryRunField,
755
+ }),
756
+ destructive: true,
757
+ scope: "external",
758
+ ioCapability: "process",
759
+ execute: async (input) => {
760
+ const tool = "CompileBundle";
761
+ const dryRun = input.dryRun ?? true;
762
+ const root = workspaceRoot();
763
+ const safe = harnessDir(tool, input.dir ?? ".");
764
+ if (!safe.ok)
765
+ return refusal(tool, safe.code, safe.reason);
766
+ const harness = safe.value.real;
767
+ const shownDir = safe.value.rel === "" ? "." : safe.value.rel;
768
+ const facts = readSpecFacts(tool, safe.value);
769
+ // A spec that leads OUT of the workspace is not a spec this tool reads,
770
+ // and it is also the file a recompile would hand to the CLI.
771
+ if (!facts.ok && facts.code === "refused")
772
+ return refusal(tool, facts.code, facts.reason);
773
+ const target = input.target ?? (facts.ok ? facts.value.target : undefined);
774
+ if (target === undefined) {
775
+ // No target ⇒ no entry file ⇒ the freshness question cannot even be
776
+ // ASKED. Reported as undetermined, never as "no bundle", never as fresh.
777
+ return json({
778
+ tool,
779
+ status: "undetermined",
780
+ harnessDir: shownDir,
781
+ verdict: "undetermined",
782
+ reason: facts.ok ? "the spec carries no target" : facts.reason,
783
+ remedy: "fix the spec, or pass `target` explicitly to check the bundle without it. An undetermined bundle is NOT a fresh one.",
784
+ });
785
+ }
786
+ // ONE GATE, before the dryRun branch, so the preview and the real call
787
+ // refuse a spec or a bundle directory that leads out of the workspace
788
+ // identically — and so nothing below can open one.
789
+ const judged = freshnessOf(tool, safe.value, target);
790
+ if (!judged.ok)
791
+ return refusal(tool, judged.code, judged.reason, { tool, harnessDir: shownDir });
792
+ const fresh = judged.value.freshness;
793
+ const located = judged.value.bundle;
794
+ const cli = resolveCli(harness, root);
795
+ // `compileOutDir` is the supervisor's own choice of `-o` and is what
796
+ // `compileIfStale` will use; `containedBundle` has already proved that
797
+ // name does not lead out of the workspace.
798
+ const outDir = compileOutDir(harness, target);
799
+ const view = {
800
+ tool,
801
+ harnessDir: shownDir,
802
+ target,
803
+ targetFrom: input.target !== undefined ? "input" : "spec",
804
+ ...(facts.ok ? { specPath: path.relative(root, facts.value.specPath) } : {}),
805
+ verdict: fresh.verdict,
806
+ freshness: fresh.state,
807
+ exact: fresh.exact,
808
+ label: fresh.label,
809
+ ...(fresh.compiledWith !== undefined ? { compiledWith: fresh.compiledWith } : {}),
810
+ bundleDir: located === undefined ? null : path.relative(root, located.bundleDir),
811
+ outDir,
812
+ cli: cli === undefined
813
+ ? { resolved: false }
814
+ : { resolved: true, bin: cli.bin, where: cli.where, inWorkspace: cli.inWorkspace },
815
+ };
816
+ if (dryRun) {
817
+ return json({
818
+ ...view,
819
+ status: "preview",
820
+ dryRun: true,
821
+ wouldRecompile: fresh.wouldRecompile,
822
+ ...(fresh.verdict === "undetermined"
823
+ ? {
824
+ wouldRefuse: "a real run refuses an undetermined verdict: compileIfStale recompiles only on `stale`/`approximate-stale`, so it would have reported success and compiled nothing",
825
+ }
826
+ : {}),
827
+ nothingWasTouched: true,
828
+ });
829
+ }
830
+ if (fresh.verdict === "undetermined") {
831
+ return refusal(tool, "refused", `the bundle's staleness could not be determined (${fresh.state}: ${fresh.label}), and an undetermined bundle is not a fresh one. compileIfStale recompiles only on a STALE verdict, so this call would have reported success while compiling nothing. Compile it explicitly — \`crewhaus compile <spec> -o ${outDir}\` from the harness directory — then run this again for an exact answer.`, view);
832
+ }
833
+ if (fresh.verdict === "fresh") {
834
+ return json({
835
+ ...view,
836
+ status: "unchanged",
837
+ dryRun: false,
838
+ compiled: false,
839
+ note: fresh.exact
840
+ ? "the bundle's spec-hash stamp matches the spec"
841
+ : "no spec-hash stamp: this is the mtime heuristic, so `fresh` means 'nothing suggests otherwise', not 'proven identical'",
842
+ });
843
+ }
844
+ if (cli === undefined) {
845
+ return refusal(tool, "unavailable", "the bundle is stale and no `crewhaus` CLI resolves (harness node_modules/.bin, then PATH), so it cannot be recompiled here", view);
846
+ }
847
+ const external = externalBinRefusal(cli, input.allowExternalCli === true);
848
+ if (external !== undefined)
849
+ return refusal(tool, "refused", external.reason, view);
850
+ // NOTE ON THE WRITE. `compileIfStale` runs `crewhaus compile … -o
851
+ // <outDir>` with the harness as its cwd and then `bun install --cwd
852
+ // <outDir>`: two child processes writing into a name this tool resolved
853
+ // but does not own, and a symlinked `dist` sends both of them out of the
854
+ // workspace with nothing downstream able to take that back. The gate for
855
+ // that is `containedBundle` ABOVE — it runs before the dryRun branch, so
856
+ // the preview and the real call refuse identically, and it contains the
857
+ // out dir, the entry and the manifest, which is every name either child
858
+ // replaces. A second check here would be a strict subset of it: a guard
859
+ // that cannot fire reads as protection and is not any.
860
+ const { env, forwarded } = spawnEnv(input.forwardEnv ?? []);
861
+ let outcome;
862
+ try {
863
+ outcome = await compileIfStale({
864
+ harnessDir: harness,
865
+ target,
866
+ ops: createProcessOps(),
867
+ env,
868
+ crewhausBin: cli.bin,
869
+ // The operator's own timeout, when this harness declares one.
870
+ settings: readManagerSettings(harness),
871
+ });
872
+ }
873
+ catch (err) {
874
+ // `spawn` can throw synchronously (an unusable cwd, an argv the OS
875
+ // refuses). A tool that lets that escape returns a stack trace where a
876
+ // caller expects a result, and says nothing about the bundle.
877
+ return refusal(tool, "unavailable", `the compile could not be launched: ${err instanceof Error ? err.message : String(err)}`, { ...view, envForwarded: forwarded });
878
+ }
879
+ // Re-read the verdict FROM DISK. The exit code says the command
880
+ // succeeded; only the stamp says the bundle now matches the spec, and a
881
+ // compile that wrote somewhere else exits 0 all the same. A compile that
882
+ // replaced `dist` with a symlink out of the workspace fails the gate on
883
+ // the way back, which is reported rather than followed.
884
+ const judgedAfter = freshnessOf(tool, safe.value, target);
885
+ const after = judgedAfter.ok
886
+ ? judgedAfter.value.freshness
887
+ : {
888
+ state: "unknown",
889
+ verdict: "undetermined",
890
+ exact: false,
891
+ label: judgedAfter.reason,
892
+ wouldRecompile: false,
893
+ };
894
+ if (!outcome.ok) {
895
+ return json({
896
+ ...view,
897
+ status: "failed",
898
+ dryRun: false,
899
+ compiled: false,
900
+ stage: outcome.refusal.stage,
901
+ reason: outcome.refusal.message,
902
+ ...(outcome.refusal.exitCode !== undefined ? { exitCode: outcome.refusal.exitCode } : {}),
903
+ // A line a spawned binary printed is text this package did not write.
904
+ output: sample(outcome.refusal.output.map((line) => renderText(line, 400)), 40),
905
+ after: { verdict: after.verdict, freshness: after.state, label: after.label },
906
+ envForwarded: forwarded,
907
+ });
908
+ }
909
+ const compiled = outcome.replan;
910
+ return json({
911
+ ...view,
912
+ status: after.verdict !== "fresh" ? "incomplete" : compiled ? "applied" : "unchanged",
913
+ dryRun: false,
914
+ compiled,
915
+ notes: outcome.notes,
916
+ after: {
917
+ verdict: after.verdict,
918
+ freshness: after.state,
919
+ exact: after.exact,
920
+ label: after.label,
921
+ ...(after.compiledWith !== undefined ? { compiledWith: after.compiledWith } : {}),
922
+ },
923
+ // A prediction that did not come true has TWO explanations, and they
924
+ // are not the same news. If the bundle is fresh now and nothing was
925
+ // compiled, somebody else compiled it between this tool's verdict and
926
+ // `compileIfStale`'s own — a race, not a defect. Only a bundle that is
927
+ // still not fresh means the mirrored stale-state set has drifted from
928
+ // the library's.
929
+ ...(compiled
930
+ ? {}
931
+ : after.verdict === "fresh"
932
+ ? {
933
+ raced: "this tool judged the bundle stale and compileIfStale found it fresh, so nothing was compiled — another writer compiled it between the two reads. The bundle on disk matches the spec.",
934
+ }
935
+ : {
936
+ disagreement: "this tool predicted a recompile and compileIfStale reported none, and the bundle is still not fresh — the two stale-state sets have drifted apart",
937
+ }),
938
+ ...(after.verdict !== "fresh"
939
+ ? {
940
+ stillNotFresh: "the compile reported success and the bundle is STILL not fresh — check that it wrote to the directory the bundle is resolved from",
941
+ }
942
+ : {}),
943
+ envForwarded: forwarded,
944
+ });
945
+ },
946
+ });
947
+ /** A semver-shaped token, wherever a CLI prints it. */
948
+ const VERSION_RE = /\b\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?\b/;
949
+ export const cliVersionPin = buildTool({
950
+ name: "CliVersionPin",
951
+ description: "Show which crewhaus CLI each harness would run and which version its bundle was COMPILED WITH, and roll the fleet up by version so a harness left behind on an old CLI is visible. The harnesses come from this machine's registry unless directories are given; the compiledWith stamp is @crewhaus/harness-supervisor's, the binary is its resolver's (harness node_modules/.bin first, then PATH). This tool does NOT install, switch or pin a version — that is @crewhaus/chvm talking to the npm registry, and this package has neither the dependency nor a network call — so the result names the command instead of pretending. With probe:true it runs `<bin> --version` once per DISTINCT binary, with a timeout, and only for a binary inside the workspace unless allowExternalCli is set. A version it could not read is reported as unknown WITH the reason, never as agreeing with the others. It writes NOTHING: the registry is enumerated through @crewhaus/harness-registry's own CREWHAUS_NO_REGISTRY switch, so the missing-directory stamps a plain list() would persist are computed and reported but not written. At most 500 harnesses are inspected; past that the result carries truncated:true and every count describes that subset rather than the fleet. A spec or bundle that a symlink puts outside the workspace is reported as undetermined with the reason, never opened.",
952
+ inputSchema: z.object({
953
+ dirs: z
954
+ .array(z.string())
955
+ .max(MAX_FLEET)
956
+ .optional()
957
+ .describe("harness directories to inspect; omitted, the machine registry supplies them"),
958
+ probe: z
959
+ .boolean()
960
+ .optional()
961
+ .describe("run `<bin> --version` once per distinct binary (default false)"),
962
+ allowExternalCli: z
963
+ .boolean()
964
+ .optional()
965
+ .describe("allow probing a binary that resolves outside the workspace"),
966
+ includeMissing: z
967
+ .boolean()
968
+ .optional()
969
+ .describe("include registry entries whose directory has vanished (default false)"),
970
+ }),
971
+ readOnly: true,
972
+ scope: "external",
973
+ ioCapability: "process",
974
+ execute: async (input) => {
975
+ const tool = "CliVersionPin";
976
+ const root = workspaceRoot();
977
+ const file = probeRegistryFile(registryFilePath());
978
+ const skipped = [];
979
+ const selected = [];
980
+ let source;
981
+ /** True when the cap stopped the enumeration before the registry was
982
+ * exhausted — so every number below describes a PART of the fleet. */
983
+ let truncated = false;
984
+ let registryRows;
985
+ // Keyed by the REAL path: two spellings of one harness (a symlink, a
986
+ // trailing slash, the same row twice) must not be inspected — or
987
+ // counted in the version roll-up — twice.
988
+ const already = new Set();
989
+ const take = (safe) => {
990
+ if (already.has(safe.real))
991
+ return;
992
+ already.add(safe.real);
993
+ selected.push(safe);
994
+ };
995
+ if (input.dirs !== undefined) {
996
+ source = "input";
997
+ for (const rel of input.dirs) {
998
+ const safe = harnessDir(tool, rel);
999
+ if (!safe.ok) {
1000
+ skipped.push({ dir: renderPath(rel), reason: safe.reason });
1001
+ continue;
1002
+ }
1003
+ take(safe.value);
1004
+ }
1005
+ }
1006
+ else {
1007
+ source = "registry";
1008
+ if (file.state !== "ok" && file.state !== "absent") {
1009
+ return refusal(tool, "unreadable", `${file.path}: ${file.detail ?? file.state} — the fleet could not be enumerated. An unreadable registry is not an empty one; pass \`dirs\` to inspect harnesses directly.`, { tool, registryFile: file.path, registryFileState: file.state });
1010
+ }
1011
+ // A READ, so the handle's writes are no-ops: this tool declares
1012
+ // `readOnly: true`, and `list()` would otherwise persist its own
1013
+ // missing-directory stamps into a machine-wide file.
1014
+ const { registry } = openRegistry("read");
1015
+ const rows = sortEntries(registry.list());
1016
+ registryRows = rows.length;
1017
+ for (const entry of rows) {
1018
+ if (selected.length >= MAX_FLEET) {
1019
+ // A cap that silently stops is a roll-up computed over part of the
1020
+ // fleet and reported as the fleet: `mixedFleet: false` for a fleet
1021
+ // whose 501st harness is the one on the old CLI. Say so.
1022
+ truncated = true;
1023
+ break;
1024
+ }
1025
+ if (entry.missingSince !== null && input.includeMissing !== true) {
1026
+ skipped.push({
1027
+ dir: renderStorePath(entry.dir),
1028
+ reason: `missing since ${renderText(entry.missingSince, 64)}`,
1029
+ });
1030
+ continue;
1031
+ }
1032
+ // A path a STORE handed back is not a path a caller contained. The
1033
+ // registry is machine-wide, so plenty of its rows legitimately point
1034
+ // outside this workspace — and this tool OPENS specs and bundles, so
1035
+ // those rows are reported and not touched.
1036
+ const safe = containExistingDir(tool, path.relative(root, entry.dir) || ".");
1037
+ if (!safe.ok) {
1038
+ skipped.push({
1039
+ dir: renderStorePath(entry.dir),
1040
+ reason: safe.code === "refused" ? "outside the workspace root — not inspected" : safe.reason,
1041
+ });
1042
+ continue;
1043
+ }
1044
+ take(safe.value);
1045
+ }
1046
+ }
1047
+ selected.sort((a, b) => compareStrings(a.real, b.real));
1048
+ const inspected = selected.map((safe) => {
1049
+ const rel = safe.rel === "" ? "." : safe.rel;
1050
+ const cli = resolveCli(safe.real, root);
1051
+ const cliField = cli === undefined
1052
+ ? {}
1053
+ : { cli: { bin: cli.bin, where: cli.where, inWorkspace: cli.inWorkspace } };
1054
+ const facts = readSpecFacts(tool, safe);
1055
+ if (!facts.ok) {
1056
+ // No target, so no bundle question can be asked — which is not the
1057
+ // same as a bundle that is up to date. A spec that leads out of the
1058
+ // workspace lands here too, with its own reason.
1059
+ return {
1060
+ safe,
1061
+ cli,
1062
+ row: {
1063
+ dir: rel,
1064
+ verdict: "undetermined",
1065
+ note: facts.reason,
1066
+ ...cliField,
1067
+ },
1068
+ };
1069
+ }
1070
+ const judged = freshnessOf(tool, safe, facts.value.target);
1071
+ if (!judged.ok) {
1072
+ return {
1073
+ safe,
1074
+ cli,
1075
+ row: {
1076
+ dir: rel,
1077
+ ...(facts.value.name !== undefined ? { specName: facts.value.name } : {}),
1078
+ target: facts.value.target,
1079
+ verdict: "undetermined",
1080
+ note: judged.reason,
1081
+ ...cliField,
1082
+ },
1083
+ };
1084
+ }
1085
+ const fresh = judged.value.freshness;
1086
+ return {
1087
+ safe,
1088
+ cli,
1089
+ row: {
1090
+ dir: rel,
1091
+ ...(facts.value.name !== undefined ? { specName: facts.value.name } : {}),
1092
+ target: facts.value.target,
1093
+ verdict: fresh.verdict,
1094
+ freshness: fresh.state,
1095
+ // Already bounded and printable by `classify` — it is also the key
1096
+ // the roll-up below is grouped by.
1097
+ ...(fresh.compiledWith !== undefined ? { compiledWith: fresh.compiledWith } : {}),
1098
+ ...cliField,
1099
+ },
1100
+ };
1101
+ });
1102
+ // One probe per DISTINCT binary: a fleet of thirty harnesses sharing one
1103
+ // CLI is one spawn, not thirty.
1104
+ const probes = {};
1105
+ if (input.probe === true) {
1106
+ const seen = new Map();
1107
+ for (const item of inspected) {
1108
+ if (item.cli !== undefined && !seen.has(item.cli.bin))
1109
+ seen.set(item.cli.bin, item);
1110
+ }
1111
+ for (const bin of [...seen.keys()].sort(compareStrings)) {
1112
+ const item = seen.get(bin);
1113
+ if (item?.cli === undefined)
1114
+ continue;
1115
+ const external = externalBinRefusal(item.cli, input.allowExternalCli === true);
1116
+ if (external !== undefined) {
1117
+ probes[bin] = { state: "not-probed", reason: external.reason };
1118
+ continue;
1119
+ }
1120
+ let outcome;
1121
+ try {
1122
+ outcome = await runPrepareCommand({
1123
+ argv: [bin, "--version"],
1124
+ cwd: item.safe.real,
1125
+ env: spawnEnv().env,
1126
+ ops: createProcessOps(),
1127
+ timeoutMs: VERSION_PROBE_TIMEOUT_MS,
1128
+ });
1129
+ }
1130
+ catch (err) {
1131
+ probes[bin] = {
1132
+ state: "unknown",
1133
+ reason: `could not be launched: ${err instanceof Error ? err.message : String(err)}`,
1134
+ };
1135
+ continue;
1136
+ }
1137
+ if (outcome.timedOut) {
1138
+ probes[bin] = {
1139
+ state: "unknown",
1140
+ reason: `the probe was killed after ${VERSION_PROBE_TIMEOUT_MS} ms`,
1141
+ };
1142
+ continue;
1143
+ }
1144
+ if (outcome.exitCode !== 0) {
1145
+ // `exitCode: null` is not an exit code: the adapter resolves a
1146
+ // FAILED SPAWN that way too (a file without the execute bit, a
1147
+ // broken interpreter line), so it must not be reported as one.
1148
+ probes[bin] = {
1149
+ state: "unknown",
1150
+ reason: outcome.exitCode === null
1151
+ ? `it never exited normally — the spawn failed, or it was killed by ${outcome.signal ?? "a signal"}`
1152
+ : `exited ${outcome.exitCode}`,
1153
+ output: sample(outcome.output.map((line) => renderText(line, 400)), 5),
1154
+ };
1155
+ continue;
1156
+ }
1157
+ // PARSE, then report the PARSED value. A line that carries no
1158
+ // version is not a version, and echoing the raw line as one is how a
1159
+ // startup banner ends up in a version table.
1160
+ const matched = VERSION_RE.exec(outcome.output.join("\n"));
1161
+ probes[bin] =
1162
+ matched === null
1163
+ ? {
1164
+ state: "unparsed",
1165
+ reason: "the output carried no semver-shaped token",
1166
+ output: sample(outcome.output.map((line) => renderText(line, 400)), 5),
1167
+ }
1168
+ : { state: "known", version: matched[0] };
1169
+ }
1170
+ }
1171
+ const inspectedRows = inspected.map((item) => item.row);
1172
+ const byVersion = new Map();
1173
+ for (const row of inspectedRows) {
1174
+ // The KEY is a string a bundle's own `package.json` supplied. Bounded
1175
+ // and printable before it becomes a field name in a statistic a reader
1176
+ // acts on — an unbounded one spends the whole context, and a newline
1177
+ // in it ends the line the roll-up is printed on.
1178
+ const key = row.compiledWith ?? "unstamped-or-undetermined";
1179
+ byVersion.set(key, (byVersion.get(key) ?? 0) + 1);
1180
+ }
1181
+ const stamped = [...byVersion.keys()].filter((k) => k !== "unstamped-or-undetermined");
1182
+ return json({
1183
+ tool,
1184
+ status: "ok",
1185
+ source,
1186
+ registryFile: file.path,
1187
+ registryFileState: file.state,
1188
+ count: inspectedRows.length,
1189
+ ...(registryRows !== undefined ? { registryRows } : {}),
1190
+ truncated,
1191
+ ...(truncated
1192
+ ? {
1193
+ truncatedNote: `the registry holds more than ${MAX_FLEET} harnesses; only the first ${MAX_FLEET} by directory were inspected, so every count and the mixedFleet verdict below describe THAT subset and not the fleet`,
1194
+ }
1195
+ : {}),
1196
+ harnesses: inspectedRows,
1197
+ compiledWith: Object.fromEntries([...byVersion.entries()].sort((a, b) => compareStrings(a[0], b[0]))),
1198
+ distinctCompiledWith: stamped.length,
1199
+ mixedFleet: stamped.length > 1,
1200
+ undetermined: inspectedRows.filter((r) => r.verdict === "undetermined").length,
1201
+ distinctCli: [...new Set(inspectedRows.map((r) => r.cli?.bin ?? "none"))].sort(compareStrings),
1202
+ ...(Object.keys(probes).length > 0 ? { probes } : {}),
1203
+ ...(skipped.length > 0 ? { skipped: sample(skipped, 20) } : {}),
1204
+ cannotDo: [
1205
+ {
1206
+ op: "install / use / pin a CLI version",
1207
+ reason: "that is @crewhaus/chvm talking to registry.npmjs.org; this package has neither the dependency nor a network call",
1208
+ instead: "chvm install <version> && chvm use <version>",
1209
+ },
1210
+ ],
1211
+ });
1212
+ },
1213
+ });
1214
+ // ---------------------------------------------------------------------------
1215
+ // HooksManage
1216
+ // ---------------------------------------------------------------------------
1217
+ export const hooksManage = buildTool({
1218
+ name: "HooksManage",
1219
+ description: "List, set and remove the MANAGER hooks in a harness's .crewhaus/settings.json — the postCompile and preSpawn steps @crewhaus/harness-supervisor runs between a compile and a spawn — and report what each declaration actually PARSES to. It never executes a hook. The grammar is the supervisor's: a string is ONE command with no arguments (deliberately never word-split), an array is an argv vector — so \"bun run prep.ts\" declares a command whose FILENAME contains spaces and will refuse every start with ENOENT, and that shape is refused here with the array form spelled out. A command that resolves to a path is probed for existence and the execute bit; a bare name is reported as resolved by the OS at spawn time rather than guessed at. A command that is a directory or a dangling symlink is `not-executable`/`absent` rather than executable, because access(X_OK) says yes to a directory and a hook that cannot spawn refuses every start. Writes preserve every other key in the file (the runtime's own hooks and permissions blocks live there too), are atomic, keep the file's mode, and are refused outright when the existing file does not parse. The settings file and the hook run log are contained before they are READ, so a symlinked .crewhaus/settings.json is refused — on `list` too — instead of reporting another file's hooks as this harness's. After a write the file is re-read THROUGH the supervisor's own reader and the result says whether the hook came back as the argv you asked for. dryRun defaults to true.",
1220
+ inputSchema: z.object({
1221
+ action: z.enum(["list", "set", "remove"]).describe("`list` never writes"),
1222
+ dir: z
1223
+ .string()
1224
+ .optional()
1225
+ .describe("the harness root — the directory holding .crewhaus/ (default: .)"),
1226
+ hook: z.enum(MANAGER_HOOK_NAMES).optional().describe("which hook `set`/`remove` acts on"),
1227
+ command: z
1228
+ .union([z.string().min(1).max(4000), z.array(z.string().min(1).max(4000)).min(1).max(64)])
1229
+ .optional()
1230
+ .describe("the declaration: a bare command name, or an argv array (the form with arguments)"),
1231
+ timeoutMs: z
1232
+ .number()
1233
+ .int()
1234
+ .positive()
1235
+ .max(3_600_000)
1236
+ .optional()
1237
+ .describe("how long any hook in this harness may run before it is killed and refused"),
1238
+ allowMissingCommand: z
1239
+ .boolean()
1240
+ .optional()
1241
+ .describe("write a hook whose command does not exist or is not executable"),
1242
+ dryRun: dryRunField,
1243
+ }),
1244
+ destructive: true,
1245
+ execute: async (input) => {
1246
+ const tool = "HooksManage";
1247
+ const dryRun = input.dryRun ?? true;
1248
+ const safe = harnessDir(tool, input.dir ?? ".");
1249
+ if (!safe.ok)
1250
+ return refusal(tool, safe.code, safe.reason);
1251
+ const harness = safe.value.real;
1252
+ const rel = settingsRelPath();
1253
+ const abs = settingsAbsPath(harness);
1254
+ const shownDir = safe.value.rel === "" ? "." : safe.value.rel;
1255
+ const shown = path.posix.join(shownDir, rel);
1256
+ // CONTAIN THE LEAVES BEFORE READING THEM, not only before writing them.
1257
+ // `readManagerSettings` and `readHookRunLog` open these two names with
1258
+ // no boundary of their own, and `<harness>/.crewhaus/settings.json ->
1259
+ // /elsewhere/settings.json` is read straight through: another harness's
1260
+ // hooks — or any JSON on the disk — come back reported as THIS harness's
1261
+ // configuration, and a file that is not JSON comes back as a parser
1262
+ // message quoting its contents. `@crewhaus/tool-crewhaus` refuses the
1263
+ // same shape for a symlinked `crewhaus.yaml`; this is that refusal, and
1264
+ // it applies to `list` too, because reading is the escape.
1265
+ //
1266
+ // The hook-log leaf is derived from the supervisor's OWN `hookLogPath`,
1267
+ // never from a second spelling of `.crewhaus/run/hooks.json` written
1268
+ // here — a mirrored path convention is the drift this package avoids.
1269
+ const hookLogRel = path.relative(harness, hookLogPath(harness)).split(path.sep).join("/");
1270
+ for (const leaf of [rel, hookLogRel]) {
1271
+ const contained = containUnder(tool, safe.value, leaf);
1272
+ if (!contained.ok) {
1273
+ return refusal(tool, contained.code, contained.reason, {
1274
+ tool,
1275
+ harnessDir: shownDir,
1276
+ settingsFile: shown,
1277
+ });
1278
+ }
1279
+ }
1280
+ const probe = probeSettings(abs, shown);
1281
+ const settings = readManagerSettings(harness);
1282
+ const lastRuns = readHookRunLog(harness);
1283
+ const declared = MANAGER_HOOK_NAMES.map((name) => {
1284
+ const hook = settings.hooks[name];
1285
+ const run = lastRuns[name];
1286
+ return hook === undefined
1287
+ ? { name, declared: false, ...(run !== undefined ? { lastRun: run } : {}) }
1288
+ : {
1289
+ declared: true,
1290
+ ...viewHook(name, hook, harness),
1291
+ ...(run !== undefined ? { lastRun: run } : {}),
1292
+ };
1293
+ });
1294
+ const base = {
1295
+ tool,
1296
+ harnessDir: shownDir,
1297
+ settingsFile: shown,
1298
+ settingsState: probe.state,
1299
+ ...(probe.detail !== undefined ? { settingsDetail: probe.detail } : {}),
1300
+ };
1301
+ if (input.action === "list") {
1302
+ const usable = probe.state === "ok" || probe.state === "absent";
1303
+ return json({
1304
+ ...base,
1305
+ status: usable ? "ok" : "unreadable",
1306
+ ...(usable
1307
+ ? {}
1308
+ : {
1309
+ reason: "@crewhaus/harness-supervisor's reader answers an unusable settings file with its DEFAULTS, so what follows is the defaults — NOT what the file says",
1310
+ }),
1311
+ hooks: declared,
1312
+ timeout: timeoutView(settings.hooks.timeoutMs),
1313
+ autoCompile: settings.autoCompile,
1314
+ envFiles: settings.envFiles,
1315
+ hookRunLog: path.relative(workspaceRoot(), hookLogPath(harness)),
1316
+ });
1317
+ }
1318
+ if (input.hook === undefined) {
1319
+ return refusal(tool, "bad-input", `\`${input.action}\` needs \`hook\``, base);
1320
+ }
1321
+ const name = input.hook;
1322
+ const blocked = writeBlockedBy(probe);
1323
+ if (!blocked.ok)
1324
+ return refusal(tool, blocked.code, blocked.reason, base);
1325
+ // THE WRITE GATE, re-checked at the last moment before the rename. The
1326
+ // read gate above will normally have refused a settings.json that leads
1327
+ // out already; this one covers the TEMP NAME the atomic replace renames
1328
+ // FROM — which the read gate never sees — and re-validates the
1329
+ // destination after all the parsing work above, because a rename
1330
+ // replaces whatever the name points at by then.
1331
+ const tmpRel = `${rel}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
1332
+ const escapes = containWritePaths(tool, safe.value, [rel, tmpRel]);
1333
+ if (escapes !== undefined)
1334
+ return refusal(tool, escapes.code, escapes.reason, base);
1335
+ const tmpAbs = path.join(harness, ...tmpRel.split("/"));
1336
+ const doc = probe.doc ?? {};
1337
+ const manager = managerBlock(doc);
1338
+ if (!manager.ok)
1339
+ return refusal(tool, manager.code, manager.reason, base);
1340
+ const current = settings.hooks[name];
1341
+ let nextDoc;
1342
+ let intended;
1343
+ let plan;
1344
+ if (input.action === "set") {
1345
+ if (input.command === undefined) {
1346
+ return refusal(tool, "bad-input", "`set` needs `command`", base);
1347
+ }
1348
+ // Parse with the supervisor's OWN parser, then act on the parsed argv
1349
+ // — never on the spelling. A declaration its parser drops is silently
1350
+ // NO hook at all.
1351
+ const parsed = parseDeclaration(input.command);
1352
+ if (!parsed.ok)
1353
+ return refusal(tool, parsed.code, parsed.reason, base);
1354
+ const warning = splitWarning(parsed.value.argv);
1355
+ if (warning !== undefined)
1356
+ return refusal(tool, "bad-input", warning, base);
1357
+ const resolved = viewHook(name, parsed.value, harness);
1358
+ if ((resolved.commandState === "absent" || resolved.commandState === "not-executable") &&
1359
+ input.allowMissingCommand !== true) {
1360
+ return refusal(tool, "bad-input", `the command "${renderPath(resolved.command)}" is ${resolved.commandState}${resolved.detail === undefined ? "" : ` (${resolved.detail})`}. A declared hook that cannot run REFUSES every start of this harness. Pass allowMissingCommand:true if it is created later.`, { ...base, hook: resolved });
1361
+ }
1362
+ intended = parsed.value.argv;
1363
+ // What goes into the file is the PARSED value, not the caller's
1364
+ // spelling — `parseManagerHook` trims each entry, so writing the raw
1365
+ // input would leave a declaration on disk that is not the one this
1366
+ // call verified. The FORM is kept (a string stays a string) so the
1367
+ // file still reads the way its author wrote it.
1368
+ const declaration = typeof input.command === "string" ? parsed.value.argv[0] : parsed.value.argv;
1369
+ nextDoc = withHook(doc, manager.value, name, declaration, input.timeoutMs);
1370
+ plan = {
1371
+ would: current === undefined ? `declare ${name}` : `replace ${name}`,
1372
+ hook: resolved,
1373
+ ...(current !== undefined ? { replacing: viewHook(name, current, harness) } : {}),
1374
+ ...(resolved.commandState === "path-lookup"
1375
+ ? {
1376
+ unverified: "argv[0] is a bare name, so it is resolved on PATH by whichever process spawns the hook — this tool cannot check it from here, and does not claim to",
1377
+ }
1378
+ : {}),
1379
+ };
1380
+ }
1381
+ else {
1382
+ if (current === undefined && input.timeoutMs === undefined) {
1383
+ return json({
1384
+ ...base,
1385
+ status: "unchanged",
1386
+ dryRun,
1387
+ note: `${name} is not declared in this harness's settings — nothing to remove`,
1388
+ hooks: declared,
1389
+ });
1390
+ }
1391
+ nextDoc = withHook(doc, manager.value, name, undefined, input.timeoutMs);
1392
+ plan = {
1393
+ would: current === undefined
1394
+ ? `set the hook timeout to ${input.timeoutMs} ms (${name} is not declared)`
1395
+ : `remove ${name}`,
1396
+ ...(current !== undefined ? { removing: viewHook(name, current, harness) } : {}),
1397
+ };
1398
+ }
1399
+ if (dryRun) {
1400
+ return json({
1401
+ ...base,
1402
+ status: "preview",
1403
+ dryRun: true,
1404
+ ...plan,
1405
+ resultingManagerHooks: nextDoc["manager"]["hooks"],
1406
+ nothingWasTouched: true,
1407
+ });
1408
+ }
1409
+ const written = writeSettingsFile(tmpAbs, abs, nextDoc, probe.mode);
1410
+ if (!written.ok) {
1411
+ try {
1412
+ unlinkSync(tmpAbs);
1413
+ }
1414
+ catch {
1415
+ // Best-effort: the write error is what matters.
1416
+ }
1417
+ return refusal(tool, written.code, written.reason, base);
1418
+ }
1419
+ // Read it back THROUGH THE SUPERVISOR'S READER. A write that lands as
1420
+ // JSON the supervisor then drops (a shape its parser refuses, a key it
1421
+ // ignores) is a hook that does not exist, and the only way to know is to
1422
+ // ask the thing that will read it at spawn time.
1423
+ const after = readManagerSettings(harness);
1424
+ const stored = after.hooks[name];
1425
+ const matches = input.action === "set"
1426
+ ? stored !== undefined &&
1427
+ intended !== undefined &&
1428
+ stored.argv.length === intended.length &&
1429
+ stored.argv.every((part, index) => part === intended?.[index])
1430
+ : stored === undefined;
1431
+ return json({
1432
+ ...base,
1433
+ status: matches ? "applied" : "failed",
1434
+ dryRun: false,
1435
+ hookAction: input.action,
1436
+ hook: name,
1437
+ verified: matches,
1438
+ ...(matches
1439
+ ? {}
1440
+ : {
1441
+ reason: "the file was written, but re-reading it through @crewhaus/harness-supervisor did not give back what was asked for",
1442
+ }),
1443
+ now: stored === undefined
1444
+ ? { name, declared: false }
1445
+ : { declared: true, ...viewHook(name, stored, harness) },
1446
+ timeout: timeoutView(after.hooks.timeoutMs),
1447
+ });
1448
+ },
1449
+ });