@memnexus-ai/mx-agent-cli 0.1.293 → 0.1.294-next.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 (215) hide show
  1. package/dist/__tests__/config-sync.test.js +54 -1
  2. package/dist/__tests__/config-sync.test.js.map +1 -1
  3. package/dist/__tests__/decision-check.test.d.ts +2 -0
  4. package/dist/__tests__/decision-check.test.d.ts.map +1 -0
  5. package/dist/__tests__/decision-check.test.js +105 -0
  6. package/dist/__tests__/decision-check.test.js.map +1 -0
  7. package/dist/__tests__/harness-extract.test.d.ts +19 -0
  8. package/dist/__tests__/harness-extract.test.d.ts.map +1 -0
  9. package/dist/__tests__/harness-extract.test.js +566 -0
  10. package/dist/__tests__/harness-extract.test.js.map +1 -0
  11. package/dist/__tests__/harness-wiring.test.d.ts +16 -0
  12. package/dist/__tests__/harness-wiring.test.d.ts.map +1 -0
  13. package/dist/__tests__/harness-wiring.test.js +469 -0
  14. package/dist/__tests__/harness-wiring.test.js.map +1 -0
  15. package/dist/__tests__/report-format.test.d.ts +2 -0
  16. package/dist/__tests__/report-format.test.d.ts.map +1 -0
  17. package/dist/__tests__/report-format.test.js +219 -0
  18. package/dist/__tests__/report-format.test.js.map +1 -0
  19. package/dist/__tests__/standards-injection.test.d.ts +2 -0
  20. package/dist/__tests__/standards-injection.test.d.ts.map +1 -0
  21. package/dist/__tests__/standards-injection.test.js +157 -0
  22. package/dist/__tests__/standards-injection.test.js.map +1 -0
  23. package/dist/agent-config/hooks/auto-capture-precompact.sh +74 -4
  24. package/dist/agent-config/hooks/auto-capture-session-end.sh +106 -4
  25. package/dist/agent-config/hooks/auto-checkpoint.sh +75 -5
  26. package/dist/agent-config/hooks/observability-sync.sh +46 -9
  27. package/dist/commands/config-sync.d.ts +37 -0
  28. package/dist/commands/config-sync.d.ts.map +1 -1
  29. package/dist/commands/config-sync.js +36 -18
  30. package/dist/commands/config-sync.js.map +1 -1
  31. package/dist/commands/dashboard.d.ts.map +1 -1
  32. package/dist/commands/dashboard.js +10 -2
  33. package/dist/commands/dashboard.js.map +1 -1
  34. package/dist/commands/decision.d.ts +20 -0
  35. package/dist/commands/decision.d.ts.map +1 -0
  36. package/dist/commands/decision.js +54 -0
  37. package/dist/commands/decision.js.map +1 -0
  38. package/dist/commands/monitor.d.ts.map +1 -1
  39. package/dist/commands/monitor.js +8 -2
  40. package/dist/commands/monitor.js.map +1 -1
  41. package/dist/commands/report.d.ts +33 -0
  42. package/dist/commands/report.d.ts.map +1 -0
  43. package/dist/commands/report.js +73 -0
  44. package/dist/commands/report.js.map +1 -0
  45. package/dist/commands/start.d.ts +4 -0
  46. package/dist/commands/start.d.ts.map +1 -1
  47. package/dist/commands/start.js +6 -0
  48. package/dist/commands/start.js.map +1 -1
  49. package/dist/commands/update.d.ts +13 -1
  50. package/dist/commands/update.d.ts.map +1 -1
  51. package/dist/commands/update.js +50 -1
  52. package/dist/commands/update.js.map +1 -1
  53. package/dist/index.d.ts.map +1 -1
  54. package/dist/index.js +67 -3
  55. package/dist/index.js.map +1 -1
  56. package/dist/lib/agent-session.d.ts +12 -0
  57. package/dist/lib/agent-session.d.ts.map +1 -1
  58. package/dist/lib/agent-session.js +183 -41
  59. package/dist/lib/agent-session.js.map +1 -1
  60. package/dist/lib/claude.d.ts +12 -0
  61. package/dist/lib/claude.d.ts.map +1 -1
  62. package/dist/lib/claude.js +29 -2
  63. package/dist/lib/claude.js.map +1 -1
  64. package/dist/lib/decision-check.d.ts +48 -0
  65. package/dist/lib/decision-check.d.ts.map +1 -0
  66. package/dist/lib/decision-check.js +149 -0
  67. package/dist/lib/decision-check.js.map +1 -0
  68. package/dist/lib/harness/console/announce.d.ts +45 -0
  69. package/dist/lib/harness/console/announce.d.ts.map +1 -0
  70. package/dist/lib/harness/console/announce.js +48 -0
  71. package/dist/lib/harness/console/announce.js.map +1 -0
  72. package/dist/lib/harness/console/announce.test.d.ts +2 -0
  73. package/dist/lib/harness/console/announce.test.d.ts.map +1 -0
  74. package/dist/lib/harness/console/announce.test.js +104 -0
  75. package/dist/lib/harness/console/announce.test.js.map +1 -0
  76. package/dist/lib/harness/console/by-session.d.ts +50 -0
  77. package/dist/lib/harness/console/by-session.d.ts.map +1 -0
  78. package/dist/lib/harness/console/by-session.js +83 -0
  79. package/dist/lib/harness/console/by-session.js.map +1 -0
  80. package/dist/lib/harness/console/by-session.test.d.ts +2 -0
  81. package/dist/lib/harness/console/by-session.test.d.ts.map +1 -0
  82. package/dist/lib/harness/console/by-session.test.js +86 -0
  83. package/dist/lib/harness/console/by-session.test.js.map +1 -0
  84. package/dist/lib/harness/console/console.d.ts +67 -0
  85. package/dist/lib/harness/console/console.d.ts.map +1 -0
  86. package/dist/lib/harness/console/console.js +373 -0
  87. package/dist/lib/harness/console/console.js.map +1 -0
  88. package/dist/lib/harness/console/console.test.d.ts +2 -0
  89. package/dist/lib/harness/console/console.test.d.ts.map +1 -0
  90. package/dist/lib/harness/console/console.test.js +269 -0
  91. package/dist/lib/harness/console/console.test.js.map +1 -0
  92. package/dist/lib/harness/console/decision-request.d.ts +32 -0
  93. package/dist/lib/harness/console/decision-request.d.ts.map +1 -0
  94. package/dist/lib/harness/console/decision-request.js +112 -0
  95. package/dist/lib/harness/console/decision-request.js.map +1 -0
  96. package/dist/lib/harness/console/decision-request.test.d.ts +2 -0
  97. package/dist/lib/harness/console/decision-request.test.d.ts.map +1 -0
  98. package/dist/lib/harness/console/decision-request.test.js +75 -0
  99. package/dist/lib/harness/console/decision-request.test.js.map +1 -0
  100. package/dist/lib/harness/console/fixtures.d.ts +16 -0
  101. package/dist/lib/harness/console/fixtures.d.ts.map +1 -0
  102. package/dist/lib/harness/console/fixtures.js +49 -0
  103. package/dist/lib/harness/console/fixtures.js.map +1 -0
  104. package/dist/lib/harness/console/index.d.ts +15 -0
  105. package/dist/lib/harness/console/index.d.ts.map +1 -0
  106. package/dist/lib/harness/console/index.js +14 -0
  107. package/dist/lib/harness/console/index.js.map +1 -0
  108. package/dist/lib/harness/console/rank.d.ts +73 -0
  109. package/dist/lib/harness/console/rank.d.ts.map +1 -0
  110. package/dist/lib/harness/console/rank.js +113 -0
  111. package/dist/lib/harness/console/rank.js.map +1 -0
  112. package/dist/lib/harness/console/rank.test.d.ts +2 -0
  113. package/dist/lib/harness/console/rank.test.d.ts.map +1 -0
  114. package/dist/lib/harness/console/rank.test.js +124 -0
  115. package/dist/lib/harness/console/rank.test.js.map +1 -0
  116. package/dist/lib/harness/console/render.d.ts +22 -0
  117. package/dist/lib/harness/console/render.d.ts.map +1 -0
  118. package/dist/lib/harness/console/render.js +65 -0
  119. package/dist/lib/harness/console/render.js.map +1 -0
  120. package/dist/lib/harness/console/render.test.d.ts +2 -0
  121. package/dist/lib/harness/console/render.test.d.ts.map +1 -0
  122. package/dist/lib/harness/console/render.test.js +96 -0
  123. package/dist/lib/harness/console/render.test.js.map +1 -0
  124. package/dist/lib/harness/console/replay-cli.test.d.ts +2 -0
  125. package/dist/lib/harness/console/replay-cli.test.d.ts.map +1 -0
  126. package/dist/lib/harness/console/replay-cli.test.js +96 -0
  127. package/dist/lib/harness/console/replay-cli.test.js.map +1 -0
  128. package/dist/lib/harness/console/replay.d.ts +36 -0
  129. package/dist/lib/harness/console/replay.d.ts.map +1 -0
  130. package/dist/lib/harness/console/replay.js +59 -0
  131. package/dist/lib/harness/console/replay.js.map +1 -0
  132. package/dist/lib/harness/console/replay.test.d.ts +2 -0
  133. package/dist/lib/harness/console/replay.test.d.ts.map +1 -0
  134. package/dist/lib/harness/console/replay.test.js +81 -0
  135. package/dist/lib/harness/console/replay.test.js.map +1 -0
  136. package/dist/lib/harness/console/turn-reader.d.ts +50 -0
  137. package/dist/lib/harness/console/turn-reader.d.ts.map +1 -0
  138. package/dist/lib/harness/console/turn-reader.js +184 -0
  139. package/dist/lib/harness/console/turn-reader.js.map +1 -0
  140. package/dist/lib/harness/console/turn-reader.test.d.ts +2 -0
  141. package/dist/lib/harness/console/turn-reader.test.d.ts.map +1 -0
  142. package/dist/lib/harness/console/turn-reader.test.js +108 -0
  143. package/dist/lib/harness/console/turn-reader.test.js.map +1 -0
  144. package/dist/lib/harness/console/types.d.ts +109 -0
  145. package/dist/lib/harness/console/types.d.ts.map +1 -0
  146. package/dist/lib/harness/console/types.js +2 -0
  147. package/dist/lib/harness/console/types.js.map +1 -0
  148. package/dist/lib/harness/contract.d.ts +229 -0
  149. package/dist/lib/harness/contract.d.ts.map +1 -0
  150. package/dist/lib/harness/contract.js +22 -0
  151. package/dist/lib/harness/contract.js.map +1 -0
  152. package/dist/lib/harness/credential.d.ts +23 -0
  153. package/dist/lib/harness/credential.d.ts.map +1 -0
  154. package/dist/lib/harness/credential.js +81 -0
  155. package/dist/lib/harness/credential.js.map +1 -0
  156. package/dist/lib/harness/credential.test.d.ts +2 -0
  157. package/dist/lib/harness/credential.test.d.ts.map +1 -0
  158. package/dist/lib/harness/credential.test.js +74 -0
  159. package/dist/lib/harness/credential.test.js.map +1 -0
  160. package/dist/lib/harness/evaluate.d.ts +390 -0
  161. package/dist/lib/harness/evaluate.d.ts.map +1 -0
  162. package/dist/lib/harness/evaluate.js +988 -0
  163. package/dist/lib/harness/evaluate.js.map +1 -0
  164. package/dist/lib/harness/evaluate.test.d.ts +2 -0
  165. package/dist/lib/harness/evaluate.test.d.ts.map +1 -0
  166. package/dist/lib/harness/evaluate.test.js +621 -0
  167. package/dist/lib/harness/evaluate.test.js.map +1 -0
  168. package/dist/lib/harness/extract.d.ts +152 -0
  169. package/dist/lib/harness/extract.d.ts.map +1 -0
  170. package/dist/lib/harness/extract.js +1601 -0
  171. package/dist/lib/harness/extract.js.map +1 -0
  172. package/dist/lib/harness/gate.d.ts +48 -0
  173. package/dist/lib/harness/gate.d.ts.map +1 -0
  174. package/dist/lib/harness/gate.js +60 -0
  175. package/dist/lib/harness/gate.js.map +1 -0
  176. package/dist/lib/harness/gate.test.d.ts +2 -0
  177. package/dist/lib/harness/gate.test.d.ts.map +1 -0
  178. package/dist/lib/harness/gate.test.js +111 -0
  179. package/dist/lib/harness/gate.test.js.map +1 -0
  180. package/dist/lib/harness/self-check.d.ts +59 -0
  181. package/dist/lib/harness/self-check.d.ts.map +1 -0
  182. package/dist/lib/harness/self-check.js +56 -0
  183. package/dist/lib/harness/self-check.js.map +1 -0
  184. package/dist/lib/harness/self-check.test.d.ts +2 -0
  185. package/dist/lib/harness/self-check.test.d.ts.map +1 -0
  186. package/dist/lib/harness/self-check.test.js +43 -0
  187. package/dist/lib/harness/self-check.test.js.map +1 -0
  188. package/dist/lib/harness/transcript.d.ts +65 -0
  189. package/dist/lib/harness/transcript.d.ts.map +1 -0
  190. package/dist/lib/harness/transcript.js +144 -0
  191. package/dist/lib/harness/transcript.js.map +1 -0
  192. package/dist/lib/harness/transcript.test.d.ts +2 -0
  193. package/dist/lib/harness/transcript.test.d.ts.map +1 -0
  194. package/dist/lib/harness/transcript.test.js +118 -0
  195. package/dist/lib/harness/transcript.test.js.map +1 -0
  196. package/dist/lib/harness-wiring.d.ts +145 -0
  197. package/dist/lib/harness-wiring.d.ts.map +1 -0
  198. package/dist/lib/harness-wiring.js +280 -0
  199. package/dist/lib/harness-wiring.js.map +1 -0
  200. package/dist/lib/report-format.d.ts +132 -0
  201. package/dist/lib/report-format.d.ts.map +1 -0
  202. package/dist/lib/report-format.js +317 -0
  203. package/dist/lib/report-format.js.map +1 -0
  204. package/dist/lib/standards.d.ts +90 -0
  205. package/dist/lib/standards.d.ts.map +1 -0
  206. package/dist/lib/standards.js +194 -0
  207. package/dist/lib/standards.js.map +1 -0
  208. package/dist/lib/terminal-ui.d.ts.map +1 -1
  209. package/dist/lib/terminal-ui.js +12 -1
  210. package/dist/lib/terminal-ui.js.map +1 -1
  211. package/dist/standards/decision-request.md +90 -0
  212. package/dist/standards/fail-loud-standard.md +495 -0
  213. package/dist/standards/report-format.md +120 -0
  214. package/dist/standards/writing-standard.md +240 -0
  215. package/package.json +3 -2
