@feigi/fleet-ctl 0.0.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.
Files changed (245) hide show
  1. package/.claude-plugin/plugin.json +9 -0
  2. package/LICENSE +202 -0
  3. package/NOTICE +18 -0
  4. package/agents/fleet-finisher.agent.md +7 -0
  5. package/agents/fleet-implementer-alt.agent.md +210 -0
  6. package/agents/fleet-implementer.agent.md +210 -0
  7. package/agents/fleet-merge-bot.agent.md +7 -0
  8. package/agents/fleet-review-comments.agent.md +40 -0
  9. package/agents/fleet-review-correctness.agent.md +43 -0
  10. package/agents/fleet-review-runner.agent.md +73 -0
  11. package/agents/fleet-review-silent-failure.agent.md +49 -0
  12. package/agents/fleet-review-simplify.agent.md +46 -0
  13. package/agents/fleet-review-snapshot.agent.md +24 -0
  14. package/agents/fleet-review-tests.agent.md +46 -0
  15. package/agents/fleet-review-types.agent.md +41 -0
  16. package/agents/fleet-review-verifier.agent.md +29 -0
  17. package/commands/review-and-fix.md +98 -0
  18. package/commands/run-merge-bot.md +357 -0
  19. package/commands/run-team-help.md +17 -0
  20. package/package.json +23 -0
  21. package/scripts/agent-test-dir-prose.test.mjs +59 -0
  22. package/scripts/agent-test.test.mjs +1636 -0
  23. package/scripts/ambient-git-vars-mjs-prose.test.mjs +354 -0
  24. package/scripts/ambient-git-vars-prose.test.mjs +192 -0
  25. package/scripts/ancestry-check-position-prose.test.mjs +175 -0
  26. package/scripts/apply-ruleset.test.mjs +420 -0
  27. package/scripts/arg-header-probes-prose.test.mjs +393 -0
  28. package/scripts/arg.mjs +600 -0
  29. package/scripts/arg.test.mjs +1354 -0
  30. package/scripts/board-cli.test.mjs +694 -0
  31. package/scripts/board-identity.test.mjs +429 -0
  32. package/scripts/board-liveness-banner.test.mjs +119 -0
  33. package/scripts/board-prev-shape.test.mjs +229 -0
  34. package/scripts/board-tryparse-null.test.mjs +119 -0
  35. package/scripts/board.html +471 -0
  36. package/scripts/board.mjs +2037 -0
  37. package/scripts/board.test.mjs +3086 -0
  38. package/scripts/brief-after-cut-prose.test.mjs +53 -0
  39. package/scripts/candidates-exit3-prose.test.mjs +302 -0
  40. package/scripts/candidates.mjs +674 -0
  41. package/scripts/candidates.test.mjs +2101 -0
  42. package/scripts/caveat-unification-prose.test.mjs +98 -0
  43. package/scripts/ci-comment-rot-prose.test.mjs +2025 -0
  44. package/scripts/ci-completes-premise-prose.test.mjs +257 -0
  45. package/scripts/ci-state-prose.test.mjs +113 -0
  46. package/scripts/ci-state.mjs +761 -0
  47. package/scripts/ci-state.test.mjs +1640 -0
  48. package/scripts/ci-vacuous-green.test.mjs +368 -0
  49. package/scripts/citation-sweep-prose.test.mjs +1572 -0
  50. package/scripts/claim-lifecycle.test.mjs +185 -0
  51. package/scripts/claim-ticket.sh +417 -0
  52. package/scripts/claim-ticket.test.mjs +1121 -0
  53. package/scripts/closing-keyword-prose.test.mjs +193 -0
  54. package/scripts/cockpit-launch-idempotent-prose.test.mjs +165 -0
  55. package/scripts/cockpit-tick-nonblocking.test.mjs +210 -0
  56. package/scripts/compute-board.mjs +579 -0
  57. package/scripts/compute-board.test.mjs +1060 -0
  58. package/scripts/compute-spend.mjs +329 -0
  59. package/scripts/compute-spend.test.mjs +451 -0
  60. package/scripts/cross-repo-citation-prose.test.mjs +156 -0
  61. package/scripts/cwd-isolation-pins.mjs +83 -0
  62. package/scripts/dedupe-guard-prose.test.mjs +243 -0
  63. package/scripts/derive-testcmd.sh +239 -0
  64. package/scripts/derive-testcmd.test.mjs +380 -0
  65. package/scripts/diff-stats.mjs +231 -0
  66. package/scripts/diff-stats.test.mjs +408 -0
  67. package/scripts/dispatch-block-golden-prose.test.mjs +1024 -0
  68. package/scripts/dispatch-block-pins-prose.test.mjs +615 -0
  69. package/scripts/drop-merged-label.sh +173 -0
  70. package/scripts/drop-merged-label.test.mjs +480 -0
  71. package/scripts/expected-jobs-prose.test.mjs +80 -0
  72. package/scripts/filing-bar-seat-prose.test.mjs +242 -0
  73. package/scripts/filing-claim-bar-prose.test.mjs +166 -0
  74. package/scripts/finisher-dispatch-premise-prose.test.mjs +312 -0
  75. package/scripts/finisher-halt-prose.test.mjs +106 -0
  76. package/scripts/finisher-name-prose.test.mjs +134 -0
  77. package/scripts/finisher-own-tree-prose.test.mjs +285 -0
  78. package/scripts/finisher-pin-race-prose.test.mjs +339 -0
  79. package/scripts/fix-applier-correction-rules-prose.test.mjs +201 -0
  80. package/scripts/fix-applier-result-file-prose.test.mjs +100 -0
  81. package/scripts/fleet-bootstrap +155 -0
  82. package/scripts/fleet-heartbeat.mjs +272 -0
  83. package/scripts/fleet-heartbeat.test.mjs +450 -0
  84. package/scripts/fleet-provenance +207 -0
  85. package/scripts/fleet-provenance.test.mjs +64 -0
  86. package/scripts/fleet-run +148 -0
  87. package/scripts/fleet-run.test.mjs +90 -0
  88. package/scripts/fleet-state.mjs +400 -0
  89. package/scripts/fleet-state.test.mjs +373 -0
  90. package/scripts/fleet-tick-prose.test.mjs +299 -0
  91. package/scripts/fleet-tick.mjs +832 -0
  92. package/scripts/fleet-tick.test.mjs +1332 -0
  93. package/scripts/force-with-lease-reason-prose.test.mjs +184 -0
  94. package/scripts/frontmatter-allowlist.json +64 -0
  95. package/scripts/frontmatter-check.mjs +256 -0
  96. package/scripts/frontmatter-check.test.mjs +436 -0
  97. package/scripts/git-env.mjs +124 -0
  98. package/scripts/git-env.test.mjs +149 -0
  99. package/scripts/git-status-untracked-mode-sweep.test.mjs +216 -0
  100. package/scripts/gone-walk.test.mjs +213 -0
  101. package/scripts/gp-sep-invariant-prose.test.mjs +188 -0
  102. package/scripts/head-moved-after-label-prose.test.mjs +233 -0
  103. package/scripts/immutable-body-claim-prose.test.mjs +413 -0
  104. package/scripts/implementer-model-tier.test.mjs +643 -0
  105. package/scripts/inflight-citation-prose.test.mjs +144 -0
  106. package/scripts/inflight-exit2-prose.test.mjs +81 -0
  107. package/scripts/inflight-probe-guard-prose.test.mjs +109 -0
  108. package/scripts/inflight-scan-scope-prose.test.mjs +57 -0
  109. package/scripts/inflight.sh +1106 -0
  110. package/scripts/inflight.test.mjs +2984 -0
  111. package/scripts/injection-control-prose.test.mjs +404 -0
  112. package/scripts/install-root-audit.test.mjs +464 -0
  113. package/scripts/instrument-check-prose.test.mjs +235 -0
  114. package/scripts/instruments.sh +394 -0
  115. package/scripts/instruments.test.mjs +787 -0
  116. package/scripts/issue-tracker-prose.test.mjs +71 -0
  117. package/scripts/json.sh +248 -0
  118. package/scripts/json.test.mjs +364 -0
  119. package/scripts/ledger-dispatch.test.mjs +516 -0
  120. package/scripts/ledger-grammar.mjs +85 -0
  121. package/scripts/ledger-grammar.test.mjs +142 -0
  122. package/scripts/ledger-read-require-file.test.mjs +197 -0
  123. package/scripts/ledger.mjs +1753 -0
  124. package/scripts/ledger.test.mjs +3554 -0
  125. package/scripts/line-distance-prose.test.mjs +245 -0
  126. package/scripts/liveness-rationale-prose.test.mjs +83 -0
  127. package/scripts/locale-pin-prose.test.mjs +189 -0
  128. package/scripts/member-outcome-prose.test.mjs +167 -0
  129. package/scripts/member-outcomes-header.test.mjs +148 -0
  130. package/scripts/member-outcomes-prose.test.mjs +63 -0
  131. package/scripts/member-outcomes.mjs +231 -0
  132. package/scripts/member-outcomes.test.mjs +507 -0
  133. package/scripts/member-prompt-prose.test.mjs +161 -0
  134. package/scripts/member-record.mjs +605 -0
  135. package/scripts/member-record.test.mjs +516 -0
  136. package/scripts/member-write-guard.mjs +279 -0
  137. package/scripts/member-write-guard.test.mjs +211 -0
  138. package/scripts/merge-commit-probe-prose.test.mjs +122 -0
  139. package/scripts/merge-gate.mjs +262 -0
  140. package/scripts/merge-gate.test.mjs +613 -0
  141. package/scripts/muted-git-guard-sweep.test.mjs +493 -0
  142. package/scripts/net-ssh-precedence-prose.test.mjs +91 -0
  143. package/scripts/net-watchdog-prose.test.mjs +79 -0
  144. package/scripts/net.sh +409 -0
  145. package/scripts/net.test.mjs +211 -0
  146. package/scripts/no-ci-gate-prose.test.mjs +108 -0
  147. package/scripts/no-undo-audit.sh +1134 -0
  148. package/scripts/no-undo-audit.test.mjs +3965 -0
  149. package/scripts/no-wave.test.mjs +138 -0
  150. package/scripts/node-floor-sweep.test.mjs +611 -0
  151. package/scripts/pointer-target-prose.test.mjs +186 -0
  152. package/scripts/pr-overlap.mjs +417 -0
  153. package/scripts/pr-overlap.test.mjs +695 -0
  154. package/scripts/printf-die-sweep.test.mjs +384 -0
  155. package/scripts/prompt-renderer.mjs +39 -0
  156. package/scripts/prompt-renderer.test.mjs +68 -0
  157. package/scripts/prose-pin.mjs +808 -0
  158. package/scripts/prose-pin.test.mjs +1034 -0
  159. package/scripts/prove-merge.sh +228 -0
  160. package/scripts/prove-merge.test.mjs +995 -0
  161. package/scripts/pull-table-relabel-prose.test.mjs +60 -0
  162. package/scripts/quiet-payload-prose.test.mjs +222 -0
  163. package/scripts/reap.sh +1768 -0
  164. package/scripts/reap.test.mjs +4395 -0
  165. package/scripts/reaping-prose.test.mjs +159 -0
  166. package/scripts/refuter-scratch-prose.test.mjs +135 -0
  167. package/scripts/release-label-required-prose.test.mjs +71 -0
  168. package/scripts/release-label-split-prose.test.mjs +169 -0
  169. package/scripts/release-ticket.sh +1716 -0
  170. package/scripts/release-ticket.test.mjs +5106 -0
  171. package/scripts/renovate-release-contract.test.mjs +379 -0
  172. package/scripts/repo-root.mjs +544 -0
  173. package/scripts/repo-root.test.mjs +873 -0
  174. package/scripts/reporter-output-rule-prose.test.mjs +208 -0
  175. package/scripts/review-agent-report-only.test.mjs +49 -0
  176. package/scripts/review-core-cwd-isolation.test.mjs +374 -0
  177. package/scripts/review-core-reads.test.mjs +478 -0
  178. package/scripts/review-core-refuter-scratch.test.mjs +148 -0
  179. package/scripts/review-core-snapshot-path.test.mjs +777 -0
  180. package/scripts/review-core-specialist-scratch.test.mjs +189 -0
  181. package/scripts/review-core-testcmd.test.mjs +288 -0
  182. package/scripts/review-core-unrun.test.mjs +530 -0
  183. package/scripts/review-core-unverified-discriminant.test.mjs +208 -0
  184. package/scripts/review-core.mjs +1028 -0
  185. package/scripts/review-eval-resolver-path.test.mjs +55 -0
  186. package/scripts/review-eval.mjs +197 -0
  187. package/scripts/review-host-fixture.mjs +73 -0
  188. package/scripts/review-in-run-retry.test.mjs +187 -0
  189. package/scripts/review-no-vendor-dispatch.test.mjs +45 -0
  190. package/scripts/review-path-default.test.mjs +796 -0
  191. package/scripts/review-runner-spawns.test.mjs +93 -0
  192. package/scripts/review-runner.test.mjs +155 -0
  193. package/scripts/review-tier-audit.test.mjs +140 -0
  194. package/scripts/run-artifact-pr-prose.test.mjs +341 -0
  195. package/scripts/run-merge-bot-prose.test.mjs +1391 -0
  196. package/scripts/scratch-partition-invariant-prose.test.mjs +74 -0
  197. package/scripts/scripts-path-citation-sweep.test.mjs +73 -0
  198. package/scripts/section-between-guard-prose.test.mjs +378 -0
  199. package/scripts/select-dimensions.test.mjs +674 -0
  200. package/scripts/shared-refusal.test.mjs +388 -0
  201. package/scripts/shell-traps-prose.test.mjs +507 -0
  202. package/scripts/shortlist.mjs +355 -0
  203. package/scripts/shortlist.test.mjs +366 -0
  204. package/scripts/slow-transport.mjs +72 -0
  205. package/scripts/snapshot-repo.test.mjs +772 -0
  206. package/scripts/snapshot-runner-audience-prose.test.mjs +129 -0
  207. package/scripts/spend-view.test.mjs +312 -0
  208. package/scripts/staleness-qualifier-prose.test.mjs +251 -0
  209. package/scripts/staleness-verdict-prose.test.mjs +142 -0
  210. package/scripts/staleness.mjs +414 -0
  211. package/scripts/staleness.test.mjs +893 -0
  212. package/scripts/stalled-member-liveness-prose.test.mjs +219 -0
  213. package/scripts/stash-prohibition-prose.test.mjs +313 -0
  214. package/scripts/strip-comments.mjs +44 -0
  215. package/scripts/tier-check.mjs +468 -0
  216. package/scripts/tier-check.test.mjs +726 -0
  217. package/scripts/tier-guard-gate-prose.test.mjs +216 -0
  218. package/scripts/tier-outcomes-header.test.mjs +586 -0
  219. package/scripts/tier-outcomes.mjs +441 -0
  220. package/scripts/tier-outcomes.test.mjs +342 -0
  221. package/scripts/tier-roles.mjs +250 -0
  222. package/scripts/tier-roles.test.mjs +316 -0
  223. package/scripts/tracker-block-copy-prose.test.mjs +288 -0
  224. package/scripts/triage-labels-gloss-prose.test.mjs +97 -0
  225. package/scripts/unattended-git-sweep.test.mjs +142 -0
  226. package/scripts/verify-sha-exit2-prose.test.mjs +269 -0
  227. package/scripts/verify-sha.sh +117 -0
  228. package/scripts/verify-sha.test.mjs +693 -0
  229. package/scripts/watcher-degraded-block.test.mjs +372 -0
  230. package/scripts/watcher-key-prose.test.mjs +106 -0
  231. package/scripts/within-run-pair-prose.test.mjs +208 -0
  232. package/scripts/worktree-audit.sh +482 -0
  233. package/scripts/worktree-audit.test.mjs +1407 -0
  234. package/scripts/worktree-head-prose.test.mjs +276 -0
  235. package/scripts/worktree-listing-sweep.test.mjs +217 -0
  236. package/scripts/worktree-model-prose.test.mjs +216 -0
  237. package/scripts/worktree.sh +470 -0
  238. package/skills/next-ticket/SKILL.md +138 -0
  239. package/skills/run-team/SKILL.md +3603 -0
  240. package/skills/run-team/references/ci-and-staleness.md +75 -0
  241. package/skills/run-team/references/correction-tickets.md +37 -0
  242. package/skills/run-team/references/isolation.md +23 -0
  243. package/skills/run-team/references/member-lifecycle.md +73 -0
  244. package/skills/run-team/references/reaping.md +73 -0
  245. package/skills/sizing-a-ticket/SKILL.md +39 -0
