@crewhaus/tool-fleet 0.7.0 → 0.8.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/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
@@ -123,10 +123,18 @@ The exception is deliberate and no input can move it. The two machine-wide files
123
123
  (`CREWHAUS_REGISTRY_ROOT`, `CREWHAUS_HANGAR_ROOT`), because a registry that only ever saw the
124
124
  current workspace would not be a registry. Their absolute paths are reported in every result.
125
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.
126
+ `CompileBundle` executes `crewhaus compile`. The binary comes from the supervisor's own resolver —
127
+ harness-local `node_modules/.bin/crewhaus` first, then `PATH` — and a binary that resolves OUTSIDE
128
+ the workspace is refused unless `allowExternalCli` is passed, with its path named.
129
+
130
+ `CliVersionPin --probe` does not run a CLI the workspace supplies. A cloned repository can commit
131
+ `node_modules/.bin/crewhaus`, and this tool is not destructive, so auto mode runs it without asking.
132
+ The version is READ from the `package.json` of the `crewhaus` package the binary belongs to (npm's
133
+ `.bin` entry links into `node_modules/crewhaus/`), found by walking up from where the binary really
134
+ is and then at `<harness>/node_modules/crewhaus/package.json`; each read is contained, and a
135
+ `package.json` a link puts outside the workspace is refused, not read. A CLI outside the workspace
136
+ is the operator's own install: it is read the same way with `allowExternalCli`, and only a
137
+ standalone binary with no `package.json` (brew, scoop) is asked with `--version`.
130
138
 
131
139
  ## What a compile is given
132
140
 
@@ -212,7 +220,8 @@ Every result is one JSON object carrying a `status`:
212
220
 
213
221
  ## Notes
214
222
 