@@ -0,0 +1,988 @@
1
+ // ── 1. The operation vocabulary ──────────────────────────────────────────────
2
+ /**
3
+ * The vocabulary `extract.ts` produces, read from that file rather than
4
+ * assumed. This file decides on these names and knows nothing about the tool
5
+ * names or the shell text behind them.
6
+ *
7
+ * write any file mutation, from Write, Edit, MultiEdit, NotebookEdit,
8
+ * a shell redirect, `sed -i`, `cp`, `tee` and the rest
9
+ * read any read, from Read, NotebookRead, Glob, Grep or `cat`
10
+ * chmod a mode change
11
+ * chdir a `cd` that moved the working directory
12
+ * unknown a command whose effect the extractor could not determine
13
+ * noop a command that touches nothing
14
+ * git.<verb> a parsed git operation, e.g. `git.reset-hard`, `git.push-main`
15
+ * tool.<Name> a tool the extractor does not model, and `tool.Task`
16
+ * change a completed change at merge time. No tool call produces it,
17
+ * and the integration lane that would is not built
18
+ *
19
+ * One operation names a call even when the call did several things, and the
20
+ * extractor picks the most consequential. `writes` and `reads` hold the union
21
+ * either way, so a rule that decides on paths loses nothing by that choice.
22
+ *
23
+ * Two consequences a rule author has to know.
24
+ *
25
+ * A `write` operation could be a Write tool call or a shell redirect, and the
26
+ * two reach different surfaces.
27
+ *
28
+ * Uncertainty is not one thing, and the operation separates the two kinds. A
29
+ * write whose target could not be resolved folds to `write` with `uncertain`
30
+ * set: `echo hi > $(pick)`, `sed -i s/a/b/ $TARGET`, `cd $X && rm -rf build`,
31
+ * and a Write tool call with no path. A command the extractor does not model
32
+ * folds to `unknown` or `chdir` with `uncertain` set: `npm test`, `pytest -q`,
33
+ * `make build`. A write rule that lists `unknown` escalates on every test run,
34
+ * which is an escalation nobody can act on. The rules below list the first kind
35
+ * and leave the second alone, and state that gap in their rationale.
36
+ */
37
+ export const OPERATIONS_THAT_CAN_WRITE = ['write', 'chmod', 'git.*'];
38
+ /** `git.*` matches every operation in the git family. A bare name matches itself. */
39
+ function operationMatches(pattern, operation) {
40
+ if (pattern === operation)
41
+ return true;
42
+ if (pattern.endsWith('.*'))
43
+ return operation.startsWith(pattern.slice(0, -1));
44
+ return false;
45
+ }
46
+ /** Two operation patterns overlap when either one could name what the other names. */
47
+ function patternsOverlap(a, b) {
48
+ return operationMatches(a, b) || operationMatches(b, a);
49
+ }
50
+ export const SURFACES = {
51
+ 'permission-callback': {
52
+ observes: ['write', 'chmod', 'chdir', 'unknown', 'noop', 'git.*'],
53
+ available: true,
54
+ basis: 'POC-1c: Write, Edit, Bash and PowerShell reached the callback every time, including 8 of 8 delegated calls. Read, Glob and the delegation call never reached it, and Grep was not measured. Refined on 2026-08-18 by two live sessions (`scripts/surface-observation-probe.mjs`, 18 commands): a Bash command reaches the callback when it mutates or when it names a path outside the working directory, and does not when it is read-only and confined to the working directory. `ls -la`, `cat README.md`, `git status --short`, `git log` and `grep` inside the worktree were run without being asked; `cd <outside> && ls`, `git -C <outside> status`, every write, `git reset --hard`, `git checkout --` and `git branch -D` were all asked. So the boundary and destructive rules do observe what they bind, and the commands that bypass are ones no rule refuses. `read` stays out of this list anyway: a shell read folds to the same `read` operation as a Read tool call, which never arrives, and partial observation an agent can step around is not enforcement.',
55
+ },
56
+ 'pre-tool-hook': {
57
+ observes: ['write', 'chmod', 'chdir', 'unknown', 'noop', 'git.*'],
58
+ available: true,
59
+ basis: 'settings.json as verified on 2026-08-17: only Bash has a tool matcher, so this surface observes what a shell command folds to. A Write or an Edit tool call folds to the same `write` operation and reaches no hook, so a write rule bound here covers the shell half only. `read` is left out for the reason given on the permission callback.',
60
+ },
61
+ 'integration-lane': {
62
+ observes: ['change'],
63
+ available: false,
64
+ basis: 'PRD component state Absent. Decides a completed change at merge time rather than a tool call.',
65
+ },
66
+ remote: {
67
+ observes: ['git.*', 'change'],
68
+ available: false,
69
+ basis: 'PRD component state Absent. Branch protection and a per-team push scope decide a ref write at the code host, and neither depends on jq being installed.',
70
+ },
71
+ };
72
+ function surfaceObservesAny(surface, operations) {
73
+ const capability = SURFACES[surface];
74
+ if (!capability)
75
+ return false;
76
+ return operations.some((op) => capability.observes.some((seen) => patternsOverlap(seen, op)));
77
+ }
78
+ /** Used when a `PolicyContext` does not name its own. */
79
+ export const DEFAULT_SCRATCH_ROOTS = ['/tmp', '/var/tmp'];
80
+ /**
81
+ * Scratch roots that do not swallow the worktree.
82
+ *
83
+ * A root containing the worktree exempts every write the rule exists to bind,
84
+ * so the rule compiles, reports healthy, and refuses nothing. That is the shape
85
+ * this compiler refuses elsewhere, and it is reachable by accident: a worktree
86
+ * created under `/tmp` sits inside the default root. Found on 2026-08-18 by a
87
+ * live-session proof whose scratch worktree was under the system temp
88
+ * directory, where the rule's own examples stopped denying.
89
+ */
90
+ export function effectiveScratchRoots(ctx) {
91
+ const configured = ctx.scratchRoots ?? DEFAULT_SCRATCH_ROOTS;
92
+ return configured.filter((root) => !isInside(root, normalizePath(ctx.worktreeRoot)));
93
+ }
94
+ /**
95
+ * Path tokens a rule may use: `${worktree}`, `${repoRoot}`, `${governingRules}`
96
+ * and `${testGuardedPaths}`.
97
+ *
98
+ * A list token used alone expands to the whole list. A list token used with a
99
+ * suffix expands to the list's first entry, which lets a rule's examples name a
100
+ * file under an assigned path without hard-coding a project's layout.
101
+ */
102
+ function tokenValue(name, ctx) {
103
+ switch (name) {
104
+ case 'worktree':
105
+ return [ctx.worktreeRoot];
106
+ case 'repoRoot':
107
+ return [ctx.repoRoot];
108
+ case 'governingRules':
109
+ return ctx.governingRulePaths;
110
+ case 'testGuardedPaths':
111
+ return ctx.testGuardedPaths;
112
+ case 'scratch':
113
+ return effectiveScratchRoots(ctx);
114
+ default:
115
+ return null;
116
+ }
117
+ }
118
+ export function expandPaths(entries, ctx) {
119
+ const paths = [];
120
+ const errors = [];
121
+ for (const entry of entries) {
122
+ const whole = /^\$\{([A-Za-z]+)\}$/.exec(entry);
123
+ if (whole) {
124
+ const value = tokenValue(whole[1], ctx);
125
+ if (!value) {
126
+ errors.push(`${entry} is not a path token`);
127
+ continue;
128
+ }
129
+ if (value.length === 0) {
130
+ errors.push(`${entry} expands to nothing in this context, so the condition can never match`);
131
+ continue;
132
+ }
133
+ paths.push(...value.map(normalizePath));
134
+ continue;
135
+ }
136
+ let failed = false;
137
+ const substituted = entry.replace(/\$\{([A-Za-z]+)\}/g, (_all, name) => {
138
+ const value = tokenValue(name, ctx);
139
+ if (!value) {
140
+ errors.push(`${entry} names ${name}, which is not a path token`);
141
+ failed = true;
142
+ return '';
143
+ }
144
+ if (value.length === 0) {
145
+ errors.push(`${entry} names ${name}, which expands to nothing in this context`);
146
+ failed = true;
147
+ return '';
148
+ }
149
+ return value[0];
150
+ });
151
+ if (!failed)
152
+ paths.push(normalizePath(substituted));
153
+ }
154
+ return { paths, errors };
155
+ }
156
+ // ── 4. Path comparison ───────────────────────────────────────────────────────
157
+ /**
158
+ * Lexical normalisation. Collapses separators, `.` and `..`, and drops a
159
+ * trailing slash. Resolving `..` matters: `/work/team/../other/x` and
160
+ * `/work/other/x` name one file, and a rule that compared the strings would
161
+ * refuse one and allow the other.
162
+ */
163
+ export function normalizePath(p) {
164
+ const raw = p.replace(/\\/g, '/');
165
+ const root = raw.startsWith('/') ? '/' : '';
166
+ const out = [];
167
+ for (const part of raw.split('/')) {
168
+ if (part === '' || part === '.')
169
+ continue;
170
+ if (part === '..') {
171
+ out.pop();
172
+ continue;
173
+ }
174
+ out.push(part);
175
+ }
176
+ return root + out.join('/');
177
+ }
178
+ /** True when `p` is `root` or lies under it. `/work/team-other` is not under `/work/team`. */
179
+ export function isInside(root, p) {
180
+ if (p === root)
181
+ return true;
182
+ return p.startsWith(root === '/' ? '/' : `${root}/`);
183
+ }
184
+ /** `**` crosses directories, `*` and `?` do not. */
185
+ export function globToRegExp(glob) {
186
+ let out = '';
187
+ for (let i = 0; i < glob.length; i += 1) {
188
+ const c = glob[i];
189
+ if (c === '*') {
190
+ if (glob[i + 1] === '*') {
191
+ if (glob[i + 2] === '/') {
192
+ out += '(?:.*/)?';
193
+ i += 2;
194
+ }
195
+ else {
196
+ out += '.*';
197
+ i += 1;
198
+ }
199
+ }
200
+ else {
201
+ out += '[^/]*';
202
+ }
203
+ }
204
+ else if (c === '?') {
205
+ out += '[^/]';
206
+ }
207
+ else {
208
+ out += c.replace(/[.+^${}()|[\]\\]/g, '\\$&');
209
+ }
210
+ }
211
+ return new RegExp(`^${out}$`);
212
+ }
213
+ const NO_MATCH = { matched: false, because: '' };
214
+ /** Conditions combine with OR. The first target that trips one reports it. */
215
+ function testCondition(condition, targets) {
216
+ for (const raw of targets) {
217
+ const target = normalizePath(raw);
218
+ if (condition.outside.length > 0 && !condition.outside.some((root) => isInside(root, target))) {
219
+ return `target ${target} is outside ${condition.outside.join(' and ')}.`;
220
+ }
221
+ if (condition.inside.length > 0) {
222
+ const hit = condition.inside.find((root) => isInside(root, target));
223
+ if (hit)
224
+ return `target ${target} is inside ${hit}.`;
225
+ }
226
+ for (let i = 0; i < condition.globs.length; i += 1) {
227
+ if (condition.globs[i].test(target))
228
+ return `target ${target} matches ${condition.globSource[i]}.`;
229
+ }
230
+ }
231
+ return null;
232
+ }
233
+ function runMatch(spec, expanded, attrs) {
234
+ if (!spec.operations.some((pattern) => operationMatches(pattern, attrs.operation)))
235
+ return NO_MATCH;
236
+ if (!expanded.writes && !expanded.reads && !expanded.workingDir) {
237
+ return { matched: true, because: `Operation ${attrs.operation} is on this rule's list.` };
238
+ }
239
+ // `onUncertain` answers an unresolved target. It does not answer an
240
+ // unmodelled command, which the operations list answers instead.
241
+ //
242
+ // The two were one flag until 2026-08-18, and the cost was measured: 62 of
243
+ // 600 ordinary commands escalated because a call wrote a resolved path inside
244
+ // the worktree and also ran `mx` or `gh` (docs/gate-coverage.md section 4).
245
+ // The write target was never consulted. A rule author reading
246
+ // `onUncertain: 'escalate'` means "ask me when you cannot tell where this
247
+ // writes", not "ask me whenever anything in the command was opaque".
248
+ //
249
+ // Absent `uncertainAbout` reads as `targets`, so a rule keeps its behaviour
250
+ // against an extractor that does not set the field.
251
+ if (attrs.uncertain && attrs.uncertainAbout !== 'effects') {
252
+ const detail = attrs.uncertainReason
253
+ ? `The extractor could not determine the targets: ${attrs.uncertainReason}.`
254
+ : 'The extractor could not determine the targets.';
255
+ if (spec.onUncertain === 'skip')
256
+ return NO_MATCH;
257
+ if (spec.onUncertain === 'escalate')
258
+ return { matched: true, effect: 'ask', because: detail };
259
+ return { matched: true, because: detail };
260
+ }
261
+ if (expanded.writes) {
262
+ const why = testCondition(expanded.writes, attrs.writes);
263
+ if (why)
264
+ return { matched: true, because: `Write ${why}` };
265
+ }
266
+ if (expanded.reads) {
267
+ const why = testCondition(expanded.reads, attrs.reads);
268
+ if (why)
269
+ return { matched: true, because: `Read ${why}` };
270
+ }
271
+ if (expanded.workingDir && attrs.workingDir) {
272
+ const why = testCondition(expanded.workingDir, [attrs.workingDir]);
273
+ if (why)
274
+ return { matched: true, because: `The call worked in a directory where ${why}` };
275
+ }
276
+ return NO_MATCH;
277
+ }
278
+ /**
279
+ * Match clauses that read an optional field on `Attributes`, and the field each
280
+ * one reads. A rule naming one of these still compiles and still runs its other
281
+ * clauses, so the failure mode is a rule that enforces less than it states
282
+ * rather than one that refuses everything. That is worth a line at startup.
283
+ */
284
+ const OPTIONAL_ATTRIBUTE_CLAUSES = [
285
+ ['workingDir', 'workingDir'],
286
+ ];
287
+ const WORKING_DIR_SETTERS = 'The shipped extract.ts sets it on every path.';
288
+ /** Does any path condition on this rule use the `${scratch}` token? */
289
+ function referencesScratch(source) {
290
+ const lists = [
291
+ source.match?.writes, source.match?.reads, source.match?.workingDir,
292
+ ].flatMap((c) => [...(c?.outside ?? []), ...(c?.inside ?? []), ...(c?.globs ?? [])]);
293
+ return [...lists, ...(source.claims?.writeScope ?? [])].some((e) => e.includes('${scratch}'));
294
+ }
295
+ export class RulesetRefused extends Error {
296
+ refusals;
297
+ constructor(refusals) {
298
+ const lines = refusals.map((r) => ` ${r.ruleId} [${r.code}]: ${r.detail}`);
299
+ super(`The compiler refused ${refusals.length} item(s):\n${lines.join('\n')}`);
300
+ this.name = 'RulesetRefused';
301
+ this.refusals = refusals;
302
+ }
303
+ }
304
+ const RESTRICTION = { deny: 3, ask: 2, allow: 1 };
305
+ function principalMatches(binding, principal) {
306
+ if (!binding)
307
+ return true;
308
+ if (binding.team !== undefined && binding.team !== principal.team)
309
+ return false;
310
+ if (binding.role !== undefined && binding.role !== principal.role)
311
+ return false;
312
+ return true;
313
+ }
314
+ function mostRestrictive(hits) {
315
+ return hits.reduce((best, h) => (RESTRICTION[h.effect] > RESTRICTION[best.effect] ? h : best), hits[0]);
316
+ }
317
+ function pastTense(effect) {
318
+ if (effect === 'deny')
319
+ return 'refused';
320
+ if (effect === 'ask')
321
+ return 'escalated';
322
+ return 'allowed';
323
+ }
324
+ export class CompiledEvaluator {
325
+ rules;
326
+ context;
327
+ warnings;
328
+ constructor(rules, context, warnings = []) {
329
+ this.rules = rules;
330
+ this.context = context;
331
+ this.warnings = warnings;
332
+ }
333
+ /**
334
+ * Decides. Never parses.
335
+ *
336
+ * A rule in observe mode matches, reports and enforces nothing. When every
337
+ * matching rule observes, the effect is `allow` and `observedOnly` is true,
338
+ * and that is the only case where the flag is set. When any matching rule
339
+ * blocks, the most restrictive of the blocking effects wins, so a specific
340
+ * allow does not punch a hole in a broader deny. Specificity orders what the
341
+ * decision reports rather than which effect wins.
342
+ */
343
+ evaluate(attrs, principal, surface) {
344
+ const hits = [];
345
+ for (const rule of this.rules) {
346
+ if (!rule.source.surfaces.includes(surface))
347
+ continue;
348
+ if (!principalMatches(rule.source.principals, principal))
349
+ continue;
350
+ const outcome = runMatch(rule.source.match, rule.expanded, attrs);
351
+ if (!outcome.matched)
352
+ continue;
353
+ hits.push({ rule, effect: outcome.effect ?? rule.source.effect, because: outcome.because });
354
+ }
355
+ if (hits.length === 0)
356
+ return { effect: 'allow', matchedRules: [] };
357
+ hits.sort((a, b) => b.rule.specificity - a.rule.specificity || a.rule.source.id.localeCompare(b.rule.source.id));
358
+ const enforcing = hits.filter((h) => h.rule.source.mode === 'block');
359
+ if (enforcing.length === 0) {
360
+ const strongest = mostRestrictive(hits);
361
+ return {
362
+ effect: 'allow',
363
+ matchedRules: hits.map((h) => h.rule.source.id),
364
+ observedOnly: true,
365
+ reason: `Observe mode. ${strongest.rule.source.id} would have ${pastTense(strongest.effect)} ${attrs.operation}. ${strongest.rule.source.statement} ${strongest.because} This rule enforced nothing.`,
366
+ };
367
+ }
368
+ const decisive = mostRestrictive(enforcing);
369
+ const observed = hits.filter((h) => h.rule.source.mode === 'observe').map((h) => h.rule.source.id);
370
+ const verb = decisive.effect === 'deny' ? 'refused' : decisive.effect === 'ask' ? 'requires approval for' : 'allowed';
371
+ let reason = `${decisive.rule.source.id} ${verb} ${attrs.operation}. ${decisive.rule.source.statement} ${decisive.because}`;
372
+ if (observed.length > 0) {
373
+ reason += ` ${observed.join(', ')} also matched in observe mode and enforced nothing.`;
374
+ }
375
+ return { effect: decisive.effect, matchedRules: enforcing.map((h) => h.rule.source.id), reason };
376
+ }
377
+ /**
378
+ * Rules this ruleset holds that the given surface cannot enforce, either
379
+ * because no rule binds them to it or because it observes none of their
380
+ * operations. An operator running one surface reads this to see what that
381
+ * surface is not enforcing.
382
+ */
383
+ unenforceableOn(surface) {
384
+ return this.rules
385
+ .filter((rule) => {
386
+ if (!rule.source.surfaces.includes(surface))
387
+ return true;
388
+ return !surfaceObservesAny(surface, rule.source.match.operations);
389
+ })
390
+ .map((rule) => rule.source);
391
+ }
392
+ /** Who owns a rule and whether its subject may propose or apply a change to it. */
393
+ changeControlFor(ruleId) {
394
+ return this.rules.find((r) => r.source.id === ruleId)?.source.changeControl;
395
+ }
396
+ /** Write scopes claimed, by rule. The operator's view of which rule owns what. */
397
+ claimedWriteScopes() {
398
+ return this.rules
399
+ .filter((r) => r.writeScope.length > 0)
400
+ .map((r) => ({ ruleId: r.source.id, scope: r.writeScope }));
401
+ }
402
+ get ruleIds() {
403
+ return this.rules.map((r) => r.source.id);
404
+ }
405
+ }
406
+ /** Compiles and reports. `compileRuleset` is the form that refuses by throwing. */
407
+ export function checkRuleset(sources, context) {
408
+ const refusals = [];
409
+ const warnings = [];
410
+ const compiled = [];
411
+ const seenIds = new Set();
412
+ for (const source of sources) {
413
+ const id = source.id ?? '(no id)';
414
+ if (seenIds.has(id)) {
415
+ refusals.push({ code: 'duplicate-id', ruleId: id, detail: 'A second rule uses this id.' });
416
+ }
417
+ seenIds.add(id);
418
+ if (!source.statement || source.statement.trim() === '') {
419
+ refusals.push({
420
+ code: 'missing-statement',
421
+ ruleId: id,
422
+ detail: 'A rule states what it decides in one sentence.',
423
+ });
424
+ }
425
+ if (!source.rationale || source.rationale.trim() === '') {
426
+ refusals.push({
427
+ code: 'missing-rationale',
428
+ ruleId: id,
429
+ detail: 'A rule records why it exists. A rule nobody can explain is a rule nobody can challenge, and the challenge path is what stops a wrong rule from outliving its reason.',
430
+ });
431
+ }
432
+ if (!source.changeControl || !source.changeControl.owner || source.changeControl.owner.trim() === '') {
433
+ refusals.push({ code: 'missing-change-control', ruleId: id, detail: 'A rule names an owner.' });
434
+ }
435
+ if (!source.examples || source.examples.length === 0) {
436
+ refusals.push({
437
+ code: 'no-examples',
438
+ ruleId: id,
439
+ detail: "The examples are the rule's test, and they live in the rule.",
440
+ });
441
+ }
442
+ if (!source.records || source.records.length === 0) {
443
+ warnings.push({
444
+ ruleId: id,
445
+ detail: 'The rule records nothing when it executes, so its decisions leave no evidence.',
446
+ });
447
+ }
448
+ const operations = source.match?.operations ?? [];
449
+ if (operations.length === 0) {
450
+ refusals.push({
451
+ code: 'no-operations',
452
+ ruleId: id,
453
+ detail: 'A rule names the operations it is about, because the surface check reads them.',
454
+ });
455
+ }
456
+ const surfaces = source.surfaces ?? [];
457
+ if (surfaces.length === 0) {
458
+ refusals.push({
459
+ code: 'no-surface',
460
+ ruleId: id,
461
+ detail: 'A rule that names no surface is a rule nothing runs.',
462
+ });
463
+ }
464
+ for (const surface of surfaces) {
465
+ const capability = SURFACES[surface];
466
+ if (!capability) {
467
+ refusals.push({ code: 'unenforceable-surface', ruleId: id, detail: `${surface} is not a surface.` });
468
+ continue;
469
+ }
470
+ if (operations.length > 0 && !surfaceObservesAny(surface, operations)) {
471
+ refusals.push({
472
+ code: 'unenforceable-surface',
473
+ ruleId: id,
474
+ detail: `${surface} observes ${capability.observes.join(', ')} and this rule is about ${operations.join(', ')}. Bound here it would report healthy and refuse nothing. ${capability.basis}`,
475
+ });
476
+ }
477
+ }
478
+ if (source.mode === 'block' && surfaces.length > 0 && operations.length > 0) {
479
+ const runnable = surfaces.filter((s) => SURFACES[s]?.available && surfaceObservesAny(s, operations));
480
+ if (runnable.length === 0) {
481
+ refusals.push({
482
+ code: 'blocking-on-unavailable-surface',
483
+ ruleId: id,
484
+ detail: `This rule blocks and every surface that could observe it is not built: ${surfaces.join(', ')}. Run it in observe mode until one exists.`,
485
+ });
486
+ }
487
+ }
488
+ if ((source.match?.writes || source.match?.reads || source.match?.workingDir) && !source.match.onUncertain) {
489
+ refusals.push({
490
+ code: 'missing-uncertainty-handling',
491
+ ruleId: id,
492
+ detail: 'A rule with a path condition says what to do when the extractor could not resolve the targets. #5434 is what an unstated answer costs.',
493
+ });
494
+ }
495
+ let writeScope = [];
496
+ if (source.claims?.writeScope && source.claims.writeScope.length > 0) {
497
+ const claim = expandPaths(source.claims.writeScope, context);
498
+ for (const error of claim.errors) {
499
+ refusals.push({ code: 'bad-path-token', ruleId: id, detail: `claims.writeScope: ${error}` });
500
+ }
501
+ writeScope = claim.paths;
502
+ }
503
+ else if (source.match?.writes) {
504
+ refusals.push({
505
+ code: 'missing-write-scope',
506
+ ruleId: id,
507
+ detail: 'A rule that decides writes declares the scope it claims, so two rules claiming one scope are visible at compile time.',
508
+ });
509
+ }
510
+ const expanded = {};
511
+ for (const kind of ['writes', 'reads', 'workingDir']) {
512
+ const condition = source.match?.[kind];
513
+ if (!condition)
514
+ continue;
515
+ const outside = expandPaths(condition.outside ?? [], context);
516
+ const inside = expandPaths(condition.inside ?? [], context);
517
+ const globs = expandPaths(condition.globs ?? [], context);
518
+ for (const error of [...outside.errors, ...inside.errors, ...globs.errors]) {
519
+ refusals.push({ code: 'bad-path-token', ruleId: id, detail: `match.${kind}: ${error}` });
520
+ }
521
+ if (outside.paths.length + inside.paths.length + globs.paths.length === 0) {
522
+ refusals.push({
523
+ code: 'empty-path-condition',
524
+ ruleId: id,
525
+ detail: `match.${kind} expands to no paths in this context, so the rule can never match.`,
526
+ });
527
+ }
528
+ expanded[kind] = {
529
+ outside: outside.paths,
530
+ inside: inside.paths,
531
+ globs: globs.paths.map(globToRegExp),
532
+ globSource: globs.paths,
533
+ };
534
+ }
535
+ if (source.principals?.role && !source.principals.team) {
536
+ warnings.push({
537
+ ruleId: id,
538
+ detail: 'This rule binds a role and no team. 92% of certain file writes came from subagents rather than team leads across 301 sessions, so a role binding governs 1,232 of 15,900 measured writes unless the roster gives subagents the same role.',
539
+ });
540
+ }
541
+ if (surfaces.length > 0 && surfaces.every((s) => !SURFACES[s]?.available)) {
542
+ warnings.push({
543
+ ruleId: id,
544
+ detail: `Every surface this rule names is not built: ${surfaces.join(', ')}. It records nothing today.`,
545
+ });
546
+ }
547
+ // A clause that reads an optional attribute goes quiet against an extractor
548
+ // that does not set it, and quiet is the shape this compiler exists to
549
+ // refuse elsewhere. It cannot be a refusal, because the ruleset compiles
550
+ // before any extractor runs and nothing here can prove what one will
551
+ // report. So it is stated, and the operator reads it at startup.
552
+ // A scratch root that contains the worktree was dropped, which changes what
553
+ // this rule binds. The operator reads why rather than discovering it.
554
+ if (referencesScratch(source)) {
555
+ const configured = context.scratchRoots ?? DEFAULT_SCRATCH_ROOTS;
556
+ const kept = effectiveScratchRoots(context);
557
+ const dropped = configured.filter((r) => !kept.includes(r));
558
+ if (dropped.length > 0) {
559
+ warnings.push({
560
+ ruleId: id,
561
+ detail: `Scratch root(s) ${dropped.join(', ')} contain the worktree ${context.worktreeRoot}, so they would exempt every write this rule binds. They are dropped. Set PolicyContext.scratchRoots to the session's own scratch directory.`,
562
+ });
563
+ }
564
+ }
565
+ for (const [clause, field] of OPTIONAL_ATTRIBUTE_CLAUSES) {
566
+ if (!source.match?.[clause])
567
+ continue;
568
+ warnings.push({
569
+ ruleId: id,
570
+ detail: `match.${clause} reads \`Attributes.${field}\`, which is optional. Against an extractor that does not set it this clause matches nothing and the rest of the rule still runs, so the rule reports healthy while enforcing less than it says. ${WORKING_DIR_SETTERS}`,
571
+ });
572
+ }
573
+ const specificity = (source.principals?.team ? 2 : 0) + (source.principals?.role ? 1 : 0);
574
+ compiled.push({ source, expanded, specificity, writeScope });
575
+ }
576
+ refusals.push(...duplicateWriteScopes(compiled));
577
+ if (refusals.length > 0)
578
+ return { evaluator: null, refusals: sortRefusals(refusals), warnings };
579
+ const evaluator = new CompiledEvaluator(compiled, context, warnings);
580
+ const exampleRefusals = runExamples(compiled, evaluator, context);
581
+ if (exampleRefusals.length > 0) {
582
+ return { evaluator: null, refusals: sortRefusals(exampleRefusals), warnings };
583
+ }
584
+ return { evaluator, refusals: [], warnings };
585
+ }
586
+ /** Throws `RulesetRefused` listing every refusal, rather than the first one found. */
587
+ export function compileRuleset(sources, context) {
588
+ const outcome = checkRuleset(sources, context);
589
+ if (!outcome.evaluator)
590
+ throw new RulesetRefused(outcome.refusals);
591
+ return outcome.evaluator;
592
+ }
593
+ function sortRefusals(refusals) {
594
+ return [...refusals].sort((a, b) => a.ruleId.localeCompare(b.ruleId) || a.code.localeCompare(b.code));
595
+ }
596
+ /**
597
+ * Two rules on one team claiming the same write scope.
598
+ *
599
+ * Nesting is not flagged: a narrower rule inside a broader one is how a lower
600
+ * scope tightens a rule without removing one, which is the point of separating
601
+ * a definition from its assignment. Equality is the ambiguous case, because
602
+ * then declaration order decides, and declaration order is not policy. A rule
603
+ * that binds no team applies to every team, so it overlaps any team-bound rule.
604
+ */
605
+ function duplicateWriteScopes(compiled) {
606
+ const refusals = [];
607
+ for (let i = 0; i < compiled.length; i += 1) {
608
+ for (let j = i + 1; j < compiled.length; j += 1) {
609
+ const a = compiled[i];
610
+ const b = compiled[j];
611
+ if (a.writeScope.length === 0 || b.writeScope.length === 0)
612
+ continue;
613
+ if (!teamsOverlap(a.source, b.source))
614
+ continue;
615
+ const shared = a.writeScope.filter((scope) => b.writeScope.includes(scope));
616
+ if (shared.length === 0)
617
+ continue;
618
+ const team = a.source.principals?.team ?? b.source.principals?.team ?? 'every team';
619
+ refusals.push({
620
+ code: 'duplicate-write-scope',
621
+ ruleId: b.source.id,
622
+ detail: `${b.source.id} and ${a.source.id} both claim ${shared.join(', ')} on ${team}. Which one decides a write there would depend on declaration order.`,
623
+ });
624
+ }
625
+ }
626
+ return refusals;
627
+ }
628
+ function teamsOverlap(a, b) {
629
+ const teamA = a.principals?.team;
630
+ const teamB = b.principals?.team;
631
+ if (teamA === undefined || teamB === undefined)
632
+ return true;
633
+ return teamA === teamB;
634
+ }
635
+ /**
636
+ * The examples run against the whole compiled ruleset rather than against the
637
+ * rule in isolation, so a new rule that breaks an existing rule's allow example
638
+ * refuses at compile time instead of at the session that hits it.
639
+ */
640
+ function runExamples(compiled, evaluator, context) {
641
+ const refusals = [];
642
+ for (const rule of compiled) {
643
+ for (let i = 0; i < rule.source.examples.length; i += 1) {
644
+ const example = rule.source.examples[i];
645
+ const surface = example.surface ?? rule.source.surfaces[0];
646
+ const principal = {
647
+ team: example.principal?.team ?? rule.source.principals?.team ?? 'product',
648
+ role: example.principal?.role ?? rule.source.principals?.role ?? 'implementation-engineer',
649
+ subagentId: example.principal?.subagentId ?? null,
650
+ sessionId: example.principal?.sessionId ?? 'compile-check',
651
+ };
652
+ const attrs = {
653
+ ...example.attrs,
654
+ writes: expandPaths(example.attrs.writes ?? [], context).paths,
655
+ reads: expandPaths(example.attrs.reads ?? [], context).paths,
656
+ ...(example.attrs.workingDir !== undefined
657
+ ? { workingDir: expandPaths([example.attrs.workingDir], context).paths[0] ?? example.attrs.workingDir }
658
+ : {}),
659
+ };
660
+ const decision = evaluator.evaluate(attrs, principal, surface);
661
+ if (decision.effect !== example.expect) {
662
+ const from = decision.matchedRules.length > 0
663
+ ? ` from ${decision.matchedRules.join(', ')}`
664
+ : ' with no rule matching';
665
+ refusals.push({
666
+ code: 'example-disagrees',
667
+ ruleId: rule.source.id,
668
+ detail: `Example ${i} states ${example.expect} for ${attrs.operation} on ${surface} and the ruleset returned ${decision.effect}${from}.`,
669
+ });
670
+ continue;
671
+ }
672
+ if (example.expectObservedOnly !== undefined &&
673
+ Boolean(decision.observedOnly) !== example.expectObservedOnly) {
674
+ refusals.push({
675
+ code: 'example-disagrees',
676
+ ruleId: rule.source.id,
677
+ detail: `Example ${i} states observedOnly ${example.expectObservedOnly} and the ruleset returned ${Boolean(decision.observedOnly)}.`,
678
+ });
679
+ }
680
+ }
681
+ }
682
+ return refusals;
683
+ }
684
+ /** Fills the attribute fields an example does not need to state. */
685
+ export function attributes(partial) {
686
+ return {
687
+ operation: partial.operation,
688
+ writes: partial.writes ?? [],
689
+ reads: partial.reads ?? [],
690
+ uncertain: partial.uncertain ?? false,
691
+ ...(partial.workingDir !== undefined ? { workingDir: partial.workingDir } : {}),
692
+ ...(partial.uncertainAbout ? { uncertainAbout: partial.uncertainAbout } : {}),
693
+ ...(partial.uncertainReason ? { uncertainReason: partial.uncertainReason } : {}),
694
+ };
695
+ }
696
+ // ── 9. The starter set ───────────────────────────────────────────────────────
697
+ /**
698
+ * Section 5 of `docs/rule-format-proposal.md` writes five rules. Four compile.
699
+ * The fifth is in `WITHHELD_RULES` below with the reason, because every surface
700
+ * the contract defines refuses it and that refusal is the honest result rather
701
+ * than a defect.
702
+ */
703
+ /** (a) A team may not write outside its worktree. */
704
+ export const TEAMS_STAY_IN_OWN_WORKTREE = {
705
+ id: 'teams-stay-in-own-worktree',
706
+ statement: 'A team writes only inside its own worktree.',
707
+ rationale: 'Two teams overwrote each other in one tree, incident #4123. The guard-coverage measurement found 0 of 146 write-outside-the-worktree commands refused, which makes this the largest measured gap. Deciding on a resolved write path covers the 18 string patterns entries 20 to 37 spell out separately. Scratch is exempt because every guard this replaces exempts it and because it was measured: the first version of this rule refused 10 of 600 ordinary commands, and all 10 wrote only to the session scratchpad. Known gap, stated rather than hidden: a command the extractor does not model folds to `unknown` and this rule does not escalate on it, because `npm test` and `pytest` fold there too and a prompt on every test run is an escalation nobody acts on. Closing that needs a measurement of how often a real session runs an unmodelled command that writes, and observe mode is how to get it.',
708
+ surfaces: ['permission-callback', 'pre-tool-hook'],
709
+ mode: 'block',
710
+ effect: 'deny',
711
+ match: {
712
+ operations: ['write', 'chmod', 'chdir', 'git.*'],
713
+ writes: { outside: ['${worktree}', '${scratch}'] },
714
+ workingDir: { outside: ['${worktree}', '${scratch}'] },
715
+ onUncertain: 'escalate',
716
+ },
717
+ claims: { writeScope: ['${worktree}', '${scratch}'] },
718
+ records: ['operation', 'writes', 'principal', 'decision', 'rule'],
719
+ changeControl: { owner: 'platform', subjectMayPropose: true, subjectMayApply: false },
720
+ examples: [
721
+ {
722
+ attrs: attributes({ operation: 'write', writes: ['${worktree}/../other-team/src/index.ts'] }),
723
+ surface: 'permission-callback',
724
+ expect: 'deny',
725
+ },
726
+ {
727
+ // `git -C /repo/worktrees/other-team commit`, which the extractor records
728
+ // as a write to the repository directory it points at.
729
+ attrs: attributes({ operation: 'git.commit', writes: ['${worktree}/../other-team'] }),
730
+ surface: 'pre-tool-hook',
731
+ expect: 'deny',
732
+ },
733
+ {
734
+ attrs: attributes({ operation: 'write', writes: ['${worktree}/src/index.ts'] }),
735
+ surface: 'permission-callback',
736
+ expect: 'allow',
737
+ },
738
+ {
739
+ // `cd /repo/worktrees/other-team && ls`. No write, so the write
740
+ // condition cannot see it: 200 of the 319 commands that leave the
741
+ // worktree fold to `chdir` with nothing in `writes`.
742
+ attrs: attributes({ operation: 'chdir', workingDir: '${worktree}/../other-team' }),
743
+ surface: 'permission-callback',
744
+ expect: 'deny',
745
+ },
746
+ {
747
+ // `git -C /repo/worktrees/other-team status`. A read-only git command
748
+ // pointed outside. The repository it acts on is the crossing.
749
+ attrs: attributes({ operation: 'git.status', workingDir: '${worktree}/../other-team' }),
750
+ surface: 'permission-callback',
751
+ expect: 'deny',
752
+ },
753
+ {
754
+ // `cd /tmp/claude-1000/…/scratchpad && ls`. Scratch is in scope, named
755
+ // through the token rather than as a literal: a project that puts scratch
756
+ // somewhere else must not fail this example for that reason alone.
757
+ attrs: attributes({ operation: 'chdir', workingDir: '${scratch}/session/scratchpad' }),
758
+ surface: 'permission-callback',
759
+ expect: 'allow',
760
+ },
761
+ {
762
+ // `cat /home/vscode/.claude/settings.json` from inside the worktree. The
763
+ // file read is outside and the call is not. A `reads` condition would
764
+ // refuse this, which is why the clause tests the working directory.
765
+ attrs: attributes({
766
+ operation: 'read',
767
+ reads: ['${worktree}', '/home/vscode/.claude/settings.json'],
768
+ workingDir: '${worktree}',
769
+ }),
770
+ surface: 'permission-callback',
771
+ expect: 'allow',
772
+ },
773
+ {
774
+ // `echo hi > $(pick)`. The call writes, and the target is unresolved.
775
+ attrs: attributes({
776
+ operation: 'write',
777
+ uncertain: true,
778
+ uncertainReason: 'redirect target $(pick): command substitution $(pick) is not evaluated',
779
+ }),
780
+ surface: 'permission-callback',
781
+ expect: 'ask',
782
+ },
783
+ {
784
+ // `npm test`. The extractor does not model npm, so it reports uncertain
785
+ // with no write target. Escalating here would prompt on every test run.
786
+ attrs: attributes({
787
+ operation: 'unknown',
788
+ uncertain: true,
789
+ uncertainReason: 'npm is not a command the extractor models',
790
+ }),
791
+ surface: 'permission-callback',
792
+ expect: 'allow',
793
+ },
794
+ ],
795
+ };
796
+ /**
797
+ * (b) Destructive git operations are refused.
798
+ *
799
+ * One decision replaces 24 permission patterns. Every operation named here is a
800
+ * name `extract.ts` produces, checked against that file rather than invented,
801
+ * because a rule naming an operation nothing emits is the silent-never-fires
802
+ * case in a different disguise.
803
+ *
804
+ * The branch half of the proposal's statement survives for push and not for
805
+ * checkout. The extractor resolves a push that names main into
806
+ * `git.push-main` and `git.push-force-main`, so this rule refuses both. It does
807
+ * not name main on a checkout or a switch, so "a team stays off main" is
808
+ * enforced here for a push and left to branch protection at the code host for
809
+ * everything else, which is why `remote` is a surface.
810
+ */
811
+ export const NO_DESTRUCTIVE_GIT = {
812
+ id: 'no-destructive-git',
813
+ statement: 'A team does not discard committed or working-tree state, does not force a push, and does not push to main.',
814
+ rationale: 'Recovering discarded agent work costs more than refusing the operation. 24 permission patterns express this today and a bare `git merge` passes all of them, which worktree-guard.sh records in its own source at lines 25 to 32, because every pattern requires an argument and prose ending on the verb would break if one did not. Deciding on a parsed subcommand catches the bare form and blocks no prose. git-mutation-guard.sh fails open when it cannot parse its input (#5434), so this rule does not depend on that script.',
815
+ surfaces: ['permission-callback', 'pre-tool-hook', 'remote'],
816
+ mode: 'block',
817
+ effect: 'deny',
818
+ match: {
819
+ operations: [
820
+ 'git.reset',
821
+ 'git.reset-hard',
822
+ 'git.checkout-path',
823
+ 'git.restore',
824
+ 'git.clean',
825
+ 'git.stash-drop',
826
+ 'git.branch-delete',
827
+ 'git.filter-branch',
828
+ 'git.merge',
829
+ 'git.push-force',
830
+ 'git.push-force-main',
831
+ 'git.push-main',
832
+ ],
833
+ },
834
+ records: ['operation', 'command', 'principal', 'decision', 'rule'],
835
+ changeControl: { owner: 'platform', subjectMayPropose: true, subjectMayApply: false },
836
+ examples: [
837
+ { attrs: attributes({ operation: 'git.reset-hard' }), surface: 'permission-callback', expect: 'deny' },
838
+ { attrs: attributes({ operation: 'git.clean' }), surface: 'permission-callback', expect: 'deny' },
839
+ { attrs: attributes({ operation: 'git.checkout-path' }), surface: 'permission-callback', expect: 'deny' },
840
+ { attrs: attributes({ operation: 'git.push-force' }), surface: 'permission-callback', expect: 'deny' },
841
+ { attrs: attributes({ operation: 'git.push-main' }), surface: 'remote', expect: 'deny' },
842
+ { attrs: attributes({ operation: 'git.merge' }), surface: 'pre-tool-hook', expect: 'deny' },
843
+ { attrs: attributes({ operation: 'git.status' }), surface: 'permission-callback', expect: 'allow' },
844
+ { attrs: attributes({ operation: 'git.rebase' }), surface: 'permission-callback', expect: 'allow' },
845
+ { attrs: attributes({ operation: 'git.push' }), surface: 'permission-callback', expect: 'allow' },
846
+ { attrs: attributes({ operation: 'git.reset-soft' }), surface: 'permission-callback', expect: 'allow' },
847
+ { attrs: attributes({ operation: 'git.clean-dry-run' }), surface: 'permission-callback', expect: 'allow' },
848
+ {
849
+ attrs: attributes({ operation: 'git.checkout-new-branch' }),
850
+ surface: 'permission-callback',
851
+ expect: 'allow',
852
+ },
853
+ ],
854
+ };
855
+ /**
856
+ * (d) A change under given paths needs a failing test first.
857
+ *
858
+ * Observe only, and it cannot move to block for two reasons the format states
859
+ * rather than hides. The integration lane is the surface that decides a
860
+ * completed change and it is not built. The decision needs test history, which
861
+ * no fact provider supplies, so the rule reports every change under the guarded
862
+ * paths and cannot confirm whether a failing test preceded one. It over-reports
863
+ * on purpose, and that is the honest mode for it now.
864
+ */
865
+ export const TESTS_FIRST_UNDER_SCOPED_PATHS = {
866
+ id: 'tests-first-under-scoped-paths',
867
+ statement: 'A change under the assigned paths requires a failing test committed before the implementation.',
868
+ rationale: 'An agent given a task and no test decides for itself when the task is done. A test written first is a definition of done the agent did not author. PRD, Decisions.',
869
+ surfaces: ['integration-lane'],
870
+ mode: 'observe',
871
+ effect: 'ask',
872
+ match: {
873
+ operations: ['change'],
874
+ writes: { inside: ['${testGuardedPaths}'] },
875
+ onUncertain: 'match',
876
+ },
877
+ claims: { writeScope: ['${testGuardedPaths}'] },
878
+ records: ['writes', 'principal', 'decision', 'rule'],
879
+ changeControl: { owner: 'project', subjectMayPropose: true, subjectMayApply: false },
880
+ examples: [
881
+ {
882
+ attrs: attributes({ operation: 'change', writes: ['${testGuardedPaths}/billing.ts'] }),
883
+ surface: 'integration-lane',
884
+ expect: 'allow',
885
+ expectObservedOnly: true,
886
+ },
887
+ {
888
+ attrs: attributes({ operation: 'change', writes: ['${repoRoot}/docs/notes.md'] }),
889
+ surface: 'integration-lane',
890
+ expect: 'allow',
891
+ expectObservedOnly: false,
892
+ },
893
+ ],
894
+ };
895
+ /** (e) An agent may not edit the rules that govern it. */
896
+ export const RULES_ARE_NOT_SELF_EDITABLE = {
897
+ id: 'rules-are-not-self-editable',
898
+ statement: 'An agent does not change the rules that bind it.',
899
+ rationale: 'A subject that can edit its own constraint is not subject to it. The deny list covers Edit(.claude/settings.json) and the allow list grants a bare Write, and no PreToolUse hook registers a Write matcher, so Write(".claude/settings.json") replaces the whole file today. Deciding on a resolved write path rather than on a tool name and a literal path closes that, and it closes `sed -i` on the same file, which the extractor folds to the same write. Enforcement is still partial while the rule files live inside the team\'s own worktree, because an agent can change its working copy and the guard reads the changed copy, which is why remote is named.',
900
+ surfaces: ['permission-callback', 'pre-tool-hook', 'remote'],
901
+ mode: 'block',
902
+ effect: 'deny',
903
+ match: {
904
+ operations: ['write', 'chmod', 'git.*'],
905
+ writes: { globs: ['${governingRules}'] },
906
+ onUncertain: 'escalate',
907
+ },
908
+ claims: { writeScope: ['${governingRules}'] },
909
+ records: ['operation', 'writes', 'principal', 'decision', 'rule'],
910
+ changeControl: { owner: 'platform', subjectMayPropose: true, subjectMayApply: false },
911
+ examples: [
912
+ {
913
+ attrs: attributes({ operation: 'write', writes: ['${repoRoot}/.claude/settings.json'] }),
914
+ surface: 'permission-callback',
915
+ expect: 'deny',
916
+ },
917
+ {
918
+ // `sed -i 's/deny/allow/' .claude/hooks/worktree-guard.sh`, which the
919
+ // extractor folds to a write to the resolved path.
920
+ attrs: attributes({ operation: 'write', writes: ['${repoRoot}/.claude/hooks/worktree-guard.sh'] }),
921
+ surface: 'pre-tool-hook',
922
+ expect: 'deny',
923
+ },
924
+ {
925
+ attrs: attributes({ operation: 'write', writes: ['${worktree}/docs/proposed-rule-change.md'] }),
926
+ surface: 'permission-callback',
927
+ expect: 'allow',
928
+ },
929
+ ],
930
+ };
931
+ /**
932
+ * (c) A tester may not read the implementation.
933
+ *
934
+ * Held out of the starter set, and this is the point of the `surfaces` field
935
+ * rather than a gap in it. The permission callback never received `Read` or
936
+ * `Glob` across POC-1c, and `Grep` was not measured. A shell read does reach
937
+ * the callback, so a binding there would refuse `cat src/billing.ts` and allow
938
+ * `Read("src/billing.ts")`, which a tester needs one turn to discover. No
939
+ * surface the contract defines observes a read it can rely on, so every binding
940
+ * this rule could declare refuses at compile time. The only surface that could
941
+ * enforce it is the context assembler, which supplies the requirement and the
942
+ * public interface and withholds the implementation, and the PRD records that
943
+ * component as Absent.
944
+ *
945
+ * Writing it out is how the gap stays visible. Shipping it bound to the
946
+ * permission callback would produce a rule that reports healthy and refuses
947
+ * nothing, which is what a tester's suite passing for a month costs.
948
+ */
949
+ export const TESTER_WORKS_FROM_THE_REQUIREMENT = {
950
+ id: 'tester-works-from-the-requirement',
951
+ statement: 'The qa-tester role does not read implementation source.',
952
+ rationale: 'A tester that reads the implementation writes tests describing what it found, which produces a suite that passes forever and proves nothing. PRD, Decisions.',
953
+ principals: { role: 'qa-tester' },
954
+ surfaces: ['permission-callback'],
955
+ mode: 'block',
956
+ effect: 'deny',
957
+ match: {
958
+ operations: ['read'],
959
+ reads: { inside: ['${repoRoot}/src'] },
960
+ onUncertain: 'escalate',
961
+ },
962
+ records: ['operation', 'reads', 'principal', 'decision', 'rule'],
963
+ changeControl: { owner: 'platform', subjectMayPropose: false, subjectMayApply: false },
964
+ examples: [
965
+ {
966
+ attrs: attributes({ operation: 'read', reads: ['${repoRoot}/src/services/billing.ts'] }),
967
+ surface: 'permission-callback',
968
+ expect: 'deny',
969
+ },
970
+ {
971
+ attrs: attributes({ operation: 'read', reads: ['${repoRoot}/docs/requirements/billing.md'] }),
972
+ surface: 'permission-callback',
973
+ expect: 'allow',
974
+ },
975
+ ],
976
+ };
977
+ /** The four rules of section 5 that compile and run. */
978
+ export const STARTER_RULES = [
979
+ TEAMS_STAY_IN_OWN_WORKTREE,
980
+ NO_DESTRUCTIVE_GIT,
981
+ TESTS_FIRST_UNDER_SCOPED_PATHS,
982
+ RULES_ARE_NOT_SELF_EDITABLE,
983
+ ];
984
+ /** The rule of section 5 that no surface can enforce. The compiler refuses it. */
985
+ export const WITHHELD_RULES = [TESTER_WORKS_FROM_THE_REQUIREMENT];
986
+ /** All five, for the test that proves why the fifth stays out. */
987
+ export const SECTION_5_RULES = [...STARTER_RULES, ...WITHHELD_RULES];
988
+ //# sourceMappingURL=evaluate.js.map