@@ -0,0 +1,279 @@
1
+ // The fleet's member write boundary, enforced (#1411, ADR 0020). An omp
2
+ // extension: `plugin/package.json#omp.extensions` names this file, and a
3
+ // native install (link/npm — ADR 0021; a marketplace cache install loads it
4
+ // the same way) loads it into every omp session on the box — the
5
+ // controller's, every member's, and every unrelated session's — rebinding the
6
+ // factory below into each subagent session the `task` tool spawns.
7
+ //
8
+ // THE HAZARD. `write`/`edit`/`ast_edit` resolve a bare relative path against
9
+ // the session cwd, and a `task`-dispatched member inherits the controller's:
10
+ // the main checkout, never the member's claimed worktree. A member that writes
11
+ // `plugin/scripts/foo.mjs` therefore edits the tree every other member and the
12
+ // controller read their instruments out of. Prose told members so and they
13
+ // kept doing it, so the rule is now a refusal: a `tool_call` handler that
14
+ // returns `{block: true, reason}` stops the call before it runs, and the
15
+ // member sees the reason as the tool's error.
16
+ //
17
+ // WHO IS GUARDED — nothing else, because this loads in every session:
18
+ // - any subagent whose definition name starts with `fleet-`;
19
+ // - any subagent whose own id is a fleet member's task name (`impl-1411`,
20
+ // `fix-pr-88`, `review-pr-2245`, `finisher-pr-7`, with an optional `-b`
21
+ // recovery suffix): this is how a fix-applier is caught, since it is
22
+ // dispatched under a generic `task` definition with no `fleet-` prefix;
23
+ // - any subagent spawned BY a fleet member: its `parentId` is the member's
24
+ // task name, while its own definition name is a generic one no prefix
25
+ // check could see.
26
+ // A top-level (`kind: "main"`) session is never guarded: that is the
27
+ // controller, whose own writes into its checkout are its job.
28
+ //
29
+ // TWO RULES.
30
+ // - Path writers (`write`, `edit`, `ast_edit`), for everyone guarded: refuse
31
+ // when a target resolves inside the main checkout and `git check-ignore`
32
+ // says it is not ignored. `.worktrees/`, `.fleet/` and `.agent-brain/` are
33
+ // ignored in a fleet repo, so worktrees, run state and agent-brain's cache
34
+ // stay writable, and what is protected is exactly what the main
35
+ // checkout's `git status` would show dirty (#2210 watches the same set).
36
+ // - `bash` cwd, for `fleet-implementer`/`fleet-implementer-alt`, and for a
37
+ // fix-applier's own id (`fix-pr-<n>`) directly, since a fix-applier is
38
+ // NOT dispatched as `fleet-implementer` today: refuse when
39
+ // `input.cwd ?? ctx.cwd` lies inside the main checkout outside
40
+ // `.worktrees/`. Command text is never parsed. Review specialists and
41
+ // refuters are REQUIRED to start from the inherited cwd (`pwd` first,
42
+ // then `cd` inside the command), the finisher runs its audit and
43
+ // `git worktree add` from there, and children follow ad-hoc briefs — so
44
+ // none of them gets this rule.
45
+ // Never a rewrite: a refusal names the resolved path and tells the member to
46
+ // re-issue it absolute under its worktree. Relative READS and `eval` are not
47
+ // guarded here; #2210's detection covers `eval`.
48
+ //
49
+ // WHEN IT CANNOT DECIDE. A cwd outside any git repository is allowed — there
50
+ // is no main checkout to protect. A git that fails while resolving the main
51
+ // checkout or answering `check-ignore` BLOCKS, naming the failure: a guard
52
+ // that fails open on "could not look" protects nothing. omp fails closed the
53
+ // same way on a handler that throws or times out.
54
+ //
55
+ // `decide()` is the whole policy and touches nothing: the handler resolves the
56
+ // main checkout, then hands it and a `check-ignore` probe in. The main
57
+ // checkout is the parent of `git rev-parse --git-common-dir` (git-env.mjs's
58
+ // `workspaceDirFromGitCommonDir`, as `fleet-tick.mjs` resolves the run's
59
+ // workspace) — never `--show-toplevel`, which answers a WORKTREE's root from
60
+ // inside one — and every git child gets `gitEnv()`, so an ambient GIT_DIR
61
+ // cannot answer for another repository (#1599).
62
+ //
63
+ // Zero deps: `node --test plugin/scripts/member-write-guard.test.mjs`.
64
+
65
+ import { spawn } from "node:child_process";
66
+ import { realpathSync } from "node:fs";
67
+ import { homedir } from "node:os";
68
+ import { basename, dirname, isAbsolute, join, resolve, sep } from "node:path";
69
+ import { fileURLToPath } from "node:url";
70
+ import { gitEnv, workspaceDirFromGitCommonDir } from "./git-env.mjs";
71
+
72
+ /** The task names the controller gives fleet members; a subagent whose parent carries one is a member's child, and a fix-applier — dispatched under a generic `task` definition with no `fleet-` prefix — is caught by its own id matching this directly. */
73
+ const MEMBER_TASK_NAME = /^(impl|fix-pr|review-pr|finisher-pr)-\d+(-[a-z])?$/;
74
+ const FIX_APPLIER_ID = /^fix-pr-\d+(-[a-z])?$/;
75
+ const BASH_CWD_AGENTS = new Set(["fleet-implementer", "fleet-implementer-alt"]);
76
+ const PATH_WRITERS = new Set(["write", "edit", "ast_edit"]);
77
+ const GIT_TIMEOUT_MS = 10_000;
78
+ const REISSUE = "Re-issue it with an absolute path under your worktree `.worktrees/<n>-<slug>/`.";
79
+
80
+ /** Whether `decide()` could refuse this call — the handler's cheap gate before it spends a git call. Never throws: it runs for every tool call in every session. */
81
+ function applies(agent, toolName) {
82
+ if (agent?.kind !== "sub") return false;
83
+ const name = typeof agent.name === "string" ? agent.name : "";
84
+ const id = typeof agent.id === "string" ? agent.id : "";
85
+ if (toolName === "bash") return BASH_CWD_AGENTS.has(name) || FIX_APPLIER_ID.test(id);
86
+ return PATH_WRITERS.has(toolName)
87
+ && (name.startsWith("fleet-") || MEMBER_TASK_NAME.test(id)
88
+ || (typeof agent.parentId === "string" && MEMBER_TASK_NAME.test(agent.parentId)));
89
+ }
90
+
91
+ // The textual shapes an `edit` payload names its files in. omp adds `path` /
92
+ // `paths` to the event from the hashline headers itself; the headers are read
93
+ // here too so a payload the host did not normalise is not a silent pass, and
94
+ // `MV` destinations and apply_patch-mode headers are read because nothing
95
+ // else names them.
96
+ function editPayloadPaths(text) {
97
+ const out = [];
98
+ const unquote = (s) => (s.length >= 2 && (s[0] === '"' || s[0] === "'") && s.at(-1) === s[0] ? s.slice(1, -1) : s);
99
+ for (const raw of text.replace(/^\uFEFF/, "").split("\n")) {
100
+ const line = raw.replace(/\r$/, "");
101
+ const header = /^\[(.+)\]$/.exec(line) ?? /^\s*¶+(.+)$/.exec(line);
102
+ if (header) {
103
+ out.push(unquote(header[1].trim().replace(/#[0-9a-fA-F]{4}$/, "")));
104
+ continue;
105
+ }
106
+ const other = /^MV\s+(.+)$/.exec(line) ?? /^\*\*\* (?:(?:Add|Update|Delete) File|Move to): (.+)$/.exec(line);
107
+ if (other) out.push(unquote(other[1].trim()));
108
+ }
109
+ return out;
110
+ }
111
+
112
+ /** Every raw target path a path-writer call names, as the model wrote it. */
113
+ function targets(toolName, input) {
114
+ const i = input && typeof input === "object" ? input : {};
115
+ const found = [];
116
+ const add = (v) => { if (typeof v === "string" && v.trim() !== "") found.push(v.trim()); };
117
+ const addAll = (v) => { if (Array.isArray(v)) v.forEach(add); };
118
+ if (toolName === "write") add(i.path);
119
+ if (toolName === "edit") {
120
+ add(i.path);
121
+ add(i._path);
122
+ addAll(i.paths);
123
+ for (const key of ["input", "_input"]) if (typeof i[key] === "string") editPayloadPaths(i[key]).forEach(add);
124
+ }
125
+ if (toolName === "ast_edit") addAll(i.paths);
126
+ return [...new Set(found)];
127
+ }
128
+
129
+ // A raw path as omp's own resolver reads it (path-utils.ts `expandPath`): a
130
+ // stray `:` or `@` ahead of an absolute or `~` path is dropped, `file://` is a
131
+ // path, `~` is home. Any other `scheme://` is an internal URL (`local://`,
132
+ // `xd://`, `agent://`) and names no file in any checkout: null. An ast_edit
133
+ // glob needs no cutting: its literal spelling lies inside or outside the main
134
+ // checkout exactly as the directory it scans from does, and `check-ignore`
135
+ // reads it as a plain pathname.
136
+ function fsPath(raw, cwd) {
137
+ let p = raw;
138
+ if (/^:(?=[/\\~]|\.\.?[/\\])/.test(p)) p = p.slice(1);
139
+ if (/^@(?=[/~])/.test(p)) p = p.slice(1);
140
+ if (/^file:\/\//i.test(p)) {
141
+ try { p = fileURLToPath(p); } catch { return null; }
142
+ } else if (/^[a-z][a-z0-9+.-]*:\/\//i.test(p)) {
143
+ return null;
144
+ }
145
+ if (p === "~" || p.startsWith("~/")) p = homedir() + p.slice(1);
146
+ return resolve(cwd, p);
147
+ }
148
+
149
+ const within = (root, p) => p === root || p.startsWith(root.endsWith(sep) ? root : root + sep);
150
+
151
+ /**
152
+ * The policy: `undefined` to let the call run, `{block: true, reason}` to
153
+ * refuse it. Pure — every effect is passed in:
154
+ * - `mainRoot`: the main checkout's absolute path, `null` when `cwd` is in
155
+ * no git repository (allow), or an `Error` when git could not say (block);
156
+ * - `isIgnored(absPath)`: resolves true/false from `git check-ignore`, and
157
+ * rejects when git fails (block);
158
+ * - `canonical(absPath)`: the symlink-free spelling of a path that may not
159
+ * exist yet, so `/var/…` and `/private/var/…` compare equal. Identity by
160
+ * default; the handler passes the real one.
161
+ * `cwd` is the session cwd relative paths resolve against, `path.resolve(cwd, p)`.
162
+ */
163
+ export async function decide({ toolName, input, cwd, agent, mainRoot, isIgnored, canonical = (p) => p }) {
164
+ if (!applies(agent, toolName)) return undefined;
165
+ if (mainRoot === null) return undefined;
166
+ if (mainRoot instanceof Error) {
167
+ return { block: true, reason: `member-write-guard: refused ${toolName} — could not resolve the main checkout from ${cwd} (${mainRoot.message}), and a guard that cannot look does not let the call through. ${REISSUE}` };
168
+ }
169
+ if (typeof mainRoot !== "string" || mainRoot === "") {
170
+ return { block: true, reason: `member-write-guard: refused ${toolName} — the main checkout resolved to an unusable value, and a guard that cannot look does not let the call through. ${REISSUE}` };
171
+ }
172
+
173
+ if (toolName === "bash") {
174
+ const asked = typeof input?.cwd === "string" && input.cwd.trim() !== "" ? input.cwd : cwd;
175
+ const at = canonical(fsPath(asked, cwd) ?? resolve(cwd, asked));
176
+ if (within(mainRoot, at) && !at.startsWith(join(mainRoot, ".worktrees") + sep)) {
177
+ return { block: true, reason: `member-write-guard: refused bash — its cwd ${at} is inside the main checkout ${mainRoot}, outside \`.worktrees/\`. Re-issue it with \`cwd\` set to the absolute path of your worktree \`.worktrees/<n>-<slug>/\`.` };
178
+ }
179
+ return undefined;
180
+ }
181
+
182
+ for (const raw of targets(toolName, input)) {
183
+ const abs = fsPath(raw, cwd);
184
+ if (abs === null) continue;
185
+ const at = canonical(abs);
186
+ if (!within(mainRoot, at)) continue;
187
+ const said = isAbsolute(raw) ? at : `${at} ("${raw}" resolved against the session cwd ${cwd})`;
188
+ let ignored;
189
+ try {
190
+ ignored = await isIgnored(at);
191
+ } catch (e) {
192
+ return { block: true, reason: `member-write-guard: refused ${toolName} to ${said} — could not tell whether it is gitignored (${e?.message ?? e}), and a guard that cannot look does not let the call through. ${REISSUE}` };
193
+ }
194
+ if (!ignored) {
195
+ return { block: true, reason: `member-write-guard: refused ${toolName} to ${said} — it is inside the main checkout ${mainRoot} and not gitignored. ${REISSUE}` };
196
+ }
197
+ }
198
+ return undefined;
199
+ }
200
+
201
+ // ── The effects decide() is handed ──────────────────────────────────────────
202
+
203
+ // The one git primitive, async so a guarded call never stalls the other
204
+ // sessions sharing omp's process. `gitEnv()` drops an ambient GIT_DIR /
205
+ // GIT_WORK_TREE (#1599); LC_ALL=C keeps "not a git repository" matchable.
206
+ function git(args, cwd) {
207
+ return new Promise((done) => {
208
+ let stdout = "";
209
+ let stderr = "";
210
+ const finish = (r) => done({ stdout, stderr, ...r });
211
+ let child;
212
+ try {
213
+ child = spawn("git", args, { cwd, env: gitEnv({ LC_ALL: "C" }), stdio: ["ignore", "pipe", "pipe"], timeout: GIT_TIMEOUT_MS });
214
+ } catch (error) {
215
+ finish({ error, status: null });
216
+ return;
217
+ }
218
+ child.stdout.on("data", (d) => { stdout += d; });
219
+ child.stderr.on("data", (d) => { stderr += d; });
220
+ child.on("error", (error) => finish({ error, status: null }));
221
+ child.on("close", (status, signal) => finish({ status, signal }));
222
+ });
223
+ }
224
+
225
+ function failure(r, what) {
226
+ if (r.error) return `${what} did not run: ${r.error.code ?? r.error.message}`;
227
+ const last = r.stderr.trim().split("\n").at(-1);
228
+ return `${what} ${r.signal ? `killed by ${r.signal}` : `exited ${r.status}`}${last ? `: ${last}` : ""}`;
229
+ }
230
+
231
+ /** The main checkout `cwd` belongs to: a path, `null` outside any repository, or an `Error`. */
232
+ async function resolveMainRoot(cwd) {
233
+ const r = await git(["rev-parse", "--git-common-dir"], cwd);
234
+ // Only git's no-repository-anywhere answer is "no main checkout". A gitfile
235
+ // pointing at a missing git dir also says "not a git repository", followed
236
+ // by the dead path rather than "(or any …": that is a broken repo, and blocks.
237
+ if (!r.error && r.status !== 0 && /not a git repository \(or any/i.test(r.stderr)) return null;
238
+ if (r.error || r.status !== 0) return new Error(failure(r, "git rev-parse --git-common-dir"));
239
+ return workspaceDirFromGitCommonDir(r.stdout, cwd, { canonicalise: true })
240
+ ?? new Error("git rev-parse --git-common-dir answered nothing");
241
+ }
242
+
243
+ /** `git check-ignore` from `mainRoot`: true ignored, false not; rejects on anything else. */
244
+ async function checkIgnored(mainRoot, absPath) {
245
+ const r = await git(["check-ignore", "-q", "--", absPath], mainRoot);
246
+ if (!r.error && r.status === 0) return true;
247
+ if (!r.error && r.status === 1) return false;
248
+ throw new Error(failure(r, "git check-ignore"));
249
+ }
250
+
251
+ /** The symlink-free spelling of `p`, whose tail need not exist yet. */
252
+ function canonicalPath(p) {
253
+ try {
254
+ return realpathSync(p);
255
+ } catch (e) {
256
+ if (e?.code !== "ENOENT") throw e;
257
+ const parent = dirname(p);
258
+ return parent === p ? p : join(canonicalPath(parent), basename(p));
259
+ }
260
+ }
261
+
262
+ /** The extension factory omp calls once per session. */
263
+ export default function memberWriteGuard(pi) {
264
+ pi.on("tool_call", async (event, ctx) => {
265
+ const agent = ctx?.agent;
266
+ if (!applies(agent, event?.toolName)) return undefined;
267
+ const cwd = canonicalPath(resolve(ctx?.cwd ?? process.cwd()));
268
+ const mainRoot = await resolveMainRoot(cwd);
269
+ return decide({
270
+ toolName: event.toolName,
271
+ input: event.input,
272
+ cwd,
273
+ agent,
274
+ mainRoot,
275
+ isIgnored: (p) => checkIgnored(mainRoot, p),
276
+ canonical: canonicalPath,
277
+ });
278
+ });
279
+ }
@@ -0,0 +1,211 @@
1
+ // member-write-guard.mjs, exercised the way omp runs it: the factory is handed
2
+ // a stand-in `pi`, and every call goes through the `tool_call` handler it
3
+ // registers — which resolves the main checkout with real git and hands it to
4
+ // `decide()`. The fixture is a real repository with a claimed-style worktree
5
+ // under `.worktrees/`, a `.gitignore` carrying the fleet's ignored
6
+ // directories, and a scratch directory outside it. On macOS `tmpdir()` lives
7
+ // behind the `/var` → `/private/var` symlink, so every row below also crosses
8
+ // the symlink the handler canonicalises away.
9
+ //
10
+ // Both halves are pinned: what the guard must refuse (a main-checkout write,
11
+ // relative or absolute, from a member or a member's child; an implementer's
12
+ // bash from the inherited cwd; a git that cannot answer) and what it must let
13
+ // through (the member's worktree, gitignored run state, scratch, internal
14
+ // URLs, every session that is not a fleet member's).
15
+ //
16
+ // Zero deps: `node --test plugin/scripts/member-write-guard.test.mjs`.
17
+
18
+ import { after, test } from "node:test";
19
+ import assert from "node:assert/strict";
20
+ import { execFileSync } from "node:child_process";
21
+ import { existsSync, mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
22
+ import { tmpdir } from "node:os";
23
+ import { join } from "node:path";
24
+ import { gitEnv } from "./git-env.mjs";
25
+ import memberWriteGuard, { decide } from "./member-write-guard.mjs";
26
+
27
+ const ENV = gitEnv({
28
+ GIT_AUTHOR_NAME: "t", GIT_AUTHOR_EMAIL: "t@example.com", GIT_COMMITTER_NAME: "t", GIT_COMMITTER_EMAIL: "t@example.com",
29
+ });
30
+ const sh = (cwd, ...args) => execFileSync("git", args, { cwd, env: ENV, stdio: "pipe" });
31
+
32
+ function repo(dir) {
33
+ mkdirSync(dir, { recursive: true });
34
+ sh(dir, "init", "-q", "-b", "main");
35
+ writeFileSync(join(dir, ".gitignore"), ".worktrees/\n.fleet/\n.agent-brain/\n");
36
+ mkdirSync(join(dir, "plugin"));
37
+ writeFileSync(join(dir, "plugin", "tool.mjs"), "export {};\n");
38
+ sh(dir, "add", "-A");
39
+ sh(dir, "commit", "-q", "-m", "init");
40
+ assert.ok(existsSync(join(dir, ".git")), `fixture: ${dir} has no .git — git init answered for some other repository`);
41
+ return dir;
42
+ }
43
+
44
+ const BASE = mkdtempSync(join(tmpdir(), "member-write-guard-"));
45
+ after(() => rmSync(BASE, { recursive: true, force: true }));
46
+ // The spelling a session would carry: NOT canonicalised, so the /var symlink stays in it.
47
+ const ROOT = repo(join(BASE, "main"));
48
+ const REAL_ROOT = realpathSync(ROOT);
49
+ const WT = join(ROOT, ".worktrees", "42-slug");
50
+ sh(ROOT, "worktree", "add", "-q", WT, "-b", "implementer/42");
51
+ const SCRATCH = join(BASE, "scratch");
52
+ mkdirSync(SCRATCH);
53
+ const ELSEWHERE = repo(join(BASE, "elsewhere"));
54
+
55
+ const IMPL = { kind: "sub", id: "impl-42", name: "fleet-implementer", depth: 1, parentId: "Main" };
56
+ const ALT = { ...IMPL, name: "fleet-implementer-alt" };
57
+ const REVIEWER = { kind: "sub", id: "review-pr-9.Correctness", name: "fleet-review-correctness", depth: 2, parentId: "review-pr-9" };
58
+ const FINISHER = { kind: "sub", id: "finisher-pr-9", name: "fleet-finisher", depth: 1, parentId: "Main" };
59
+ const CHILD = { kind: "sub", id: "impl-42.Probe", name: "task", depth: 2, parentId: "impl-42" };
60
+ const UNRELATED = { kind: "sub", id: "0-Explore", name: "explore", depth: 1, parentId: "Main" };
61
+ const MAIN = { kind: "main", id: "Main", name: "main", depth: 0 };
62
+ // A fix-applier: dispatched under the generic `task` definition (no `fleet-`
63
+ // prefix) directly by the controller, so only its own id names it.
64
+ const FIX_APPLIER = { kind: "sub", id: "fix-pr-2246", name: "task", depth: 0, parentId: "Main" };
65
+
66
+ let handler;
67
+ memberWriteGuard({ on: (event, fn) => { if (event === "tool_call") handler = fn; } });
68
+ const call = (agent, toolName, input, cwd) => handler({ type: "tool_call", toolCallId: "t", toolName, input }, { cwd, agent });
69
+
70
+ async function refused(agent, toolName, input, cwd, what) {
71
+ const r = await call(agent, toolName, input, cwd);
72
+ assert.equal(r?.block, true, `${what}: expected a refusal, got ${JSON.stringify(r)}`);
73
+ assert.match(r.reason, /member-write-guard/, `${what}: the refusal does not name the guard`);
74
+ assert.match(r.reason, /\.worktrees\/<n>-<slug>\//, `${what}: the refusal does not tell the member where to re-issue it`);
75
+ return r.reason;
76
+ }
77
+ async function allowed(agent, toolName, input, cwd, what) {
78
+ assert.equal(await call(agent, toolName, input, cwd), undefined, `${what}: expected the call to run`);
79
+ }
80
+
81
+ test("a member's relative and absolute writes into the main checkout are refused, naming the resolved path", async () => {
82
+ const rel = await refused(IMPL, "write", { path: "plugin/new.mjs", content: "x" }, ROOT, "relative write");
83
+ assert.ok(rel.includes(join(REAL_ROOT, "plugin", "new.mjs")), `the refusal does not name the resolved path: ${rel}`);
84
+ assert.match(rel, /"plugin\/new\.mjs" resolved against the session cwd/, "a relative refusal does not say what it resolved against");
85
+ await refused(IMPL, "write", { path: join(ROOT, "plugin", "tool.mjs"), content: "x" }, ROOT, "absolute write to a tracked file");
86
+ await refused(IMPL, "write", { path: join(ROOT, "README.md"), content: "x" }, ROOT, "absolute write to a new file at the root");
87
+ await refused(REVIEWER, "write", { path: "plugin/tool.mjs" }, ROOT, "a review specialist's relative write");
88
+ await refused(FINISHER, "write", { path: "plugin/tool.mjs" }, ROOT, "the finisher's relative write");
89
+ });
90
+
91
+ test("edit is refused on any target in the main checkout — header, omp's derived paths, a MV destination", async () => {
92
+ await refused(IMPL, "edit", { input: "[plugin/tool.mjs#ABCD]\nPUT 1.=1:\n+x\n" }, ROOT, "hashline header, unnormalised");
93
+ await refused(IMPL, "edit", { input: "…", path: "plugin/tool.mjs", paths: ["plugin/tool.mjs"] }, ROOT, "omp-normalised path");
94
+ await refused(IMPL, "edit", { input: `[${join(WT, "plugin", "tool.mjs")}#ABCD]\nMV "plugin/moved.mjs"\n` }, ROOT, "a worktree file moved into the main checkout");
95
+ await refused(IMPL, "edit", { input: "*** Begin Patch\n*** Update File: plugin/tool.mjs\n*** End Patch\n" }, ROOT, "apply_patch-mode header");
96
+ await refused(IMPL, "edit", { _path: join(ROOT, "plugin", "tool.mjs") }, ROOT, "a host-added _path key, un-normalised");
97
+ await refused(IMPL, "edit", { _input: `[${join(ROOT, "plugin", "tool.mjs")}#ABCD]\nPUT 1.=1:\n+x\n` }, ROOT, "a host-added _input key, un-normalised");
98
+ await allowed(IMPL, "edit", { input: `[${join(WT, "plugin", "tool.mjs")}#ABCD]\nPUT 1.=1:\n+x\n` }, ROOT, "a worktree edit");
99
+ });
100
+
101
+ test("ast_edit is refused on a main-checkout path or glob and allowed in the worktree", async () => {
102
+ await refused(IMPL, "ast_edit", { ops: [{ pat: "a", out: "b" }], paths: ["plugin/**/*.mjs"] }, ROOT, "a relative glob");
103
+ await refused(IMPL, "ast_edit", { ops: [{ pat: "a", out: "b" }], paths: [join(WT, "plugin"), "plugin/tool.mjs"] }, ROOT, "one bad path among good ones");
104
+ await allowed(IMPL, "ast_edit", { ops: [{ pat: "a", out: "b" }], paths: [join(WT, "plugin", "**", "*.mjs")] }, ROOT, "a worktree glob");
105
+ });
106
+
107
+ test("writes the guard must let through: the worktree, gitignored run state, scratch, internal URLs", async () => {
108
+ await allowed(IMPL, "write", { path: join(WT, "plugin", "new.mjs") }, ROOT, "absolute write into the worktree");
109
+ await allowed(IMPL, "write", { path: ".worktrees/42-slug/plugin/new.mjs" }, ROOT, "relative write into the worktree");
110
+ await allowed(IMPL, "write", { path: ".fleet/ledger.md" }, ROOT, "gitignored .fleet/");
111
+ await allowed(IMPL, "write", { path: join(ROOT, ".agent-brain", "index.md") }, ROOT, "gitignored .agent-brain/");
112
+ await allowed(IMPL, "write", { path: join(SCRATCH, "impl-42", "probe.mjs") }, ROOT, "scratch outside the repository");
113
+ await allowed(IMPL, "write", { path: "local://notes.md" }, ROOT, "a local:// artifact");
114
+ await allowed(IMPL, "write", { path: "xd://ast_edit", content: "{}" }, ROOT, "an xd:// device");
115
+ // From the worktree itself — the cwd a member would have if omp ever gave it one.
116
+ await allowed(IMPL, "write", { path: "plugin/new.mjs" }, WT, "relative write from a worktree cwd");
117
+ });
118
+
119
+ test("only fleet members and their children are guarded — nothing else in the session", async () => {
120
+ await allowed(UNRELATED, "write", { path: "plugin/tool.mjs" }, ROOT, "a non-fleet subagent");
121
+ await allowed(MAIN, "write", { path: "plugin/tool.mjs" }, ROOT, "the top-level session");
122
+ await allowed(MAIN, "bash", { command: "true" }, ROOT, "the top-level session's bash");
123
+ await allowed(undefined, "write", { path: "plugin/tool.mjs" }, ROOT, "a context with no agent");
124
+ await refused(CHILD, "write", { path: "plugin/tool.mjs" }, ROOT, "a child of impl-42");
125
+ await refused({ ...CHILD, parentId: "impl-42-b" }, "write", { path: "plugin/tool.mjs" }, ROOT, "a child of a recovery member");
126
+ for (const parentId of ["fix-pr-7", "review-pr-2245", "finisher-pr-3"]) {
127
+ await refused({ ...CHILD, parentId }, "write", { path: "plugin/tool.mjs" }, ROOT, `a child of ${parentId}`);
128
+ }
129
+ // The pattern is anchored at both ends: near-misses are someone else's agents.
130
+ for (const parentId of ["impl-42x", "impl-", "myimpl-42", "impl-42.Probe", "Main"]) {
131
+ await allowed({ ...CHILD, parentId }, "write", { path: "plugin/tool.mjs" }, ROOT, `a subagent whose parent is ${parentId}`);
132
+ }
133
+ });
134
+
135
+ test("a fix-applier dispatched under the generic `task` definition is guarded by its own id, not its definition name", async () => {
136
+ await refused(FIX_APPLIER, "write", { path: "plugin/tool.mjs" }, ROOT, "a fix-applier's relative write");
137
+ await refused(FIX_APPLIER, "edit", { input: "[plugin/tool.mjs#ABCD]\nPUT 1.=1:\n+x\n" }, ROOT, "a fix-applier's edit");
138
+ await refused(FIX_APPLIER, "bash", { command: "true" }, ROOT, "a fix-applier's bash with no cwd");
139
+ await refused(FIX_APPLIER, "bash", { command: "true", cwd: ROOT }, WT, "a fix-applier's bash at the main checkout root");
140
+ await allowed(FIX_APPLIER, "write", { path: "plugin/tool.mjs" }, WT, "a fix-applier's write from its worktree");
141
+ await allowed(FIX_APPLIER, "bash", { command: "true", cwd: WT }, ROOT, "a fix-applier's bash cwd set to its worktree");
142
+ // The pattern is anchored: a generic `task` agent whose own id does not
143
+ // match `fix-pr-<n>` is nobody's fix-applier and stays unguarded — the
144
+ // existing UNRELATED/CHILD near-miss rows above already cover this shape.
145
+ });
146
+
147
+ test("bash: an implementer is refused from the main checkout, never from its worktree; nobody else is", async () => {
148
+ const r = await refused(IMPL, "bash", { command: "git status" }, ROOT, "implementer bash with no cwd");
149
+ assert.ok(r.includes(REAL_ROOT), `the bash refusal does not name the cwd it resolved: ${r}`);
150
+ await refused(ALT, "bash", { command: "true" }, ROOT, "implementer-alt bash with no cwd");
151
+ await refused(IMPL, "bash", { command: "true", cwd: "plugin" }, ROOT, "a relative cwd inside the main checkout");
152
+ await refused(IMPL, "bash", { command: "true", cwd: ROOT }, WT, "an explicit cwd at the main checkout root");
153
+ await refused(IMPL, "bash", { command: "true", cwd: join(ROOT, ".worktrees") }, ROOT, "cwd at the bare .worktrees directory itself, not a worktree under it");
154
+ await allowed(IMPL, "bash", { command: "true", cwd: WT }, ROOT, "cwd set to the worktree");
155
+ await allowed(IMPL, "bash", { command: "true", cwd: SCRATCH }, ROOT, "cwd set to scratch");
156
+ await allowed(IMPL, "bash", { command: "true" }, WT, "no cwd, session already in the worktree");
157
+ await allowed(REVIEWER, "bash", { command: "pwd" }, ROOT, "a review specialist's pwd-first bash");
158
+ await allowed(FINISHER, "bash", { command: "sh worktree-audit.sh" }, ROOT, "the finisher's audit");
159
+ await allowed(CHILD, "bash", { command: "true" }, ROOT, "a member's child");
160
+ await allowed(IMPL, "read", { path: "plugin/tool.mjs" }, ROOT, "a relative read");
161
+ await allowed(IMPL, "eval", { code: "open('x','w')" }, ROOT, "eval");
162
+ });
163
+
164
+ test("when git cannot answer, the guard refuses; when there is no repository at all, it allows", async () => {
165
+ await allowed(IMPL, "write", { path: "x.txt" }, SCRATCH, "cwd outside any repository");
166
+ await allowed(IMPL, "bash", { command: "true" }, SCRATCH, "implementer bash outside any repository");
167
+
168
+ const broken = join(BASE, "broken");
169
+ mkdirSync(broken);
170
+ writeFileSync(join(broken, ".git"), `gitdir: ${join(BASE, "gone")}\n`);
171
+ const r = await refused(IMPL, "write", { path: "x.txt" }, broken, "a gitfile naming a missing git dir");
172
+ assert.match(r, /git rev-parse --git-common-dir exited/, `the refusal does not name the git failure: ${r}`);
173
+ await refused(IMPL, "write", { path: "x.txt" }, join(BASE, "no-such-dir"), "a session cwd that does not exist");
174
+
175
+ const failing = await decide({
176
+ toolName: "write", input: { path: "plugin/tool.mjs" }, cwd: REAL_ROOT, agent: IMPL, mainRoot: REAL_ROOT,
177
+ isIgnored: async () => { throw new Error("git check-ignore exited 128: fatal: boom"); },
178
+ });
179
+ assert.equal(failing?.block, true, "a check-ignore failure let the write through");
180
+ assert.match(failing.reason, /fatal: boom/, "the refusal does not carry the check-ignore failure");
181
+
182
+ // decide() is exported and callable directly (as this test does), so a
183
+ // mainRoot outside its null/Error/non-empty-string contract must fail
184
+ // closed rather than let `within()`'s empty-prefix match everything.
185
+ const emptyRoot = await decide({
186
+ toolName: "write", input: { path: "/etc/passwd" }, cwd: "/tmp", agent: IMPL, mainRoot: "",
187
+ isIgnored: async () => false,
188
+ });
189
+ assert.equal(emptyRoot?.block, true, "an empty-string mainRoot let an arbitrary absolute path through");
190
+ });
191
+
192
+ test("an ambient GIT_DIR naming another repository does not change the answer", async () => {
193
+ const saved = process.env.GIT_DIR;
194
+ process.env.GIT_DIR = join(ELSEWHERE, ".git");
195
+ try {
196
+ await refused(IMPL, "write", { path: "plugin/tool.mjs" }, ROOT, "main-checkout write under an ambient GIT_DIR");
197
+ await allowed(IMPL, "write", { path: ".fleet/ledger.md" }, ROOT, "ignored write under an ambient GIT_DIR");
198
+ await refused(IMPL, "bash", { command: "true" }, ROOT, "implementer bash under an ambient GIT_DIR");
199
+ } finally {
200
+ if (saved === undefined) delete process.env.GIT_DIR;
201
+ else process.env.GIT_DIR = saved;
202
+ }
203
+ });
204
+
205
+ test("a symlinked route into the main checkout is the main checkout", async () => {
206
+ const link = join(BASE, "link");
207
+ symlinkSync(ROOT, link);
208
+ await refused(IMPL, "write", { path: "plugin/tool.mjs" }, link, "relative write from a symlinked cwd");
209
+ await refused(IMPL, "write", { path: join(link, "plugin", "tool.mjs") }, ROOT, "absolute write through the symlink");
210
+ await allowed(IMPL, "write", { path: join(link, ".worktrees", "42-slug", "a.mjs") }, ROOT, "worktree write through the symlink");
211
+ });
@@ -0,0 +1,122 @@
1
+ // #911. `run-team/SKILL.md`'s five-condition note sends the fix-applier to
2
+ // measure the merge-commit condition by hand, because `ci.yml`'s `rebase-check`
3
+ // exits on the staleness condition before the merge-commit one is evaluated, so
4
+ // the job log cannot name it. That hand-run probe is the whole of the evidence,
5
+ // and it shipped broken.
6
+ //
7
+ // `376c19c` wrote it as `git rev-list --merges --count "$BASE..HEAD"`. `$BASE`
8
+ // is assigned nowhere — `grep -rIn --exclude-dir=.git -E '(^|[^A-Z_])BASE=' .`
9
+ // prints nothing against this tree — so it expanded to `..HEAD`, which git
10
+ // reads as `HEAD..HEAD`: `git rev-list --merges --count "..HEAD"` prints `0` and
11
+ // exits 0. The broken probe returned the "no merge commits" answer, silently, at
12
+ // success, which is precisely the benign misreading the note exists to deny.
13
+ // `7b48720`, landed in the same PR #881 as the bug it fixes, corrected it to
14
+ // the angle-bracket placeholder form
15
+ // this file pins; that commit also edited
16
+ // `staleness-qualifier-prose.test.mjs`, but added no assertion on the command.
17
+ //
18
+ // WHY A PIN AND NOT A COMMENT: nothing pinned the corrected form. Measured:
19
+ // with this file's own test removed from the suite and the `$BASE` range
20
+ // reinstated in `SKILL.md`, the full suite
21
+ // (`node --test plugin/scripts/*.test.mjs`) still passes at 2202/2202 —
22
+ // nothing else in the suite catches the regression. The corrected form had
23
+ // no guard, so a dedup pass, a reword, or a "let's make this copy-pasteable"
24
+ // edit could restore the silent-zero probe with the suite green.
25
+ //
26
+ // ONE EXACT SPAN, NOT TWO REGEXES. Both halves of the command are load-bearing
27
+ // and they fail in OPPOSITE directions:
28
+ // - the `origin/<base>..HEAD` placeholder shape. A `$VAR` range reads as a
29
+ // variable the reader has already set, and when it is not set the probe is
30
+ // the silent false negative above.
31
+ // - the `git fetch origin &&` prefix. The document states the consequence of
32
+ // dropping it: a stale local `origin/<base>` widens the range over the
33
+ // base's own merge commits, turning the false negative into a false
34
+ // positive.
35
+ // Pinned as a single contiguous span because the invariant lives in the JOIN.
36
+ // Separate `git fetch origin` and `origin/<base>..HEAD` matches over this slice
37
+ // would pin two facts and not their adjacency: a rewrite mentioning the fetch in
38
+ // the surrounding prose while leaving the command fetch-less satisfies both and
39
+ // says neither. The command's own correctness is #881's, settled there and not
40
+ // re-argued here; this asserts only that the corrected text is still the text.
41
+ //
42
+ // SLICE SIZE IS THE PIN, as in `staleness-qualifier-prose.test.mjs`. The note
43
+ // sits inside the fix-applier's blockquoted prompt, and this same document
44
+ // carries a near-miss at SKILL.md:149 — `git fetch origin && git rev-list
45
+ // --count main..origin/main`, same command family, no `--merges` — so a copy
46
+ // of this command left anywhere in the document would satisfy a file-wide
47
+ // match with the live one gutted. Measured: with the command replaced by the
48
+ // `$BASE` form in place AND a correct copy appended elsewhere in the
49
+ // document, in a genuinely separate paragraph with its `>` separator intact,
50
+ // this still reds. What it does NOT close is that separator deleted outright
51
+ // — the paragraphs then merge and the slice takes both, a hole that predates
52
+ // this bound and is open still (#1377).
53
+ //
54
+ // `stripQuoteGutter` before `paragraph`, which is what makes the shared
55
+ // paragraph bound reach into a blockquote at all: the `>`-only lines that fence
56
+ // this note become genuinely blank, so `paragraph`'s `\n[ \t]*\n` search finds
57
+ // them. It is also the reflow guard. `phrase()` joins on `\s+` and `\s+` does
58
+ // not span a `>`, so a rewrap that moved a word of the command onto the next
59
+ // blockquote line would red an untouched document without the strip.
60
+ //
61
+ // REFLOW CONTROL, measured on a scratch copy: the note rewrapped at 60, 72 and
62
+ // 100 columns (Python `textwrap.fill`, `break_on_hyphens=False`,
63
+ // `break_long_words=False`, `>` gutter re-applied) stays green — and at all
64
+ // three the command itself is split across blockquote lines, so this control
65
+ // exercises the gutter strip rather than passing on an unchanged line.
66
+ //
67
+ // THE CEILING is the hyphen-break one `staleness-qualifier-prose.test.mjs`
68
+ // records, and here it has exactly ONE carrier: `rev-list` is the only
69
+ // hyphenated token inside the pinned span, so it is the only one a wrapper can
70
+ // break where `\s+` cannot rejoin. Measured over widths 40-120 with
71
+ // `break_on_hyphens` on, this reds at 45, 46, 77, 78, 87 and 88 — precisely the
72
+ // widths that split `rev-list`, set-equal, not merely overlapping. The slice's
73
+ // other hyphenated tokens are NOT a mechanism: `gh pr update-branch` splits at
74
+ // 47, 48, 50 and 94 and this stays green there, because it sits in the note but
75
+ // outside the pinned span. `--merges` and `--count` never split — a leading
76
+ // double hyphen is not a break point. So the ceiling is a property of the
77
+ // wrapper and of one token, not a width to memorise; a Markdown wrapper does
78
+ // not break hyphenated words.
79
+ //
80
+ // THE CEILING on the assertion itself: it pins this command's text and nothing
81
+ // else in the note — not the five-condition claim, not the `solely` qualifier
82
+ // (`staleness-qualifier-prose.test.mjs` holds that, on a different paragraph of
83
+ // this document), not the server-side-rebase consequence. A deliberate reword of
84
+ // the command reds this; re-anchor PROBE here rather than deleting the
85
+ // assertion, and keep whichever form replaces it honest about both halves.
86
+
87
+ import { test } from "node:test";
88
+ import assert from "node:assert/strict";
89
+ import { readFileSync } from "node:fs";
90
+ import { join } from "node:path";
91
+ import { paragraph, phrase, stripQuoteGutter } from "./prose-pin.mjs";
92
+
93
+ const REPO = join(import.meta.dirname, "..");
94
+ const SKILL = "skills/run-team/SKILL.md";
95
+
96
+ // The note, and no more of the document than that. A moved anchor throws rather
97
+ // than widening the slice back to the file, which is the false green the bound
98
+ // exists to prevent.
99
+ const note = () =>
100
+ paragraph(
101
+ stripQuoteGutter(readFileSync(join(REPO, ...SKILL.split("/")), "utf8")),
102
+ "The CI facts in that file apply to you",
103
+ SKILL,
104
+ );
105
+
106
+ // Backticks included: they are what keeps this a code span the reader can run,
107
+ // rather than a sentence describing one.
108
+ const PROBE = '`git fetch origin && git rev-list --merges --count "origin/<base>..HEAD"`';
109
+
110
+ test("the five-condition note measures merge commits with a fetched, origin-relative range", () => {
111
+ assert.match(
112
+ note(),
113
+ phrase(PROBE),
114
+ `${SKILL}'s five-condition note no longer spells the merge-commit probe ${PROBE}.
115
+
116
+ Both halves are load-bearing, and dropping either is silent:
117
+ - a \`$VAR\` range (the \`"$BASE..HEAD"\` form \`376c19c\` shipped and \`7b48720\` fixed) expands to \`..HEAD\` when unset, which git reads as \`HEAD..HEAD\` — count \`0\`, exit 0, the "no merge commits" answer this note exists to deny.
118
+ - without \`git fetch origin &&\`, a stale local \`origin/<base>\` widens the range over the base's own merge commits and reports one this branch never added.
119
+
120
+ If the command was reworded on purpose, re-anchor PROBE in this file to the new wording — and keep the angle-bracket placeholder and the fetch, or say in the commit which of the two failure modes you are accepting.`,
121
+ );
122
+ });