215
- - `HarnessJobStatus` and `CliVersionPin` declare `readOnly: true`, and nothing they do writes.
223
+ - `HarnessJobStatus` declares `readOnly: true`; `CliVersionPin` does not (0.7.1: it can run the
224
+ operator's own standalone CLI, see above), but is not destructive either. Nothing either does writes.
216
225
  `harness-registry`'s `list()` normally persists its own missing-directory stamps and any pending
217
226
  pre-v2 lift ON A READ, so merely reporting the fleet would edit a machine-wide file — and
218
227
  `readOnly` is a flag a permission layer acts on, not a note. Every enumerating READ here opens
package/dist/index.js CHANGED
@@ -68,8 +68,8 @@ 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
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";
71
+ import { CLI_VERSION_RE, externalBinRefusal, freshnessOf, readCliVersion, readSpecFacts, resolveCli, spawnEnv, } from "./lib/bundle";
72
+ import { countByState, filterJobs, jobView, ledgerBlockedBy, parseIsoInstant, probeLedger, sortJobs, } from "./lib/jobs";
73
73
  import { entryView, mutationBlockedBy, probeRegistryFile, sortEntries } from "./lib/registry";
74
74
  import { compareStrings, contain, containExistingDir, containUnder, containWritePaths, isInside, json, refusal, renderPath, renderStorePath, renderText, sample, } from "./lib/result";
75
75
  import { jobLedgerPath, registryFilePath } from "./lib/roots";
@@ -209,7 +209,12 @@ const updateFields = {
209
209
  };
210
210
  export const harnessRegister = buildTool({
211
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.",
212
+ operativeArgs: [
213
+ { field: "dir", kind: "path" },
214
+ { field: "from", kind: "path" },
215
+ { field: "id", kind: "id" },
216
+ ],
217
+ 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
218
  inputSchema: z.object({
214
219
  action: z
215
220
  .enum(["list", "register", "remove", "relocate", "update"])
@@ -642,6 +647,7 @@ const JOB_STATES = [
642
647
  export const JOB_STATES_COVER_JOBSTATE = true;
643
648
  export const harnessJobStatus = buildTool({
644
649
  name: "HarnessJobStatus",
650
+ operativeArgs: [{ field: "dir", kind: "path" }],
645
651
  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
652
  inputSchema: z.object({
647
653
  jobId: z.string().min(1).max(200).optional().describe("a single job"),
@@ -656,7 +662,7 @@ export const harnessJobStatus = buildTool({
656
662
  .string()
657
663
  .min(1)
658
664
  .optional()
659
- .describe("only jobs enqueued at or after this ISO 8601 instant"),
665
+ .describe("only jobs enqueued at or after this ISO 8601 instant; one without Z or an offset is read as UTC"),
660
666
  limit: z
661
667
  .number()
662
668
  .int()
@@ -688,8 +694,9 @@ export const harnessJobStatus = buildTool({
688
694
  // Both spellings: the manager records whichever path it was handed.
689
695
  harnessDirs = spellings(safe.value);
690
696
  }
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);
697
+ const since = input.since === undefined ? undefined : parseIsoInstant(input.since);
698
+ if (input.since !== undefined && since === undefined) {
699
+ 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
700
  }
694
701
  const records = createFileJobStore(ledger).read();
695
702
  const { kept, unparsedTimestamps } = filterJobs(records, {
@@ -707,6 +714,15 @@ export const harnessJobStatus = buildTool({
707
714
  status: "ok",
708
715
  // Three different questions: how many records the fold produced, how
709
716
  // many survived the filter, how many are shown.
717
+ ...(since !== undefined
718
+ ? {
719
+ // The instant actually filtered on, so a reader can check it.
720
+ sinceUtc: new Date(since.ms).toISOString(),
721
+ ...(since.offsetGiven
722
+ ? {}
723
+ : { sinceNote: "since had no Z or offset, so it was read as UTC" }),
724
+ }
725
+ : {}),
710
726
  recordsInLedger: records.length,
711
727
  matched: ordered.length,
712
728
  shown: Math.min(ordered.length, limit),
@@ -731,7 +747,8 @@ export const harnessJobStatus = buildTool({
731
747
  // ---------------------------------------------------------------------------
732
748
  export const compileBundle = buildTool({
733
749
  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.",
750
+ operativeArgs: [{ field: "dir", kind: "path", default: ".", beneath: "all" }],
751
+ 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
752
  inputSchema: z.object({
736
753
  dir: z
737
754
  .string()
@@ -944,11 +961,10 @@ export const compileBundle = buildTool({
944
961
  });
945
962
  },
946
963
  });
947
- /** A semver-shaped token, wherever a CLI prints it. */
948
- const VERSION_RE = /\b\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?\b/;
949
964
  export const cliVersionPin = buildTool({
950
965
  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.",
966
+ operativeArgs: [{ field: "dirs", kind: "path" }],
967
+ 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
968
  inputSchema: z.object({
953
969
  dirs: z
954
970
  .array(z.string())
@@ -958,17 +974,24 @@ export const cliVersionPin = buildTool({
958
974
  probe: z
959
975
  .boolean()
960
976
  .optional()
961
- .describe("run `<bin> --version` once per distinct binary (default false)"),
977
+ .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
978
  allowExternalCli: z
963
979
  .boolean()
964
980
  .optional()
965
- .describe("allow probing a binary that resolves outside the workspace"),
981
+ .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
982
  includeMissing: z
967
983
  .boolean()
968
984
  .optional()
969
985
  .describe("include registry entries whose directory has vanished (default false)"),
970
986
  }),
971
- readOnly: true,
987
+ // NOT read-only (0.7.1, permission-integration#7), and never runs a
988
+ // program the workspace supplies (C048): a harness-local CLI's version is
989
+ // READ from its package.json. The one thing it may run is the operator's
990
+ // own install outside the workspace, with allowExternalCli, when that is a
991
+ // standalone binary with no package.json — hence scope/io stay external
992
+ // and process. Nothing it runs changes anything, so it is not destructive,
993
+ // and auto mode allows it.
994
+ readOnly: false,
972
995
  scope: "external",
973
996
  ioCapability: "process",
974
997
  execute: async (input) => {
@@ -1117,6 +1140,22 @@ export const cliVersionPin = buildTool({
1117
1140
  probes[bin] = { state: "not-probed", reason: external.reason };
1118
1141
  continue;
1119
1142
  }
1143
+ // C048: the version is READ from the crewhaus package the binary
1144
+ // belongs to. A binary inside the workspace is never run — a cloned
1145
+ // repository can commit one, and auto mode runs this tool unasked.
1146
+ const reading = readCliVersion(item.cli, item.safe.real, root, input.allowExternalCli === true);
1147
+ if (reading.state !== "needs-exec") {
1148
+ probes[bin] =
1149
+ reading.state === "known"
1150
+ ? { state: "known", version: reading.version, source: reading.source }
1151
+ : reading.state === "unparsed"
1152
+ ? { state: "unparsed", reason: reading.reason, source: reading.source }
1153
+ : { state: "unknown", reason: reading.reason };
1154
+ continue;
1155
+ }
1156
+ // Only the operator's own install outside the workspace, allowed by
1157
+ // allowExternalCli, with no package.json (a standalone binary) gets
1158
+ // here: running its `--version` is the only way to ask it.
1120
1159
  let outcome;
1121
1160
  try {
1122
1161
  outcome = await runPrepareCommand({
@@ -1157,7 +1196,7 @@ export const cliVersionPin = buildTool({
1157
1196
  // PARSE, then report the PARSED value. A line that carries no
1158
1197
  // version is not a version, and echoing the raw line as one is how a
1159
1198
  // startup banner ends up in a version table.
1160
- const matched = VERSION_RE.exec(outcome.output.join("\n"));
1199
+ const matched = CLI_VERSION_RE.exec(outcome.output.join("\n"));
1161
1200
  probes[bin] =
1162
1201
  matched === null
1163
1202
  ? {
@@ -1216,7 +1255,14 @@ export const cliVersionPin = buildTool({
1216
1255
  // ---------------------------------------------------------------------------
1217
1256
  export const hooksManage = buildTool({
1218
1257
  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.",
1258
+ operativeArgs: [
1259
+ // The harness's settings file, which it reads and rewrites.
1260
+ { field: "dir", kind: "path", default: ".", opens: [{ path: ".crewhaus/settings.json" }] },
1261
+ // The supervisor runs the hook from the harness root, and resolves a
1262
+ // `./prep.sh` there: the command is another program in another `dir`.
1263
+ { field: "command", kind: "command", within: "dir" },
1264
+ ],
1265
+ 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
1266
  inputSchema: z.object({
1221
1267
  action: z.enum(["list", "set", "remove"]).describe("`list` never writes"),
1222
1268
  dir: z
@@ -1332,7 +1378,7 @@ export const hooksManage = buildTool({
1332
1378
  const escapes = containWritePaths(tool, safe.value, [rel, tmpRel]);
1333
1379
  if (escapes !== undefined)
1334
1380
  return refusal(tool, escapes.code, escapes.reason, base);
1335
- const tmpAbs = path.join(harness, ...tmpRel.split("/"));
1381
+ const tmpAbs = path.join(harness, tmpRel);
1336
1382
  const doc = probe.doc ?? {};
1337
1383
  const manager = managerBlock(doc);
1338
1384
  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));
@@ -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
  }
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.0",
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.0",
20
+ "@crewhaus/harness-registry": "0.8.0",
21
+ "@crewhaus/harness-supervisor": "0.8.0",
22
+ "@crewhaus/spec": "0.8.0",
23
+ "@crewhaus/tool-builder": "0.8.0",
24
+ "@crewhaus/tool-catalog": "0.8.0",
25
+ "@crewhaus/tool-safety": "0.8.0",
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
  }