@crewhaus/tool-fleet 0.7.0 → 0.8.1

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/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,9 @@
1
+ CrewHaus Factory
2
+ Copyright 2026 Max Meier
3
+
4
+ This product includes software developed by Max Meier
5
+ (operating as StudioMax — https://studiomax.io) and contributors.
6
+
7
+ The CrewHaus name and logo are trademarks of Max Meier. See
8
+ https://github.com/crewhaus/factory/blob/main/TRADEMARK.md for the
9
+ use-of-marks policy.
package/README.md CHANGED
@@ -12,6 +12,13 @@ hooks that wrap a start.
12
12
  | `CliVersionPin` | which CLI each harness would run, which one built its bundle | `harness-supervisor` (`resolveCrewhausBin`, the bundle stamp) |
13
13
  | `HooksManage` | list / set / remove the manager hooks in `.crewhaus/settings.json` | `harness-supervisor` (`parseManagerHook`, `readManagerSettings`) |
14
14
 
15
+ On the harness it runs in, `HooksManage` is refused by the runtime-state floor, `list` included
16
+ (the tool is not read-only); it manages other harnesses as before.
17
+
18
+ `CompileBundle` of the working directory goes by the rules. Of another directory, it refuses, in
19
+ the preview and the real call alike, when the output, the entry or the manifest resolves into one
20
+ of the floor's roots, or when the output directory holds one.
21
+
15
22
  ## These tools are thin on purpose
16
23
 
17
24
  Everything they enforce belongs to a package they depend on. The registry file is written by
@@ -118,15 +125,32 @@ Paths a STORE hands back are contained too: `CliVersionPin` re-contains every re
118
125
  opening a spec or a bundle under it and reports the rest as skipped, and rows are deduped by real
119
126
  path so one harness cannot be counted twice in the version roll-up.
120
127
 
128
+ A row that a store hands back is treated the same way. `HarnessRegister` relocates or removes a row,
129
+ or sets its `hidden`, `groups`, `group` or `order`, only when the row's directory, resolved through
130
+ its symlinks, is inside the workspace or is gone, and a dry run answers the same as the real call.
131
+ Any other row is the operator's, and the refusal names the verb: `crewhaus harness relocate`,
132
+ `crewhaus harness remove`, `crewhaus harness group`, or the Library in `crewhaus hangar` for
133
+ `hidden`. `tags`, `notes` and `pinned` work on every row.
134
+
121
135
  The exception is deliberate and no input can move it. The two machine-wide files —
122
136
  `<registryRoot>/harnesses.json` and `<hangarRoot>/jobs.jsonl` — are resolved from the environment
123
- (`CREWHAUS_REGISTRY_ROOT`, `CREWHAUS_HANGAR_ROOT`), because a registry that only ever saw the
124
- current workspace would not be a registry. Their absolute paths are reported in every result.
125
-
126
- Two binaries are executed: `crewhaus compile` (by `CompileBundle`) and `<bin> --version` (by
127
- `CliVersionPin --probe`). Both come from the supervisor's own resolver — harness-local
128
- `node_modules/.bin/crewhaus` first, then `PATH` — and a binary that resolves OUTSIDE the workspace
129
- is refused unless `allowExternalCli` is passed, with its path named.
137
+ (`CREWHAUS_REGISTRY_ROOT`, `CREWHAUS_HANGAR_ROOT`) by `@crewhaus/harness-registry`'s
138
+ `resolveRegistryRoot` and `resolveHangarRoot`, the resolvers the CLI uses, because a registry that
139
+ only ever saw the current workspace would not be a registry. Their absolute paths are reported in
140
+ every result.
141
+
142
+ `CompileBundle` executes `crewhaus compile`. The binary comes from the supervisor's own resolver —
143
+ harness-local `node_modules/.bin/crewhaus` first, then `PATH` — and a binary that resolves OUTSIDE
144
+ the workspace is refused unless `allowExternalCli` is passed, with its path named.
145
+
146
+ `CliVersionPin --probe` does not run a CLI the workspace supplies. A cloned repository can commit
147
+ `node_modules/.bin/crewhaus`, and this tool is not destructive, so auto mode runs it without asking.
148
+ The version is READ from the `package.json` of the `crewhaus` package the binary belongs to (npm's
149
+ `.bin` entry links into `node_modules/crewhaus/`), found by walking up from where the binary really
150
+ is and then at `<harness>/node_modules/crewhaus/package.json`; each read is contained, and a
151
+ `package.json` a link puts outside the workspace is refused, not read. A CLI outside the workspace
152
+ is the operator's own install: it is read the same way with `allowExternalCli`, and only a
153
+ standalone binary with no `package.json` (brew, scoop) is asked with `--version`.
130
154
 
131
155
  ## What a compile is given
132
156
 
@@ -212,7 +236,8 @@ Every result is one JSON object carrying a `status`:
212
236
 
213
237
  ## Notes
214
238
 
215
- - `HarnessJobStatus` and `CliVersionPin` declare `readOnly: true`, and nothing they do writes.
239
+ - `HarnessJobStatus` declares `readOnly: true`; `CliVersionPin` does not (0.7.1: it can run the
240
+ operator's own standalone CLI, see above), but is not destructive either. Nothing either does writes.
216
241
  `harness-registry`'s `list()` normally persists its own missing-directory stamps and any pending
217
242
  pre-v2 lift ON A READ, so merely reporting the fleet would edit a machine-wide file — and
218
243
  `readOnly` is a flag a permission layer acts on, not a note. Every enumerating READ here opens
package/dist/index.js CHANGED
@@ -67,10 +67,11 @@ import * as path from "node:path";
67
67
  import { HARNESS_ID_RE, openHangarRegistry, } from "@crewhaus/harness-registry";
68
68
  import { MANAGER_HOOK_NAMES, compileIfStale, compileOutDir, createFileJobStore, createProcessOps, hookLogPath, readHookRunLog, readManagerSettings, runPrepareCommand, } from "@crewhaus/harness-supervisor";
69
69
  import { buildTool } from "@crewhaus/tool-builder";
70
+ import { protectedRootBeneath, protectedRootHolding, protectedRootsOf, protectedWriteRefusal, } from "@crewhaus/tool-safety/fs";
70
71
  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";
72
+ import { CLI_VERSION_RE, externalBinRefusal, freshnessOf, readCliVersion, readSpecFacts, resolveCli, spawnEnv, } from "./lib/bundle";
73
+ import { countByState, filterJobs, jobView, ledgerBlockedBy, parseIsoInstant, probeLedger, sortJobs, } from "./lib/jobs";
74
+ import { entryView, mutationBlockedBy, probeRegistryFile, rowDirIsElsewhere, sortEntries, } from "./lib/registry";
74
75
  import { compareStrings, contain, containExistingDir, containUnder, containWritePaths, isInside, json, refusal, renderPath, renderStorePath, renderText, sample, } from "./lib/result";
75
76
  import { jobLedgerPath, registryFilePath } from "./lib/roots";
76
77
  import { managerBlock, parseDeclaration, probeSettings, settingsAbsPath, settingsRelPath, splitWarning, timeoutView, viewHook, withHook, writeBlockedBy, writeSettingsFile, } from "./lib/settings";
@@ -207,9 +208,35 @@ const updateFields = {
207
208
  .optional()
208
209
  .describe("this member's 1-based boot order inside `group`; omit with `group` to clear it"),
209
210
  };
211
+ /**
212
+ * Where the operator makes the change a `HarnessRegister` call asks for, for
213
+ * each change this tool makes only on a row inside its workspace or gone. Empty
214
+ * for the rest: `register` and `list` select no row, and `tags`, `notes` and
215
+ * `pinned` annotate a row without changing where it runs or what starts it.
216
+ */
217
+ function operatorVerbsFor(input) {
218
+ const { action, groups, group, order, hidden } = input;
219
+ if (action === "relocate")
220
+ return ["`crewhaus harness relocate`"];
221
+ if (action === "remove")
222
+ return ["`crewhaus harness remove`"];
223
+ if (action !== "update")
224
+ return [];
225
+ return [
226
+ ...(groups !== undefined || group !== undefined || order !== undefined
227
+ ? ["`crewhaus harness group`"]
228
+ : []),
229
+ ...(hidden !== undefined ? ["the Library in `crewhaus hangar`"] : []),
230
+ ];
231
+ }
210
232
  export const harnessRegister = buildTool({
211
233
  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.",
234
+ operativeArgs: [
235
+ { field: "dir", kind: "path" },
236
+ { field: "from", kind: "path" },
237
+ { field: "id", kind: "id" },
238
+ ],
239
+ 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). Writes go through @crewhaus/harness-registry's atomic read-merge-write, so a concurrent session or a running manager cannot lose an edit. A relocate keeps the hrn_ id, and the result re-reads the registry to prove it. It refuses to write a registry file that exists but does not parse, a registry CREWHAUS_NO_REGISTRY has made read-only, an id that is not an hrn_ id, and a second row for a directory already registered under another spelling. A register reads the harness's crewhaus.yaml for its name and shape, and refuses one a symlink puts outside the workspace. A write the filesystem refuses is reported, and a multi-field update names which fields landed. dryRun defaults to true.",
213
240
  inputSchema: z.object({
214
241
  action: z
215
242
  .enum(["list", "register", "remove", "relocate", "update"])
@@ -414,6 +441,13 @@ export const harnessRegister = buildTool({
414
441
  const selectedId = entry.id;
415
442
  const selectedDir = entry.dir;
416
443
  const selected = entryView(entry, root);
444
+ // The tool works inside its workspace, and a row elsewhere is the
445
+ // operator's. Before the dry-run branches, so the preview says what the
446
+ // real call would do. A moved harness (old directory gone) stays open.
447
+ const operatorVerbs = operatorVerbsFor(input);
448
+ if (operatorVerbs.length > 0 && rowDirIsElsewhere(root, entry.dir)) {
449
+ return refusal(tool, "refused", `${selectedId} points at a directory outside this workspace that still exists. This change is the operator's: ${operatorVerbs.join(" or ")}.`, { ...base, entry: selected });
450
+ }
417
451
  if (action === "remove") {
418
452
  if (dryRun) {
419
453
  return json({
@@ -642,6 +676,7 @@ const JOB_STATES = [
642
676
  export const JOB_STATES_COVER_JOBSTATE = true;
643
677
  export const harnessJobStatus = buildTool({
644
678
  name: "HarnessJobStatus",
679
+ operativeArgs: [{ field: "dir", kind: "path" }],
645
680
  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
681
  inputSchema: z.object({
647
682
  jobId: z.string().min(1).max(200).optional().describe("a single job"),
@@ -656,7 +691,7 @@ export const harnessJobStatus = buildTool({
656
691
  .string()
657
692
  .min(1)
658
693
  .optional()
659
- .describe("only jobs enqueued at or after this ISO 8601 instant"),
694
+ .describe("only jobs enqueued at or after this ISO 8601 instant; one without Z or an offset is read as UTC"),
660
695
  limit: z
661
696
  .number()
662
697
  .int()
@@ -688,8 +723,9 @@ export const harnessJobStatus = buildTool({
688
723
  // Both spellings: the manager records whichever path it was handed.
689
724
  harnessDirs = spellings(safe.value);
690
725
  }
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);
726
+ const since = input.since === undefined ? undefined : parseIsoInstant(input.since);
727
+ if (input.since !== undefined && since === undefined) {
728
+ return refusal(tool, "bad-input", `"${renderPath(input.since)}" is not an ISO 8601 instant (2026-09-26, 2026-09-26T10:00:00Z or 2026-09-26T10:00:00+02:00) — filtering on it would have silently kept every record`, base);
693
729
  }
694
730
  const records = createFileJobStore(ledger).read();
695
731
  const { kept, unparsedTimestamps } = filterJobs(records, {
@@ -707,6 +743,15 @@ export const harnessJobStatus = buildTool({
707
743
  status: "ok",
708
744
  // Three different questions: how many records the fold produced, how
709
745
  // many survived the filter, how many are shown.
746
+ ...(since !== undefined
747
+ ? {
748
+ // The instant actually filtered on, so a reader can check it.
749
+ sinceUtc: new Date(since.ms).toISOString(),
750
+ ...(since.offsetGiven
751
+ ? {}
752
+ : { sinceNote: "since had no Z or offset, so it was read as UTC" }),
753
+ }
754
+ : {}),
710
755
  recordsInLedger: records.length,
711
756
  matched: ordered.length,
712
757
  shown: Math.min(ordered.length, limit),
@@ -731,7 +776,8 @@ export const harnessJobStatus = buildTool({
731
776
  // ---------------------------------------------------------------------------
732
777
  export const compileBundle = buildTool({
733
778
  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.",
779
+ operativeArgs: [{ field: "dir", kind: "path", default: ".", beneath: "all" }],
780
+ description: "Compare a harness's compiled bundle against its spec using @crewhaus/harness-supervisor's spec-hash stamp — the check the manager gates a start on — and recompile it when stale, running the same `crewhaus compile` (and `bun install` in the bundle) as `daemon start --compile`. Three verdicts: fresh, stale and UNDETERMINED (no stamp and no usable mtimes, or a spec that cannot be read or parsed). The supervisor treats undetermined as not stale; this tool says so, and refuses a real run on it with the command that fixes it. The compile runs with a minimal environment (no .env chain), and freshness is re-read afterwards: a compile that exited 0 and left the bundle stale says so. Every file it opens is contained, so a crewhaus.yaml or bundle directory a symlink puts outside the workspace is refused, in the preview and the real call alike. dryRun defaults to true.",
735
781
  inputSchema: z.object({
736
782
  dir: z
737
783
  .string()
@@ -756,7 +802,7 @@ export const compileBundle = buildTool({
756
802
  destructive: true,
757
803
  scope: "external",
758
804
  ioCapability: "process",
759
- execute: async (input) => {
805
+ execute: async (input, ctx) => {
760
806
  const tool = "CompileBundle";
761
807
  const dryRun = input.dryRun ?? true;
762
808
  const root = workspaceRoot();
@@ -813,6 +859,26 @@ export const compileBundle = buildTool({
813
859
  ? { resolved: false }
814
860
  : { resolved: true, bin: cli.bin, where: cli.where, inWorkspace: cli.inWorkspace },
815
861
  };
862
+ // The working directory's own compile is the run's to ask for, and the
863
+ // floor leaves it to the rules. Any other directory's output, entry and
864
+ // manifest stay out of the runtime-state roots, with links followed, and
865
+ // its output directory holds none of them, since the install writes
866
+ // `node_modules` and the lockfile there: before the dryRun branch, so the
867
+ // preview and the real call refuse identically.
868
+ if (safe.value.rel !== "") {
869
+ const roots = protectedRootsOf(ctx);
870
+ const output = path.join(harness, outDir);
871
+ const written = [
872
+ output,
873
+ ...(located === undefined
874
+ ? []
875
+ : [located.entryPath, path.join(located.bundleDir, "package.json")]),
876
+ ];
877
+ if (written.some((name) => protectedRootHolding(name, roots, root) !== undefined) ||
878
+ protectedRootBeneath(output, roots, root) !== undefined) {
879
+ return refusal(tool, "refused", protectedWriteRefusal(tool, `compiling ${shownDir}`), view);
880
+ }
881
+ }
816
882
  if (dryRun) {
817
883
  return json({
818
884
  ...view,
@@ -944,11 +1010,10 @@ export const compileBundle = buildTool({
944
1010
  });
945
1011
  },
946
1012
  });
947
- /** A semver-shaped token, wherever a CLI prints it. */
948
- const VERSION_RE = /\b\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?\b/;
949
1013
  export const cliVersionPin = buildTool({
950
1014
  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.",
1015
+ operativeArgs: [{ field: "dirs", kind: "path" }],
1016
+ 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 on an old CLI is visible. Harnesses come from this machine's registry unless dirs are given; the binary is @crewhaus/harness-supervisor's choice (harness node_modules/.bin first, then PATH). It does NOT install, switch or pin a version — that is @crewhaus/chvm — so the result names the command instead. With probe:true it reads each distinct CLI's version from the package.json of the crewhaus package it belongs to; a CLI inside the workspace is never run. A CLI outside the workspace is read only with allowExternalCli, and run with --version only when it has no package.json. A version it could not read is unknown, with the reason. It writes nothing. At most 500 harnesses are inspected (truncated:true past that). A spec or bundle a symlink puts outside the workspace is reported as undetermined, never opened.",
952
1017
  inputSchema: z.object({
953
1018
  dirs: z
954
1019
  .array(z.string())
@@ -958,17 +1023,24 @@ export const cliVersionPin = buildTool({
958
1023
  probe: z
959
1024
  .boolean()
960
1025
  .optional()
961
- .describe("run `<bin> --version` once per distinct binary (default false)"),
1026
+ .describe("report each distinct CLI's version, read from the package.json of the crewhaus package it belongs to; a CLI inside the workspace is never run (default false)"),
962
1027
  allowExternalCli: z
963
1028
  .boolean()
964
1029
  .optional()
965
- .describe("allow probing a binary that resolves outside the workspace"),
1030
+ .describe("also report a CLI that resolves outside the workspace (the operator's own install); one with no package.json, a standalone binary, is asked with `--version`"),
966
1031
  includeMissing: z
967
1032
  .boolean()
968
1033
  .optional()
969
1034
  .describe("include registry entries whose directory has vanished (default false)"),
970
1035
  }),
971
- readOnly: true,
1036
+ // NOT read-only (0.7.1, permission-integration#7), and never runs a
1037
+ // program the workspace supplies (C048): a harness-local CLI's version is
1038
+ // READ from its package.json. The one thing it may run is the operator's
1039
+ // own install outside the workspace, with allowExternalCli, when that is a
1040
+ // standalone binary with no package.json — hence scope/io stay external
1041
+ // and process. Nothing it runs changes anything, so it is not destructive,
1042
+ // and auto mode allows it.
1043
+ readOnly: false,
972
1044
  scope: "external",
973
1045
  ioCapability: "process",
974
1046
  execute: async (input) => {
@@ -1117,6 +1189,22 @@ export const cliVersionPin = buildTool({
1117
1189
  probes[bin] = { state: "not-probed", reason: external.reason };
1118
1190
  continue;
1119
1191
  }
1192
+ // C048: the version is READ from the crewhaus package the binary
1193
+ // belongs to. A binary inside the workspace is never run — a cloned
1194
+ // repository can commit one, and auto mode runs this tool unasked.
1195
+ const reading = readCliVersion(item.cli, item.safe.real, root, input.allowExternalCli === true);
1196
+ if (reading.state !== "needs-exec") {
1197
+ probes[bin] =
1198
+ reading.state === "known"
1199
+ ? { state: "known", version: reading.version, source: reading.source }
1200
+ : reading.state === "unparsed"
1201
+ ? { state: "unparsed", reason: reading.reason, source: reading.source }
1202
+ : { state: "unknown", reason: reading.reason };
1203
+ continue;
1204
+ }
1205
+ // Only the operator's own install outside the workspace, allowed by
1206
+ // allowExternalCli, with no package.json (a standalone binary) gets
1207
+ // here: running its `--version` is the only way to ask it.
1120
1208
  let outcome;
1121
1209
  try {
1122
1210
  outcome = await runPrepareCommand({
@@ -1157,7 +1245,7 @@ export const cliVersionPin = buildTool({
1157
1245
  // PARSE, then report the PARSED value. A line that carries no
1158
1246
  // version is not a version, and echoing the raw line as one is how a
1159
1247
  // startup banner ends up in a version table.
1160
- const matched = VERSION_RE.exec(outcome.output.join("\n"));
1248
+ const matched = CLI_VERSION_RE.exec(outcome.output.join("\n"));
1161
1249
  probes[bin] =
1162
1250
  matched === null
1163
1251
  ? {
@@ -1216,7 +1304,14 @@ export const cliVersionPin = buildTool({
1216
1304
  // ---------------------------------------------------------------------------
1217
1305
  export const hooksManage = buildTool({
1218
1306
  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.",
1307
+ operativeArgs: [
1308
+ // The harness's settings file, which it reads and rewrites.
1309
+ { field: "dir", kind: "path", default: ".", opens: [{ path: ".crewhaus/settings.json" }] },
1310
+ // The supervisor runs the hook from the harness root, and resolves a
1311
+ // `./prep.sh` there: the command is another program in another `dir`.
1312
+ { field: "command", kind: "command", within: "dir" },
1313
+ ],
1314
+ description: "List, set and remove the MANAGER hooks (postCompile, preSpawn) in a harness's .crewhaus/settings.json — the steps @crewhaus/harness-supervisor runs between a compile and a spawn — and report what each declaration PARSES to. It never executes a hook. The grammar is the supervisor's: a string is ONE command with no arguments, never word-split; an array is an argv. So \"bun run prep.ts\" names a file with spaces in it and is refused, with the array form spelled out. A command path is checked for existence and the execute bit (a directory or a dangling link is not executable); a bare name is left to the OS at spawn time. Writes keep every other key, are atomic, keep the file's mode, and are refused when the existing file does not parse. The settings file is contained before it is read, so a symlinked one is refused, on list too. After a write the file is re-read through the supervisor's own reader to confirm the argv came back. dryRun defaults to true.",
1220
1315
  inputSchema: z.object({
1221
1316
  action: z.enum(["list", "set", "remove"]).describe("`list` never writes"),
1222
1317
  dir: z
@@ -1332,7 +1427,7 @@ export const hooksManage = buildTool({
1332
1427
  const escapes = containWritePaths(tool, safe.value, [rel, tmpRel]);
1333
1428
  if (escapes !== undefined)
1334
1429
  return refusal(tool, escapes.code, escapes.reason, base);
1335
- const tmpAbs = path.join(harness, ...tmpRel.split("/"));
1430
+ const tmpAbs = path.join(harness, tmpRel);
1336
1431
  const doc = probe.doc ?? {};
1337
1432
  const manager = managerBlock(doc);
1338
1433
  if (!manager.ok)
@@ -112,6 +112,48 @@ export type CliResolution = {
112
112
  * re-implementing the search.
113
113
  */
114
114
  export declare function resolveCli(harnessRoot: string, workspaceRoot: string): CliResolution | undefined;
115
+ /** A semver-shaped token, wherever a CLI or a package.json prints it. */
116
+ export declare const CLI_VERSION_RE: RegExp;
117
+ /** What reading a CLI's version WITHOUT running it found. */
118
+ export type CliVersionReading = {
119
+ readonly state: "known";
120
+ readonly version: string;
121
+ readonly source: string;
122
+ } | {
123
+ readonly state: "unparsed";
124
+ readonly reason: string;
125
+ readonly source: string;
126
+ } | {
127
+ readonly state: "unknown";
128
+ readonly reason: string;
129
+ }
130
+ /** Outside the workspace, allowed, and no package.json: only running it can tell. */
131
+ | {
132
+ readonly state: "needs-exec";
133
+ };
134
+ /**
135
+ * A harness CLI's version, read from the `package.json` of the `crewhaus`
136
+ * package it belongs to — never by running it when it is inside the
137
+ * workspace (C048).
138
+ *
139
+ * A binary under the workspace (`<harness>/node_modules/.bin/crewhaus`, or a
140
+ * PATH entry that leads into the workspace) is code the workspace supplies:
141
+ * a cloned repository can commit one. `CliVersionPin` is not destructive, so
142
+ * auto mode runs it unasked, and `--version` would have run that code with
143
+ * the harness's environment. npm's layout makes running it unnecessary: the
144
+ * `.bin` entry links to `../crewhaus/<entry>`, so the version is in
145
+ * `node_modules/crewhaus/package.json`. The package.json is found by walking
146
+ * up from where the binary really is (at most four directories), then at
147
+ * `<harness>/node_modules/crewhaus/package.json`; it counts only if its
148
+ * `name` is `crewhaus`. Each read is contained to the workspace (a leaf
149
+ * linked out of it is refused, not followed) and bounded.
150
+ *
151
+ * A binary OUTSIDE the workspace is the operator's own install. It is read
152
+ * the same way when `allowExternal` is set, and only when it has no
153
+ * package.json (a standalone brew/scoop binary) does the caller get
154
+ * `needs-exec` — the one case where `--version` may still run.
155
+ */
156
+ export declare function readCliVersion(cli: CliResolution, harnessRoot: string, workspaceRoot: string, allowExternal: boolean): CliVersionReading;
115
157
  /**
116
158
  * Refuse to EXECUTE a binary that sits outside the workspace unless the
117
159
  * caller said so.
@@ -23,9 +23,11 @@
23
23
  * last month's CLI with every status line green.
24
24
  */
25
25
  import { readFileSync, realpathSync, statSync } from "node:fs";
26
- import { join, relative } from "node:path";
26
+ import { dirname, join, relative } from "node:path";
27
27
  import { bundleStaleness, findSpecPath, resolveBundle, resolveCrewhausBin, } from "@crewhaus/harness-supervisor";
28
28
  import { parseSpec, parseSpecIssues } from "@crewhaus/spec";
29
+ import { openForReadSync } from "@crewhaus/tool-safety/fs";
30
+ import { readFileBoundedSync } from "@crewhaus/tool-safety/streams";
29
31
  import { containUnder, fail, isInside, renderPath, renderText } from "./result";
30
32
  /** A spec is YAML a human wrote; anything past this is not one. */
31
33
  const MAX_SPEC_BYTES = 4 * 1024 * 1024;
@@ -280,6 +282,102 @@ export function resolveCli(harnessRoot, workspaceRoot) {
280
282
  ...(real !== bin ? { real } : {}),
281
283
  };
282
284
  }
285
+ /** A semver-shaped token, wherever a CLI or a package.json prints it. */
286
+ export const CLI_VERSION_RE = /\b\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?\b/;
287
+ /** Largest package.json read for a version. A real one is a few KB. */
288
+ const MAX_PACKAGE_JSON_BYTES = 256 * 1024;
289
+ /** How many directories above the binary are searched for its package.json. */
290
+ const PACKAGE_JSON_LEVELS = 4;
291
+ /**
292
+ * A harness CLI's version, read from the `package.json` of the `crewhaus`
293
+ * package it belongs to — never by running it when it is inside the
294
+ * workspace (C048).
295
+ *
296
+ * A binary under the workspace (`<harness>/node_modules/.bin/crewhaus`, or a
297
+ * PATH entry that leads into the workspace) is code the workspace supplies:
298
+ * a cloned repository can commit one. `CliVersionPin` is not destructive, so
299
+ * auto mode runs it unasked, and `--version` would have run that code with
300
+ * the harness's environment. npm's layout makes running it unnecessary: the
301
+ * `.bin` entry links to `../crewhaus/<entry>`, so the version is in
302
+ * `node_modules/crewhaus/package.json`. The package.json is found by walking
303
+ * up from where the binary really is (at most four directories), then at
304
+ * `<harness>/node_modules/crewhaus/package.json`; it counts only if its
305
+ * `name` is `crewhaus`. Each read is contained to the workspace (a leaf
306
+ * linked out of it is refused, not followed) and bounded.
307
+ *
308
+ * A binary OUTSIDE the workspace is the operator's own install. It is read
309
+ * the same way when `allowExternal` is set, and only when it has no
310
+ * package.json (a standalone brew/scoop binary) does the caller get
311
+ * `needs-exec` — the one case where `--version` may still run.
312
+ */
313
+ export function readCliVersion(cli, harnessRoot, workspaceRoot, allowExternal) {
314
+ if (!cli.inWorkspace && !allowExternal) {
315
+ const refused = externalBinRefusal(cli, false);
316
+ return { state: "unknown", reason: refused?.reason ?? "outside the workspace root" };
317
+ }
318
+ const candidates = [];
319
+ let dir = dirname(cli.real ?? cli.bin);
320
+ for (let i = 0; i < PACKAGE_JSON_LEVELS; i++) {
321
+ candidates.push(join(dir, "package.json"));
322
+ const up = dirname(dir);
323
+ if (up === dir)
324
+ break;
325
+ dir = up;
326
+ }
327
+ if (cli.where === "harness-local") {
328
+ candidates.push(join(harnessRoot, "node_modules", "crewhaus", "package.json"));
329
+ }
330
+ const refusals = [];
331
+ for (const candidate of [...new Set(candidates)]) {
332
+ const inside = isInside(workspaceRoot, candidate);
333
+ // A walk that climbs out of the workspace from an in-workspace binary
334
+ // stops at the boundary: what is above it is not this binary's package.
335
+ if (cli.inWorkspace && !inside)
336
+ continue;
337
+ const read = inside
338
+ ? openForReadSync(workspaceRoot, candidate, { maxBytes: MAX_PACKAGE_JSON_BYTES })
339
+ : readFileBoundedSync(candidate, { maxBytes: MAX_PACKAGE_JSON_BYTES });
340
+ const shown = inside ? renderPath(relative(workspaceRoot, candidate)) : renderPath(candidate);
341
+ if (!read.ok) {
342
+ // Absent is the ordinary case; anything else — a link out of the
343
+ // workspace, a FIFO, a permission error — is said, and not followed.
344
+ if (read.code !== "not-found")
345
+ refusals.push(`${shown}: ${read.reason}`);
346
+ continue;
347
+ }
348
+ if (read.truncated) {
349
+ refusals.push(`${shown}: larger than ${MAX_PACKAGE_JSON_BYTES} bytes`);
350
+ continue;
351
+ }
352
+ let pkg;
353
+ try {
354
+ pkg = JSON.parse(read.text);
355
+ }
356
+ catch {
357
+ continue; // not a package manifest at all; keep looking
358
+ }
359
+ if (typeof pkg !== "object" ||
360
+ pkg === null ||
361
+ pkg.name !== "crewhaus") {
362
+ continue;
363
+ }
364
+ const version = pkg.version;
365
+ const matched = typeof version === "string" ? CLI_VERSION_RE.exec(version) : null;
366
+ return matched === null
367
+ ? {
368
+ state: "unparsed",
369
+ reason: `${shown} names crewhaus but its version (${renderText(String(version), 80)}) is not semver-shaped`,
370
+ source: shown,
371
+ }
372
+ : { state: "known", version: matched[0], source: shown };
373
+ }
374
+ if (!cli.inWorkspace)
375
+ return { state: "needs-exec" };
376
+ return {
377
+ state: "unknown",
378
+ reason: `this crewhaus CLI is inside the workspace, so it is not run to ask its version, and no package.json naming crewhaus was found beside it${refusals.length > 0 ? ` (${refusals.join("; ")})` : ""}`,
379
+ };
380
+ }
283
381
  /**
284
382
  * Refuse to EXECUTE a binary that sits outside the workspace unless the
285
383
  * caller said so.
@@ -20,9 +20,23 @@ export type JobFilter = {
20
20
  readonly jobId?: string;
21
21
  readonly kind?: string;
22
22
  readonly state?: string;
23
- /** ISO 8601; keeps records enqueued at or after this instant. */
23
+ /** ISO 8601; keeps records enqueued at or after this instant (no offset: UTC). */
24
24
  readonly sinceIso?: string;
25
25
  };
26
+ export type ParsedInstant = {
27
+ readonly ms: number;
28
+ /** False when the text carried no `Z` or offset and was read as UTC. */
29
+ readonly offsetGiven: boolean;
30
+ };
31
+ /**
32
+ * An ISO 8601 date or date-time as epoch milliseconds, never read in the
33
+ * host's time zone (0.7.1 policy): a value with no `Z` or offset is read as
34
+ * UTC, and `offsetGiven` says so. `Date.parse` reads `2026-09-26T10:00:00`
35
+ * in the host's zone, so the same call kept a job on a UTC host and dropped
36
+ * it in Los Angeles; it also reads forms like `Sep 26 2026` host-local,
37
+ * which are not ISO 8601 and are not instants here.
38
+ */
39
+ export declare function parseIsoInstant(text: string): ParsedInstant | undefined;
26
40
  /**
27
41
  * Apply the filter to already-folded records.
28
42
  *
package/dist/lib/jobs.js CHANGED
@@ -47,6 +47,51 @@ export function ledgerBlockedBy(probe) {
47
47
  return { ok: true, value: undefined };
48
48
  return fail("unreadable", `${probe.path}: ${probe.detail ?? probe.state}. @crewhaus/harness-supervisor's job store answers an unopenable ledger with an empty list, so this would otherwise have been reported as "no jobs".`);
49
49
  }
50
+ /**
51
+ * ISO 8601: a date, or a date-time with an optional `Z` or ±hh:mm offset.
52
+ * Anchored, one pass, no nested repetition.
53
+ */
54
+ const ISO_INSTANT = /^(\d{4})-(\d{2})-(\d{2})(?:[Tt ](\d{2}):(\d{2})(?::(\d{2})(?:[.,](\d{1,9}))?)?(?:([Zz])|([+-])(\d{2}):?(\d{2}))?)?$/;
55
+ function daysIn(year, month) {
56
+ if (month === 2)
57
+ return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0) ? 29 : 28;
58
+ return month === 4 || month === 6 || month === 9 || month === 11 ? 30 : 31;
59
+ }
60
+ /**
61
+ * An ISO 8601 date or date-time as epoch milliseconds, never read in the
62
+ * host's time zone (0.7.1 policy): a value with no `Z` or offset is read as
63
+ * UTC, and `offsetGiven` says so. `Date.parse` reads `2026-09-26T10:00:00`
64
+ * in the host's zone, so the same call kept a job on a UTC host and dropped
65
+ * it in Los Angeles; it also reads forms like `Sep 26 2026` host-local,
66
+ * which are not ISO 8601 and are not instants here.
67
+ */
68
+ export function parseIsoInstant(text) {
69
+ const m = ISO_INSTANT.exec(text.trim());
70
+ if (m === null)
71
+ return undefined;
72
+ const num = (i) => (m[i] === undefined ? 0 : Number(m[i]));
73
+ const [year, month, day, hour, minute, second] = [1, 2, 3, 4, 5, 6].map(num);
74
+ if (month < 1 || month > 12 || day < 1 || day > daysIn(year, month))
75
+ return undefined;
76
+ if (hour > 23 || minute > 59 || second > 59)
77
+ return undefined;
78
+ const fraction = m[7] === undefined ? 0 : Number(`0.${m[7]}`);
79
+ const zulu = m[8] !== undefined;
80
+ const sign = m[9] === "-" ? -1 : 1;
81
+ const offsetHours = num(10);
82
+ const offsetMinutes = num(11);
83
+ if (offsetHours > 23 || offsetMinutes > 59)
84
+ return undefined;
85
+ const at = new Date(0);
86
+ at.setUTCFullYear(year, month - 1, day);
87
+ at.setUTCHours(hour, minute, second, Math.floor(fraction * 1000));
88
+ const offsetMs = m[9] === undefined ? 0 : sign * (offsetHours * 60 + offsetMinutes) * 60_000;
89
+ return { ms: at.getTime() - offsetMs, offsetGiven: zulu || m[9] !== undefined };
90
+ }
91
+ /** {@link parseIsoInstant}'s milliseconds, or NaN, for code that sorts and compares. */
92
+ function instantMs(text) {
93
+ return parseIsoInstant(text)?.ms ?? Number.NaN;
94
+ }
50
95
  /**
51
96
  * Apply the filter to already-folded records.
52
97
  *
@@ -58,7 +103,7 @@ export function ledgerBlockedBy(probe) {
58
103
  * malformed field.
59
104
  */
60
105
  export function filterJobs(records, filter) {
61
- const since = filter.sinceIso === undefined ? undefined : Date.parse(filter.sinceIso);
106
+ const since = filter.sinceIso === undefined ? undefined : instantMs(filter.sinceIso);
62
107
  const dirs = filter.harnessDirs === undefined ? undefined : new Set(filter.harnessDirs);
63
108
  const unparsedTimestamps = [];
64
109
  const kept = records.filter((record) => {
@@ -73,7 +118,7 @@ export function filterJobs(records, filter) {
73
118
  if (filter.state !== undefined && record.state !== filter.state)
74
119
  return false;
75
120
  if (since !== undefined && !Number.isNaN(since)) {
76
- const at = Date.parse(record.enqueuedAt);
121
+ const at = instantMs(record.enqueuedAt);
77
122
  if (Number.isNaN(at)) {
78
123
  unparsedTimestamps.push(record.jobId);
79
124
  return true;
@@ -89,7 +134,7 @@ export function filterJobs(records, filter) {
89
134
  * ties break on `jobId` so the order is stable rather than readdir-shaped. */
90
135
  export function sortJobs(records) {
91
136
  const at = (record) => {
92
- const ms = Date.parse(record.enqueuedAt);
137
+ const ms = instantMs(record.enqueuedAt);
93
138
  return Number.isNaN(ms) ? Number.NEGATIVE_INFINITY : ms;
94
139
  };
95
140
  return [...records].sort((a, b) => at(b) - at(a) || compareStrings(a.jobId, b.jobId));
@@ -30,6 +30,13 @@ export declare function probeRegistryFile(path: string): RegistryFileProbe;
30
30
  * not read with one built from `EMPTY_DOC`.
31
31
  */
32
32
  export declare function mutationBlockedBy(probe: RegistryFileProbe): Loaded<undefined>;
33
+ /**
34
+ * True when a row's directory exists and stands outside the workspace,
35
+ * resolved through its symlinks. Absent is the one answer that makes a row
36
+ * "gone": a directory that could not be read (a permission, a symlink loop) is
37
+ * still taken to be there, and judged by the path the row holds.
38
+ */
39
+ export declare function rowDirIsElsewhere(workspaceRoot: string, dir: string): boolean;
33
40
  /** The entry fields a result carries, in a stable order. */
34
41
  export type EntryView = Record<string, unknown>;
35
42
  /**
@@ -27,7 +27,7 @@
27
27
  * whose file exists but did not parse is REFUSED here, and a listing says
28
28
  * `unparseable` rather than reporting zero harnesses.
29
29
  */
30
- import { readFileSync } from "node:fs";
30
+ import { readFileSync, realpathSync } from "node:fs";
31
31
  import { compareStrings, fail, isInside, probeName, renderStorePath, renderText, } from "./result";
32
32
  /** Longest registry file this tool will read for its integrity probe. */
33
33
  const MAX_REGISTRY_BYTES = 32 * 1024 * 1024;
@@ -97,6 +97,23 @@ export function mutationBlockedBy(probe) {
97
97
  const shared = "@crewhaus/harness-registry reads an unusable registry as an EMPTY one and heals it on the next write, so proceeding would replace every row, group, tag and note in that file with an empty document. A registry that could not be read is not an empty registry.";
98
98
  return fail(probe.state === "unreadable" || probe.state === "not-a-file" ? "unreadable" : "refused", `${probe.path}: ${probe.detail ?? probe.state}. ${shared}`);
99
99
  }
100
+ /**
101
+ * True when a row's directory exists and stands outside the workspace,
102
+ * resolved through its symlinks. Absent is the one answer that makes a row
103
+ * "gone": a directory that could not be read (a permission, a symlink loop) is
104
+ * still taken to be there, and judged by the path the row holds.
105
+ */
106
+ export function rowDirIsElsewhere(workspaceRoot, dir) {
107
+ try {
108
+ return !isInside(workspaceRoot, realpathSync(dir));
109
+ }
110
+ catch (err) {
111
+ const code = err.code;
112
+ if (code === "ENOENT" || code === "ENOTDIR")
113
+ return false;
114
+ return !isInside(workspaceRoot, dir);
115
+ }
116
+ }
100
117
  /**
101
118
  * One registry row, shaped for a result.
102
119
  *
@@ -43,6 +43,13 @@ export type Loaded<T> = {
43
43
  export declare function fail(code: FailCode, reason: string): Failure;
44
44
  /** The JSON a tool returns when it will not proceed. */
45
45
  export declare function refusal(tool: string, code: FailCode, reason: string, extra?: {}): string;
46
+ /**
47
+ * True when `rel` resolves to a path longer than any path can be
48
+ * ({@link MAX_PATH_CHARS}). It cannot be opened or created, so it leads
49
+ * nowhere and is no escape; `contain` refuses it, naming the length and the
50
+ * limit, and anything that touches it meets the filesystem's own refusal.
51
+ */
52
+ export declare function pastPathLimit(rel: string): boolean;
46
53
  /**
47
54
  * Resolve a caller-supplied path inside the workspace.
48
55
  *
@@ -21,7 +21,7 @@
21
21
  */
22
22
  import { lstatSync, statSync } from "node:fs";
23
23
  import * as path from "node:path";
24
- import { ToolPermissionError, resolveSafe } from "../paths";
24
+ import { MAX_PATH_CHARS, ToolPermissionError, resolveSafe } from "../paths";
25
25
  /** Compact JSON — the reader is a model, and every byte is context. */
26
26
  export const json = (value) => JSON.stringify(value);
27
27
  /**
@@ -78,6 +78,15 @@ export function fail(code, reason) {
78
78
  export function refusal(tool, code, reason, extra = {}) {
79
79
  return json({ tool, status: "refused", code, reason, ...extra });
80
80
  }
81
+ /**
82
+ * True when `rel` resolves to a path longer than any path can be
83
+ * ({@link MAX_PATH_CHARS}). It cannot be opened or created, so it leads
84
+ * nowhere and is no escape; `contain` refuses it, naming the length and the
85
+ * limit, and anything that touches it meets the filesystem's own refusal.
86
+ */
87
+ export function pastPathLimit(rel) {
88
+ return path.resolve(process.cwd(), rel).length > MAX_PATH_CHARS;
89
+ }
81
90
  /**
82
91
  * Resolve a caller-supplied path inside the workspace.
83
92
  *
@@ -98,7 +107,7 @@ export function contain(toolName, rel) {
98
107
  if (err instanceof ToolPermissionError) {
99
108
  // The error's own message carries the path unrendered; rebuild it so a
100
109
  // control character in the caller's input cannot reach the output.
101
- return fail("refused", `tool "${toolName}" rejected path "${renderPath(rel)}": resolved location escapes the workspace root`);
110
+ return fail("refused", `tool "${toolName}" rejected path "${renderPath(rel)}": ${err.reason ?? "resolved location escapes the workspace root"}`);
102
111
  }
103
112
  throw err;
104
113
  }
@@ -150,7 +159,8 @@ function underRel(root, rel) {
150
159
  */
151
160
  export function containUnder(toolName, root, rel) {
152
161
  const safe = contain(toolName, underRel(root, rel));
153
- if (safe.ok)
162
+ // Refused for its length, not for a link: `contain` says so.
163
+ if (safe.ok || pastPathLimit(underRel(root, rel)))
154
164
  return safe;
155
165
  const shownRoot = root.rel === "" ? "." : root.rel;
156
166
  return fail("refused", `"${renderPath(rel)}" under "${renderPath(shownRoot)}" resolves outside the workspace root — a symlink on that path leads out, so this call would open, and a recompile would WRITE, a location the workspace does not contain, and report it as this harness's own. Remove the link and run again; there is no flag for following it.`);
@@ -178,6 +188,9 @@ export function containUnder(toolName, root, rel) {
178
188
  export function containWritePaths(toolName, root, rels) {
179
189
  const shownRoot = root.rel === "" ? "." : root.rel;
180
190
  for (const rel of rels) {
191
+ // Too long to open or create: it leads nowhere, so it is no escape.
192
+ if (pastPathLimit(underRel(root, rel)))
193
+ continue;
181
194
  if (!contain(toolName, underRel(root, rel)).ok) {
182
195
  return fail("refused", `"${renderPath(rel)}" under "${renderPath(shownRoot)}" resolves outside the workspace root — a symlink on that path leads out, so the write would land on the link's target rather than inside "${renderPath(shownRoot)}". Remove the link and run again; there is no flag for writing through it.`);
183
196
  }
@@ -1,17 +1,11 @@
1
+ import { resolveHangarRoot } from "@crewhaus/harness-registry";
1
2
  /** `<registryRoot>/harnesses.json` — the file `openHangarRegistry` opens. */
2
3
  export declare function registryFilePath(env?: Readonly<Record<string, string | undefined>>): string;
3
4
  /**
4
- * The hangar root: `CREWHAUS_HANGAR_ROOT`, else `<registryRoot>/hangar`.
5
- *
6
- * MIRRORED, not imported. `resolveHangarRoot` lives in
7
- * `apps/cli/src/hangar-cmd.ts` and a package cannot depend on the app — the
8
- * same reason `harness-supervisor/src/bundle-freshness.ts` mirrors the
9
- * bundle manifest shape instead of importing it. The second half of the rule
10
- * is not re-derived: `resolveRegistryRoot` is the registry package's own.
11
- * `roots.test.ts` pins both halves, so a change in the app fails a test here
12
- * rather than silently pointing this tool at a ledger nobody writes.
5
+ * The hangar root (`CREWHAUS_HANGAR_ROOT`, else `<registryRoot>/hangar`),
6
+ * resolved by the registry package's own resolver, the one the CLI uses.
13
7
  */
14
- export declare function resolveHangarRoot(env?: Readonly<Record<string, string | undefined>>): string;
8
+ export { resolveHangarRoot };
15
9
  /** The durable job ledger the manager appends to. */
16
10
  export declare const JOB_LEDGER_FILENAME = "jobs.jsonl";
17
11
  /** `<hangarRoot>/jobs.jsonl` — the path `createFileJobStore` is opened on. */
package/dist/lib/roots.js CHANGED
@@ -17,32 +17,17 @@
17
17
  * directory, a settings file — still goes through `resolveSafe` and stays
18
18
  * inside the workspace.
19
19
  */
20
- import { join, resolve } from "node:path";
21
- import { REGISTRY_FILENAME, resolveRegistryRoot } from "@crewhaus/harness-registry";
20
+ import { join } from "node:path";
21
+ import { REGISTRY_FILENAME, resolveHangarRoot, resolveRegistryRoot, } from "@crewhaus/harness-registry";
22
22
  /** `<registryRoot>/harnesses.json` — the file `openHangarRegistry` opens. */
23
23
  export function registryFilePath(env = process.env) {
24
24
  return join(resolveRegistryRoot(env), REGISTRY_FILENAME);
25
25
  }
26
26
  /**
27
- * The hangar root: `CREWHAUS_HANGAR_ROOT`, else `<registryRoot>/hangar`.
28
- *
29
- * MIRRORED, not imported. `resolveHangarRoot` lives in
30
- * `apps/cli/src/hangar-cmd.ts` and a package cannot depend on the app — the
31
- * same reason `harness-supervisor/src/bundle-freshness.ts` mirrors the
32
- * bundle manifest shape instead of importing it. The second half of the rule
33
- * is not re-derived: `resolveRegistryRoot` is the registry package's own.
34
- * `roots.test.ts` pins both halves, so a change in the app fails a test here
35
- * rather than silently pointing this tool at a ledger nobody writes.
27
+ * The hangar root (`CREWHAUS_HANGAR_ROOT`, else `<registryRoot>/hangar`),
28
+ * resolved by the registry package's own resolver, the one the CLI uses.
36
29
  */
37
- export function resolveHangarRoot(env = process.env) {
38
- const explicit = env["CREWHAUS_HANGAR_ROOT"];
39
- // `resolve`, like the app's copy: a relative CREWHAUS_HANGAR_ROOT must
40
- // become the same absolute path the manager opened, not one relative to
41
- // whatever directory this tool happens to run in.
42
- if (explicit !== undefined && explicit !== "")
43
- return resolve(explicit);
44
- return join(resolveRegistryRoot(env), "hangar");
45
- }
30
+ export { resolveHangarRoot };
46
31
  /** The durable job ledger the manager appends to. */
47
32
  export const JOB_LEDGER_FILENAME = "jobs.jsonl";
48
33
  /** `<hangarRoot>/jobs.jsonl` — the path `createFileJobStore` is opened on. */
package/dist/paths.d.ts CHANGED
@@ -1,10 +1,29 @@
1
1
  import { CrewhausError } from "@crewhaus/errors";
2
- /** Raised when a caller-supplied path resolves outside the workspace root. */
2
+ /**
3
+ * The longest path this resolves, in UTF-16 code units; a longer one is
4
+ * refused before it is walked. Nothing that long can be opened or created:
5
+ * PATH_MAX is 1,024 bytes on macOS and 4,096 on Linux, Windows stops at
6
+ * 32,767 UTF-16 units, and a path's UTF-8 form is never shorter than its
7
+ * UTF-16 one. The limit is twice that because the part of a path that exists
8
+ * is itself under PATH_MAX, so the part that does not is over PATH_MAX on its
9
+ * own: no spelling of the place reaches it, not even one through a symlink
10
+ * that shortens the part that exists.
11
+ */
12
+ export declare const MAX_PATH_CHARS: number;
13
+ /**
14
+ * Raised when a caller-supplied path resolves outside the workspace root, or
15
+ * is longer than any path can be.
16
+ */
3
17
  export declare class ToolPermissionError extends CrewhausError {
4
18
  readonly name = "ToolPermissionError";
5
19
  readonly toolName: string;
6
20
  readonly path: string;
7
- constructor(toolName: string, attemptedPath: string);
21
+ /**
22
+ * Why, when it is not that the location escapes the workspace root: a path
23
+ * longer than any path can be. A caller that rewords the refusal says this.
24
+ */
25
+ readonly reason: string | undefined;
26
+ constructor(toolName: string, attemptedPath: string, reason?: string);
8
27
  }
9
28
  /**
10
29
  * A validated path, in both forms the tools need.
package/dist/paths.js CHANGED
@@ -11,15 +11,45 @@
11
11
  import { lstatSync, readlinkSync, realpathSync } from "node:fs";
12
12
  import * as path from "node:path";
13
13
  import { CrewhausError } from "@crewhaus/errors";
14
- /** Raised when a caller-supplied path resolves outside the workspace root. */
14
+ /**
15
+ * The longest path this resolves, in UTF-16 code units; a longer one is
16
+ * refused before it is walked. Nothing that long can be opened or created:
17
+ * PATH_MAX is 1,024 bytes on macOS and 4,096 on Linux, Windows stops at
18
+ * 32,767 UTF-16 units, and a path's UTF-8 form is never shorter than its
19
+ * UTF-16 one. The limit is twice that because the part of a path that exists
20
+ * is itself under PATH_MAX, so the part that does not is over PATH_MAX on its
21
+ * own: no spelling of the place reaches it, not even one through a symlink
22
+ * that shortens the part that exists.
23
+ */
24
+ export const MAX_PATH_CHARS = 2 * (process.platform === "darwin" ? 1_024 : process.platform === "win32" ? 32_767 : 4_096);
25
+ /** A path as a refusal quotes it: whole, unless it is past {@link MAX_PATH_CHARS}. */
26
+ function shownPath(given) {
27
+ return given.length > MAX_PATH_CHARS ? `${given.slice(0, 64)}…` : given;
28
+ }
29
+ /** Why a path past {@link MAX_PATH_CHARS} is refused: its length and the limit. */
30
+ function tooLong(abs) {
31
+ return `it is ${abs.length} characters once resolved, over the ${MAX_PATH_CHARS}-character limit: no path that long can be opened or created`;
32
+ }
33
+ /**
34
+ * Raised when a caller-supplied path resolves outside the workspace root, or
35
+ * is longer than any path can be.
36
+ */
15
37
  export class ToolPermissionError extends CrewhausError {
16
38
  name = "ToolPermissionError";
17
39
  toolName;
18
40
  path;
19
- constructor(toolName, attemptedPath) {
20
- super("tool", `tool "${toolName}" rejected path "${attemptedPath}": resolved location escapes the workspace root`);
41
+ /**
42
+ * Why, when it is not that the location escapes the workspace root: a path
43
+ * longer than any path can be. A caller that rewords the refusal says this.
44
+ */
45
+ reason;
46
+ constructor(toolName, attemptedPath, reason) {
47
+ super("tool", reason === undefined
48
+ ? `tool "${toolName}" rejected path "${attemptedPath}": resolved location escapes the workspace root`
49
+ : `tool "${toolName}" rejected path "${shownPath(attemptedPath)}": ${reason}`);
21
50
  this.toolName = toolName;
22
51
  this.path = attemptedPath;
52
+ this.reason = reason;
23
53
  }
24
54
  }
25
55
  /** The workspace root, resolved. Every path is contained within it. */
@@ -67,15 +97,7 @@ function nameExists(p) {
67
97
  function resolveLocation(target, depth = 0) {
68
98
  if (depth > 40)
69
99
  throw new Error(`symlink chain at "${target}" is too long to resolve`);
70
- let probe = target;
71
- const tail = [];
72
- while (!nameExists(probe)) {
73
- tail.unshift(path.basename(probe));
74
- const parent = path.dirname(probe);
75
- if (parent === probe)
76
- break; // reached the filesystem root
77
- probe = parent;
78
- }
100
+ const { probe, tail } = deepestName(target);
79
101
  let probeReal;
80
102
  try {
81
103
  probeReal = realpathSync(probe);
@@ -97,7 +119,41 @@ function resolveLocation(target, depth = 0) {
97
119
  const base = realpathSync(path.dirname(probe));
98
120
  probeReal = resolveLocation(path.resolve(base, link), depth + 1);
99
121
  }
100
- return tail.length > 0 ? path.join(probeReal, ...tail) : probeReal;
122
+ // One string, not one argument per name: Bun's `path.join` keeps only
123
+ // (argument count mod 65,536) of its arguments.
124
+ return tail.length > 0 ? path.join(probeReal, tail) : probeReal;
125
+ }
126
+ /**
127
+ * `target`, an absolute path, split where its deepest prefix that exists as
128
+ * a NAME ends: that prefix, and the names below it, which do not exist, as
129
+ * one string ("" when `target` itself exists). This is `path.dirname` and
130
+ * `path.basename` worked by index on `target` itself: handing them each
131
+ * shorter prefix in turn copied the rest of the path once per missing name,
132
+ * the square of a count the caller picks.
133
+ */
134
+ function deepestName(target) {
135
+ const top = path.parse(target).root.length;
136
+ const isSep = (i) => target[i] === "/" || target[i] === path.sep;
137
+ let probe = target;
138
+ let start = target.length;
139
+ let stop = -1;
140
+ while (!nameExists(probe)) {
141
+ // `path.basename(probe)` is `target.slice(start, end)`, and
142
+ // `path.dirname(probe)` is `target.slice(0, up)`.
143
+ let end = probe.length;
144
+ while (end > top && isSep(end - 1))
145
+ end--;
146
+ if (stop < 0)
147
+ stop = end;
148
+ start = end;
149
+ while (start > top && !isSep(start - 1))
150
+ start--;
151
+ const up = start > top ? start - 1 : top;
152
+ if (up === probe.length)
153
+ break; // reached the filesystem root
154
+ probe = target.slice(0, up);
155
+ }
156
+ return { probe, tail: stop < 0 ? "" : target.slice(start, stop) };
101
157
  }
102
158
  export function resolveSafe(toolName, rel, root = workspaceRoot()) {
103
159
  const rootResolved = path.resolve(root);
@@ -107,6 +163,9 @@ export function resolveSafe(toolName, rel, root = workspaceRoot()) {
107
163
  if (abs !== rootResolved && !abs.startsWith(`${rootResolved}${path.sep}`)) {
108
164
  throw new ToolPermissionError(toolName, rel);
109
165
  }
166
+ // Longer than any path can be: refused before the walk below reads it.
167
+ if (abs.length > MAX_PATH_CHARS)
168
+ throw new ToolPermissionError(toolName, rel, tooLong(abs));
110
169
  let real;
111
170
  try {
112
171
  const rootReal = realpathSync(rootResolved);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@crewhaus/tool-fleet",
3
- "version": "0.7.0",
3
+ "version": "0.8.1",
4
4
  "type": "module",
5
5
  "description": "Deterministic fleet operations: register, recompile, version-pin and inspect the harnesses on this machine",
6
6
  "main": "dist/index.js",
@@ -8,19 +8,21 @@
8
8
  "exports": {
9
9
  ".": {
10
10
  "types": "./dist/index.d.ts",
11
- "import": "./dist/index.js"
11
+ "import": "./dist/index.js",
12
+ "default": "./dist/index.js"
12
13
  }
13
14
  },
14
15
  "scripts": {
15
16
  "test": "bun test src"
16
17
  },
17
18
  "dependencies": {
18
- "@crewhaus/errors": "0.7.0",
19
- "@crewhaus/harness-registry": "0.7.0",
20
- "@crewhaus/harness-supervisor": "0.7.0",
21
- "@crewhaus/spec": "0.7.0",
22
- "@crewhaus/tool-builder": "0.7.0",
23
- "@crewhaus/tool-catalog": "0.7.0",
19
+ "@crewhaus/errors": "0.8.1",
20
+ "@crewhaus/harness-registry": "0.8.1",
21
+ "@crewhaus/harness-supervisor": "0.8.1",
22
+ "@crewhaus/spec": "0.8.1",
23
+ "@crewhaus/tool-builder": "0.8.1",
24
+ "@crewhaus/tool-catalog": "0.8.1",
25
+ "@crewhaus/tool-safety": "0.8.1",
24
26
  "zod": "^3.23.8"
25
27
  },
26
28
  "devDependencies": {
@@ -44,5 +46,8 @@
44
46
  "publishConfig": {
45
47
  "access": "public"
46
48
  },
47
- "files": ["dist", "README.md", "LICENSE", "NOTICE"]
49
+ "files": ["dist", "README.md", "LICENSE", "NOTICE"],
50
+ "engines": {
51
+ "bun": ">=1.3.14"
52
+ }
48
53
  }