shipgate-cli 0.0.0-stage → 0.2.2

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 (123) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +261 -2
  3. package/agents/context-builder.md +158 -0
  4. package/agents/debug-executor.md +234 -0
  5. package/assets/gates/classifier.js +245 -0
  6. package/assets/gates/dsh/index.js +767 -0
  7. package/assets/gates/dsh/policy.json +93 -0
  8. package/assets/gates/index.js +3 -0
  9. package/assets/gates/pi/index.js +1131 -0
  10. package/assets/gates/pi/policy.json +93 -0
  11. package/assets/gates/policy.js +4267 -0
  12. package/assets/gates/profiles/ai4s-dry-lab.json +64 -0
  13. package/assets/gates/profiles/ai4s-quant.json +36 -0
  14. package/assets/pi-extensions/auto-continue.ts +176 -0
  15. package/assets/pi-extensions/goal-mode.ts +313 -0
  16. package/bin/shipgate.mjs +9 -0
  17. package/commands/ai-spec.md +9 -0
  18. package/commands/api-first.md +33 -0
  19. package/commands/code-review.md +7 -0
  20. package/commands/codebase-context.md +19 -0
  21. package/commands/debug-ui.md +147 -0
  22. package/commands/debug.md +101 -0
  23. package/commands/dev-env-scan.md +18 -0
  24. package/commands/dev-host-init.md +28 -0
  25. package/commands/discover-skill-opportunities.md +33 -0
  26. package/commands/fork-sync.md +17 -0
  27. package/commands/gh-actions.md +26 -0
  28. package/commands/goal-driven-development.md +7 -0
  29. package/commands/intent-grill.md +7 -0
  30. package/commands/iteration-manager.md +7 -0
  31. package/commands/loop-engineer.md +21 -0
  32. package/commands/nodejs-npm-auto-release.md +12 -0
  33. package/commands/prd.md +7 -0
  34. package/commands/project-health-audit.md +7 -0
  35. package/commands/ralph-yolo.md +346 -0
  36. package/commands/ralph.md +226 -0
  37. package/commands/security-audit.md +7 -0
  38. package/commands/ux-experience-audit.md +133 -0
  39. package/docs/ARCHITECTURE.md +63 -0
  40. package/docs/GATES.md +106 -0
  41. package/docs/HARNESS.md +257 -0
  42. package/package.json +48 -4
  43. package/references/ADR-FORMAT.md +67 -0
  44. package/references/CONTEXT-FORMAT.md +62 -0
  45. package/references/mcp-config-template.json +54 -0
  46. package/scripts/fix-skill-frontmatter.mjs +66 -0
  47. package/scripts/migrate-skillpack.mjs +257 -0
  48. package/skills/ai-spec/SKILL.md +90 -0
  49. package/skills/api-first-modular/SKILL.md +411 -0
  50. package/skills/code-debugger/SKILL.md +379 -0
  51. package/skills/code-review/SKILL.md +62 -0
  52. package/skills/codebase-context/SKILL.md +139 -0
  53. package/skills/debug-ui/SKILL.md +220 -0
  54. package/skills/dev-env-scan/SKILL.md +147 -0
  55. package/skills/dev-host-init/SKILL.md +198 -0
  56. package/skills/dev-host-init/scripts/fill-placeholders.py +226 -0
  57. package/skills/dev-host-init/scripts/host-scan.ps1 +159 -0
  58. package/skills/dev-host-init/scripts/host-scan.sh +201 -0
  59. package/skills/dev-host-init/scripts/render-now.py +488 -0
  60. package/skills/dev-host-init/scripts/tools-catalog.py +229 -0
  61. package/skills/dev-host-init/templates/graph-first-gate.ts +291 -0
  62. package/skills/dev-host-init/templates/host-injection.template.md +725 -0
  63. package/skills/discover-skill-opportunities/SKILL.md +145 -0
  64. package/skills/discover-skill-opportunities/references/accounting-finance-ops.md +24 -0
  65. package/skills/discover-skill-opportunities/references/business-consulting.md +24 -0
  66. package/skills/discover-skill-opportunities/references/evidence-and-privacy.md +39 -0
  67. package/skills/discover-skill-opportunities/references/finance-investment.md +24 -0
  68. package/skills/discover-skill-opportunities/references/legal-and-compliance.md +24 -0
  69. package/skills/discover-skill-opportunities/references/output-contract.md +75 -0
  70. package/skills/discover-skill-opportunities/references/product-and-operations.md +24 -0
  71. package/skills/discover-skill-opportunities/references/quant-trading.md +24 -0
  72. package/skills/discover-skill-opportunities/references/scientific-research.md +24 -0
  73. package/skills/discover-skill-opportunities/references/scoring-rubric.md +45 -0
  74. package/skills/discover-skill-opportunities/references/session-skill-review.md +78 -0
  75. package/skills/discover-skill-opportunities/references/software-development.md +24 -0
  76. package/skills/fork-sync/SKILL.md +86 -0
  77. package/skills/gh-actions-architect/SKILL.md +395 -0
  78. package/skills/goal-driven-development/SKILL.md +132 -0
  79. package/skills/intent-grill/SKILL.md +46 -0
  80. package/skills/iteration-manager/SKILL.md +53 -0
  81. package/skills/loop-engineer/SKILL.md +108 -0
  82. package/skills/nodejs-npm-auto-release/SKILL.md +141 -0
  83. package/skills/prd/SKILL.md +63 -0
  84. package/skills/project-health-audit/SKILL.md +64 -0
  85. package/skills/ralph/SKILL.md +329 -0
  86. package/skills/ralph-yolo/SKILL.md +623 -0
  87. package/skills/security-audit/SKILL.md +114 -0
  88. package/skills/security-audit/references/audit-checklist.md +135 -0
  89. package/skills/security-audit/references/evidence-conventions.md +54 -0
  90. package/skills/security-audit/references/findings-schema.md +37 -0
  91. package/skills/security-audit/references/stack-signatures.md +66 -0
  92. package/skills/shipgate/SKILL.md +40 -0
  93. package/skills/shipgate-install/SKILL.md +87 -0
  94. package/skills/shipgate-quality/SKILL.md +80 -0
  95. package/skills/shipgate-security/SKILL.md +97 -0
  96. package/skills/shipgate-spec/SKILL.md +67 -0
  97. package/skills/ux-experience-audit/SKILL.md +202 -0
  98. package/src/cli.mjs +118 -0
  99. package/src/commands/ask.mjs +82 -0
  100. package/src/commands/deploy.mjs +587 -0
  101. package/src/commands/gates.mjs +83 -0
  102. package/src/commands/policy.mjs +116 -0
  103. package/src/gates/quality.mjs +123 -0
  104. package/src/gates/security.mjs +92 -0
  105. package/src/gates/ship.mjs +74 -0
  106. package/src/gates/spec.mjs +88 -0
  107. package/src/harness/index.mjs +203 -0
  108. package/src/inject/render.mjs +75 -0
  109. package/src/lib/cfg.mjs +66 -0
  110. package/src/lib/duration.mjs +41 -0
  111. package/src/lib/engines.mjs +182 -0
  112. package/src/lib/exec.mjs +80 -0
  113. package/src/lib/fsx.mjs +119 -0
  114. package/src/lib/gate.mjs +329 -0
  115. package/src/lib/log.mjs +31 -0
  116. package/src/lib/skills.mjs +347 -0
  117. package/src/lib/state.mjs +50 -0
  118. package/src/lib/update.mjs +67 -0
  119. package/src/version.mjs +14 -0
  120. package/templates/agents-snippet.md +82 -0
  121. package/templates/dev-profile.schema.json +119 -0
  122. package/templates/prd.json.example +64 -0
  123. package/templates/rule.json.example +28 -0
@@ -0,0 +1,4267 @@
1
+ /**
2
+ * Gate policy: environment-agnostic rules for "hard gates" that a coding agent
3
+ * cannot talk its way past.
4
+ *
5
+ * Why this file exists at all
6
+ * ---------------------------
7
+ * A rules document (AGENTS.md / CLAUDE.md) is advice: the model reads it and
8
+ * usually complies. Some rules are not advice — "do not read source before
9
+ * asking the code graph", "never print a credential", "do not write outside the
10
+ * repo". Those need to be enforced by the harness, not by the model's goodwill.
11
+ *
12
+ * But every harness enforces things differently:
13
+ *
14
+ * pi pi.on('tool_call') -> { block: true, reason }
15
+ * dsh ctx.on('tools/pre-execute') -> { kind: 'deny', reason } | next()
16
+ *
17
+ * So the rules live here, in plain JavaScript that has no idea which harness is
18
+ * running, and each adapter in bridge/gates/<harness>/ is a thin translator:
19
+ * native event in, normalized question out, native decision back.
20
+ *
21
+ * Consequence: the rule logic is unit-testable off-harness (see
22
+ * bridge/test/gates.test.js) and the adapters stay small enough to read in one
23
+ * sitting — which matters, because an adapter bug silently disables enforcement.
24
+ *
25
+ * Language
26
+ * --------
27
+ * Identifiers, comments and internal reason strings are English (this is a
28
+ * published repository). Everything a user READS — the denial text and the
29
+ * per-turn reminder — is Simplified Chinese, because the person being blocked
30
+ * is the person who wrote the rules. Keep new checks consistent with that
31
+ * split, and note that the block text always carries its layer as ASCII
32
+ * ("Layer 1/2/3"), which is what the tests assert on instead of wording.
33
+ *
34
+ * Failure policy
35
+ * --------------
36
+ * If the policy cannot be read or parsed, the gate FAILS OPEN (allows the call)
37
+ * and warns. A gate that fails closed on a missing file would brick the agent,
38
+ * and a bricked agent is worse than an unenforced rule. The reverse choice
39
+ * (fail closed) is right for *secrets* and *writes*, and that is why those
40
+ * rules are expressed as explicit checks rather than as "policy failed to load".
41
+ */
42
+
43
+ import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
44
+ import { dirname, isAbsolute, join, normalize, posix, relative, resolve, sep } from 'node:path';
45
+ import { fileURLToPath } from 'node:url';
46
+
47
+ const WIN32 = process.platform === 'win32';
48
+
49
+ /**
50
+ * Real-filesystem probes the loader uses itself.
51
+ *
52
+ * Adapters inject their own probe object (they must be TOTAL — answer, never
53
+ * throw); this one exists so loading a policy can read the sibling `profiles/`
54
+ * directory without the caller having to supply a filesystem it never touched.
55
+ */
56
+ const NODE_FS = {
57
+ exists: (p) => existsSync(p),
58
+ isFile: (p) => {
59
+ try {
60
+ return statSync(p).isFile();
61
+ } catch {
62
+ return false;
63
+ }
64
+ },
65
+ isDirectory: (p) => {
66
+ try {
67
+ return statSync(p).isDirectory();
68
+ } catch {
69
+ return false;
70
+ }
71
+ },
72
+ statMtime: (p) => {
73
+ try {
74
+ return statSync(p).mtimeMs;
75
+ } catch {
76
+ return 0;
77
+ }
78
+ },
79
+ listDir: (p) => {
80
+ try {
81
+ return readdirSync(p);
82
+ } catch {
83
+ return [];
84
+ }
85
+ },
86
+ readText: (p) => {
87
+ try {
88
+ return readFileSync(p, 'utf8');
89
+ } catch {
90
+ return null;
91
+ }
92
+ },
93
+ };
94
+
95
+ /** Cached "newest mtime inside the index marker directory", keyed by directory. */
96
+ const mtimeCache = new Map();
97
+
98
+ /**
99
+ * The permission categories a destructive command can belong to.
100
+ *
101
+ * Categories exist so a user can grant "I trust you to force-push on my own
102
+ * branch" without also granting "you may drop a production database". Each one
103
+ * is a *permission*: adjustable at runtime through the `/gate` command, with
104
+ * three tiers per category (`allow` / `confirm` / `deny`).
105
+ *
106
+ * The hard red lines in `unrecoverableTarget` and the host/disk verbs are
107
+ * deliberately NOT categories. They are not "deny by default", they are
108
+ * "deny always": no grant can reach them. That is the difference between a
109
+ * permission and a guardrail, and collapsing the two is how a gate becomes
110
+ * theatre.
111
+ */
112
+ export const DESTRUCTIVE_CATEGORIES = {
113
+ delete: '删除文件或目录(rm / rmdir / del / rd / Remove-Item / find -delete / clear-content)',
114
+ 'git-history':
115
+ '丢弃未提交工作或重写本地历史(reset --hard / clean -f / checkout -f / switch -f / checkout -- . / restore / branch -D / filter-* / stash drop|clear;受保护工作区里的 stash 另按红线处理)',
116
+ 'git-force-push': '强制推送远端历史(push --force / --force-with-lease / -f)',
117
+ 'db-ddl': '删除或清空数据库对象(DROP TABLE|DATABASE|SCHEMA / TRUNCATE TABLE)',
118
+ 'perm-recursive': '递归修改权限或属主(chmod -R / chown -R / chgrp -R)',
119
+ 'process-kill': '强制结束进程(taskkill /F)',
120
+ 'raw-write': '向文件或设备裸写(dd of=…,裸设备本身是红线)',
121
+ };
122
+
123
+ /** The three tiers a category can sit at. */
124
+ export const DESTRUCTIVE_TIERS = ['allow', 'confirm', 'deny'];
125
+ /**
126
+ * The destructive-command gate's mode (ADR-013).
127
+ *
128
+ * SCOPE: `no-destructive-bash` ONLY. This is deliberately not a switch for the
129
+ * whole gate - the research rules, the secret/scope rules, the contract rule and
130
+ * the AI4S rules are not "questions the user gets tired of", they are the
131
+ * discipline the gate exists for, and silencing them because a delete at 03:00
132
+ * wants a dialog would trade one annoyance for a much worse blind spot.
133
+ *
134
+ * enforce - the permission tiers decide allow / ask / deny.
135
+ * bypass - the permission layer of `no-destructive-bash` is off: no dialog,
136
+ * no refusal. The unrecoverable guardrail inside that same check is
137
+ * untouched, and `no-self-grant` keeps protecting this switch.
138
+ *
139
+ * Deliberately NOT a category either: seven categories answer "may the agent do
140
+ * this class of thing?"; the mode answers "should I keep being asked about
141
+ * deletes right now?" - a different axis with a different lifetime (one long
142
+ * night, then back).
143
+ */
144
+ export const DESTRUCTIVE_MODES = ['enforce', 'bypass'];
145
+
146
+ export const DEFAULT_CONFIG = {
147
+ /** Absolute paths whose files are in scope. Empty = auto-detect a VCS root. */
148
+ project_roots: [],
149
+ /** Path fragments that take a file out of scope regardless of the above. */
150
+ exclude_globs: [
151
+ '**/node_modules/**',
152
+ '**/vendor/**',
153
+ '**/dist/**',
154
+ '**/build/**',
155
+ '**/.git/**',
156
+ '**/site-packages/**',
157
+ '**/.venv/**',
158
+ ],
159
+ /** File extensions treated as source code. */
160
+ code_extensions: [
161
+ 'ts', 'tsx', 'mts', 'cts', 'js', 'jsx', 'mjs', 'cjs',
162
+ 'py', 'pyi', 'rs', 'go', 'java', 'c', 'h', 'cc', 'cpp', 'hpp', 'hh',
163
+ 'rb', 'php', 'sql', 'sh', 'bash', 'zsh', 'ps1', 'psm1', 'scala', 'kt', 'kts',
164
+ 'swift', 'lua', 'vue', 'svelte', 'r', 'jl', 'cs', 'fs', 'ex', 'exs',
165
+ 'toml', 'proto', 'gradle', 'tf', 'tfvars', 'hcl', 'nix', 'dart', 'groovy',
166
+ 'yml', 'yaml', 'ipynb', 'json5',
167
+ ],
168
+ /** Extensionless files that are still source code. */
169
+ code_filenames: ['Dockerfile', 'Containerfile', 'Makefile', 'Rakefile', 'Gemfile', 'Procfile'],
170
+ /**
171
+ * How many times one session may be blocked before the research rules give up.
172
+ *
173
+ * v4 raised this from 30 to 200. Thirty was reached by ordinary read-heavy
174
+ * sessions, and after that point every Layer-0/1/2 rule stood down for the
175
+ * rest of the session — the gate looked installed and was inert. Safety checks
176
+ * remain uncapped (`HARD_CHECKS`).
177
+ */
178
+ max_blocks_per_session: 200,
179
+ /**
180
+ * Sliding window for the block cap. Once the first block is older than this,
181
+ * the counter resets, so a long session never permanently loses its research
182
+ * rules. 0 disables the reset (old behaviour).
183
+ */
184
+ block_cap_reset_ms: 30 * 60 * 1000,
185
+ /**
186
+ * How long a successful read counts as evidence for `think-before-write`.
187
+ * A read used to unlock the file for the entire session; that turned "look
188
+ * before you edit" into a one-time ritual. -1 means "never expire" for users
189
+ * who intentionally want the old behaviour.
190
+ */
191
+ inspected_ttl_ms: 30 * 60 * 1000,
192
+ /**
193
+ * A graph query newer than this many ms counts as fresh, session-wide.
194
+ *
195
+ * Keep this SHORT. The first version let a single query unlock an hour of
196
+ * reading: the model asked the graph once, then read the tree freely — which
197
+ * is exactly the failure the gate exists to prevent. Ten minutes covers a
198
+ * burst of reads and forces the next burst to consult the graph again.
199
+ */
200
+ signal_ttl_ms: 10 * 60 * 1000,
201
+ /**
202
+ * An *unlock* is stronger evidence than a session signal: the graph query
203
+ * actually mentioned this file / package / directory, so it stays valid for
204
+ * longer than the blanket signal.
205
+ */
206
+ unlock_ttl_ms: 30 * 60 * 1000,
207
+ /**
208
+ * Gate read-like bash commands (`cat`, `grep`, `sed -n`, …) as reads.
209
+ * Reading source through the shell is the same act as reading it with the
210
+ * `read` tool, and used to be the one hole that made the gate cosmetic.
211
+ */
212
+ bash_read_check: true,
213
+ /** Where an index marker directory is expected, for advisory reasons. */
214
+ index_marker: '.codebase-memory',
215
+ /**
216
+ * A file counts as newer than the index only if it leads by more than this.
217
+ * Same-second writes and coarse (FAT, network share) timestamps otherwise
218
+ * make a freshly built index look stale, and a rule that cries wolf gets
219
+ * switched off instead of fixed.
220
+ */
221
+ index_mtime_epsilon_ms: 2000,
222
+ /**
223
+ * How long a computed "newest file inside the marker directory" is trusted.
224
+ * The scan is a readdir plus a stat per entry; a read-heavy turn would
225
+ * otherwise repeat it for every read.
226
+ */
227
+ index_mtime_ttl_ms: 30000,
228
+
229
+ // -------------------------------------------------------------------------
230
+ // v3: evidence, Layer 0 ("think before acting"), and shell-write coverage
231
+ // -------------------------------------------------------------------------
232
+ /**
233
+ * A graph call only counts as evidence when it actually returned something.
234
+ *
235
+ * v2 recorded a signal for any non-error tool result, including an empty
236
+ * `search_graph` (`{"total":0,"results":[]}`). That let an unindexed or
237
+ * stale index buy a full read window with no information at all — the exact
238
+ * "searched, found nothing, read the tree anyway" failure the rules forbid.
239
+ * The pi adapter verifies the result text with `graphResultIsEvidence` before
240
+ * recording a signal. dsh cannot see results, so its policy leaves this off
241
+ * and the asymmetry is documented in ADR-003.
242
+ */
243
+ graph_signal_requires_content: false,
244
+ /** Below this many characters a graph result is treated as empty noise. */
245
+ graph_signal_min_chars: 40,
246
+
247
+ /**
248
+ * Layer 0: require evidence that the model looked at the *specific* target
249
+ * before overwriting it. `hasScopedUnlock` (graph named the file) or a
250
+ * successful read of that exact file (`state.inspected`) both qualify.
251
+ * New files are exempt: there is nothing to inspect yet, and requiring a
252
+ * graph hit would brick greenfield work in an empty repository.
253
+ */
254
+ require_target_evidence: true,
255
+ /**
256
+ * Layer 0: require a successful read of a project convention document before
257
+ * the first code write in that repository. Only enforced when such a file
258
+ * exists; a repository without conventions is not punished for it.
259
+ */
260
+ require_conventions: false,
261
+ convention_files: ['AGENTS.md', 'CLAUDE.md', 'CONTRIBUTING.md', '.cursorrules'],
262
+
263
+ /**
264
+ * ai-spec 层:改代码前必须确认本次改动对应哪个立项 CHG,且本会话读过它的契约。
265
+ *
266
+ * 为什么必须做成硬门控:AGENTS.md 说「按 CHG 推进」只是建议。实测教训
267
+ * (2026-10-29,40 个 CHG 批量开发):31 个缺 PRD、28 个缺 TRACEABILITY,
268
+ * 先合并的 CHG 用「全局状态断言」把后合并的合法改动判红——全部源于
269
+ * 「没先核对契约就动手」。
270
+ *
271
+ * 判定分三层(v6 起),只约束代码文件(isCodeFile),文档与数据文件不拦:
272
+ * 1) `state.docReads` 里有没有落在 `chg_contract_globs` 的路径;
273
+ * 2) 那条路径必须属于**当前项目**(读别的仓库的 CHG 不算数);
274
+ * 3) 它所在的 `tasks/CHG-<id>/` 必须是一份**成立的契约** —— 四件套齐全、
275
+ * SPEC 有验收判据、status 不是草稿态。
276
+ *
277
+ * 为什么第 3 层必须存在:v5 只看第 1 层,于是「写一个 SPEC.md → 读它 → 改代码」
278
+ * 全流程畅通。实测(2026-11-16)agent 反复走这条路,PRD 与 TRACEABILITY
279
+ * 根本不存在。读过一份文件不等于立过项。
280
+ */
281
+ require_chg_contract: true,
282
+ // 大小写不敏感(`isChgContract` 对两侧统一小写化),可写成自然的大写形态。
283
+ chg_contract_globs: [
284
+ '**/tasks/CHG-*/SPEC.md',
285
+ '**/tasks/CHG-*/PRD.md',
286
+ '**/tasks/CHG-*/CHANGE.md',
287
+ '**/tasks/CHG-*/TRACEABILITY.md',
288
+ ],
289
+ /**
290
+ * Optional narrowing for the CHG-contract rule. Empty = every code file in a
291
+ * CHG-governed repository needs one contract read per session (v3 behaviour).
292
+ * Set it to e.g. 'bridge/**' when only part of the repository is actually
293
+ * governed by CHGs; historical `tasks/CHG-*` directories otherwise keep the
294
+ * whole tree gated forever.
295
+ */
296
+ chg_contract_scope_globs: [],
297
+
298
+ // -------------------------------------------------------------------------
299
+ // v6: a CHG contract must be STANDING, not merely touched
300
+ // -------------------------------------------------------------------------
301
+ /** Files that must all exist before a CHG counts as a usable contract. */
302
+ chg_contract_required_files: ['SPEC.md', 'PRD.md', 'TRACEABILITY.md'],
303
+ /**
304
+ * Markers that prove the SPEC names a checkable end state. Empty = no check.
305
+ *
306
+ * A SPEC without one of these is a wish, not a contract: after the code is
307
+ * written nobody can say whether the change succeeded.
308
+ */
309
+ chg_acceptance_markers: ['验收', 'AC-', '断言', '可判定', 'Acceptance'],
310
+ /**
311
+ * Status values that permit development. Empty = status is not checked.
312
+ *
313
+ * A MISSING status field is never a refusal: frontmatter conventions differ
314
+ * between repositories, and punishing format variety turns a rule into a
315
+ * deadlock. Only an explicitly declared draft-ish value blocks.
316
+ */
317
+ chg_status_allow: ['approved', 'executing', 'active', 'in-progress', 'in_progress'],
318
+ /** Frontmatter keys accepted as the status field. */
319
+ chg_status_fields: ['status', 'state'],
320
+
321
+ /**
322
+ * Layer 0: retrying an identical failing command is the mechanical loop the
323
+ * thinking rule exists to stop. Two failures are tolerated (a flaky test, a
324
+ * transient tool); the third needs investigation (read or graph) first.
325
+ */
326
+ max_identical_failures: 2,
327
+ retry_window_ms: 10 * 60 * 1000,
328
+
329
+ /**
330
+ * Turn-level anti-slack (v4). A tool-call gate cannot see a reply that does no
331
+ * work at all — "I'll finish it later" is the most common shape of that, and
332
+ * it used to pass untouched. The adapter checks the assistant's final text at
333
+ * `turn_end` and asks for one more turn when it finds a first-person deferral.
334
+ *
335
+ * This is deliberately narrow: it must never punish ordinary Q&A or a plan the
336
+ * user explicitly asked for. Extra patterns may be added per machine through
337
+ * `slack_patterns` (array of RegExp sources).
338
+ */
339
+ slack_check: true,
340
+ /** Hard stop so a false positive cannot loop the agent forever. */
341
+ slack_max_continues: 2,
342
+ slack_patterns: [],
343
+
344
+ /**
345
+ * Layer 0: destructive shell operations never run automatically. Paths that
346
+ * contain one of these segments are considered disposable build output and
347
+ * are allowed for `rm -rf` (removing `node_modules` is routine, removing
348
+ * `src` is not). `destructive_allow_patterns` is a list of regex sources for
349
+ * legitimate exceptions on a given machine.
350
+ */
351
+ destructive_disposable_segments: [
352
+ 'node_modules', 'dist', 'build', 'out', 'coverage', '.next', '.nuxt',
353
+ '.cache', '.venv', 'venv', 'target', '__pycache__', '.pytest_cache',
354
+ '.turbo', '.parcel-cache', 'tmp', 'temp',
355
+ ],
356
+ destructive_allow_patterns: [],
357
+ /**
358
+ * Three-tier destructive policy (2026-11-05).
359
+ *
360
+ * `true` - unrecoverable targets are blocked outright, ordinary deletes ask
361
+ * the user instead of being refused.
362
+ * `false` - rollback: every destructive finding is blocked, exactly the
363
+ * behaviour before this switch existed.
364
+ */
365
+ destructive_confirm_mode: true,
366
+ /**
367
+ * Per-category permission tiers.
368
+ *
369
+ * `allow` - run it without asking (the user has granted this class)
370
+ * `confirm` - ask the user (the default for recoverable-but-serious work)
371
+ * `deny` - refuse it (the user tightened the gate)
372
+ *
373
+ * `db-ddl` starts at `deny` on purpose: a dropped schema is the one class here
374
+ * that routinely destroys data no backup covers. Granting it is a deliberate
375
+ * act (`/gate grant db-ddl`), not something that happens because a default
376
+ * leaned permissive.
377
+ *
378
+ * A policy-level `deny` cannot be reopened by a session grant: tightening is
379
+ * always stronger than loosening (see `effectiveDestructiveTier`).
380
+ */
381
+ destructive_grants: {
382
+ delete: 'confirm',
383
+ 'git-history': 'confirm',
384
+ 'git-force-push': 'confirm',
385
+ 'db-ddl': 'deny',
386
+ 'perm-recursive': 'confirm',
387
+ 'process-kill': 'confirm',
388
+ 'raw-write': 'confirm',
389
+ },
390
+ /**
391
+ * Mode of the destructive-command gate (ADR-013). `enforce` is the only
392
+ * acceptable default: a gate that ships bypassed is indistinguishable from no
393
+ * gate at all. Scope is `no-destructive-bash` only - see `DESTRUCTIVE_MODES`.
394
+ */
395
+ destructive_mode: 'enforce',
396
+ /**
397
+ * When a `bypass` expires (ms epoch). 0 = never.
398
+ *
399
+ * This is what makes an unattended night safe: `/gate mode bypass 8h`, and the
400
+ * destructive gate tightens itself in the morning. A forgotten permanent
401
+ * bypass is exactly the "naked agent" ADR-012 warned about, so expiry is a
402
+ * first-class knob rather than a follow-up.
403
+ */
404
+ destructive_mode_until: 0,
405
+
406
+ /**
407
+ * Protected worktrees (ADR-015): directories whose UNCOMMITTED content is
408
+ * live state, not work in progress - a service instance checked out of a
409
+ * template repository, where the configuration and the credentials next to it
410
+ * are deliberately never committed. `git status` calls such a tree "dirty";
411
+ * to the service it is the running configuration.
412
+ *
413
+ * Inside one of these roots, a git command that discards or replaces the
414
+ * working tree (`git stash`, `reset --hard`, `clean -f`, `checkout -- .`, ...)
415
+ * is a guardrail: blocked outright, under every mode, with no grant for it.
416
+ * What brought this in: an agent "tidied" such a directory with two
417
+ * `git stash` calls before a commit. The service restarted on the template
418
+ * defaults, went offline, and nothing reported an error anywhere - git had
419
+ * done exactly what it was asked.
420
+ *
421
+ * Absolute paths, and machine-local by design: the public repository carries
422
+ * no real path. An ordinary repository is NOT affected - there the
423
+ * uncommitted work is exactly what a stash keeps, so plain `git stash` stays
424
+ * unclassified outside these roots.
425
+ */
426
+ protected_worktrees: [],
427
+
428
+ // -------------------------------------------------------------------------
429
+ // v5: domain profiles (AI4S dry lab / quant)
430
+ // -------------------------------------------------------------------------
431
+ /**
432
+ * Domain profile used when the classifier could not name one.
433
+ *
434
+ * `general-dev` is deliberately NOT a profile definition: it means "base
435
+ * checks only", i.e. exactly what the gate did before v5. Defining it as a
436
+ * real profile would make "no domain" and "a domain that adds nothing"
437
+ * indistinguishable, and would give the fallback path a rule set to drift.
438
+ */
439
+ default_profile: 'general-dev',
440
+ /** Where profile definitions are looked up, relative to the policy file. */
441
+ profiles_dir: 'profiles',
442
+ /**
443
+ * W1: a research script may not be the first thing that happens after a long
444
+ * gap. Requiring a fresh Worklog is what turns "write down what you are about
445
+ * to do" from a suggestion into a gate — and it is cheapest to satisfy *before*
446
+ * the run, while nothing has been computed yet.
447
+ */
448
+ worklog_path: 'docs/WORKLOG.md',
449
+ worklog_ttl_ms: 30 * 60 * 1000,
450
+ /**
451
+ * W2: result directories whose every touched subdirectory must carry a note
452
+ * file (`<readme_prefix>...`) explaining what it holds. Empty by default, so a
453
+ * non-research repository never sees this rule.
454
+ */
455
+ result_dirs: [],
456
+ readme_prefix: 'README_',
457
+ /** W4: extensions that count as an analysis script (run before/after checks). */
458
+ script_extensions: ['.R', '.Rmd', '.r', '.py', '.ipynb'],
459
+ /** W4 can be switched off per machine without touching the profile table. */
460
+ script_log_check: true,
461
+ /**
462
+ * Extensions whose runs must leave a `.log` of their own.
463
+ *
464
+ * Deliberately narrower than `script_extensions`: a notebook (`.ipynb`) and a
465
+ * knitted report (`.Rmd`) persist their own output — the executed cells and the
466
+ * rendered document ARE the record. Demanding a separate `.log` from them would
467
+ * be a guaranteed false positive on every legitimate run, and a rule that cries
468
+ * wolf gets switched off instead of fixed (ADR-008). They still get W1 (a
469
+ * Worklog before the first run), because "what am I about to compute" is just as
470
+ * true for a notebook.
471
+ */
472
+ log_required_extensions: ['.R', '.r', '.py'],
473
+ /**
474
+ * Tolerance when comparing a file's mtime against a wall-clock timestamp.
475
+ *
476
+ * `Date.now()` and a filesystem timestamp do NOT agree to the millisecond —
477
+ * measured on a real host, a file written *after* `t` can carry an mtime a few
478
+ * milliseconds *before* `t` (clock granularity, filesystem timestamp rounding).
479
+ * The same trap is why `index_mtime_epsilon_ms` exists for the index check.
480
+ *
481
+ * Without it, "this run produced its log" is judged false for the log it just
482
+ * produced — a guaranteed false positive on every run, which is worse than the
483
+ * odd stale log slipping through.
484
+ */
485
+ artifact_mtime_epsilon_ms: 2000,
486
+ };
487
+
488
+ export const POLICY_FILENAME = 'policy.json';
489
+
490
+ /**
491
+ * Load a policy next to the adapter that uses it.
492
+ * @param {string} adapterUrl pass `import.meta.url` from the adapter
493
+ * @returns {{ok: boolean, policy: object|null, error: string|null}}
494
+ */
495
+ export const loadPolicyNear = (adapterUrl) => {
496
+ const file = new URL(`./${POLICY_FILENAME}`, adapterUrl);
497
+ return loadPolicy(file);
498
+ };
499
+
500
+ export const loadPolicy = (fileOrUrl) => {
501
+ try {
502
+ const text = readFileSync(fileOrUrl, 'utf8');
503
+ const parsed = JSON.parse(text);
504
+ const policy = normalizePolicy(parsed);
505
+ return { ok: true, policy: attachProfiles(policy, profileDirsFor(fileOrUrl, policy), NODE_FS), error: null };
506
+ } catch (err) {
507
+ return { ok: false, policy: null, error: `${fileOrUrl}: ${err?.message ?? err}` };
508
+ }
509
+ };
510
+
511
+ /**
512
+ * Where to look for `profiles/`, in order.
513
+ *
514
+ * Two layouts have to work, and getting this wrong fails SILENTLY (every session
515
+ * silently falls back to `general-dev`):
516
+ *
517
+ * repo checkout : bridge/gates/pi/policy.json -> ../profiles
518
+ * installed : <gate dir>/policy.json -> ./profiles
519
+ *
520
+ * Both are returned; `attachProfiles` takes the first directory that has the file.
521
+ */
522
+ const profileDirsFor = (fileOrUrl, policy) => {
523
+ let base;
524
+ try {
525
+ base = fileOrUrl instanceof URL ? fileURLToPath(fileOrUrl) : String(fileOrUrl);
526
+ } catch {
527
+ return [];
528
+ }
529
+ const name = policy.config.profiles_dir ?? 'profiles';
530
+ const dir = dirname(base);
531
+ return [join(dir, name), join(dir, '..', name)];
532
+ };
533
+
534
+ /** The signature the config accepts in place of a file path. */
535
+ export const policyFromObject = (raw) => ({ ok: true, policy: normalizePolicy(raw), error: null });
536
+
537
+ /** A destructive-gate mode string, or the fail-closed default. Never throws. */
538
+ export const normalizeDestructiveMode = (raw) => {
539
+ const mode = typeof raw === 'string' ? raw.trim().toLowerCase() : '';
540
+ return DESTRUCTIVE_MODES.includes(mode) ? mode : DEFAULT_CONFIG.destructive_mode;
541
+ };
542
+
543
+ /**
544
+ * An epoch-ms expiry, or 0 for "never".
545
+ *
546
+ * `null`/`''` mean "not set", NOT zero (the same trap `index_mtime_*` documents):
547
+ * `Number(null)` is 0, and turning an absent value into a real timestamp would
548
+ * make a bypass expire in 1970 — or, with a sign flip, never.
549
+ */
550
+ export const normalizeDestructiveModeUntil = (raw) => {
551
+ const n = raw === null || raw === undefined || raw === '' ? NaN : Number(raw);
552
+ return Number.isFinite(n) && n > 0 ? Math.floor(n) : 0;
553
+ };
554
+
555
+ export const normalizePolicy = (raw) => {
556
+ const config = { ...DEFAULT_CONFIG, ...(raw?.config ?? {}) };
557
+ config.code_extensions = config.code_extensions.map((e) => String(e).replace(/^\./, '').toLowerCase());
558
+ config.max_blocks_per_session = Number.isFinite(config.max_blocks_per_session)
559
+ ? config.max_blocks_per_session
560
+ : DEFAULT_CONFIG.max_blocks_per_session;
561
+ // Non-negative finite numbers only. A hand-edited policy.json is the normal
562
+ // way these get set, and a string here would compare as NaN — which is false
563
+ // for every comparison, i.e. a rule that silently never fires.
564
+ //
565
+ // `null` and `undefined` mean "not set", NOT zero: `Number(null)` is 0, and
566
+ // silently turning an absent value into a disabled epsilon is the class of
567
+ // bug this coercion exists to prevent. An explicit 0 still means 0.
568
+ for (const key of ['index_mtime_epsilon_ms', 'index_mtime_ttl_ms']) {
569
+ const raw = config[key];
570
+ const n = raw === null || raw === undefined || raw === '' ? NaN : Number(raw);
571
+ config[key] = Number.isFinite(n) && n >= 0 ? n : DEFAULT_CONFIG[key];
572
+ }
573
+
574
+ // `destructive_grants` is merged one key at a time, not replaced wholesale: a
575
+ // policy.json that grants one category must not silently reset the other six
576
+ // to "missing", which the tier lookup would read as "not configured".
577
+ const grants = {};
578
+ for (const [name, tier] of Object.entries(DEFAULT_CONFIG.destructive_grants)) grants[name] = tier;
579
+ const rawGrants = raw?.config?.destructive_grants;
580
+ if (rawGrants && typeof rawGrants === 'object' && !Array.isArray(rawGrants)) {
581
+ for (const [name, tier] of Object.entries(rawGrants)) {
582
+ if (!Object.prototype.hasOwnProperty.call(DESTRUCTIVE_CATEGORIES, name)) continue;
583
+ if (DESTRUCTIVE_TIERS.includes(tier)) grants[name] = tier;
584
+ }
585
+ }
586
+ config.destructive_grants = grants;
587
+
588
+ // The mode keys are sanitized here rather than trusted: they are hand-edited in
589
+ // `policy.json` and written by `/gate`, and a typo must degrade to `enforce`
590
+ // (fail closed) - never to a gate that refuses to start, and never to one that
591
+ // silently stays open.
592
+ config.destructive_mode = normalizeDestructiveMode(config.destructive_mode);
593
+ config.destructive_mode_until = normalizeDestructiveModeUntil(config.destructive_mode_until);
594
+ // Hand-edited too, and a bad entry must not become a path that matches the
595
+ // wrong tree (or an exception on first use).
596
+ config.protected_worktrees = normalizeProtectedWorktrees(config.protected_worktrees);
597
+
598
+ // Two accepted shapes for `profiles`; see the comment in the return below.
599
+ const profiles = new Map();
600
+ const pendingProfiles = [];
601
+ if (Array.isArray(raw?.profiles)) {
602
+ for (const item of raw.profiles) {
603
+ if (typeof item === 'string' && item !== '') pendingProfiles.push(item);
604
+ }
605
+ } else if (raw?.profiles && typeof raw.profiles === 'object') {
606
+ for (const [name, def] of Object.entries(raw.profiles)) {
607
+ if (def && typeof def === 'object') profiles.set(name, normalizeProfile(name, def));
608
+ }
609
+ }
610
+
611
+ return {
612
+ name: typeof raw?.name === 'string' ? raw.name : 'unnamed-gate',
613
+ version: raw?.version ?? 1,
614
+ description: raw?.description ?? '',
615
+ reminded: typeof raw?.reminder === 'string' ? raw.reminder : '',
616
+ checks: Array.isArray(raw?.checks) ? raw.checks : [],
617
+ config,
618
+ // --- v5: domain profiles ---------------------------------------------
619
+ // `profiles` arrives in one of two shapes and both must work:
620
+ // array of names -> policy.json; the definitions live in profiles/ and
621
+ // `attachProfiles` fills them in at load time
622
+ // object of objects -> an in-memory policy (tests, a host that injects one)
623
+ // Anything else is ignored rather than fatal: a typo must degrade to
624
+ // "general-dev", never to a gate that refuses to start.
625
+ defaultProfile:
626
+ typeof raw?.default_profile === 'string' && raw.default_profile !== ''
627
+ ? raw.default_profile
628
+ : DEFAULT_CONFIG.default_profile,
629
+ profiles,
630
+ pendingProfiles: pendingProfiles,
631
+ profileOrder: [...profiles.keys()],
632
+ classifier: {
633
+ enabled: raw?.classifier?.enabled !== false,
634
+ model_judge: raw?.classifier?.model_judge === true,
635
+ timeout_ms: Number.isFinite(raw?.classifier?.timeout_ms)
636
+ ? raw.classifier.timeout_ms
637
+ : 8000,
638
+ // Kept as a field only. Calling an external judge is out of scope for this
639
+ // change (the user confirmed it is not needed yet); leaving the key here
640
+ // documents the intent without pretending it works.
641
+ external_judge: raw?.classifier?.external_judge ?? { enabled: false },
642
+ },
643
+ };
644
+ };
645
+
646
+ // ---------------------------------------------------------------------------
647
+ // Domain profiles (v5)
648
+ // ---------------------------------------------------------------------------
649
+
650
+ /**
651
+ * One profile definition, normalized.
652
+ *
653
+ * A profile is a NAMED CHECK SET plus the config those checks read — nothing
654
+ * else. Keeping it that small is the point: the adapter asks "which name is
655
+ * active?" and the policy layer answers with a check list. No harness and no
656
+ * session context crosses that boundary.
657
+ *
658
+ * Every field is optional and defaulted: a hand-written profile JSON is the
659
+ * normal way these get created, and a missing key must produce "adds nothing"
660
+ * rather than a throw at load time.
661
+ */
662
+ const normalizeProfile = (name, def) => ({
663
+ name: typeof def.name === 'string' && def.name !== '' ? def.name : name,
664
+ description: typeof def.description === 'string' ? def.description : '',
665
+ /**
666
+ * Teaching text injected per turn while this profile is active.
667
+ *
668
+ * It lives on the profile rather than in `policy.json` because the reminder is
669
+ * injected into EVERY session: text about Worklogs in a plain JavaScript
670
+ * repository is noise, and noise teaches the model to ignore reminders.
671
+ */
672
+ reminder: typeof def.reminder === 'string' ? def.reminder : '',
673
+ // Fingerprints are lists of repository-relative paths that must ALL exist.
674
+ fingerprints: Array.isArray(def.fingerprints)
675
+ ? def.fingerprints.filter((g) => Array.isArray(g) || typeof g === 'string')
676
+ : [],
677
+ keywords: {
678
+ min_hits: Number.isInteger(def.keywords?.min_hits) ? def.keywords.min_hits : 2,
679
+ strong: Array.isArray(def.keywords?.strong)
680
+ ? def.keywords.strong.filter((w) => typeof w === 'string' && w !== '')
681
+ : [],
682
+ weak: Array.isArray(def.keywords?.weak)
683
+ ? def.keywords.weak.filter((w) => typeof w === 'string' && w !== '')
684
+ : [],
685
+ },
686
+ checks: Array.isArray(def.checks) ? def.checks.filter((c) => typeof c === 'string') : [],
687
+ config: def.config && typeof def.config === 'object' ? def.config : {},
688
+ });
689
+
690
+ /**
691
+ * Read a `profiles/` directory into `name -> profile`.
692
+ *
693
+ * Returns null when the directory does not exist, which the caller must treat as
694
+ * "profiles unavailable" (every session degrades to the default profile, and the
695
+ * adapter can say so) — never as "no profiles needed".
696
+ */
697
+ export const profilesFromDir = (dir, fs = NODE_FS) => {
698
+ if (typeof dir !== 'string' || dir === '') return null;
699
+ if (!fs?.exists?.(dir) || typeof fs.listDir !== 'function') return null;
700
+ const table = new Map();
701
+ for (const file of fs.listDir(dir)) {
702
+ if (typeof file !== 'string' || !file.endsWith('.json')) continue;
703
+ const text = typeof fs.readText === 'function' ? fs.readText(join(dir, file)) : null;
704
+ if (typeof text !== 'string') continue;
705
+ let parsed;
706
+ try {
707
+ parsed = JSON.parse(text);
708
+ } catch {
709
+ continue; // an unparsable profile contributes nothing; it must not be fatal
710
+ }
711
+ if (!parsed || typeof parsed !== 'object') continue;
712
+ const name = typeof parsed.name === 'string' && parsed.name !== ''
713
+ ? parsed.name
714
+ : file.slice(0, -5);
715
+ table.set(name, normalizeProfile(name, parsed));
716
+ }
717
+ return table;
718
+ };
719
+
720
+ /**
721
+ * Fill in the profiles a policy only named.
722
+ *
723
+ * Inline profiles (an object in the policy) always win over files on disk: a host
724
+ * that injects a policy object is stating what it wants, and disk contents
725
+ * discovered later must not silently override it. Names that cannot be resolved
726
+ * stay in `pendingProfiles` so `status`/tests can report the gap instead of the
727
+ * session quietly losing a rule set.
728
+ */
729
+ export const attachProfiles = (policy, dirs = [], fs = NODE_FS) => {
730
+ const pending = Array.isArray(policy?.pendingProfiles) ? policy.pendingProfiles : [];
731
+ if (pending.length === 0) return policy;
732
+ const onDisk = new Map();
733
+ for (const dir of Array.isArray(dirs) ? dirs : [dirs]) {
734
+ const table = profilesFromDir(dir, fs);
735
+ if (!table) continue;
736
+ for (const [name, def] of table) if (!onDisk.has(name)) onDisk.set(name, def);
737
+ }
738
+ const missing = [];
739
+ for (const name of pending) {
740
+ if (policy.profiles.has(name)) continue;
741
+ const def = onDisk.get(name);
742
+ if (def) policy.profiles.set(name, def);
743
+ else missing.push(name);
744
+ }
745
+ policy.pendingProfiles = missing;
746
+ policy.profileOrder = [...policy.profiles.keys()];
747
+ return policy;
748
+ };
749
+
750
+ /** The definition a name resolves to, or null (`general-dev` always resolves to null). */
751
+ export const profileFor = (policy, profile = null) => {
752
+ const name = typeof profile === 'string' && profile !== ''
753
+ ? profile
754
+ : policy?.defaultProfile ?? DEFAULT_CONFIG.default_profile;
755
+ if (name === DEFAULT_CONFIG.default_profile) return null;
756
+ const table = policy?.profiles;
757
+ if (table instanceof Map) return table.get(name) ?? null;
758
+ return table && typeof table === 'object' ? table[name] ?? null : null;
759
+ };
760
+
761
+ /**
762
+ * The checks that actually run for a profile: base list first, then the
763
+ * profile's own additions, de-duplicated in order.
764
+ *
765
+ * `general-dev` (or an unknown name) adds nothing, which is why "the base check
766
+ * list is unchanged for general-dev" needs no code at all: there is no branch to
767
+ * get wrong. A profile can only ADD checks; it can never remove a safety rule.
768
+ */
769
+ export const activeChecks = (policy, profile = null) => {
770
+ const base = Array.isArray(policy?.checks) ? policy.checks : [];
771
+ const extra = profileFor(policy, profile)?.checks ?? [];
772
+ const out = [];
773
+ for (const name of [...base, ...extra]) {
774
+ if (typeof name === 'string' && name !== '' && !out.includes(name)) out.push(name);
775
+ }
776
+ return out;
777
+ };
778
+
779
+ /**
780
+ * The policy a check sees for one session: same object, trimmed check list, and
781
+ * the active profile's config merged over the base config.
782
+ *
783
+ * This is the ONLY thing the adapters hand to `shouldBlock`. The session context
784
+ * (which domain, why, when the turn started) stays in `state`; nothing harness-
785
+ * shaped leaks into the rule layer, which is what keeps the dsh adapter from
786
+ * having to imitate a context object it does not have (ADR-003).
787
+ */
788
+ export const profilePolicy = (policy, profile = null) => {
789
+ const def = profileFor(policy, profile);
790
+ return {
791
+ ...policy,
792
+ checks: activeChecks(policy, profile),
793
+ config: def?.config && typeof def.config === 'object'
794
+ ? { ...policy.config, ...def.config }
795
+ : policy.config,
796
+ };
797
+ };
798
+
799
+ // ---------------------------------------------------------------------------
800
+ // Path predicates
801
+ // ---------------------------------------------------------------------------
802
+
803
+ const toPosix = (p) => p.split(sep).join('/');
804
+
805
+ // Minimal glob matcher. `**` spans separators and the slash after it is
806
+ // optional, so the pattern "**/node_modules/**" also matches "node_modules/x".
807
+ // A single `*` stops at a separator, `?` is one non-separator character.
808
+ // (Written as line comments on purpose: a block comment would be terminated
809
+ // early by the "*/" inside the pattern example above.)
810
+ export const globToRegExp = (glob) => {
811
+ let out = '';
812
+ let i = 0;
813
+ while (i < glob.length) {
814
+ const ch = glob[i];
815
+ if (ch === '*') {
816
+ if (glob[i + 1] === '*') {
817
+ i += 2;
818
+ if (glob[i] === '/') {
819
+ i += 1;
820
+ out += '(?:.*/)?'; // zero or more leading path segments
821
+ } else {
822
+ out += '.*';
823
+ }
824
+ } else {
825
+ i += 1;
826
+ out += '[^/]*';
827
+ }
828
+ continue;
829
+ }
830
+ if (ch === '?') {
831
+ i += 1;
832
+ out += '[^/]';
833
+ continue;
834
+ }
835
+ out += ch.replace(/[.+^${}()|[\]\\]/g, '\\$&');
836
+ i += 1;
837
+ }
838
+ return new RegExp(`^${out}$`);
839
+ };
840
+
841
+ export const matchesAnyGlob = (path, globs) => {
842
+ const p = toPosix(path);
843
+ return (globs ?? []).some((g) => globToRegExp(g).test(p));
844
+ };
845
+
846
+ export const isCodeFile = (path, config = DEFAULT_CONFIG) => {
847
+ const name = toPosix(path).split('/').pop() ?? '';
848
+ const commonNames = config.code_filenames ?? DEFAULT_CONFIG.code_filenames;
849
+ if (commonNames.some((n) => n.toLowerCase() === name.toLowerCase())) return true;
850
+ const dot = name.lastIndexOf('.');
851
+ if (dot === -1) return false;
852
+ return config.code_extensions.includes(name.slice(dot + 1).toLowerCase());
853
+ };
854
+
855
+ export const isExcluded = (path, config = DEFAULT_CONFIG) =>
856
+ matchesAnyGlob(path, config.exclude_globs);
857
+
858
+ /**
859
+ * Walk up from `filePath` looking for a VCS root. This replaces the old
860
+ * hard-coded "my projects live in /home/<someone>/Development" constant: a rule
861
+ * that only works on one person's machine is not a rule.
862
+ *
863
+ * @param {string} filePath
864
+ * @param {(dir: string) => boolean} exists injected so tests need no filesystem
865
+ * @param {{markers?: string[], maxDepth?: number}} [opts]
866
+ * @returns {string|null} the repository root, or null
867
+ */
868
+ export const findRepoRoot = (filePath, exists, opts = {}) => {
869
+ const markers = opts.markers ?? ['.git'];
870
+ const maxDepth = opts.maxDepth ?? 40;
871
+ let dir = dirname(filePath);
872
+ for (let i = 0; i < maxDepth; i += 1) {
873
+ for (const marker of markers) {
874
+ if (exists(join(dir, marker))) return dir;
875
+ }
876
+ const parent = dirname(dir);
877
+ if (parent === dir) return null;
878
+ dir = parent;
879
+ }
880
+ return null;
881
+ };
882
+
883
+ /**
884
+ * Is `child` the same as `parent`, or inside it?
885
+ *
886
+ * Compared with `path.relative` rather than a string prefix. The prefix form
887
+ * ("does the path start with `<root>/`") only works when the separator is a
888
+ * literal forward slash, which is a POSIX assumption: on Windows every path
889
+ * uses `\`, so a configured project root never matched anything and the gate
890
+ * silently stopped applying to the projects it was configured for. The string
891
+ * form also gets `<root>-sibling` wrong, which the tests pin separately.
892
+ */
893
+ const withinRoot = (parent, child) => {
894
+ if (child === parent) return true;
895
+ const rel = relative(parent, child);
896
+ return rel !== '' && !rel.startsWith('..') && !isAbsolute(rel);
897
+ };
898
+
899
+ /**
900
+ * Is this path in scope for the gate, and which project does it belong to?
901
+ *
902
+ * `root` is the BOUNDARY: the configured project root (or the detected repo)
903
+ * that decides whether the gate applies at all. `projectRoot` is the PROJECT:
904
+ * the nearest repository inside that boundary.
905
+ *
906
+ * The two are deliberately separate. A machine lists a whole dev tree as its
907
+ * boundary when it needs to cover non-git working directories (see the target
908
+ * manifest), and answering "the project is <dev tree>" made the conventions
909
+ * rule look for `<dev tree>/AGENTS.md` — a file that does not exist — so the
910
+ * rule was silently inert for every repository underneath. When the boundary IS
911
+ * the project (the usual case), both fields are identical and nothing changes.
912
+ * @returns {{inScope: boolean, reason: string, root: string|null, projectRoot: string|null}}
913
+ */
914
+ export const scopeOf = (filePath, { config = DEFAULT_CONFIG, exists }) => {
915
+ const out = (inScope, reason, root = null, projectRoot = null) => ({ inScope, reason, root, projectRoot });
916
+ if (!filePath) return out(false, '没有路径');
917
+ if (!isAbsolute(filePath)) return out(false, '不是绝对路径');
918
+ if (!isCodeFile(filePath, config)) return out(false, '不是代码文件');
919
+ if (isExcluded(filePath, config)) return out(false, '在排除清单内(vendor/依赖/构建产物)');
920
+
921
+ const repoRoot = findRepoRoot(
922
+ filePath,
923
+ exists,
924
+ config.repo_markers ? { markers: config.repo_markers } : {},
925
+ );
926
+
927
+ if (Array.isArray(config.project_roots) && config.project_roots.length > 0) {
928
+ const boundary = config.project_roots.find((r) => withinRoot(r, filePath));
929
+ if (!boundary) return out(false, '不在任何配置的项目根之下');
930
+ const insideBoundary = repoRoot === boundary || (repoRoot && withinRoot(boundary, repoRoot));
931
+ return out(true, '在配置的项目根之下', boundary, insideBoundary ? repoRoot : boundary);
932
+ }
933
+
934
+ return repoRoot
935
+ ? out(true, '在某个代码仓库内', repoRoot, repoRoot)
936
+ : out(false, '不在任何代码仓库内');
937
+ };
938
+
939
+ // ---------------------------------------------------------------------------
940
+ // Session state
941
+ // ---------------------------------------------------------------------------
942
+
943
+ /**
944
+ * Per-session bookkeeping every adapter needs. Kept as a plain object (not a
945
+ * class) so an adapter can hand it to `shouldBlock` without ceremony and tests
946
+ * can build one literal.
947
+ */
948
+ export const newSessionState = () => ({
949
+ /** Count of successful "I consulted the code graph" signals. */
950
+ signals: 0,
951
+ /** Timestamp of the most recent signal (ms). */
952
+ lastSignalAt: 0,
953
+ /**
954
+ * Files this session actually read (normalized). A read is stronger evidence
955
+ * than a scoped unlock for the same file: it proves the model looked at the
956
+ * exact target it is about to overwrite.
957
+ */
958
+ inspected: new Map(),
959
+ /** Project convention documents this session read (normalized). */
960
+ docReads: new Set(),
961
+ /**
962
+ * Failed shell commands, keyed by normalized command, with a streak count.
963
+ * `no-blind-retry` uses this; the adapter feeds it from tool results.
964
+ */
965
+ failedCommands: new Map(),
966
+ /** Timestamp of the most recent signal/read/write, used by the retry rule. */
967
+ lastInvestigationAt: 0,
968
+ /**
969
+ * Scoped unlocks: path tokens that a successful graph query actually named
970
+ * (file, package dir, module). A read is allowed when its normalized path
971
+ * contains a fresh unlock — "the graph was asked about this, specifically".
972
+ */
973
+ unlocks: new Map(),
974
+ /** Files this session itself wrote; reading them back is always fine. */
975
+ written: new Set(),
976
+ /**
977
+ * Per-category grants the user made for THIS session only, through the
978
+ * confirmation dialog. Kept in memory: a session grant must not outlive the
979
+ * conversation that granted it, and it must not be writable by the agent
980
+ * (see the `no-self-grant` check).
981
+ */
982
+ destructiveGrants: new Map(),
983
+ /**
984
+ * v6: this session's destructive-gate mode override (`/gate mode … session`).
985
+ *
986
+ * `null` means "follow the global `config.destructive_mode`". Memory-only on
987
+ * purpose: a session override must not outlive the conversation that made it,
988
+ * which is exactly why `/gate mode bypass session` needs no cleanup.
989
+ */
990
+ destructiveMode: null,
991
+ /** How many times the gate has blocked, to bound the damage of a false rule. */
992
+ blocks: 0,
993
+ /** When the current cap window started; 0 = no block yet. */
994
+ firstBlockAt: 0,
995
+ /** Successful `index_repository` / `detect_changes` calls this session. */
996
+ lastIndexRefreshAt: 0,
997
+ /** How many no-slack continuations have been issued this session. */
998
+ slackContinues: 0,
999
+ /**
1000
+ * v5: the active domain profile, and where that answer came from.
1001
+ *
1002
+ * Starts at `general-dev` / `fallback` on purpose: until a hook has actually
1003
+ * classified, the gate must behave exactly as it did before v5. A guess at
1004
+ * startup would apply research rules to a session nobody has looked at yet.
1005
+ */
1006
+ profile: DEFAULT_CONFIG.default_profile,
1007
+ profileSource: 'fallback',
1008
+ /**
1009
+ * Analysis scripts this session started, keyed by normalized path, valued
1010
+ * `{ startedAt }`. W1 uses the key set for "is this the first run?"; the
1011
+ * turn-end W4 check uses `startedAt` to date the expected `.log` file.
1012
+ */
1013
+ scriptsRun: new Map(),
1014
+ /**
1015
+ * Start of the current user turn (ms). W2 only judges result directories that
1016
+ * something touched AFTER this instant, so an old directory without a README
1017
+ * - which nobody is working on right now - is not a finding.
1018
+ */
1019
+ turnStart: 0,
1020
+ /** Reasons already surfaced, so the user is not shouted at every turn. */
1021
+ announced: new Set(),
1022
+ });
1023
+
1024
+ /**
1025
+ * One spelling for a path, so "the file I am reading" and "the file I wrote a
1026
+ * turn ago" can be compared at all.
1027
+ *
1028
+ * Why this exists
1029
+ * ---------------
1030
+ * A harness resolves tool paths itself: pi's `read` schema says "relative or
1031
+ * absolute" and resolves the relative form against the session directory. The
1032
+ * rules below refuse relative paths on purpose (an absolute path is the only
1033
+ * thing they can scope), so before this the model could dodge the gate by
1034
+ * spelling a path relatively — `scopeOf` answered "not an absolute path",
1035
+ * `inScope` was false, and the read sailed through. The same mismatch made the
1036
+ * gate fight the model over its own work: `write` recorded one spelling,
1037
+ * `read` came back with another, `written.has(...)` missed, and a file the
1038
+ * session had just created was blocked.
1039
+ *
1040
+ * So both sides of the `written` comparison go through here, and the harness is
1041
+ * responsible for handing `recordWrite` the spelling it will later report.
1042
+ *
1043
+ * What it does, and deliberately does not do
1044
+ * ------------------------------------------
1045
+ * resolve a relative path against the directory the harness resolves it
1046
+ * against (`cwd`), passed in — never read from `process.cwd()`,
1047
+ * because for a session-shaped harness the process directory is
1048
+ * not the session directory.
1049
+ * normalize collapse `..`, `.` and duplicate separators.
1050
+ * win32 fold case and the `\\?\` long-path prefix, because Windows
1051
+ * treats `C:\repo` and `c:\repo` as one file and the model will
1052
+ * spell them both in consecutive turns.
1053
+ * NOT resolving links (needs I/O; this stays a pure function) and NOT
1054
+ * expanding 8.3 short names.
1055
+ *
1056
+ * Case is folded only on win32: on a case-sensitive filesystem `/Repo/a.ts` and
1057
+ * `/repo/a.ts` really are two files, and conflating them would open a hole.
1058
+ */
1059
+ export const normalizePath = (p, cwd = null) => {
1060
+ if (typeof p !== 'string' || p === '') return p ?? null;
1061
+ const resolved = cwd ? resolve(cwd, p) : resolve(p);
1062
+ if (!WIN32) return normalize(resolved);
1063
+ let out = resolved.startsWith('\\\\?\\') ? resolved.slice(4) : resolved;
1064
+ out = out.split('/').join('\\');
1065
+ // Keep the root separator ("C:\") because "C:" alone means "the current
1066
+ // directory on drive C", which is a different thing.
1067
+ if (out.length > 3 && out.endsWith('\\')) out = out.slice(0, -1);
1068
+ return out.toLowerCase();
1069
+ };
1070
+
1071
+ export const recordSignal = (state, now = Date.now()) => {
1072
+ state.signals += 1;
1073
+ state.lastSignalAt = now;
1074
+ state.lastInvestigationAt = now;
1075
+ };
1076
+
1077
+ /** Record that this session read a file, whatever tool performed the read. */
1078
+ export const recordInspection = (state, path, now = Date.now()) => {
1079
+ if (!path || !state?.inspected) return;
1080
+ // v4: a Map<path, timestamp> so the evidence can expire. A Set unlocked the
1081
+ // file for the whole session, which made "look before you edit" a one-time
1082
+ // ritual performed at turn 2 and forgotten by turn 40.
1083
+ if (typeof state.inspected.set === 'function') state.inspected.set(path, now);
1084
+ else state.inspected.add(path); // tolerate older/custom state objects
1085
+ state.lastInvestigationAt = now;
1086
+ };
1087
+
1088
+ /** Is a read of `path` still fresh enough to justify an edit? */
1089
+ export const hasFreshInspection = (state, path, config = DEFAULT_CONFIG, now = Date.now()) => {
1090
+ const inspected = state?.inspected;
1091
+ if (!inspected) return false;
1092
+ let at = null;
1093
+ if (typeof inspected.get === 'function') at = inspected.get(path) ?? null;
1094
+ else if (typeof inspected.has === 'function' && inspected.has(path)) at = 0;
1095
+ if (at === null) return false;
1096
+ const ttl = config.inspected_ttl_ms ?? DEFAULT_CONFIG.inspected_ttl_ms;
1097
+ if (ttl < 0) return true;
1098
+ if (!(at > 0)) return false; // legacy Set entry: cannot prove freshness
1099
+ return now - at <= ttl;
1100
+ };
1101
+
1102
+ /**
1103
+ * Record a successful index refresh (`index_repository` / `detect_changes`).
1104
+ *
1105
+ * Layer 2 used to key off `<repo>/.codebase-memory`, which only exists when the
1106
+ * indexer was asked to persist its artifact. A normal global index therefore
1107
+ * made the stale-check abstain forever. The session's own refresh timestamp is
1108
+ * evidence that works regardless of where the index lives.
1109
+ */
1110
+ export const recordIndexRefresh = (state, now = Date.now()) => {
1111
+ if (!state) return;
1112
+ state.lastIndexRefreshAt = now;
1113
+ state.lastInvestigationAt = now;
1114
+ };
1115
+
1116
+ /** Record a convention-document read. */
1117
+ export const recordDocRead = (state, path, now = Date.now()) => {
1118
+ if (!path || !state?.docReads) return;
1119
+ state.docReads.add(path);
1120
+ state.lastInvestigationAt = now;
1121
+ };
1122
+
1123
+ /** Any substantive action (query/read/write) resets the blind-retry clock. */
1124
+ export const recordInvestigation = (state, now = Date.now()) => {
1125
+ if (!state) return;
1126
+ state.lastInvestigationAt = now;
1127
+ };
1128
+
1129
+ /** One spelling for a shell command, so "the same retry" is comparable. */
1130
+ export const normalizeCommand = (command) =>
1131
+ typeof command === 'string' ? command.trim().replace(/\s+/g, ' ') : '';
1132
+
1133
+ /**
1134
+ * Record the outcome of a shell command.
1135
+ *
1136
+ * A success forgets the command's failure streak (the retry worked). A failure
1137
+ * increments it. Streaks are bounded by `retry_window_ms` at read time and the
1138
+ * map is capped so a long session cannot grow it without bound.
1139
+ */
1140
+ export const recordCommandResult = (state, command, failed, now = Date.now()) => {
1141
+ const key = normalizeCommand(command);
1142
+ if (!key || !state?.failedCommands) return;
1143
+ if (!failed) {
1144
+ state.failedCommands.delete(key);
1145
+ return;
1146
+ }
1147
+ const prev = state.failedCommands.get(key);
1148
+ state.failedCommands.set(key, {
1149
+ count: (prev?.count ?? 0) + 1,
1150
+ lastAt: now,
1151
+ });
1152
+ // Keep the map small. Oldest insertion order is the least interesting.
1153
+ while (state.failedCommands.size > 50) {
1154
+ state.failedCommands.delete(state.failedCommands.keys().next().value);
1155
+ }
1156
+ };
1157
+
1158
+ /** Does this path name a project convention document? */
1159
+ export const isConventionDoc = (path, config = DEFAULT_CONFIG) => {
1160
+ if (typeof path !== 'string' || path === '') return false;
1161
+ const name = toPosix(path).split('/').pop() ?? '';
1162
+ return (config.convention_files ?? []).some((n) => n.toLowerCase() === name.toLowerCase());
1163
+ };
1164
+
1165
+ /**
1166
+ * Does this path name a CHG contract document (`tasks/CHG-<id>/SPEC|PRD|CHANGE|TRACEABILITY`)?
1167
+ *
1168
+ * 与 `isConventionDoc` 分开是故意的:约定文档是「怎么做事」,CHG 契约是
1169
+ * 「这次做什么、做到什么算完」。缺少前者只能提醒,缺少后者**不允许改代码**。
1170
+ *
1171
+ * 大小写不敏感:`normalizePath` 会把**路径**小写化,而 glob 是人手写的,
1172
+ * `tasks/CHG-<id>/SPEC.md` 是自然写法。两侧统一小写化后再比——不让
1173
+ * 「配置怎么写」决定门控是否生效。历史事故:曾要求配置全小写,门控因此静默失效。
1174
+ */
1175
+ export const isChgContract = (path, config = DEFAULT_CONFIG) => {
1176
+ if (typeof path !== 'string' || path === '') return false;
1177
+ const globs = (config.chg_contract_globs ?? []).map((g) => String(g).toLowerCase());
1178
+ return matchesAnyGlob(toPosix(path).toLowerCase(), globs);
1179
+ };
1180
+
1181
+ /**
1182
+ * The `tasks/CHG-<id>/` directory a contract file belongs to, or null.
1183
+ *
1184
+ * Reading `SPEC.md` only means something if the PRD and TRACEABILITY that turn
1185
+ * it into a *contract* exist beside it — that is a property of the directory,
1186
+ * not of the file that was opened.
1187
+ */
1188
+ export const chgDirOf = (path, config = DEFAULT_CONFIG) =>
1189
+ isChgContract(path, config) ? dirname(toPosix(path)) : null;
1190
+
1191
+ /**
1192
+ * Declared status of a CHG, or null when the document declares none.
1193
+ *
1194
+ * `null` is deliberately distinct from "invalid": only an explicit draft value
1195
+ * is a refusal, so a repository without frontmatter is never blocked for it.
1196
+ */
1197
+ export const chgStatusOf = (text, config = DEFAULT_CONFIG) => {
1198
+ if (typeof text !== 'string' || text === '') return null;
1199
+ const fields = config.chg_status_fields ?? DEFAULT_CONFIG.chg_status_fields;
1200
+ const close = text.startsWith('---') ? text.indexOf('\n---', 3) : -1;
1201
+ const scope = close >= 0 ? text.slice(0, close + 1) : text.slice(0, 2000);
1202
+ for (const field of fields) {
1203
+ const hit = new RegExp(`^\\s*${String(field)}\\s*:\\s*(.+)$`, 'im').exec(scope);
1204
+ if (hit) {
1205
+ // `status: approved # 用户批准…` → `approved`. Trailing prose is common.
1206
+ return hit[1].trim().replace(/^["']|["']$/g, '').split(/\s+/)[0].toLowerCase();
1207
+ }
1208
+ }
1209
+ return null;
1210
+ };
1211
+
1212
+ /** Does the SPEC name a checkable acceptance condition? */
1213
+ export const chgSpecHasAcceptance = (text, config = DEFAULT_CONFIG) => {
1214
+ const markers = config.chg_acceptance_markers ?? DEFAULT_CONFIG.chg_acceptance_markers;
1215
+ if (!Array.isArray(markers) || markers.length === 0) return true;
1216
+ if (typeof text !== 'string' || text === '') return false;
1217
+ const lower = text.toLowerCase();
1218
+ return markers.some((m) => lower.includes(String(m).toLowerCase()));
1219
+ };
1220
+
1221
+ /**
1222
+ * Is this CHG directory a *standing* contract — complete, verifiable, started?
1223
+ *
1224
+ * Three independent questions, because "the model opened one file" answers none
1225
+ * of them:
1226
+ * complete? SPEC + PRD + TRACEABILITY all exist
1227
+ * checkable? the SPEC names an acceptance condition
1228
+ * started? a declared status is not a draft value
1229
+ *
1230
+ * Repository binding is the caller's job: it needs the edit target, not the
1231
+ * contract directory. Returns the problem list rather than a boolean so the
1232
+ * denial can name the exact file to create.
1233
+ */
1234
+ export const auditChgContract = (dir, config = DEFAULT_CONFIG, deps = {}) => {
1235
+ const exists = deps.exists ?? (() => false);
1236
+ const isFile = typeof deps.isFile === 'function' ? deps.isFile : null;
1237
+ const problems = [];
1238
+
1239
+ const required = config.chg_contract_required_files ?? DEFAULT_CONFIG.chg_contract_required_files;
1240
+ for (const name of Array.isArray(required) ? required : []) {
1241
+ const file = join(dir, name);
1242
+ if (!(exists(file) && (isFile ? isFile(file) : true))) problems.push(`${name} 不存在`);
1243
+ }
1244
+
1245
+ // Without a reader this is a breadth-only audit. Abstaining is better than
1246
+ // failing an edit because a harness (or a test double) cannot read bytes.
1247
+ if (typeof deps.readText !== 'function') {
1248
+ return { ok: problems.length === 0, problems };
1249
+ }
1250
+
1251
+ const text = deps.readText(join(dir, 'SPEC.md'));
1252
+ if (typeof text !== 'string') {
1253
+ if (!problems.includes('SPEC.md 不存在')) problems.push('SPEC.md 读不出内容');
1254
+ return { ok: false, problems };
1255
+ }
1256
+ if (!chgSpecHasAcceptance(text, config)) {
1257
+ problems.push('SPEC.md 没有可判定的验收判据(验收 / AC / 断言 / 可判定)');
1258
+ }
1259
+ const status = chgStatusOf(text, config);
1260
+ const allow = config.chg_status_allow ?? DEFAULT_CONFIG.chg_status_allow;
1261
+ if (status !== null && Array.isArray(allow) && allow.length > 0 && !allow.includes(status)) {
1262
+ problems.push(`SPEC.md status=${status} 不是可开工状态(允许:${allow.join(' / ')})`);
1263
+ }
1264
+ return { ok: problems.length === 0, problems };
1265
+ };
1266
+
1267
+ /** Record a file the session wrote. The caller passes the normalized spelling. */
1268
+ export const recordWrite = (state, path) => {
1269
+ if (path) state.written.add(path);
1270
+ };
1271
+
1272
+ export const hasFreshSignal = (state, ttlMs, now = Date.now()) =>
1273
+ state.signals > 0 && now - state.lastSignalAt <= ttlMs;
1274
+
1275
+ // ---------------------------------------------------------------------------
1276
+ // Scoped unlocks: "the graph query actually talked about this file"
1277
+ // ---------------------------------------------------------------------------
1278
+
1279
+ /** Shortest token kept; below this the substring match starts lying ("a", "js"). */
1280
+ const UNLOCK_MIN_LEN = 4;
1281
+ /** Hard cap so a huge query result cannot grow the map without bound. */
1282
+ const MAX_UNLOCKS = 4000;
1283
+ /** Directory names too common to mean anything on their own. */
1284
+ const GENERIC_DIR_SEGMENTS = new Set([
1285
+ 'packages', 'package', 'src', 'source', 'lib', 'libs', 'test', 'tests', 'spec',
1286
+ 'app', 'apps', 'docs', 'doc', 'bridge', 'scripts', 'script', 'bin', 'dist',
1287
+ 'build', 'out', 'output', 'node_modules', 'vendor', 'python', 'site-packages',
1288
+ 'development', 'projects', 'repos', 'workspace', 'workspaces',
1289
+ ]);
1290
+
1291
+ /** One spelling for unlock entries: forward slashes, no drive prefix, lowercase. */
1292
+ export const normalizeUnlockToken = (token) => {
1293
+ if (typeof token !== 'string') return null;
1294
+ const cleaned = token
1295
+ .replace(/\\/g, '/')
1296
+ .replace(/^[a-z]:/i, '')
1297
+ .replace(/^\/+/, '')
1298
+ .trim()
1299
+ .toLowerCase();
1300
+ return cleaned.length >= UNLOCK_MIN_LEN ? cleaned : null;
1301
+ };
1302
+
1303
+ /**
1304
+ * Turn free text (usually a graph query's arguments or its result) into
1305
+ * unlock tokens.
1306
+ *
1307
+ * The tokens are *path suffixes* — the basename, the last few segments, and
1308
+ * the whole drive-stripped path — never bare generic directories. A query that
1309
+ * mentioned `packages/xyb/client.js` must unlock that file (and its suffix
1310
+ * spellings), not every file under `packages/`: an unlock is evidence about a
1311
+ * named target, and evidence that broad is not evidence.
1312
+ */
1313
+ export const unlockTokensFromText = (text, { limit = 400, maxSuffixSegments = 4 } = {}) => {
1314
+ if (typeof text !== 'string' || text === '') return [];
1315
+ const tokens = new Set();
1316
+ const pathish = /[A-Za-z0-9_@.$-]+(?:[\\/][A-Za-z0-9_@.$-]+)+/g;
1317
+ for (const match of text.match(pathish) ?? []) {
1318
+ const key = normalizeUnlockToken(match);
1319
+ if (!key) continue;
1320
+ const segments = key.split('/').filter(Boolean);
1321
+ // Suffixes of the path: basename, last two, last three … up to maxSuffixSegments.
1322
+ // `c:\repo\packages\xyb\client.js` contains `packages/xyb/client.js`, so the
1323
+ // suffix form matches absolute paths on any machine.
1324
+ const max = Math.min(segments.length, maxSuffixSegments);
1325
+ for (let take = 1; take <= max; take += 1) {
1326
+ const suffix = segments.slice(-take).join('/');
1327
+ if (suffix.length >= UNLOCK_MIN_LEN) tokens.add(suffix);
1328
+ }
1329
+ // The immediate parent is useful when the file itself is renamed, but only
1330
+ // when it is specific enough to mean something (see the doc above).
1331
+ const parent = segments[segments.length - 2];
1332
+ if (parent && parent.length >= UNLOCK_MIN_LEN && !GENERIC_DIR_SEGMENTS.has(parent)) tokens.add(parent);
1333
+ if (tokens.size >= limit) break;
1334
+ }
1335
+ return [...tokens].slice(0, limit);
1336
+ };
1337
+
1338
+ /** Record tokens as unlocks; returns how many were stored. */
1339
+ export const recordUnlocks = (state, tokens, now = Date.now()) => {
1340
+ if (!state?.unlocks || !tokens) return 0;
1341
+ let added = 0;
1342
+ for (const raw of tokens) {
1343
+ const key = normalizeUnlockToken(raw);
1344
+ if (!key) continue;
1345
+ state.unlocks.set(key, now);
1346
+ added += 1;
1347
+ if (state.unlocks.size > MAX_UNLOCKS) state.unlocks.delete(state.unlocks.keys().next().value);
1348
+ }
1349
+ return added;
1350
+ };
1351
+
1352
+ /**
1353
+ * May this path be read right now?
1354
+ *
1355
+ * True when either the whole session has a fresh signal (short TTL — see
1356
+ * DEFAULT_CONFIG) or the path itself was named by a fresh unlock.
1357
+ */
1358
+ /**
1359
+ * Like `hasUnlock`, but ignores the session-wide window.
1360
+ *
1361
+ * Layer 0 needs *evidence*, not a blanket pass: a query about some other file
1362
+ * must not authorise overwriting this one. `hasUnlock` stays as "may I read
1363
+ * this at all" (session window OR named target); `hasScopedUnlock` is "did the
1364
+ * graph actually name this target".
1365
+ */
1366
+ export const hasScopedUnlock = (state, path, config = DEFAULT_CONFIG, now = Date.now()) => {
1367
+ if (!path || !state?.unlocks || state.unlocks.size === 0) return false;
1368
+ const norm = String(path).replace(/\\/g, '/').toLowerCase();
1369
+ for (const [key, at] of state.unlocks) {
1370
+ if (now - at > config.unlock_ttl_ms) continue;
1371
+ if (norm.includes(key)) return true;
1372
+ }
1373
+ return false;
1374
+ };
1375
+
1376
+ /** May this path be read right now? Session window OR a named-target unlock. */
1377
+ export const hasUnlock = (state, path, config = DEFAULT_CONFIG, now = Date.now()) => {
1378
+ if (hasFreshSignal(state, config.signal_ttl_ms, now)) return true;
1379
+ return hasScopedUnlock(state, path, config, now);
1380
+ };
1381
+
1382
+ /**
1383
+ * Unlock tokens from a dotted qualified name (`pkg.sub.module.symbol`).
1384
+ *
1385
+ * Graph results already carry `file_path` fields, which the text extractor
1386
+ * picks up. `get_code_snippet` is the exception: its input is a qualified name
1387
+ * and its result is source text, so a scoped write check would otherwise say
1388
+ * "you never looked at this file" right after the model did exactly that.
1389
+ * Suffixes joined with slashes match the repository path (`bridge/lib/gates`
1390
+ * is a substring of `.../bridge/lib/gates.js`).
1391
+ */
1392
+ export const unlockTokensFromQualifiedName = (qualifiedName, { limit = 60 } = {}) => {
1393
+ if (typeof qualifiedName !== 'string') return [];
1394
+ const parts = qualifiedName.split(/[.::]+/).filter(Boolean);
1395
+ if (parts.length < 2) return [];
1396
+ const tokens = new Set();
1397
+ for (let start = 0; start < parts.length; start += 1) {
1398
+ const tail = parts.slice(start).join('/');
1399
+ if (tail.length >= UNLOCK_MIN_LEN) tokens.add(tail.toLowerCase());
1400
+ // Also keep the parent directory form: .../bridge/lib/gates (no symbol).
1401
+ if (start < parts.length - 1) {
1402
+ const parent = parts.slice(start, -1).join('/');
1403
+ if (parent.length >= UNLOCK_MIN_LEN) tokens.add(parent.toLowerCase());
1404
+ }
1405
+ if (tokens.size >= limit) break;
1406
+ }
1407
+ return [...tokens].slice(0, limit);
1408
+ };
1409
+
1410
+ /** Patterns that make a graph result an empty answer rather than evidence. */
1411
+ const EMPTY_GRAPH_RESULT = [
1412
+ /"total"\s*:\s*0\b/,
1413
+ /"total_nodes"\s*:\s*0\b/,
1414
+ /"results"\s*:\s*\[\s*\]/,
1415
+ /"nodes"\s*:\s*\[\s*\]/,
1416
+ /"edges"\s*:\s*\[\s*\]/,
1417
+ /\bno (?:results?|matches?|symbols?|nodes?|projects?)\b/i,
1418
+ /(?:未找到|没有找到|无匹配|空结果|查无)/,
1419
+ ];
1420
+
1421
+ /**
1422
+ * Is a graph tool result strong enough to count as "the graph was consulted"?
1423
+ *
1424
+ * Empty is not evidence. A model that searched, found nothing, and immediately
1425
+ * read the tree has learned nothing from the graph — the rules require fixing
1426
+ * the query or refreshing the index and querying again first.
1427
+ */
1428
+ export const graphResultIsEvidence = (text, config = DEFAULT_CONFIG) => {
1429
+ if (config.graph_signal_requires_content === false) return true;
1430
+ if (typeof text !== 'string') return false;
1431
+ const trimmed = text.trim();
1432
+ if (trimmed.length < (config.graph_signal_min_chars ?? 0)) return false;
1433
+ return !EMPTY_GRAPH_RESULT.some((re) => re.test(trimmed));
1434
+ };
1435
+
1436
+ // ---------------------------------------------------------------------------
1437
+ // bash reads: cat / grep / sed -n / python -c "open(...)" are reads too
1438
+ // ---------------------------------------------------------------------------
1439
+
1440
+ /** Commands whose arguments are files opened for reading. */
1441
+ const BASH_READ_VERBS = new Set([
1442
+ 'cat', 'tac', 'head', 'tail', 'sed', 'awk', 'grep', 'egrep', 'fgrep', 'rg',
1443
+ 'less', 'more', 'view', 'strings', 'xxd', 'od', 'wc', 'cut', 'sort', 'uniq',
1444
+ 'diff', 'cmp', 'comm', 'file', 'bat', 'nl', 'fold', 'paste', 'join', 'tr',
1445
+ 'split', 'csplit', 'base64', 'zcat', 'bzcat', 'xzcat', 'iconv',
1446
+ // Copying a source tree is reading it: `cp src/a.js /tmp/x` used to take the
1447
+ // file out of scope, after which the read gate could not see it at all.
1448
+ 'cp', 'install', 'rsync',
1449
+ ]);
1450
+
1451
+ /** Commands whose operands are files created or modified. */
1452
+ const BASH_WRITE_VERBS = new Set([
1453
+ 'tee', 'cp', 'mv', 'install', 'rsync', 'rm', 'rmdir', 'unlink',
1454
+ 'truncate', 'touch', 'dd',
1455
+ ]);
1456
+
1457
+ /** Prefixes that wrap the real command; the parser strips them. */
1458
+ const BASH_WRAPPERS = new Set([
1459
+ 'sudo', 'doas', 'command', 'builtin', 'exec', 'env', 'time', 'nice',
1460
+ 'nohup', 'ionice', 'stdbuf', 'xargs',
1461
+ ]);
1462
+
1463
+ /**
1464
+ * Verbs that take something away, in either shell. `no-self-grant` reads them to
1465
+ * decide whether a target that is a PARENT of a gate directory means the gate is
1466
+ * being deleted (`rm -rf ~/.pi`) or is merely a destination (`cp notes ~`).
1467
+ */
1468
+ const GATE_REMOVAL_VERBS = new Set([
1469
+ 'rm', 'rmdir', 'rd', 'unlink', 'remove-item', 'ri', 'del', 'erase',
1470
+ ]);
1471
+
1472
+ /**
1473
+ * Verbs that take their SOURCE away by moving it. `mv <gate dir> /tmp` deletes
1474
+ * the gate as surely as `rm -rf` does; the parser reports the source as a read
1475
+ * operand, so the destination check alone would miss it.
1476
+ */
1477
+ const GATE_MOVE_VERBS = new Set(['mv', 'move', 'move-item', 'mi', 'rename-item', 'rni', 'ren']);
1478
+
1479
+ /**
1480
+ * Directories the gate itself is made of (ADR-015): where this adapter is
1481
+ * installed and where its machine-local override lives. The adapter supplies
1482
+ * them from its own location (`fs.gateDirs`), so no install path is baked in
1483
+ * here. A bare engine has none and guards nothing on this account.
1484
+ */
1485
+ const gateDirsOf = (deps) =>
1486
+ (Array.isArray(deps?.gateDirs) ? deps.gateDirs : [])
1487
+ .filter((dir) => typeof dir === 'string' && dir)
1488
+ .map((dir) => normalize(dir.replace(/\\/g, '/')));
1489
+
1490
+ /**
1491
+ * Is `p` a gate directory, or something inside one? With `withAncestors`, also
1492
+ * a directory a gate is installed under.
1493
+ *
1494
+ * The ancestor half is switched on for removal commands only: `cp notes ~`
1495
+ * names the same parent and must keep working.
1496
+ */
1497
+ const isGateOwned = (p, gateDirs, withAncestors = false) => {
1498
+ const posix = String(p ?? '').replace(/\\/g, '/');
1499
+ if (!posix || !isAbsolute(posix) || gateDirs.length === 0) return false;
1500
+ // `rm -rf <dir>/` is the same deletion; a trailing separator must not make
1501
+ // the target a stranger to the directory it names.
1502
+ const target = withoutTrailingSeparators(normalize(posix));
1503
+ return gateDirs.some(
1504
+ (dir) => withinRoot(withoutTrailingSeparators(dir), target) || (withAncestors && withinRoot(target, dir)),
1505
+ );
1506
+ };
1507
+
1508
+ /** Which segment verbs of the command are in `verbs`. */
1509
+ const shellUsesAny = (command, verbs) => {
1510
+ for (const segment of splitShellSegments(command)) {
1511
+ const tokens = shellTokens(segment);
1512
+ if (tokens.length === 0) continue;
1513
+ if (verbs.has(parseCommandHead(tokens).verb)) return true;
1514
+ }
1515
+ return false;
1516
+ };
1517
+
1518
+ /** Drop trailing separators, but never reduce a root (`/` stays `/`). */
1519
+ const withoutTrailingSeparators = (path) => path.replace(/[\\/]+$/, '') || path;
1520
+
1521
+ const gateOwnedVerdict = (path) => ({
1522
+ code: 'GATE_SELF_GRANT',
1523
+ reason: [
1524
+ '⛔ 门控自保护:agent 不能拆掉门控自己。',
1525
+ ` 目标:${path}`,
1526
+ '',
1527
+ '这个路径是门控自己的安装目录或配置目录(或装着它的上级目录)。',
1528
+ '删掉、移走或改写它,等于把全部规则——包括任何模式都不放行的红线——一起卸掉,',
1529
+ '下一次会话就什么都不剩了。',
1530
+ '',
1531
+ '要更新门控:改 ShipGate 仓库 assets/gates/(门控源已迁出 bridge)→ node --test → node bin/shipgate.mjs install。',
1532
+ '确实要卸载或手工修复:请主人亲手在终端执行。',
1533
+ ].join('\n'),
1534
+ });
1535
+
1536
+ /**
1537
+ * The gate directory a `mv`/`rename` takes away, or null.
1538
+ *
1539
+ * The operand parser records a move's destination as a write and neither
1540
+ * operand as a read, so a source that IS the gate would otherwise be invisible.
1541
+ * Option operands are skipped the way the parser skips them; `-t <dir>` makes
1542
+ * every other operand a source.
1543
+ */
1544
+ const movedGateSource = (command, gateDirs, cwd) => {
1545
+ let activeCwd = cwd;
1546
+ for (const segment of splitShellSegments(command)) {
1547
+ const tokens = shellTokens(segment);
1548
+ if (tokens.length === 0) continue;
1549
+ const { verb, args } = parseCommandHead(tokens);
1550
+ if (['cd', 'pushd', 'set-location', 'sl', 'chdir'].includes(verb)) {
1551
+ const target = args.find((a) => a.quoted || !a.value.startsWith('-'));
1552
+ const resolved = target ? resolveShellPath(target.value, activeCwd) : null;
1553
+ if (resolved) activeCwd = resolved;
1554
+ continue;
1555
+ }
1556
+ if (!GATE_MOVE_VERBS.has(verb)) continue;
1557
+ const values = args.map((a) => a.value);
1558
+ const flagAt = values.indexOf('-t');
1559
+ const destination = flagAt >= 0 ? values[flagAt + 1] : values.filter((v) => !v.startsWith('-')).at(-1);
1560
+ // The operand after `-t` is the destination; without `-t` there is no
1561
+ // operand to skip by index (and `i !== 0` would have dropped the source).
1562
+ const skipIndex = flagAt >= 0 ? flagAt + 1 : -1;
1563
+ const sources = values.filter((v, i) => !v.startsWith('-') && v !== destination && i !== skipIndex);
1564
+ for (const source of sources) {
1565
+ const resolved = resolveShellPath(source, activeCwd);
1566
+ if (resolved && isGateOwned(resolved, gateDirs, true)) return resolved;
1567
+ }
1568
+ }
1569
+ return null;
1570
+ };
1571
+
1572
+ /** The first path a shell command writes to that is the gate's own, or null. */
1573
+ const gateOwnedShellTarget = (input, config, deps) => {
1574
+ const gateDirs = gateDirsOf(deps);
1575
+ if (gateDirs.length === 0 || input?.action !== 'bash' || typeof input.command !== 'string') return null;
1576
+ const removing = shellUsesAny(input.command, GATE_REMOVAL_VERBS);
1577
+ const opts = { config, cwd: input.cwd ?? null, isFile: deps?.isFile, exists: deps?.exists };
1578
+ // `shellWriteTargets` returns the list itself, not a {writes} record.
1579
+ const written = shellWriteTargets(input, opts).find((target) => isGateOwned(target, gateDirs, removing));
1580
+ if (written) return written;
1581
+ return movedGateSource(input.command, gateDirs, input.cwd ?? null);
1582
+ };
1583
+
1584
+ /**
1585
+ * Split a command on `&&`, `||`, `;`, newlines and pipes, but never inside a
1586
+ * quoted string. A regex split would tear `grep "a|b" file` in half and lose
1587
+ * the file operand — which is how a parser starts missing exactly the commands
1588
+ * it was written to catch.
1589
+ */
1590
+ const splitShellSegments = (command) => {
1591
+ const out = [];
1592
+ let buf = '';
1593
+ let quote = null;
1594
+ for (let i = 0; i < command.length; i += 1) {
1595
+ const c = command[i];
1596
+ const next = command[i + 1];
1597
+ if (quote) {
1598
+ buf += c;
1599
+ if (c === quote) quote = null;
1600
+ continue;
1601
+ }
1602
+ if (c === '"' || c === "'") {
1603
+ quote = c;
1604
+ buf += c;
1605
+ continue;
1606
+ }
1607
+ if ((c === '&' && next === '&') || (c === '|' && next === '|')) {
1608
+ out.push(buf);
1609
+ buf = '';
1610
+ i += 1;
1611
+ continue;
1612
+ }
1613
+ if (c === ';' || c === '\n' || c === '|') {
1614
+ out.push(buf);
1615
+ buf = '';
1616
+ continue;
1617
+ }
1618
+ buf += c;
1619
+ }
1620
+ out.push(buf);
1621
+ return out;
1622
+ };
1623
+
1624
+ /**
1625
+ * Tokenize one shell segment. Quotes are kept so a path with spaces stays one
1626
+ * token; the `quoted` flag is what tells `echo "rm -rf /"` apart from an actual
1627
+ * `rm -rf /`.
1628
+ */
1629
+ const shellTokens = (segment) => {
1630
+ const raw = segment.match(/"[^"]*"|'[^']*'|[^\s]+/g) ?? [];
1631
+ return raw.map((t) => ({
1632
+ raw: t,
1633
+ value: t.replace(/^["']|["']$/g, ''),
1634
+ quoted: t.length >= 2 && (t[0] === '"' || t[0] === "'"),
1635
+ }));
1636
+ };
1637
+
1638
+ const commandBase = (value) => String(value).replace(/^.*[\\/]/, '').toLowerCase();
1639
+
1640
+ /**
1641
+ * Strip env assignments and wrappers, then return the real verb and its args.
1642
+ *
1643
+ * Handles the spellings that used to hide a read: `FOO=1 cat x`, `sudo -u me
1644
+ * cat x`, `xargs -0 cat`, `command cat`. It intentionally does not try to be a
1645
+ * shell parser; see the note above `bashReadTargets`.
1646
+ */
1647
+ const parseCommandHead = (tokens) => {
1648
+ let i = 0;
1649
+ while (i < tokens.length) {
1650
+ const entry = tokens[i];
1651
+ if (!entry.quoted && /^[A-Za-z_][A-Za-z0-9_]*=/.test(entry.value)) {
1652
+ i += 1;
1653
+ continue;
1654
+ }
1655
+ const base = commandBase(entry.value);
1656
+ if (!BASH_WRAPPERS.has(base)) return { verb: base, args: tokens.slice(i + 1) };
1657
+ i += 1;
1658
+ // Wrapper options. A few take a scalar operand, which would otherwise be
1659
+ // mistaken for the command name (`sudo -u root cat`).
1660
+ while (i < tokens.length && !tokens[i].quoted && tokens[i].value.startsWith('-')) {
1661
+ const opt = tokens[i].value;
1662
+ i += 1;
1663
+ if (
1664
+ ['-u', '-g', '-p', '-C', '-h', '-r', '-t', '-n', '-I', '-P', '-d', '-L', '-s', '-E', '-a'].includes(opt) &&
1665
+ i < tokens.length
1666
+ ) {
1667
+ i += 1;
1668
+ }
1669
+ }
1670
+ if (base === 'env') {
1671
+ while (i < tokens.length && !tokens[i].quoted && /^[A-Za-z_][A-Za-z0-9_]*=/.test(tokens[i].value)) i += 1;
1672
+ }
1673
+ }
1674
+ return { verb: '', args: [] };
1675
+ };
1676
+
1677
+ /** Default file probe; injected in tests so the rule layer stays disk-free. */
1678
+ const defaultIsFile = (p) => {
1679
+ try {
1680
+ return statSync(p).isFile();
1681
+ } catch {
1682
+ return false;
1683
+ }
1684
+ };
1685
+
1686
+ /** Resolve a shell path token, or null when it is not knowable statically. */
1687
+ const resolveShellPath = (raw, cwd) => {
1688
+ const cleaned = String(raw).replace(/^["']|["']$/g, '');
1689
+ if (!cleaned || cleaned.startsWith('-')) return null;
1690
+ if (/^[a-z]+:\/\//i.test(cleaned)) return null; // URL
1691
+ if (cleaned === '{' || cleaned === '}' || cleaned === '{}' || cleaned === '\\;') return null;
1692
+ if (/^\$/.test(cleaned)) return null; // $VAR / ${VAR}: unknowable here
1693
+ if (cleaned === '~') return process.env.HOME ?? process.env.USERPROFILE ?? null;
1694
+ if (/^~[\\/]/.test(cleaned)) {
1695
+ const home = process.env.HOME ?? process.env.USERPROFILE;
1696
+ return home ? normalize(join(home, cleaned.slice(2))) : null;
1697
+ }
1698
+ return normalize(isAbsolute(cleaned) ? cleaned : join(cwd ?? process.cwd(), cleaned));
1699
+ };
1700
+
1701
+ /** Extract quoted path literals from an interpreter one-liner. */
1702
+ const quotedPaths = (script) =>
1703
+ [...String(script).matchAll(/'([^']+)'|"([^"]+)"/g)].map((m) => m[1] ?? m[2]).filter(Boolean);
1704
+
1705
+ /** Read-call patterns that hide a path inside a one-liner script. */
1706
+ const BASH_READ_CALL = /\b(?:open|read_text|read_text_sync|readFileSync|readFile|readFileSync|read_text)\s*\(/;
1707
+ /** Write-call patterns; `open(..., 'w')` is a write, not a read. */
1708
+ const BASH_WRITE_CALL =
1709
+ /\b(?:writeFileSync|appendFileSync|write_text|write_bytes|writeFile|File\.write|open\s*\([^)]*,\s*['"][wax+])/;
1710
+
1711
+ /**
1712
+ * Extract what a bash command would read, write, or recursively scan.
1713
+ *
1714
+ * This is deliberately a *conservative* static parser, not a shell. It handles
1715
+ * the shapes that hid real bypasses on a real machine:
1716
+ *
1717
+ * - `cd repo && cat src/a.ts` (cwd tracking between segments)
1718
+ * - `git show HEAD:src/a.ts`, `git diff`, `git grep`, `git log -p`
1719
+ * - `find ... -exec cat {} +`, `xargs cat`
1720
+ * - `sh -c 'cat ...'`, `python -c "open(...)"`, `node -e "readFileSync(...)"`
1721
+ * - `cat < src/a.ts`, globs and recursive directory scans
1722
+ * - `sed -i`, `tee`, `cp/mv/rm`, redirections (write targets)
1723
+ *
1724
+ * Anything the parser cannot resolve (a variable path, an unsupported
1725
+ * interpreter) is skipped: over-blocking is handled by the block cap, but a
1726
+ * parser that invents paths would block work that has nothing to do with source.
1727
+ */
1728
+ const parseBashCommand = (command, { config = DEFAULT_CONFIG, cwd = null, isFile = defaultIsFile, exists = () => false } = {}, depth = 0) => {
1729
+ const files = [];
1730
+ const dirs = [];
1731
+ const writes = [];
1732
+ if (typeof command !== 'string' || command === '' || depth > 2) return { files, dirs, writes };
1733
+ let activeCwd = cwd;
1734
+
1735
+ const pushFile = (raw, { allowGlob = true } = {}) => {
1736
+ const candidate = resolveShellPath(raw, activeCwd);
1737
+ if (!candidate) return;
1738
+ if (!isCodeFile(candidate, config)) return;
1739
+ if (isExcluded(candidate, config)) return;
1740
+ if (isFile(candidate)) {
1741
+ files.push(candidate);
1742
+ return;
1743
+ }
1744
+ // A glob (`cat src/*.js`) is a read of everything it expands to. We cannot
1745
+ // enumerate it without a real glob walk, so the pattern itself becomes the
1746
+ // target: after a graph query it is allowed, before one it is not.
1747
+ if (allowGlob && /[*?[\]{}]/.test(candidate)) {
1748
+ const wildcard = candidate.search(/[*?[\]{}]/);
1749
+ const prefix = candidate.slice(0, wildcard);
1750
+ const dir = prefix.endsWith(sep) ? prefix : dirname(prefix);
1751
+ if (dir && exists(dir)) files.push(candidate);
1752
+ }
1753
+ };
1754
+
1755
+ const pushDir = (raw) => {
1756
+ const candidate = resolveShellPath(raw, activeCwd);
1757
+ if (!candidate || !exists(candidate)) return;
1758
+ // Scope a directory through a synthetic code child: the same project-root,
1759
+ // exclusion and code-extension logic then applies without a second copy.
1760
+ const scope = scopeOf(join(candidate, '.gate-probe.ts'), { config, exists });
1761
+ if (!scope.inScope) return;
1762
+ dirs.push(candidate);
1763
+ };
1764
+
1765
+ const pushWrite = (raw) => {
1766
+ const candidate = resolveShellPath(raw, activeCwd);
1767
+ if (!candidate) return;
1768
+ const base = candidate.replace(/\\/g, '/').split('/').pop()?.toLowerCase();
1769
+ if (['/dev/null', 'nul', '/dev/stdout', '/dev/stderr'].includes(base) || candidate.endsWith('/dev/null')) return;
1770
+ writes.push(candidate);
1771
+ };
1772
+
1773
+ for (const segment of splitShellSegments(command)) {
1774
+ if (!segment.trim()) continue;
1775
+ const tokens = shellTokens(segment);
1776
+ if (tokens.length === 0) continue;
1777
+ const { verb, args } = parseCommandHead(tokens);
1778
+ if (!verb) continue;
1779
+ const values = args.map((a) => a.value);
1780
+
1781
+ if (verb === 'cd' || verb === 'pushd') {
1782
+ const target = args.find((a) => a.quoted || !a.value.startsWith('-'));
1783
+ const resolved = target ? resolveShellPath(target.value, activeCwd) : null;
1784
+ if (resolved) activeCwd = resolved;
1785
+ continue;
1786
+ }
1787
+
1788
+ // Input redirection is a read; `<<` is a heredoc, not a file read.
1789
+ for (const match of segment.matchAll(/(?:^|[^0-9])<\s*("(?:[^"]*)"|'(?:[^']*)'|[^\s;&|]+)/g)) {
1790
+ if (match[1].startsWith('<<')) continue;
1791
+ pushFile(match[1]);
1792
+ }
1793
+
1794
+ // Output redirection is a write. `2>&1` and `>/dev/null` are noise.
1795
+ for (const match of segment.matchAll(/(?:^|[^<])(?:\d?>>?)\s*("(?:[^"]*)"|'(?:[^']*)'|[^\s;&|]+)/g)) {
1796
+ const target = match[1];
1797
+ if (target.startsWith('&') || target === '>&1' || target === '>&2') continue;
1798
+ pushWrite(target);
1799
+ }
1800
+
1801
+ if (BASH_READ_VERBS.has(verb)) {
1802
+ if (verb === 'sed' && values.some((v) => /^-[a-z]*i/.test(v) || v.startsWith('--in-place'))) {
1803
+ // In-place sed reads *and* writes; the write side gets the path below,
1804
+ // and treating the same path as a read too would double-report it.
1805
+ } else {
1806
+ for (const value of values) {
1807
+ if (value.startsWith('-')) continue;
1808
+ pushFile(value);
1809
+ // `cp -r src dest`, `rsync -a src/ dest/`: the source may be a tree.
1810
+ if ((verb === 'cp' || verb === 'install' || verb === 'rsync') && !isFile(resolveShellPath(value, activeCwd) ?? '')) {
1811
+ pushDir(value);
1812
+ }
1813
+ }
1814
+ }
1815
+ }
1816
+
1817
+ if (verb === 'git') {
1818
+ const sub = commandBase(values[0] ?? '');
1819
+ const rest = values.slice(1);
1820
+ const dash = rest.indexOf('--');
1821
+ const pathValues = dash >= 0 ? rest.slice(dash + 1) : rest;
1822
+ const readsGit =
1823
+ sub === 'show' || sub === 'diff' || sub === 'grep' || sub === 'blame' || sub === 'cat-file' ||
1824
+ (sub === 'log' && rest.some((v) => v === '-p' || v === '--patch' || v === '-u'));
1825
+ if (readsGit) {
1826
+ const hasPath = pathValues.some((v) => !v.startsWith('-'));
1827
+ for (const value of pathValues) {
1828
+ if (value.startsWith('-')) continue;
1829
+ // `HEAD:src/a.ts` / `HEAD~1:path`
1830
+ const colon = value.lastIndexOf(':');
1831
+ if (colon > 0 && !/^[A-Za-z]:[\\/]/.test(value)) pushFile(value.slice(colon + 1));
1832
+ else pushFile(value);
1833
+ }
1834
+ // No explicit path means the whole worktree is the target.
1835
+ if (!hasPath) pushDir(activeCwd ?? '.');
1836
+ }
1837
+ }
1838
+
1839
+ if (verb === 'find') {
1840
+ const execAt = values.findIndex((v) => ['-exec', '-execdir', '-ok', '-okdir'].includes(v));
1841
+ if (execAt >= 0) {
1842
+ const root = values[0] && !values[0].startsWith('-') ? values[0] : '.';
1843
+ pushDir(root);
1844
+ const end = values.findIndex((v, i) => i > execAt && (v === ';' || v === '+'));
1845
+ const inner = values.slice(execAt + 1, end < 0 ? values.length : end).join(' ');
1846
+ const nested = parseBashCommand(inner, { config, cwd: resolveShellPath(root, activeCwd) ?? activeCwd, isFile, exists }, depth + 1);
1847
+ files.push(...nested.files);
1848
+ dirs.push(...nested.dirs);
1849
+ writes.push(...nested.writes);
1850
+ }
1851
+ if (values.includes('-delete')) {
1852
+ const root = values[0] && !values[0].startsWith('-') ? values[0] : '.';
1853
+ pushDir(root);
1854
+ }
1855
+ }
1856
+
1857
+ if (['sh', 'bash', 'zsh', 'dash', 'ksh', 'cmd', 'powershell', 'pwsh'].includes(verb)) {
1858
+ const flagAt = values.findIndex((v) => ['-c', '/c', '/C', '-Command', '-command'].includes(v));
1859
+ if (flagAt >= 0 && values[flagAt + 1]) {
1860
+ const nested = parseBashCommand(values.slice(flagAt + 1).join(' '), { config, cwd: activeCwd, isFile, exists }, depth + 1);
1861
+ files.push(...nested.files);
1862
+ dirs.push(...nested.dirs);
1863
+ writes.push(...nested.writes);
1864
+ }
1865
+ }
1866
+
1867
+ if (['python', 'python3', 'node', 'nodejs', 'perl', 'ruby'].includes(verb)) {
1868
+ const flagAt = values.findIndex((v) => ['-c', '-e', '--eval', '-Command', '-command'].includes(v));
1869
+ const script = flagAt >= 0 ? values.slice(flagAt + 1).join(' ') : '';
1870
+ if (script) {
1871
+ const paths = quotedPaths(script);
1872
+ const reads = BASH_READ_CALL.test(script);
1873
+ const writesCall = BASH_WRITE_CALL.test(script);
1874
+ for (const p of paths) {
1875
+ if (writesCall) pushWrite(p);
1876
+ else if (reads) pushFile(p);
1877
+ }
1878
+ }
1879
+ }
1880
+
1881
+ if (BASH_WRITE_VERBS.has(verb) && verb !== 'dd') {
1882
+ // cp/mv/rsync/install: the last non-option operand is the destination.
1883
+ if (['cp', 'mv', 'install', 'rsync'].includes(verb)) {
1884
+ const operands = values.filter((v) => !v.startsWith('-'));
1885
+ const tIndex = values.indexOf('-t');
1886
+ if (tIndex >= 0 && values[tIndex + 1]) pushWrite(values[tIndex + 1]);
1887
+ else if (operands.length >= 2) pushWrite(operands[operands.length - 1]);
1888
+ } else if (verb === 'tee') {
1889
+ for (const value of values) if (!value.startsWith('-')) pushWrite(value);
1890
+ } else if (verb === 'sed' || verb === 'perl') {
1891
+ // Handled above for read suppression; in-place operands are files.
1892
+ } else {
1893
+ for (const value of values) if (!value.startsWith('-')) pushWrite(value);
1894
+ }
1895
+ }
1896
+ if (verb === 'dd') {
1897
+ for (const value of values) if (value.startsWith('of=')) pushWrite(value.slice(3));
1898
+ }
1899
+ if (verb === 'sed' && values.some((v) => /^-[a-z]*i/.test(v) || v.startsWith('--in-place'))) {
1900
+ const operands = values.filter((v) => !v.startsWith('-'));
1901
+ // First operand is the script; the rest are files.
1902
+ for (const value of operands.slice(1)) pushWrite(value);
1903
+ }
1904
+ if (verb === 'perl' && values.some((v) => /^-[a-z]*i/.test(v) || v.startsWith('--in-place'))) {
1905
+ const operands = values.filter((v) => !v.startsWith('-'));
1906
+ for (const value of operands.slice(1)) pushWrite(value);
1907
+ }
1908
+
1909
+ // Recursive content scans: `grep -r pat src`, `rg pat src`, `git grep pat`.
1910
+ const recursive =
1911
+ (['grep', 'egrep', 'fgrep'].includes(verb) && values.some((v) => /^-[a-zA-Z]*[rR]/.test(v) || v === '--recursive')) ||
1912
+ (verb === 'rg' && !values.includes('--files')) ||
1913
+ (verb === 'git' && values[0] === 'grep');
1914
+ if (recursive) {
1915
+ const candidates = values.filter((v, i) => i > 0 && !v.startsWith('-'));
1916
+ const pathArgs = candidates.filter((v) => exists(resolveShellPath(v, activeCwd) ?? ''));
1917
+ if (pathArgs.length > 0) for (const p of pathArgs) pushDir(p);
1918
+ else pushDir(activeCwd ?? '.');
1919
+ }
1920
+ }
1921
+
1922
+ const unique = (list) => [...new Set(list)];
1923
+ return { files: unique(files), dirs: unique(dirs), writes: unique(writes) };
1924
+ };
1925
+
1926
+ /** Files a bash command would open for reading (the v2 contract). */
1927
+ export const bashReadTargets = (command, opts = {}) => parseBashCommand(command, opts).files;
1928
+
1929
+ /** Directories a bash command would scan recursively (grep -r, find -exec, …). */
1930
+ export const bashReadDirs = (command, opts = {}) => parseBashCommand(command, opts).dirs;
1931
+
1932
+ /** Paths a bash command would create, overwrite or delete. */
1933
+ export const bashWriteTargets = (command, opts = {}) => parseBashCommand(command, opts).writes;
1934
+
1935
+ /** Is this path disposable build output rather than user data? */
1936
+ const isDisposablePath = (raw, cwd, config) => {
1937
+ const resolved = resolveShellPath(raw, cwd);
1938
+ if (!resolved) return false;
1939
+ const segments = resolved.replace(/\\/g, '/').toLowerCase().split('/').filter(Boolean);
1940
+ if (segments.length <= 1) return false; // drive root / "/"
1941
+ if (segments.some((s) => s === '..')) return false;
1942
+ const home = (process.env.HOME ?? process.env.USERPROFILE ?? '').replace(/\\/g, '/').toLowerCase();
1943
+ if (home && (resolved.replace(/\\/g, '/').toLowerCase() === home || home.startsWith(`${resolved.replace(/\\/g, '/').toLowerCase()}/`))) {
1944
+ return false;
1945
+ }
1946
+ const cwdNorm = cwd ? normalize(cwd).replace(/\\/g, '/').toLowerCase() : null;
1947
+ const resolvedNorm = resolved.replace(/\\/g, '/').toLowerCase();
1948
+ if (cwdNorm && (resolvedNorm === cwdNorm || cwdNorm.startsWith(`${resolvedNorm}/`))) return false;
1949
+ const disposable = new Set((config.destructive_disposable_segments ?? []).map((s) => s.toLowerCase()));
1950
+ return segments.some((s) => disposable.has(s));
1951
+ };
1952
+
1953
+ /**
1954
+ * Is deleting this path unrecoverable, as opposed to "recoverable, but the user
1955
+ * should still be asked"?
1956
+ *
1957
+ * The distinction the gate actually needs is not "does the path look like build
1958
+ * output" (that is `isDisposablePath`) but "can this be undone". Four shapes
1959
+ * cannot: the filesystem root, a top-level directory, anything at or above the
1960
+ * user's home directory, and anything at or above the current working directory
1961
+ * (removing an ancestor removes the working directory with it). A git repository
1962
+ * root that none of those cover still takes its whole history with it, so an
1963
+ * optional probe can name it.
1964
+ *
1965
+ * A `..` segment is judged on the RAW token: `normalize()` collapses it, which
1966
+ * would hide an escape like `data/../..` that lands on the repository parent.
1967
+ *
1968
+ * Everything else - a single file, a named data directory, a build tree - is
1969
+ * recoverable enough to be a question rather than a refusal.
1970
+ *
1971
+ * @param {string} raw the path token as written in the command
1972
+ * @param {string|null} cwd the directory the command runs in
1973
+ * @param {((dir: string) => boolean)|null} isGitRepo optional disk probe; null = never look at disk
1974
+ * @returns {boolean}
1975
+ */
1976
+ const unrecoverableTarget = (raw, cwd, isGitRepo = null) => {
1977
+ const rawPosix = String(raw).replace(/\\/g, '/');
1978
+ if (rawPosix.split('/').includes('..')) return true;
1979
+
1980
+ const resolved = resolveShellPath(raw, cwd);
1981
+ // A path this parser cannot resolve ($VAR, a URL, a shell placeholder) is not
1982
+ // evidence of a catastrophe. Guessing here would block work the parser merely
1983
+ // failed to understand - the same failure mode `parseBashCommand` avoids.
1984
+ if (!resolved) return false;
1985
+
1986
+ const posix = resolved.replace(/\\/g, '/').replace(/\/+$/, '').toLowerCase();
1987
+ if (posix === '' || posix === '/') return true; // filesystem root
1988
+ if (/^[a-z]:$/.test(posix)) return true; // drive root
1989
+ const segments = posix.split('/').filter(Boolean);
1990
+ if (segments.length <= 1) return true; // /tmp, /usr, /home: removing a top-level tree
1991
+
1992
+ const home = (process.env.HOME ?? process.env.USERPROFILE ?? '')
1993
+ .replace(/\\/g, '/')
1994
+ .replace(/\/+$/, '')
1995
+ .toLowerCase();
1996
+ if (home && (posix === home || home.startsWith(`${posix}/`))) return true;
1997
+
1998
+ const cwdPosix = cwd
1999
+ ? normalize(cwd).replace(/\\/g, '/').replace(/\/+$/, '').toLowerCase()
2000
+ : '';
2001
+ if (cwdPosix && (posix === cwdPosix || cwdPosix.startsWith(`${posix}/`))) return true;
2002
+
2003
+ if (typeof isGitRepo === 'function') {
2004
+ try {
2005
+ if (isGitRepo(resolved)) return true;
2006
+ } catch {
2007
+ // A probe that throws is not evidence of anything; fall through to the
2008
+ // recoverable branch instead of turning a filesystem hiccup into a block.
2009
+ }
2010
+ }
2011
+ return false;
2012
+ };
2013
+
2014
+ /** Severity of deleting `raw`: `high` when it cannot be undone, else `confirm`. */
2015
+ const targetSeverity = (raw, cwd, isGitRepo = null) => {
2016
+ if (typeof raw !== 'string' || raw === '') return 'high';
2017
+ return unrecoverableTarget(raw, cwd, isGitRepo) ? 'high' : 'confirm';
2018
+ };
2019
+
2020
+ /**
2021
+ * Resolve the tier for a permission category.
2022
+ *
2023
+ * Precedence is deliberately asymmetric: **tightening beats loosening**.
2024
+ *
2025
+ * policy `deny` -> deny (the user said "never"; a session cannot reopen it)
2026
+ * session `deny` -> deny (a session may always be stricter than its policy)
2027
+ * session `allow`-> allow (the grant made in the dialog)
2028
+ * policy `allow` -> allow (the grant made through `/gate`)
2029
+ * otherwise -> confirm
2030
+ *
2031
+ * The asymmetry is the whole point: if loosening won, an agent that talked a
2032
+ * user into one session grant would also undo a permanent `deny`.
2033
+ *
2034
+ * @param {string} category
2035
+ * @param {object} config
2036
+ * @param {object} [state] session state (its grants are memory-only)
2037
+ * @returns {'allow'|'confirm'|'deny'}
2038
+ */
2039
+ export const effectiveDestructiveTier = (category, config, state) => {
2040
+ const policyTier = config?.destructive_grants?.[category];
2041
+ const sessionTier =
2042
+ state?.destructiveGrants instanceof Map
2043
+ ? (state.destructiveGrants.get(category) ?? null)
2044
+ : (state?.destructiveGrants?.[category] ?? null);
2045
+
2046
+ if (policyTier === 'deny') return 'deny';
2047
+ if (sessionTier === 'deny') return 'deny';
2048
+ if (sessionTier === 'allow') return 'allow';
2049
+ if (policyTier === 'allow') return 'allow';
2050
+ return 'confirm';
2051
+ };
2052
+
2053
+ /**
2054
+ * Resolve the destructive gate's mode: session override first, then the global
2055
+ * setting.
2056
+ *
2057
+ * Unlike `effectiveDestructiveTier` (where tightening beats loosening), the
2058
+ * session override wins in BOTH directions. The threat models differ: a category
2059
+ * grant can be talked out of a user through a dialog the AGENT caused, so a
2060
+ * session grant must not undo a permanent `deny`; the mode is only reachable
2061
+ * through a slash command the user types, which an agent cannot invoke.
2062
+ * Precedence here is therefore "the most recent explicit user decision wins".
2063
+ *
2064
+ * An expired `destructive_mode_until` reads as `enforce` without rewriting the
2065
+ * file - no timer, no background job, and the next `/gate mode` shows the expiry
2066
+ * for what it is.
2067
+ *
2068
+ * @param {object} config
2069
+ * @param {object} [state] session state (its `destructiveMode` is memory-only)
2070
+ * @param {number} [now]
2071
+ * @returns {'enforce'|'bypass'}
2072
+ */
2073
+ export const effectiveDestructiveMode = (config, state, now = Date.now()) => {
2074
+ const sessionMode = state?.destructiveMode;
2075
+ if (DESTRUCTIVE_MODES.includes(sessionMode)) return sessionMode;
2076
+
2077
+ if (normalizeDestructiveMode(config?.destructive_mode) !== 'bypass') return 'enforce';
2078
+ const until = normalizeDestructiveModeUntil(config?.destructive_mode_until);
2079
+ if (until > 0 && now >= until) return 'enforce';
2080
+ return 'bypass';
2081
+ };
2082
+
2083
+ export const isDestructiveBypass = (config, state, now = Date.now()) =>
2084
+ effectiveDestructiveMode(config, state, now) === 'bypass';
2085
+
2086
+ /** How long until a bypass expires, in ms; `null` when it does not expire. */
2087
+ export const destructiveModeRemainingMs = (config, now = Date.now()) => {
2088
+ if (normalizeDestructiveMode(config?.destructive_mode) !== 'bypass') return null;
2089
+ const until = normalizeDestructiveModeUntil(config?.destructive_mode_until);
2090
+ if (until <= 0) return null;
2091
+ const left = until - now;
2092
+ return left > 0 ? left : 0;
2093
+ };
2094
+
2095
+ /**
2096
+ * Where the machine-local gate override lives.
2097
+ *
2098
+ * ShipGate owns this gate - the bridge stopped shipping it - so the override
2099
+ * sits beside the policy truth instead of in the bridge's old directory. One
2100
+ * configuration root per machine: a tier the operator cannot find is a tier
2101
+ * nobody audits. Deliberately outside every repository: a permission is a
2102
+ * property of the machine and its user, not of the code being worked on.
2103
+ */
2104
+ export const machineGateConfigPath = (home = null) => {
2105
+ const base = home ?? process.env.HOME ?? process.env.USERPROFILE ?? '';
2106
+ return base ? join(base, '.config', 'shipgate', 'machine-override.json') : null;
2107
+ };
2108
+
2109
+ /**
2110
+ * The pre-ShipGate override path, read-only fallback only.
2111
+ *
2112
+ * Machines that predate this gate kept their grants there. It is never a write
2113
+ * target again: a grant created today lands in `machineGateConfigPath()`. The
2114
+ * file may be deleted at any time - the gate then runs on the shipped policy.
2115
+ */
2116
+ export const legacyMachineOverridePath = (home = null) => {
2117
+ const base = home ?? process.env.HOME ?? process.env.USERPROFILE ?? '';
2118
+ return base ? join(base, '.config', 'agent-config-bridge', 'gate-policy.json') : null;
2119
+ };
2120
+
2121
+ /**
2122
+ * The only override keys the gate accepts from disk.
2123
+ *
2124
+ * `destructive_mode` is deliberately absent. One hand-edited `bypass` with
2125
+ * `destructive_mode_until: 0` used to outrank the policy truth forever (the
2126
+ * merge is `{ ...policy.config, ...override }`) while `doctor` only reported
2127
+ * "a second policy file", so nothing on the surface said the gate had stopped
2128
+ * enforcing. The mode therefore has exactly one source: `gate-policy.json`,
2129
+ * reached through `shipgate policy --mode`. Grants and the protected list stay
2130
+ * overridable - those are per-machine facts, not a global policy decision.
2131
+ */
2132
+ const OVERRIDE_ALLOWED_KEYS = ['destructive_grants', 'protected_worktrees'];
2133
+
2134
+ const sanitizeOverride = (doc) => {
2135
+ const config = doc?.config;
2136
+ if (!config || typeof config !== 'object' || Array.isArray(config)) return null;
2137
+ const kept = {};
2138
+ for (const key of OVERRIDE_ALLOWED_KEYS) {
2139
+ if (config[key] !== undefined) kept[key] = config[key];
2140
+ }
2141
+ return Object.keys(kept).length > 0 ? { config: kept } : null;
2142
+ };
2143
+
2144
+ /**
2145
+ * Read one override file. `undefined` = no file, `null` = file without usable
2146
+ * keys, object = usable override. The distinction matters: an existing file
2147
+ * that clears the grants must win over a legacy file that still has them.
2148
+ */
2149
+ const readOneOverride = (file) => {
2150
+ if (!file) return undefined;
2151
+ let raw;
2152
+ try {
2153
+ raw = readFileSync(file, 'utf8');
2154
+ } catch {
2155
+ return undefined;
2156
+ }
2157
+ let parsed = null;
2158
+ try {
2159
+ parsed = JSON.parse(raw);
2160
+ } catch {
2161
+ return null;
2162
+ }
2163
+ return sanitizeOverride(parsed);
2164
+ };
2165
+
2166
+ /**
2167
+ * The machine-local override as written, or null when absent or unparsable.
2168
+ *
2169
+ * One reader for the file: `applyMachineOverride` merges it, and
2170
+ * `machineProtectedListProblems` reports what the merge had to drop. The new
2171
+ * path wins whenever it exists; the legacy path is read only when the new file
2172
+ * is missing, so an untouched machine keeps its grants through the upgrade.
2173
+ */
2174
+ const readMachineOverride = (home = null) => {
2175
+ const fresh = readOneOverride(machineGateConfigPath(home));
2176
+ if (fresh !== undefined) return fresh;
2177
+ return readOneOverride(legacyMachineOverridePath(home)) ?? null;
2178
+ };
2179
+
2180
+ /**
2181
+ * Entries of the machine-local `protected_worktrees` that are being ignored
2182
+ * (ADR-015). The list is a red line that exists only for as long as it is
2183
+ * right, and it is maintained by hand; a relative path in it silently protects
2184
+ * nothing. An adapter prints these when a session starts.
2185
+ */
2186
+ export const machineProtectedListProblems = (home = null) => {
2187
+ const raw = readMachineOverride(home)?.config?.protected_worktrees;
2188
+ return raw === undefined || raw === null ? [] : droppedProtectedWorktrees(raw);
2189
+ };
2190
+
2191
+ /**
2192
+ * Merge the machine-local `config` override into a loaded policy.
2193
+ *
2194
+ * The bridge already does this at install time, but a grant must take effect the
2195
+ * moment the user makes it, not at the next `apply`. Reading it here keeps one
2196
+ * source of truth for both paths: the installed `policy.json` and the live
2197
+ * override never disagree about a tier.
2198
+ */
2199
+ export const applyMachineOverride = (policy, home = null) => {
2200
+ if (!machineGateConfigPath(home)) return policy;
2201
+ // Absent or unreadable: the shipped policy stands. A broken override must
2202
+ // not disable the gate, and it must not silently reset grants either.
2203
+ const parsed = readMachineOverride(home);
2204
+ const override = parsed?.config;
2205
+ if (!override || typeof override !== 'object' || Array.isArray(override)) return policy;
2206
+
2207
+ const config = { ...policy.config, ...override };
2208
+ // Grants merge per key. Replacing the object wholesale would make a single
2209
+ // granted category reset the other six to "not configured".
2210
+ const grants = { ...(policy.config.destructive_grants ?? {}) };
2211
+ if (override.destructive_grants && typeof override.destructive_grants === 'object') {
2212
+ for (const [name, tier] of Object.entries(override.destructive_grants)) {
2213
+ if (
2214
+ Object.prototype.hasOwnProperty.call(DESTRUCTIVE_CATEGORIES, name) &&
2215
+ DESTRUCTIVE_TIERS.includes(tier)
2216
+ ) {
2217
+ grants[name] = tier;
2218
+ }
2219
+ }
2220
+ }
2221
+ config.destructive_grants = grants;
2222
+ // The mode keys come from a hand-editable file, so they get the same
2223
+ // sanitization `normalizePolicy` applies. Without this a typo like
2224
+ // `"destructive_mode": "Bypass "` would merge straight into the live config and
2225
+ // silently decide the mode by string inequality.
2226
+ config.destructive_mode = normalizeDestructiveMode(config.destructive_mode);
2227
+ config.destructive_mode_until = normalizeDestructiveModeUntil(config.destructive_mode_until);
2228
+ // The protected-worktree list lives in this same file. It is a red line, so a
2229
+ // malformed value may not reach the classifier raw. Red lines only ever grow:
2230
+ // an override may ADD a protected tree, never drop one the policy declared
2231
+ // (`mergePolicy` unions them at install time; doing it again here keeps the
2232
+ // live gate from being weaker than the installed document).
2233
+ const policyRoots = normalizeProtectedWorktrees(policy.config?.protected_worktrees);
2234
+ const overrideRoots = normalizeProtectedWorktrees(config.protected_worktrees);
2235
+ config.protected_worktrees = [...new Set([...policyRoots, ...overrideRoots])];
2236
+ return { ...policy, config };
2237
+ };
2238
+
2239
+ /**
2240
+ * Detect a destructive shell operation that must not run unattended.
2241
+ *
2242
+ * This is Layer 0 in mechanical form: the thinking rule says "know the root
2243
+ * cause and the impact before you act", and a recursive delete / hard reset /
2244
+ * force push is the class of action where acting first is unrecoverable. The
2245
+ * rule is intentionally narrow: build directories (`node_modules`, `dist`, …)
2246
+ * and temp directories remain disposable, so routine cleanup is not blocked.
2247
+ *
2248
+ * @returns {{why: string, segment: string, severity: 'high'|'confirm'}|null}
2249
+ */
2250
+ /**
2251
+ * Host-level destructive verbs, matched against the analysed command head.
2252
+ *
2253
+ * `mkfs` needs a suffix family so `mkfs.ext4` / `mkfs.xfs` are covered, and
2254
+ * `diskpart.exe` needs its extension; everything else is an exact verb, because a
2255
+ * prefix silently swallows unrelated programs. That is exactly how `format` used to
2256
+ * eat PowerShell's read-only `Format-Table` / `Format-List` / `Format-Wide` /
2257
+ * `Format-Custom` / `Format-Hex` cmdlets: `format` + `-table` matched `/^format/`,
2258
+ * so every `... | Format-Table` inspection pipeline was reported as disk formatting.
2259
+ * `format` is therefore an exact verb now, and `format-volume` — the one cmdlet in
2260
+ * that family that really wipes a volume — is named explicitly so the tightening
2261
+ * does not open a hole.
2262
+ */
2263
+ const HOST_DESTRUCTIVE_VERB =
2264
+ /^(?:mkfs(?:\.[a-z0-9]+)?|fdisk|parted|diskpart(?:\.exe)?|format(?:\.(?:com|exe))?|format-volume)$/;
2265
+
2266
+ /**
2267
+ * Raw block devices, where `dd of=` is unrecoverable rather than merely risky.
2268
+ *
2269
+ * Matched by device family, not by a prefix on the whole path: `/dev/sda` and
2270
+ * `/dev/nvme0n1` are devices, `/dev/shm/x` is memory-backed scratch and a plain
2271
+ * file target is a permission the user may grant.
2272
+ */
2273
+ const RAW_DEVICE =
2274
+ /^\/dev\/(?:sd[a-z]|nvme\d|hd[a-z]|vd[a-z]|xvd[a-z]|disk\d|mmcblk\d|loop\d|dm-\d|md\d|sr\d|nbd\d|zram\d)|^\\[.?]\\physicaldrive/i;
2275
+
2276
+ /**
2277
+ * Clients that take a SQL statement as an argument.
2278
+ *
2279
+ * `psql -c "drop database prod"` runs the identical statement a bare
2280
+ * `drop database prod` would. The DDL pattern below is anchored at the verb, so
2281
+ * before this list existed the single category that starts at `deny` could be
2282
+ * bypassed by typing a client name in front of the statement.
2283
+ *
2284
+ * Scanned only for these verbs on purpose: matching the pattern anywhere in
2285
+ * every command would also fire on `echo "drop table x"` and on documentation
2286
+ * quotes, which is the class of false positive that gets a gate uninstalled.
2287
+ */
2288
+ const DB_CLIENTS = new Set([
2289
+ 'psql', 'pgcli', 'mysql', 'mysqlsh', 'mariadb', 'sqlite3', 'sqlcmd', 'clickhouse-client',
2290
+ 'cockroach', 'duckdb', 'usql',
2291
+ ]);
2292
+
2293
+ /** A DDL statement appears anywhere in the payload (used for client arguments). */
2294
+ const DDL_ANYWHERE = /(?:^|[\s'"`(])(?:drop\s+(?:table|database|schema)|truncate\s+table)\b/;
2295
+
2296
+ /**
2297
+ * mongo shells express the same act in JavaScript (`db.dropDatabase()`) rather
2298
+ * than SQL, so the SQL pattern above cannot see it.
2299
+ */
2300
+ const MONGO_DROP = /\.(?:dropdatabase|dropcollection|drop)\s*\(/i;
2301
+
2302
+ /**
2303
+ * Normalise `config.protected_worktrees` (see DEFAULT_CONFIG for what it is).
2304
+ *
2305
+ * A kept entry is a non-empty string, `~` expanded, absolute, without a
2306
+ * trailing separator. Everything else is dropped rather than guessed at: a
2307
+ * relative path would resolve against whatever directory the session happens
2308
+ * to sit in and so protect the wrong tree, and a number is a typo. Dropping is
2309
+ * the visible failure (`/gate list` prints the list that actually took
2310
+ * effect); guessing would be the invisible one.
2311
+ */
2312
+ export const normalizeProtectedWorktrees = (raw) => {
2313
+ const entries = Array.isArray(raw) ? raw : typeof raw === 'string' ? [raw] : [];
2314
+ const home = process.env.HOME ?? process.env.USERPROFILE ?? null;
2315
+ const out = [];
2316
+ for (const entry of entries) {
2317
+ if (typeof entry !== 'string') continue;
2318
+ let value = entry.trim();
2319
+ if (!value) continue;
2320
+ if (value === '~' || /^~[\\/]/.test(value)) {
2321
+ if (!home) continue;
2322
+ value = value === '~' ? home : join(home, value.slice(2));
2323
+ }
2324
+ if (!isAbsolute(value)) continue;
2325
+ const resolved = normalize(value).replace(/[\\/]+$/, '');
2326
+ if (resolved && !out.includes(resolved)) out.push(resolved);
2327
+ }
2328
+ return out;
2329
+ };
2330
+
2331
+ /**
2332
+ * Hand-written entries `normalizeProtectedWorktrees` had to drop, each with the
2333
+ * reason (ADR-015).
2334
+ *
2335
+ * Every dropped entry is a directory its owner believes is protected and is
2336
+ * not. Returning them lets an adapter say so when a session starts, instead of
2337
+ * leaving the typo to be found by the command it should have stopped. Blank
2338
+ * entries are not reported: they protect nothing and claim nothing.
2339
+ */
2340
+ export const droppedProtectedWorktrees = (raw) => {
2341
+ const entries = Array.isArray(raw) ? raw : [raw];
2342
+ const out = [];
2343
+ for (const entry of entries) {
2344
+ if (typeof entry !== 'string') {
2345
+ if (entry !== undefined && entry !== null) out.push({ entry: String(entry), why: '不是字符串' });
2346
+ continue;
2347
+ }
2348
+ const value = entry.trim();
2349
+ if (!value || isAbsolute(value)) continue;
2350
+ if (value === '~' || /^~[\\/]/.test(value)) {
2351
+ if (process.env.HOME ?? process.env.USERPROFILE ?? null) continue;
2352
+ out.push({ entry: value, why: '~ 展不开(HOME / USERPROFILE 都没设)' });
2353
+ continue;
2354
+ }
2355
+ out.push({ entry: value, why: '不是绝对路径' });
2356
+ }
2357
+ return out;
2358
+ };
2359
+
2360
+ /**
2361
+ * git's own options, i.e. the ones that may sit between `git` and the
2362
+ * subcommand: `git -C <dir> stash`, `git --work-tree=<dir> reset --hard`.
2363
+ *
2364
+ * They matter here because two of them MOVE the command into another
2365
+ * repository without a `cd`. A rule that reads the subcommand off the first
2366
+ * argument sees neither `git -C elsewhere stash` nor `git -C elsewhere reset
2367
+ * --hard` - which was true of every git rule in this file until 2026-11-25.
2368
+ * The lists are the OPTIONS section of `git --help`; a token that is in none
2369
+ * of them is the subcommand.
2370
+ */
2371
+ const GIT_OPTIONS_TAKING_AN_OPERAND = new Set([
2372
+ '-C', '-c', '--git-dir', '--work-tree', '--namespace', '--exec-path', '--super-prefix',
2373
+ ]);
2374
+ const GIT_OPTIONS_STANDING_ALONE = new Set([
2375
+ '-p', '-P', '--paginate', '--no-pager', '--bare', '--literal-pathspecs', '--glob-pathspecs',
2376
+ '--noglob-pathspecs', '--icase-pathspecs', '--no-replace-objects', '--no-optional-locks',
2377
+ ]);
2378
+ const GIT_OPTIONS_WRITTEN_WITH_EQUALS = new Set([
2379
+ '--git-dir', '--work-tree', '--namespace', '--super-prefix', '--exec-path', '--config-env',
2380
+ ]);
2381
+
2382
+ /**
2383
+ * Split a `git` argument list into the subcommand, its arguments, and the
2384
+ * directory git will run in once `-C` / `--work-tree` have been applied.
2385
+ *
2386
+ * `dir` is `null` when that directory cannot be known statically (it started
2387
+ * out unknown and a relative `-C` followed, or the operand was `$VAR`). The
2388
+ * caller must read that as "is this a protected worktree? - unanswered", and
2389
+ * must not turn it into a claim either way.
2390
+ */
2391
+ const gitInvocation = (values, cwd) => {
2392
+ let dir = typeof cwd === 'string' && cwd !== '' ? cwd : null;
2393
+ let i = 0;
2394
+ // `-C` is cumulative and relative to the previous `-C`, exactly as in git.
2395
+ const moveTo = (operand) => {
2396
+ if (typeof operand !== 'string' || operand === '') {
2397
+ dir = null;
2398
+ return;
2399
+ }
2400
+ if (dir === null && !isAbsolute(operand)) {
2401
+ dir = null;
2402
+ return;
2403
+ }
2404
+ const resolved = resolveShellPath(operand, dir);
2405
+ dir = resolved === null ? null : normalize(resolved);
2406
+ };
2407
+ while (i < values.length) {
2408
+ const value = values[i];
2409
+ if (GIT_OPTIONS_TAKING_AN_OPERAND.has(value)) {
2410
+ if (value === '-C' || value === '--work-tree') moveTo(values[i + 1]);
2411
+ i += 2;
2412
+ continue;
2413
+ }
2414
+ if (GIT_OPTIONS_STANDING_ALONE.has(value)) {
2415
+ i += 1;
2416
+ continue;
2417
+ }
2418
+ const equals = value.indexOf('=');
2419
+ if (equals > 2 && GIT_OPTIONS_WRITTEN_WITH_EQUALS.has(value.slice(0, equals))) {
2420
+ if (value.startsWith('--work-tree=')) moveTo(value.slice('--work-tree='.length));
2421
+ i += 1;
2422
+ continue;
2423
+ }
2424
+ break;
2425
+ }
2426
+ return {
2427
+ sub: i < values.length ? commandBase(values[i]) : '',
2428
+ rest: values.slice(i + 1),
2429
+ dir,
2430
+ };
2431
+ };
2432
+
2433
+ /**
2434
+ * The protected worktree `dir` sits in, or null. A PARENT of a protected root
2435
+ * is not itself protected: a command reaches into the root from there by
2436
+ * naming it (`git -C <root> ...`), and `gitInvocation` has already resolved
2437
+ * that to `dir`.
2438
+ */
2439
+ export const protectedRootOf = (dir, config) => {
2440
+ if (!dir) return null;
2441
+ const target = normalize(String(dir).replace(/\\/g, '/'));
2442
+ return normalizeProtectedWorktrees(config.protected_worktrees).find((root) => withinRoot(root, target)) ?? null;
2443
+ };
2444
+
2445
+ /**
2446
+ * Whether `content` replaces the gate file wholesale while leaving out the
2447
+ * protected-worktree list the file on disk still carries.
2448
+ *
2449
+ * Recognised by shape - `content` parses as a JSON object, i.e. it is a whole
2450
+ * document and not a fragment - because a fragment cannot be judged: an edit
2451
+ * that rewrites one line says nothing about the lines it leaves alone. With no
2452
+ * readable file behind the path there is nothing being dropped.
2453
+ */
2454
+ const dropsProtectedList = (content, path, fs) => {
2455
+ let doc;
2456
+ try {
2457
+ doc = JSON.parse(content);
2458
+ } catch {
2459
+ return false;
2460
+ }
2461
+ if (!doc || typeof doc !== 'object' || Array.isArray(doc)) return false;
2462
+ let current = null;
2463
+ try {
2464
+ current = fs?.readText?.(path) ?? null;
2465
+ } catch {
2466
+ current = null;
2467
+ }
2468
+ return typeof current === 'string' && /protected_worktrees/.test(current);
2469
+ };
2470
+
2471
+ /**
2472
+ * Whether a git subcommand discards or replaces the working tree's uncommitted
2473
+ * content, and how the gate treats it OUTSIDE a protected worktree.
2474
+ *
2475
+ * `permission: true` - irreversibly destroys uncommitted work, the way
2476
+ * `reset --hard` does. A `git-history` confirmation in an
2477
+ * ordinary repository (ADR-012).
2478
+ * `permission: false` - reversible there, so an ordinary repository does not
2479
+ * ask: `git stash` keeps what it removes, `--autostash`
2480
+ * puts it back, `git rm` is how a file is retired. Only a
2481
+ * protected worktree makes these a red line, because
2482
+ * there "removed from the working tree" already IS the
2483
+ * outage, whatever becomes of the saved copy.
2484
+ *
2485
+ * Read-only and history commands never match - `status`, `diff`, `log`, `add`,
2486
+ * `commit`, `show HEAD:<path>` leave the working tree alone - and neither does
2487
+ * anything that only puts state back (`stash pop` / `apply` / `branch`).
2488
+ */
2489
+ const gitWorktreeWipe = (sub, rest) => {
2490
+ // Flags after `--` belong to the pathspec, not to the command.
2491
+ const pathspecAt = rest.indexOf('--');
2492
+ const opts = pathspecAt >= 0 ? rest.slice(0, pathspecAt) : rest;
2493
+ if (opts.includes('-h') || opts.includes('--help')) return null;
2494
+ const short = (letter) =>
2495
+ opts.some((v) => v.length > 1 && v[0] === '-' && v[1] !== '-' && [...v].slice(1).includes(letter));
2496
+ const long = (name) => opts.includes(name);
2497
+ const dryRun = short('n') || long('--dry-run');
2498
+
2499
+ switch (sub) {
2500
+ case 'stash': {
2501
+ // `git stash [-p|-S|-k|-q|-u|-a|-m <msg>] [--] [<pathspec>…]` is a push;
2502
+ // the subcommand word is optional, so the first non-option token is only
2503
+ // an action when it is one of these.
2504
+ const action = opts[0];
2505
+ if (['list', 'show', 'pop', 'apply', 'branch', 'create', 'store'].includes(action)) return null;
2506
+ if (action === 'drop' || action === 'clear') {
2507
+ return { why: `git stash ${action}`, permission: true };
2508
+ }
2509
+ return { why: 'git stash removes uncommitted changes from the working tree', permission: false };
2510
+ }
2511
+ case 'reset':
2512
+ if (long('--hard')) return { why: 'git reset --hard discards uncommitted work', permission: true };
2513
+ if (long('--merge')) return { why: 'git reset --merge discards uncommitted work', permission: true };
2514
+ return null;
2515
+ case 'clean':
2516
+ if (dryRun) return null;
2517
+ return short('f') || long('--force')
2518
+ ? { why: 'git clean --force deletes untracked files', permission: true }
2519
+ : null;
2520
+ case 'checkout':
2521
+ if (short('f') || long('--force')) {
2522
+ return { why: 'git checkout --force discards uncommitted work', permission: true };
2523
+ }
2524
+ if (rest.includes('--') || rest.includes('.') || long('--ours') || long('--theirs')) {
2525
+ return { why: 'git checkout -- . discards uncommitted work', permission: true };
2526
+ }
2527
+ return null;
2528
+ case 'restore': {
2529
+ // `--staged` alone touches the index only; `--staged --worktree` does not.
2530
+ const stagedOnly = (long('--staged') || short('S')) && !(long('--worktree') || short('W'));
2531
+ return stagedOnly ? null : { why: 'git restore discards uncommitted work', permission: true };
2532
+ }
2533
+ case 'switch':
2534
+ return short('f') || long('--force') || long('--discard-changes')
2535
+ ? { why: 'git switch --force discards uncommitted work', permission: true }
2536
+ : null;
2537
+ case 'read-tree':
2538
+ return long('--reset')
2539
+ ? { why: 'git read-tree --reset overwrites the index and working tree', permission: true }
2540
+ : null;
2541
+ case 'checkout-index':
2542
+ return short('f') || long('--force')
2543
+ ? { why: 'git checkout-index --force overwrites working tree files', permission: true }
2544
+ : null;
2545
+ case 'update-ref':
2546
+ return (short('d') || long('--delete')) && rest.some((v) => v === 'refs/stash' || v.startsWith('refs/stash/'))
2547
+ ? { why: 'git update-ref -d refs/stash destroys every saved stash', permission: true }
2548
+ : null;
2549
+ case 'rm':
2550
+ return long('--cached') || dryRun
2551
+ ? null
2552
+ : { why: 'git rm deletes tracked files from the working tree', permission: false };
2553
+ default:
2554
+ if (['pull', 'fetch', 'rebase', 'merge', 'revert', 'cherry-pick', 'am'].includes(sub) && long('--autostash')) {
2555
+ return { why: `git ${sub} --autostash stashes uncommitted changes before it runs`, permission: false };
2556
+ }
2557
+ return null;
2558
+ }
2559
+ };
2560
+
2561
+ export const bashDestructiveFinding = (command, { config = DEFAULT_CONFIG, cwd = null, isGitRepo = null } = {}, depth = 0) => {
2562
+ if (typeof command !== 'string' || command === '' || depth > 2) return null;
2563
+ const allow = (config.destructive_allow_patterns ?? []).some((src) => {
2564
+ try {
2565
+ return new RegExp(src).test(command);
2566
+ } catch {
2567
+ return false;
2568
+ }
2569
+ });
2570
+ if (allow) return null;
2571
+
2572
+ let activeCwd = cwd;
2573
+ // Quote-aware on purpose. A plain split tore `bash -c "cd <dir> && git stash"`
2574
+ // into `bash -c "cd <dir>` and `git stash"`, so the nested shell was never
2575
+ // entered AND the torn-off half read as an unknown subcommand: nothing was
2576
+ // found, in any directory (ADR-015).
2577
+ for (const segment of splitShellSegments(command)) {
2578
+ if (!segment.trim()) continue;
2579
+ const tokens = shellTokens(segment);
2580
+ if (tokens.length === 0) continue;
2581
+ const { verb, args } = parseCommandHead(tokens);
2582
+ if (!verb) continue;
2583
+ const values = args.map((a) => a.value);
2584
+ /**
2585
+ * `high` - a guardrail: unrecoverable, and no grant can reach it.
2586
+ * `confirm` - a permission: the category's tier decides allow/ask/deny.
2587
+ *
2588
+ * `high` is the default on purpose: a branch that forgets to pass a
2589
+ * severity keeps the un-grantable behaviour instead of silently becoming a
2590
+ * question the user can click through.
2591
+ *
2592
+ * `protectedRoot` is set only by the protected-worktree red line (ADR-015),
2593
+ * so the check can explain that one in its own words.
2594
+ */
2595
+ const finding = (why, severity = 'high', category = null, protectedRoot = null) => ({
2596
+ why,
2597
+ segment: segment.trim().slice(0, 200),
2598
+ severity,
2599
+ category,
2600
+ protectedRoot,
2601
+ });
2602
+
2603
+ if (['cd', 'pushd', 'set-location', 'sl', 'chdir'].includes(verb)) {
2604
+ const target = args.find((a) => a.quoted || !a.value.startsWith('-'));
2605
+ const resolved = target ? resolveShellPath(target.value, activeCwd) : null;
2606
+ if (resolved) activeCwd = resolved;
2607
+ continue;
2608
+ }
2609
+
2610
+ // Recursively inspect a nested shell: `bash -c 'git reset --hard'`.
2611
+ if (['sh', 'bash', 'zsh', 'dash', 'ksh', 'cmd', 'powershell', 'pwsh'].includes(verb)) {
2612
+ const flagAt = values.findIndex((v) => ['-c', '/c', '/C', '-Command', '-command'].includes(v));
2613
+ if (flagAt >= 0 && values[flagAt + 1]) {
2614
+ const nested = bashDestructiveFinding(
2615
+ values.slice(flagAt + 1).join(' '),
2616
+ { config, cwd: activeCwd, isGitRepo },
2617
+ depth + 1,
2618
+ );
2619
+ if (nested) return nested;
2620
+ }
2621
+ continue;
2622
+ }
2623
+
2624
+ if (verb === 'rm' || verb === 'rmdir' || verb === 'unlink') {
2625
+ const recursive = values.some((v) => /^-[a-z]*[rR]/.test(v) || v === '--recursive');
2626
+ const force = values.some((v) => /^-[a-z]*f/.test(v) || v === '--force');
2627
+ const targets = values.filter((v) => !v.startsWith('-'));
2628
+ const dangerous = targets.filter((t) => !isDisposablePath(t, activeCwd, config));
2629
+ if (dangerous.length > 0 && (recursive || force || targets.length > 1)) {
2630
+ // One unrecoverable target is enough to make the whole command high:
2631
+ // `rm -rf scratch.txt $HOME` must not become a question.
2632
+ const severity = dangerous.some((t) => unrecoverableTarget(t, activeCwd, isGitRepo))
2633
+ ? 'high'
2634
+ : 'confirm';
2635
+ return finding(
2636
+ `${verb} ${recursive ? 'recursive ' : ''}${force ? 'forced ' : ''}on ${dangerous[0]}`,
2637
+ severity,
2638
+ 'delete',
2639
+ );
2640
+ }
2641
+ }
2642
+
2643
+ if (verb === 'git') {
2644
+ const { sub, rest, dir } = gitInvocation(values, activeCwd);
2645
+ const wipe = gitWorktreeWipe(sub, rest);
2646
+ if (wipe) {
2647
+ // ---- red line: a protected worktree ------------------------------
2648
+ // First, and before any permission logic, for the same reason the
2649
+ // `severity === 'high'` return sits ahead of the bypass check in
2650
+ // `no-destructive-bash`: in this directory "uncommitted" means "in
2651
+ // use", so removing it is an outage whether or not a copy survives in
2652
+ // a stash. See `gitWorktreeWipe` for why plain `git stash` is a red
2653
+ // line here and nothing at all everywhere else.
2654
+ const root = protectedRootOf(dir, config);
2655
+ if (root) {
2656
+ return finding(wipe.why, 'high', 'git-history', root);
2657
+ }
2658
+ if (wipe.permission) return finding(wipe.why, 'confirm', 'git-history');
2659
+ }
2660
+
2661
+ // Every git branch below is a *permission*, not a guardrail: discarding
2662
+ // local work or rewriting a branch you own is a normal thing to want, and
2663
+ // the user can grant it (`/gate grant git-history`). The guardrail tier is
2664
+ // reserved for things no grant can undo.
2665
+ if (sub === 'push' && rest.some((v) => v === '--force' || v === '--force-with-lease' || /^-f$/.test(v))) {
2666
+ return finding('git push --force rewrites shared history', 'confirm', 'git-force-push');
2667
+ }
2668
+ if (sub === 'branch' && rest.some((v) => /^-[a-zA-Z]*D/.test(v) || v === '--delete')) {
2669
+ return finding('git branch --delete removes a branch', 'confirm', 'git-history');
2670
+ }
2671
+ if (['filter-branch', 'filter-repo'].includes(sub)) {
2672
+ return finding(`git ${sub} rewrites history`, 'confirm', 'git-history');
2673
+ }
2674
+ }
2675
+
2676
+ if (verb === 'find' && values.includes('-delete')) {
2677
+ const root = values.find((v) => !v.startsWith('-')) ?? '.';
2678
+ if (!isDisposablePath(root, activeCwd, config)) {
2679
+ return finding(`find ${root} -delete`, targetSeverity(root, activeCwd, isGitRepo), 'delete');
2680
+ }
2681
+ }
2682
+
2683
+ if (verb === 'dd' && values.some((v) => v.startsWith('of='))) {
2684
+ const target = values.find((v) => v.startsWith('of=')).slice(3);
2685
+ if (['/dev/null', 'nul'].includes(target.toLowerCase())) return null;
2686
+ // Writing to a raw device is a guardrail: there is no "undo" for it. A
2687
+ // plain file is a permission the user may grant.
2688
+ if (RAW_DEVICE.test(target)) return finding(`dd of=${target} writes a raw device`);
2689
+ if (!isDisposablePath(target, activeCwd, config)) {
2690
+ return finding(`dd of=${target}`, 'confirm', 'raw-write');
2691
+ }
2692
+ }
2693
+
2694
+ if (HOST_DESTRUCTIVE_VERB.test(verb) || ['shutdown', 'reboot', 'poweroff', 'halt'].includes(verb)) {
2695
+ return finding(`${verb} is a host-level destructive command`);
2696
+ }
2697
+ if (verb === 'init' && ['0', '6'].includes(values[0])) return finding('init 0/6 shuts the machine down');
2698
+ if (verb === 'taskkill' && values.some((v) => v.toLowerCase() === '/f')) {
2699
+ return finding('taskkill /F forcibly terminates processes', 'confirm', 'process-kill');
2700
+ }
2701
+
2702
+ if (['del', 'erase'].includes(verb) && values.some((v) => ['/s', '/q', '/f'].includes(v.toLowerCase()))) {
2703
+ const target = values.find((v) => !v.startsWith('-') && !v.startsWith('/'));
2704
+ return finding(`${verb} deletes files recursively`, targetSeverity(target, activeCwd, isGitRepo), 'delete');
2705
+ }
2706
+ if (['rd', 'rmdir'].includes(verb) && values.some((v) => v.toLowerCase() === '/s')) {
2707
+ const target = values.find((v) => !v.startsWith('-') && !v.startsWith('/'));
2708
+ return finding(`${verb} /s deletes a tree`, targetSeverity(target, activeCwd, isGitRepo), 'delete');
2709
+ }
2710
+ if (verb === 'remove-item' && values.some((v) => v.toLowerCase().startsWith('-recurse'))) {
2711
+ const target = values.find((v) => !v.startsWith('-'));
2712
+ if (!target || !isDisposablePath(target, activeCwd, config)) {
2713
+ return finding('Remove-Item -Recurse', targetSeverity(target, activeCwd, isGitRepo), 'delete');
2714
+ }
2715
+ }
2716
+ if (verb === 'stop-computer') return finding('Stop-Computer shuts the machine down');
2717
+
2718
+ if (['chmod', 'chown', 'chgrp'].includes(verb) && values.some((v) => /^-[a-z]*R/.test(v))) {
2719
+ const target = values.filter((v) => !v.startsWith('-')).pop();
2720
+ if (target && !isDisposablePath(target, activeCwd, config)) {
2721
+ return finding(`${verb} -R on ${target}`, targetSeverity(target, activeCwd, isGitRepo), 'perm-recursive');
2722
+ }
2723
+ }
2724
+
2725
+ const sql = `${verb} ${values.join(' ')}`.toLowerCase();
2726
+ if (/^(?:drop\s+(?:table|database|schema)|truncate\s+table)\b/.test(sql)) {
2727
+ return finding('destructive SQL', 'confirm', 'db-ddl');
2728
+ }
2729
+
2730
+ // The same statement passed to a database client's flag is still DDL.
2731
+ if (DB_CLIENTS.has(verb) && DDL_ANYWHERE.test(values.join(' ').toLowerCase())) {
2732
+ return finding(`destructive SQL via ${verb}`, 'confirm', 'db-ddl');
2733
+ }
2734
+ if (['mongo', 'mongosh'].includes(verb) && MONGO_DROP.test(values.join(' '))) {
2735
+ return finding(`destructive MongoDB drop via ${verb}`, 'confirm', 'db-ddl');
2736
+ }
2737
+ }
2738
+ return null;
2739
+ };
2740
+
2741
+
2742
+ // ---------------------------------------------------------------------------
2743
+ // PowerShell: the same read/write semantics, different verb names
2744
+ // ---------------------------------------------------------------------------
2745
+
2746
+ const PS_READ_VERBS = new Set([
2747
+ 'get-content', 'gc', 'cat', 'type', 'select-string', 'sls', 'format-hex', 'fhx',
2748
+ 'get-item', 'gi', 'get-itemproperty', 'gp', 'resolve-path', 'rvpa', 'get-filehash',
2749
+ ]);
2750
+ const PS_SCAN_VERBS = new Set(['get-childitem', 'gci', 'ls', 'dir']);
2751
+ const PS_WRITE_VERBS = new Set([
2752
+ 'set-content', 'sc', 'add-content', 'ac', 'out-file', 'tee-object', 'tee',
2753
+ 'new-item', 'ni', 'copy-item', 'cpi', 'cp', 'copy', 'move-item', 'mi', 'mv', 'move',
2754
+ 'rename-item', 'rni', 'ren', 'remove-item', 'ri', 'rm', 'del', 'erase', 'rmdir',
2755
+ 'clear-content', 'clc', 'export-csv', 'export-clixml', 'set-item', 'si',
2756
+ ]);
2757
+ /** Flags whose next token is a path. */
2758
+ const PS_PATH_FLAGS = new Set(['-path', '-filepath', '-literalpath', '-destination', '-outfile', '-target', '-name']);
2759
+ /** Flags whose next token is a value (content, encoding, pattern), never a path. */
2760
+ const PS_VALUE_FLAGS = new Set([
2761
+ '-value', '-encoding', '-delimiter', '-pattern', '-inputobject', '-width', '-totalcount',
2762
+ '-head', '-tail', '-first', '-last', '-replace', '-credential', '-pipelinevariable',
2763
+ '-filter', '-include', '-exclude', '-erroraction', '-warningaction', '-verbose',
2764
+ ]);
2765
+ /** Verbs where every operand after the first is a destination. */
2766
+ const PS_MULTI_PATH_VERBS = new Set(['copy-item', 'cpi', 'cp', 'copy', 'move-item', 'mi', 'mv', 'move', 'rename-item', 'rni', 'ren']);
2767
+
2768
+ const psFlag = (value) => String(value).toLowerCase().split(':')[0];
2769
+
2770
+ /**
2771
+ * Static parser for the PowerShell shapes that overlap with file work.
2772
+ *
2773
+ * Like the bash parser this is deliberately conservative: it understands the
2774
+ * common read/write/scan verbs and `-Path`-style flags, and skips anything it
2775
+ * cannot resolve. It never executes a command.
2776
+ */
2777
+ const parsePowerShell = (
2778
+ command,
2779
+ { config = DEFAULT_CONFIG, cwd = null, isFile = defaultIsFile, exists = () => false } = {},
2780
+ ) => {
2781
+ const files = [];
2782
+ const dirs = [];
2783
+ const writes = [];
2784
+ if (typeof command !== 'string' || command === '') return { files, dirs, writes };
2785
+ let activeCwd = cwd;
2786
+
2787
+ const pushFile = (raw) => {
2788
+ const candidate = resolveShellPath(raw, activeCwd);
2789
+ if (!candidate || !isCodeFile(candidate, config) || isExcluded(candidate, config)) return;
2790
+ if (isFile(candidate)) files.push(candidate);
2791
+ };
2792
+ const pushDir = (raw) => {
2793
+ const candidate = resolveShellPath(raw, activeCwd);
2794
+ if (!candidate || !exists(candidate)) return;
2795
+ const scope = scopeOf(join(candidate, '.gate-probe.ts'), { config, exists });
2796
+ if (scope.inScope) dirs.push(candidate);
2797
+ };
2798
+ const pushWrite = (raw) => {
2799
+ const candidate = resolveShellPath(raw, activeCwd);
2800
+ if (!candidate) return;
2801
+ const base = candidate.replace(/\\/g, '/').split('/').pop()?.toLowerCase();
2802
+ if (['/dev/null', 'nul', '/dev/stdout', '/dev/stderr'].includes(base)) return;
2803
+ writes.push(candidate);
2804
+ };
2805
+
2806
+ for (const rawSegment of splitShellSegments(command)) {
2807
+ const segment = rawSegment.trim();
2808
+ if (!segment) continue;
2809
+ const tokens = shellTokens(segment);
2810
+ if (tokens.length === 0) continue;
2811
+ const { verb, args } = parseCommandHead(tokens);
2812
+ if (!verb) continue;
2813
+
2814
+ // Nested invocation: `powershell -Command "Get-Content x"`.
2815
+ if (['powershell', 'pwsh'].includes(verb)) {
2816
+ const at = args.findIndex((a) => ['-c', '-command', '/c'].includes(a.value.toLowerCase()));
2817
+ if (at >= 0 && args[at + 1]) {
2818
+ const nested = args.slice(at + 1).map((a) => a.raw).join(' ');
2819
+ const inner = parsePowerShell(nested, { config, cwd: activeCwd, isFile, exists });
2820
+ files.push(...inner.files);
2821
+ dirs.push(...inner.dirs);
2822
+ writes.push(...inner.writes);
2823
+ }
2824
+ continue;
2825
+ }
2826
+
2827
+ if (verb === 'cd' || verb === 'set-location' || verb === 'sl') {
2828
+ const target = args.find((a) => a.quoted || !a.value.startsWith('-'));
2829
+ const resolved = target ? resolveShellPath(target.value, activeCwd) : null;
2830
+ if (resolved) activeCwd = resolved;
2831
+ continue;
2832
+ }
2833
+
2834
+ // Redirection: `... > file`, `... >> file`, `2> file`.
2835
+ for (const m of segment.matchAll(/(?:^|\s)(?:\d?>>?)\s*("[^"]+"|'[^']+'|\S+)/g)) {
2836
+ pushWrite(m[1]);
2837
+ }
2838
+
2839
+ const isRead = PS_READ_VERBS.has(verb);
2840
+ const isScan = PS_SCAN_VERBS.has(verb);
2841
+ const isWrite = PS_WRITE_VERBS.has(verb);
2842
+ if (!isRead && !isScan && !isWrite) continue;
2843
+
2844
+ const operands = [];
2845
+ for (let i = 0; i < args.length; i += 1) {
2846
+ const value = args[i].value;
2847
+ if (!args[i].quoted && value.startsWith('-')) {
2848
+ const flag = psFlag(value);
2849
+ if (PS_PATH_FLAGS.has(flag) && args[i + 1]) {
2850
+ operands.push(args[i + 1].value);
2851
+ i += 1;
2852
+ } else if (PS_VALUE_FLAGS.has(flag) && args[i + 1]) {
2853
+ i += 1;
2854
+ }
2855
+ continue;
2856
+ }
2857
+ operands.push(value);
2858
+ }
2859
+
2860
+ if (isScan) {
2861
+ pushDir(operands[0] ?? activeCwd ?? '.');
2862
+ continue;
2863
+ }
2864
+
2865
+ if (isRead) {
2866
+ // Positional `Select-String <pattern> <path>`: the first operand is the pattern.
2867
+ const hasPathFlag = args.some((a) => PS_PATH_FLAGS.has(psFlag(a.value)));
2868
+ const start = (verb === 'select-string' || verb === 'sls') && !hasPathFlag ? 1 : 0;
2869
+ for (const p of operands.slice(start)) pushFile(p);
2870
+ continue;
2871
+ }
2872
+
2873
+ if (PS_MULTI_PATH_VERBS.has(verb)) {
2874
+ const [source, ...dests] = operands;
2875
+ if (source) pushFile(source);
2876
+ for (const d of dests) pushWrite(d);
2877
+ continue;
2878
+ }
2879
+
2880
+ // Set-Content / Out-File / New-Item / Remove-Item: first operand is the path,
2881
+ // later operands are content or values and must not be judged as paths.
2882
+ if (operands[0]) pushWrite(operands[0]);
2883
+ }
2884
+
2885
+ const unique = (list) => [...new Set(list)];
2886
+ return { files: unique(files), dirs: unique(dirs), writes: unique(writes) };
2887
+ };
2888
+
2889
+ export const powershellReadTargets = (command, opts = {}) => parsePowerShell(command, opts).files;
2890
+ export const powershellReadDirs = (command, opts = {}) => parsePowerShell(command, opts).dirs;
2891
+ export const powershellWriteTargets = (command, opts = {}) => parsePowerShell(command, opts).writes;
2892
+
2893
+ export const powershellDestructiveFinding = (command, opts = {}) => {
2894
+ const base = bashDestructiveFinding(command, opts);
2895
+ if (base) return base; // Remove-Item -Recurse / del /s are already covered there
2896
+ const { config = DEFAULT_CONFIG, cwd = null } = opts;
2897
+ for (const segment of splitShellSegments(command)) {
2898
+ const tokens = shellTokens(segment);
2899
+ if (tokens.length === 0) continue;
2900
+ const { verb, args } = parseCommandHead(tokens);
2901
+ if (verb !== 'clear-content' && verb !== 'clc') continue;
2902
+ const target = args.map((a) => a.value).find((v) => !v.startsWith('-'));
2903
+ if (target && !isDisposablePath(target, cwd, config)) {
2904
+ return {
2905
+ why: `${verb} wipes file contents`,
2906
+ segment: segment.trim().slice(0, 200),
2907
+ severity: targetSeverity(target, cwd, opts.isGitRepo ?? null),
2908
+ };
2909
+ }
2910
+ }
2911
+ return null;
2912
+ };
2913
+
2914
+ /** Shell-agnostic dispatch: one seam so every check handles both shells. */
2915
+ const shellOf = (input) => (input?.shell === 'powershell' ? 'powershell' : 'bash');
2916
+ export const shellReadTargets = (input, opts = {}) =>
2917
+ shellOf(input) === 'powershell' ? powershellReadTargets(input.command, opts) : bashReadTargets(input.command, opts);
2918
+ export const shellReadDirs = (input, opts = {}) =>
2919
+ shellOf(input) === 'powershell' ? powershellReadDirs(input.command, opts) : bashReadDirs(input.command, opts);
2920
+ export const shellWriteTargets = (input, opts = {}) =>
2921
+ shellOf(input) === 'powershell' ? powershellWriteTargets(input.command, opts) : bashWriteTargets(input.command, opts);
2922
+ export const shellDestructiveFinding = (input, opts = {}) =>
2923
+ shellOf(input) === 'powershell'
2924
+ ? powershellDestructiveFinding(input.command, opts)
2925
+ : bashDestructiveFinding(input.command, opts);
2926
+
2927
+ // ---------------------------------------------------------------------------
2928
+ // Index freshness
2929
+ // ---------------------------------------------------------------------------
2930
+
2931
+ /**
2932
+ * The filesystem facts a check may consult, injected so the rule layer stays
2933
+ * unit-testable off-harness (a harness with a virtual or remote filesystem can
2934
+ * still be policed, and the test suite needs no disk).
2935
+ *
2936
+ * Each probe is TOTAL: it answers, it never throws. A probe that can throw
2937
+ * turns a filesystem hiccup into a dead gate, and a gate that stops existing is
2938
+ * the one failure this whole design is built to avoid.
2939
+ */
2940
+ const NO_FS = {
2941
+ exists: () => false,
2942
+ isFile: () => false,
2943
+ isDirectory: () => false,
2944
+ statMtime: () => 0,
2945
+ listDir: () => [],
2946
+ readText: () => null,
2947
+ };
2948
+
2949
+ /** Newest mtime inside a directory, or 0 when it cannot be read. */
2950
+ export const newestMtimeIn = (dir, fs, now = Date.now(), ttlMs = 0) => {
2951
+ const hit = mtimeCache.get(dir);
2952
+ // `now >= hit.at` rather than trusting the clock: a backwards clock must not
2953
+ // make a stale answer look fresh. Keeping the comparison on the arguments
2954
+ // (instead of calling Date.now() in here) is what makes the TTL testable
2955
+ // without fake timers.
2956
+ if (hit && now >= hit.at && now - hit.at <= ttlMs) return hit.mtime;
2957
+
2958
+ let newest = 0;
2959
+ for (const name of fs.listDir(dir)) {
2960
+ const m = fs.statMtime(join(dir, name));
2961
+ if (m > newest) newest = m;
2962
+ }
2963
+ mtimeCache.set(dir, { at: now, mtime: newest });
2964
+ return newest;
2965
+ };
2966
+
2967
+ /**
2968
+ * Module-level on purpose: this caches a fact about the disk, not about a
2969
+ * session's permissions, so a per-session reset must not clear it. Exported for
2970
+ * tests; not part of the policy contract.
2971
+ */
2972
+ export const resetMtimeCache = () => mtimeCache.clear();
2973
+
2974
+ /**
2975
+ * AI4S turn-end findings: W4 (run half) + W2.
2976
+ *
2977
+ * Both are OUTPUT-shape problems, and output problems are discovered after the
2978
+ * computation. That is why they are findings for a `continue` (one more turn to
2979
+ * fix) rather than denials: blocking a call that already finished teaches
2980
+ * nothing and breaks a completed analysis.
2981
+ *
2982
+ * Returns `[]` when there is nothing to judge. In particular it returns `[]`
2983
+ * when the session never recorded a turn start: without a boundary there is no
2984
+ * "this turn's output", and judging the whole history would flag every old
2985
+ * directory on the machine.
2986
+ *
2987
+ * @param {object} args
2988
+ * @param {object} args.policy normalized (profile-applied) policy
2989
+ * @param {object} args.state session state from newSessionState()
2990
+ * @param {object} args.fs probe set: {exists, isFile, statMtime, listDir, readText}
2991
+ * @param {string} [args.cwd] session directory the relative result dirs hang off
2992
+ * @param {number} [args.now]
2993
+ * @returns {Array<{code:string, reason:string, path:string}>}
2994
+ */
2995
+ export const outputArtifactFindings = ({ policy, state, fs, cwd = null, now = Date.now() } = {}) => {
2996
+ const config = policy?.config ?? DEFAULT_CONFIG;
2997
+ const probes = { ...NO_FS, ...(fs ?? {}) };
2998
+ const since = Number.isFinite(state?.turnStart) ? state.turnStart : 0;
2999
+ if (since <= 0) return [];
3000
+ // See `artifact_mtime_epsilon_ms`: file timestamps and Date.now() disagree by a
3001
+ // few milliseconds in both directions, so every comparison below is tolerant.
3002
+ const epsilon = Number.isFinite(config.artifact_mtime_epsilon_ms)
3003
+ ? config.artifact_mtime_epsilon_ms
3004
+ : DEFAULT_CONFIG.artifact_mtime_epsilon_ms;
3005
+ const findings = [];
3006
+
3007
+ // --- W4 (run half): every script started this turn must have left a log ----
3008
+ if (config.script_log_check !== false && state?.scriptsRun instanceof Map) {
3009
+ for (const [script, info] of state.scriptsRun) {
3010
+ const startedAt = Number.isFinite(info?.startedAt) ? info.startedAt : 0;
3011
+ if (startedAt < since) continue; // an earlier turn already answered for it
3012
+ if (!hasExtension(script, config.log_required_extensions
3013
+ ?? DEFAULT_CONFIG.log_required_extensions)) continue;
3014
+ // Two accepted spellings: `run.R.log` (what the W4 remediation suggests)
3015
+ // and `run.log` (what most pipelines write). Accepting only one would turn
3016
+ // a formatting preference into a blocked turn.
3017
+ const stem = script.replace(/\.[^./\\]+$/, '');
3018
+ const candidates = [`${script}.log`, `${stem}.log`];
3019
+ const log = candidates.find(
3020
+ (p) => probes.isFile(p) && probes.statMtime(p) >= startedAt - epsilon,
3021
+ );
3022
+ if (log) continue;
3023
+ findings.push({
3024
+ code: 'AI4S_SCRIPT_LOG_MISSING',
3025
+ path: script,
3026
+ reason: [
3027
+ '⛔ AI4S 域控 · W4 提醒:本轮跑过的脚本没有留下日志文件。',
3028
+ ` 脚本:${script}`,
3029
+ ` 期待:${candidates.join(' 或 ')}(mtime 不早于启动时刻)`,
3030
+ '',
3031
+ '把输出重定向到日志(如 `Rscript run.R 2>&1 | tee run.R.log`),',
3032
+ '或让脚本自己 sink / logging 写文件。日志是这几月后唯一能复核的现场。',
3033
+ ].join('\n'),
3034
+ });
3035
+ }
3036
+ }
3037
+
3038
+ // --- W2: a result subdirectory touched this turn needs a note --------------
3039
+ const resultDirs = Array.isArray(config.result_dirs) ? config.result_dirs : [];
3040
+ const prefix = String(config.readme_prefix ?? DEFAULT_CONFIG.readme_prefix).toLowerCase();
3041
+ if (resultDirs.length > 0 && prefix !== '' && typeof cwd === 'string' && cwd !== '') {
3042
+ for (const rel of resultDirs) {
3043
+ if (typeof rel !== 'string' || rel === '') continue;
3044
+ const dir = normalizePath(join(cwd, rel));
3045
+ if (!probes.exists(dir)) continue;
3046
+ for (const child of probes.listDir(dir)) {
3047
+ const childPath = normalizePath(join(dir, child));
3048
+ // "Touched this turn" is derived from the newest mtime INSIDE the entry,
3049
+ // so a plain file in `results/` is skipped without needing an extra
3050
+ // isDirectory probe: a file has no entries, hence no mtime, hence 0.
3051
+ const newest = newestMtimeIn(childPath, probes, now, 0);
3052
+ if (newest < since - epsilon) continue;
3053
+ const annotated = probes.listDir(childPath)
3054
+ .some((name) => String(name).toLowerCase().startsWith(prefix));
3055
+ if (annotated) continue;
3056
+ findings.push({
3057
+ code: 'AI4S_RESULT_README',
3058
+ path: childPath,
3059
+ reason: [
3060
+ '⛔ AI4S 域控 · W2 提醒:本轮更新的结果目录没有说明文件。',
3061
+ ` 目录:${childPath}`,
3062
+ ` 期待:目录下有一个以 ${config.readme_prefix ?? DEFAULT_CONFIG.readme_prefix} 开头的文件`,
3063
+ '',
3064
+ '写一句:这个目录是什么、用哪个脚本跑的、关键参数、怎么读。',
3065
+ '半年后打开 results/ 的人(包括你自己)靠它才知道哪张图是什么。',
3066
+ ].join('\n'),
3067
+ });
3068
+ }
3069
+ }
3070
+ }
3071
+
3072
+ return findings;
3073
+ };
3074
+
3075
+ // ---------------------------------------------------------------------------
3076
+ // Checks
3077
+ // ---------------------------------------------------------------------------
3078
+
3079
+ /**
3080
+ * Verbs whose operands mention a script but do not execute it.
3081
+ *
3082
+ * `cat annotate.R` is reading the script, and demanding a Worklog for it would
3083
+ * make the rule hate its own debugging: the model must be free to open the file
3084
+ * to see what it is about to run.
3085
+ */
3086
+ const SKIP_SCRIPT_VERBS = new Set([
3087
+ ...BASH_READ_VERBS,
3088
+ 'ls', 'dir', 'vdir', 'tree', 'find', 'echo', 'printf', 'test', '[', 'stat',
3089
+ 'du', 'df', 'which', 'type', 'command', 'open', 'xdg-open', 'git', 'file',
3090
+ 'grep', 'rg', 'diff', 'cmp',
3091
+ ]);
3092
+
3093
+ /** Does `file` end with one of `exts`? Case-insensitive, list may be undefined. */
3094
+ const hasExtension = (file, exts) => {
3095
+ const lower = String(file ?? '').toLowerCase();
3096
+ return (Array.isArray(exts) ? exts : []).some((e) => lower.endsWith(String(e).toLowerCase()));
3097
+ };
3098
+
3099
+ /**
3100
+ * Analysis scripts a shell command would EXECUTE.
3101
+ *
3102
+ * Only existing files with an analysis extension count, and only when the verb
3103
+ * is an executor — a path-shaped argument is not a run. Kept deliberately
3104
+ * conservative: a false positive here asks for a Worklog update, a false
3105
+ * negative skips one rule set, and the second is the cheaper mistake.
3106
+ */
3107
+ export const analysisScriptTargets = (
3108
+ command,
3109
+ { config = DEFAULT_CONFIG, cwd = null, isFile = defaultIsFile } = {},
3110
+ ) => {
3111
+ if (typeof command !== 'string' || command === '') return [];
3112
+ const exts = (config.script_extensions ?? DEFAULT_CONFIG.script_extensions)
3113
+ .map((e) => String(e).toLowerCase());
3114
+ if (exts.length === 0) return [];
3115
+ const found = [];
3116
+ for (const rawSegment of splitShellSegments(command)) {
3117
+ const segment = rawSegment.trim();
3118
+ if (segment === '') continue;
3119
+ const tokens = shellTokens(segment);
3120
+ if (tokens.length === 0) continue;
3121
+ const { verb, args } = parseCommandHead(tokens);
3122
+ if (!verb || SKIP_SCRIPT_VERBS.has(verb)) continue;
3123
+ for (const arg of args) {
3124
+ const value = arg?.value;
3125
+ if (typeof value !== 'string' || value === '' || value.startsWith('-')) continue;
3126
+ const lowerValue = value.toLowerCase();
3127
+ if (!exts.some((ext) => lowerValue.endsWith(ext))) continue;
3128
+ const resolved = resolveShellPath(value, cwd);
3129
+ if (!resolved || !isFile(resolved)) continue;
3130
+ found.push(resolved);
3131
+ }
3132
+ }
3133
+ return [...new Set(found)];
3134
+ };
3135
+
3136
+ /**
3137
+ * Remember that this session started an analysis script.
3138
+ *
3139
+ * `startedAt` is refreshed on every run (the turn-end check dates the expected
3140
+ * `.log` against the latest one), while the KEY's presence is what makes W1 a
3141
+ * "first run only" rule — a long pipeline must not be interrupted by a Worklog
3142
+ * demand before every step.
3143
+ */
3144
+ export const recordScriptRun = (state, scriptPath, now = Date.now()) => {
3145
+ const norm = normalizePath(scriptPath);
3146
+ if (!norm || !(state?.scriptsRun instanceof Map)) return;
3147
+ state.scriptsRun.set(norm, { startedAt: now });
3148
+ };
3149
+
3150
+ /** R: `sink()` / `Sys.time()` / log4r / logger / futile.logger. */
3151
+ const R_LOG_INIT = /\bsink\s*\(|\bSys\.time\s*\(|\blog4r\b|\blogger\s*::|\bfutile\.logger/;
3152
+ /** Python: the logging module (or loguru), which is the only portable answer. */
3153
+ const PY_LOG_INIT = /\blogging\s*\.|\bFileHandler\b|\bbasicConfig\s*\(|\bloguru\b/;
3154
+
3155
+ /**
3156
+ * Does this script set up a log sink of its own?
3157
+ *
3158
+ * Static and shallow ON PURPOSE: the question is "did the author remember to
3159
+ * leave a trace", not "is the logging correct". A deep answer is not decidable
3160
+ * without running the script, and a rule that cannot be checked is worse than no
3161
+ * rule.
3162
+ */
3163
+ export const hasLogInitialization = (text, scriptPath = '') => {
3164
+ if (typeof text !== 'string') return false;
3165
+ const ext = String(scriptPath).toLowerCase();
3166
+ if (ext.endsWith('.r') || ext.endsWith('.rmd')) return R_LOG_INIT.test(text);
3167
+ if (ext.endsWith('.py') || ext.endsWith('.ipynb')) return PY_LOG_INIT.test(text);
3168
+ return R_LOG_INIT.test(text) || PY_LOG_INIT.test(text);
3169
+ };
3170
+
3171
+ /**
3172
+ * A check answers one question about one tool call and returns either null
3173
+ * (abstain) or a `{ code, reason }` denial.
3174
+ *
3175
+ * `input` is the normalized shape every adapter produces:
3176
+ * { action: 'read'|'write'|'bash'|'other', path: string|null, tool: string }
3177
+ *
3178
+ * `deps` carries what a check may need from the running harness:
3179
+ * { exists(dir): boolean, state, now: number }
3180
+ *
3181
+ * CASCADE ORDER
3182
+ * -------------
3183
+ * `shouldBlock` stops at the FIRST check that returns a verdict, so the order
3184
+ * of the policy's `checks` array decides which layer speaks. The shipped
3185
+ * policies list the two Layer-2 checks BEFORE `graph-before-read`, because:
3186
+ *
3187
+ * - an unindexed repository must hear "build the index first", not
3188
+ * "the index exists, query the graph" — with the reverse order Layer 2 is
3189
+ * unreachable and the Layer-1 wording is simply false;
3190
+ * - the reverse order was tried once, on the theory that Layer 2 would
3191
+ * re-block a session right after its first graph query. It would not: both
3192
+ * Layer-2 checks short-circuit on a fresh signal, exactly like
3193
+ * `graph-before-read`. The theory was wrong and the order it produced hid
3194
+ * the index rules on every unindexed repository.
3195
+ *
3196
+ * A policy that lists only `graph-before-read` remains valid and means "always
3197
+ * ask the graph first"; the cascade is a property of the array, not the code.
3198
+ */
3199
+ const CHECKS = {
3200
+ /**
3201
+ * Layer 0: do not overwrite a file you have never looked at.
3202
+ *
3203
+ * The v2 gate only policed reads. A model could query the graph about one
3204
+ * file, then edit any other file in the repository without ever opening it —
3205
+ * mechanical action, which is exactly what the first rule forbids. This check
3206
+ * demands evidence about the *specific* target: a successful read of that
3207
+ * file or a scoped graph unlock that named it. A fresh session-wide signal is
3208
+ * deliberately NOT enough (that is the "I queried once" hole in a new coat).
3209
+ *
3210
+ * New files are exempt from target evidence: there is nothing to inspect yet,
3211
+ * and requiring a graph hit would brick the first file in an empty repo. The
3212
+ * convention check still applies to them.
3213
+ */
3214
+ /**
3215
+ * ai-spec Layer 0.5:改代码前必须核对该改动对应的立项 CHG 契约。
3216
+ *
3217
+ * 与 `think-before-write` 的分工:
3218
+ * - `think-before-write` 管「你看过这个文件吗」(图层/证据)
3219
+ * - 本检查管「这个改动属于哪个 CHG、那个 CHG 契约齐全吗」(契约/范围)
3220
+ *
3221
+ * 两者都过,才允许改代码。缺前者 = 篡改;缺后者 = 跑偏。
3222
+ */
3223
+ 'chg-contract-before-edit': (policy, input, deps) => {
3224
+ if (input.action !== 'write') return null;
3225
+ const config = policy.config;
3226
+ if (config.require_chg_contract === false) return null;
3227
+
3228
+ const norm = normalizePath(input.path);
3229
+ const scope = scopeOf(norm, { config, exists: deps.exists });
3230
+ if (!scope.inScope || !scope.root) return null;
3231
+ // 只约束代码:改文档 / 数据 / 台账不要求 CHG 契约。
3232
+ if (!isCodeFile(norm, config)) return null;
3233
+ // 可选收窄:只在真正受 CHG 治理的目录里要求契约。
3234
+ const scopeGlobs = (config.chg_contract_scope_globs ?? []).map((g) => String(g).toLowerCase());
3235
+ if (scopeGlobs.length > 0 && !matchesAnyGlob(toPosix(norm).toLowerCase(), scopeGlobs)) return null;
3236
+
3237
+ // 项目适用性:不用 CHG 体系的项目(如以 ADR 管理的仓库)不该被这条拦死。
3238
+ // 判据取文件系统事实:`tasks/` 存在且含 `CHG-*` 子目录,才认为本项目采纳了 CHG。
3239
+ // 不跳过的后果:任何不用 CHG 的仓库都改不了代码 —— 死锁。
3240
+ const projectRoot = scope.projectRoot ?? scope.root;
3241
+ const tasksDir = join(projectRoot, 'tasks');
3242
+ if (!deps.exists(tasksDir)) return null;
3243
+ if (typeof deps.listDir === 'function') {
3244
+ const entries = deps.listDir(tasksDir) ?? [];
3245
+ if (!entries.some((name) => /^CHG-/i.test(String(name)))) return null;
3246
+ }
3247
+
3248
+ // 本会话读过的契约,且必须属于**当前项目**:读别的仓库的 CHG 不算数。
3249
+ // v5 少了这层过滤 —— 读 A 仓库的 SPEC.md 可以解锁 B 仓库的代码改动。
3250
+ const dirs = new Set();
3251
+ for (const p of deps.state.docReads ?? []) {
3252
+ const read = normalizePath(p);
3253
+ if (!withinRoot(projectRoot, read)) continue;
3254
+ const dir = chgDirOf(read, config);
3255
+ if (dir) dirs.add(dir);
3256
+ }
3257
+ if (dirs.size === 0) {
3258
+ return {
3259
+ code: 'CHG_CONTRACT',
3260
+ reason: [
3261
+ '⛔ ai-spec 门控:改代码前没有核对**本项目**的立项 CHG 契约。',
3262
+ ` 目标:${norm}`,
3263
+ ` 项目:${projectRoot}`,
3264
+ ' 缺口:本会话没有读过本项目 tasks/CHG-*/ 下的任何 SPEC / PRD / TRACEABILITY。',
3265
+ '',
3266
+ '先做(按序,缺一不可):',
3267
+ ' 1) 定位本次开发属于哪个 CHG:ls tasks/CHG-*/(按 date-slug 判定)',
3268
+ ' 2) 读它的四件套(至少 SPEC + PRD):',
3269
+ ' read tasks/CHG-<id>/SPEC.md # 目标 / 独占文件 / 验收断言 / 绝不做什么',
3270
+ ' read tasks/CHG-<id>/PRD.md # 承诺什么、不承诺什么',
3271
+ ' read tasks/CHG-<id>/TRACEABILITY.md # 每条 AC 的证据在哪',
3272
+ ' 3) 五问自检再动手:',
3273
+ ' · 这个改动属于哪个 CHG?(答不出 = 不许改)',
3274
+ ' · 该 CHG 四件套齐全吗?(缺哪件就先补,缺料不许开工)',
3275
+ ' · 目标文件在该 CHG 的「独占文件」清单里吗?(不在 = 可能越界)',
3276
+ ' · 改完哪条 AC 会从红变绿?(答不出 = 没有验收目标)',
3277
+ ' · 是先用第一性原理判了根因,还是照症状打补丁?',
3278
+ '',
3279
+ '注意:读别的仓库的 CHG 不算数,本规则按项目绑定。',
3280
+ '',
3281
+ '开发中发现的问题必须当场修,不许留给「后续」;',
3282
+ '收尾必须让该 CHG 的预定功能目标达成,而不是「大部分做完」。',
3283
+ '',
3284
+ '这条不是建议:未核对契约的代码改动一律拒绝。',
3285
+ ].join('\n'),
3286
+ };
3287
+ }
3288
+
3289
+ // 读过 ≠ 契约成立。缺 PRD / 缺 TRACEABILITY / SPEC 塞的是空壳 / 还是 draft,
3290
+ // 都不能支撑开工。v5 只看「碰过文件」,于是「写一个 SPEC.md → 读它 → 改代码」
3291
+ // 全流程畅通,而 PRD 与 TRACEABILITY 根本不存在。
3292
+ const gaps = [];
3293
+ for (const dir of dirs) {
3294
+ const audit = auditChgContract(dir, config, deps);
3295
+ if (audit.ok) return null;
3296
+ gaps.push({ dir, problems: audit.problems });
3297
+ }
3298
+
3299
+ const prefix = `${toPosix(projectRoot)}/`;
3300
+ return {
3301
+ code: 'CHG_CONTRACT_INCOMPLETE',
3302
+ reason: [
3303
+ '⛔ ai-spec 门控:本次改动对应的 CHG 契约**不成立**。',
3304
+ ` 目标:${norm}`,
3305
+ '',
3306
+ '本会话读过的契约,没有一个能支撑开工:',
3307
+ ...gaps.flatMap(({ dir, problems }) => [
3308
+ ` · ${toPosix(dir).replace(prefix, '')}`,
3309
+ ...problems.map((p) => ` ✗ ${p}`),
3310
+ ]),
3311
+ '',
3312
+ '「读过一份文件」不等于「立项完成」。补齐后再改代码:',
3313
+ ' 1) 缺 PRD.md → 写清承诺什么、不承诺什么、判定口径',
3314
+ ' 2) 缺 TRACEABILITY.md → 每条验收断言对应哪个产物、怎么验',
3315
+ ' 3) SPEC.md 没有验收判据 → 至少写一节「验收断言 / AC」',
3316
+ ' 4) status 是 draft → 先把 SPEC 改到 approved,或确认这不是本次要做的 CHG',
3317
+ '',
3318
+ '这条不是建议:契约不成立时,代码改动一律拒绝。',
3319
+ ].join('\n'),
3320
+ };
3321
+ },
3322
+
3323
+ 'think-before-write': (policy, input, deps) => {
3324
+ if (input.action !== 'write' && input.action !== 'bash') return null;
3325
+ const config = policy.config;
3326
+ if (config.require_target_evidence === false && config.require_conventions === false) return null;
3327
+
3328
+ const targets = input.action === 'write'
3329
+ ? [input.path]
3330
+ : bashWriteTargets(input.command, {
3331
+ config,
3332
+ cwd: input.cwd ?? null,
3333
+ isFile: deps.isFile,
3334
+ exists: deps.exists,
3335
+ });
3336
+ if (targets.length === 0) return null;
3337
+
3338
+ const roots = new Set();
3339
+ for (const target of targets) {
3340
+ if (!target) continue;
3341
+ const norm = normalizePath(target);
3342
+ const scope = scopeOf(norm, { config, exists: deps.exists });
3343
+ if (!scope.inScope || !scope.root) continue;
3344
+ roots.add(scope.projectRoot ?? scope.root);
3345
+ if (config.require_target_evidence !== false) {
3346
+ if (deps.state.written.has(norm)) continue;
3347
+ // A directory or a path that does not exist yet: nothing to inspect.
3348
+ if (!deps.isFile(norm)) continue;
3349
+ if (hasFreshInspection(deps.state, norm, config, deps.now)) continue;
3350
+ if (hasScopedUnlock(deps.state, norm, config, deps.now)) continue;
3351
+ return {
3352
+ code: 'THINK_TARGET',
3353
+ reason: [
3354
+ '⛔ 动脑子铁律 · Layer 0 拦截:动手前没有看过这个文件。',
3355
+ ` 目标:${norm}`,
3356
+ ` 工具:${input.tool ?? input.action}`,
3357
+ ' 证据缺口:本会话既没有成功读取过它,也没有一次图谱查询点名过它。',
3358
+ '',
3359
+ '先做(任一即可):',
3360
+ ' a) read 这个文件(read 本身通过 Layer 1 后即可);',
3361
+ ' b) search_graph / get_code_snippet / trace_path / query_graph 查询并命中它',
3362
+ ' (命中后 30 分钟内该目标可改)。',
3363
+ '然后重试。不要在没看代码、没判根因的情况下直接改。',
3364
+ '',
3365
+ '顺手过一遍五问:项目约定?环境现状?字面背后的真实需求?任务目的?产出价值?',
3366
+ ].join('\n'),
3367
+ };
3368
+ }
3369
+ }
3370
+
3371
+ if (config.require_conventions) {
3372
+ for (const root of roots) {
3373
+ const docs = (config.convention_files ?? []).filter((name) => deps.exists(join(root, name)));
3374
+ if (docs.length === 0) continue;
3375
+ const read = [...deps.state.docReads].some(
3376
+ (p) => withinRoot(root, p) && isConventionDoc(p, config),
3377
+ );
3378
+ if (read) continue;
3379
+ return {
3380
+ code: 'THINK_CONVENTIONS',
3381
+ reason: [
3382
+ '⛔ 动脑子铁律 · Layer 0 拦截:还没读项目约定就要改代码。',
3383
+ ` 仓库:${root}`,
3384
+ ` 存在的约定文件:${docs.join(', ')}`,
3385
+ '',
3386
+ '先 read 其中一个(AGENTS.md / CLAUDE.md / CONTRIBUTING.md / .cursorrules),',
3387
+ '确认架构、约定和当前状态后再动手。没有约定文件的仓库不触发这条。',
3388
+ ].join('\n'),
3389
+ };
3390
+ }
3391
+ }
3392
+ return null;
3393
+ },
3394
+
3395
+ /**
3396
+ * Layer 0: a failing command repeated verbatim is not debugging, it is
3397
+ * flailing. After `max_identical_failures` failures the model must do
3398
+ * something investigative (read, graph query, or a real edit) before running
3399
+ * the same command again. The evidence timestamp, not a timer, is what opens
3400
+ * it — "wait a bit and retry" is still mechanical.
3401
+ */
3402
+ 'no-blind-retry': (policy, input, deps) => {
3403
+ if (input.action !== 'bash') return null;
3404
+ const config = policy.config;
3405
+ const key = normalizeCommand(input.command);
3406
+ if (!key) return null;
3407
+ const rec = deps.state.failedCommands.get(key);
3408
+ if (!rec || rec.count < config.max_identical_failures) return null;
3409
+ if (deps.now - rec.lastAt > config.retry_window_ms) return null;
3410
+ if (deps.state.lastInvestigationAt >= rec.lastAt) return null;
3411
+ return {
3412
+ code: 'BLIND_RETRY',
3413
+ reason: [
3414
+ '⛔ 动脑子铁律 · Layer 0 拦截:同一条命令已经失败 ' + rec.count + ' 次,仍要原样重试。',
3415
+ ` 命令:${String(input.command).slice(0, 200)}`,
3416
+ '',
3417
+ '先判根因,再重试。做下面任一动作即可解除:',
3418
+ ' - 读失败输出对应的代码(read / get_code_snippet);',
3419
+ ' - 查图谱(search_graph / trace_path / query_graph);',
3420
+ ' - 做出真正的修改(write / edit)。',
3421
+ '不要靠“再跑一次看看”推进。',
3422
+ ].join('\n'),
3423
+ };
3424
+ },
3425
+
3426
+ /**
3427
+ * AI4S W1: an analysis script may not be the first thing that runs after a
3428
+ * long gap — the Worklog has to be fresher than `worklog_ttl_ms`.
3429
+ *
3430
+ * Only the FIRST run of a given script in a session is judged: a stepwise
3431
+ * pipeline (`01_qc.R`, `02_annotate.R`, …) would otherwise demand a Worklog
3432
+ * edit before every step, which turns the rule into a tax and gets it disabled.
3433
+ *
3434
+ * Blocking BEFORE the run is the whole point: nothing has been computed yet, so
3435
+ * the fix (write down the plan) costs one edit. After the run it is a
3436
+ * retrospective entry nobody reads.
3437
+ */
3438
+ 'ai4s-worklog-before-run': (policy, input, deps) => {
3439
+ if (input.action !== 'bash') return null;
3440
+ const config = policy.config;
3441
+ const firstRun = analysisScriptTargets(input.command, {
3442
+ config,
3443
+ cwd: input.cwd ?? null,
3444
+ isFile: deps.isFile,
3445
+ }).find((script) => !deps.state.scriptsRun.has(normalizePath(script)));
3446
+ if (!firstRun) return null;
3447
+
3448
+ const norm = normalizePath(firstRun);
3449
+ // The Worklog lives at the project root, which the path itself tells us: a
3450
+ // script outside any repository cannot be judged, and guessing a root would
3451
+ // scope the rule to whatever directory the agent happened to start in.
3452
+ const root = scopeOf(norm, { config, exists: deps.exists }).projectRoot
3453
+ ?? findRepoRoot(norm, deps.exists);
3454
+ if (!root) return null; // unknown project: fail open, see ADR-011 §fail-open
3455
+
3456
+ const rel = config.worklog_path ?? DEFAULT_CONFIG.worklog_path;
3457
+ const worklog = normalizePath(join(root, rel));
3458
+ const ttl = Number.isFinite(config.worklog_ttl_ms)
3459
+ ? config.worklog_ttl_ms
3460
+ : DEFAULT_CONFIG.worklog_ttl_ms;
3461
+ const mtime = typeof deps.statMtime === 'function' ? deps.statMtime(worklog) : 0;
3462
+ if (mtime > 0 && deps.now - mtime <= ttl) return null;
3463
+
3464
+ const age = mtime > 0 ? Math.round((deps.now - mtime) / 60000) : null;
3465
+ return {
3466
+ code: 'AI4S_WORKLOG',
3467
+ reason: [
3468
+ '⛔ AI4S 域控 · W1 拦截:跑分析脚本之前没有一份新鲜的 Worklog。',
3469
+ ` 脚本:${norm}`,
3470
+ ` Worklog:${worklog}${age === null ? '(不存在)' : `(最后更新 ${age} 分钟前)`}`,
3471
+ ` 窗口:${Math.round(ttl / 60000)} 分钟`,
3472
+ '',
3473
+ '先把这一轮要做的事写进 Worklog(目标 / 输入数据 / 关键参数 / 预期产出),再跑:',
3474
+ ` - 要做什么、为什么这么做;`,
3475
+ ` - 输入数据与筛选条件;`,
3476
+ ' - 预期产出的目录与文件;',
3477
+ ' - 已知风险与回退方式。',
3478
+ '这不是形式主义:Worklog 是几个月后唯一能回答“当时为什么这么跑”的记录。',
3479
+ ].join('\n'),
3480
+ };
3481
+ },
3482
+
3483
+ /**
3484
+ * AI4S W4 (run half): the script itself must set up a log sink.
3485
+ *
3486
+ * Static and cheap. A run whose output lives only in the agent's scrollback is
3487
+ * unrecoverable — the session ends, the numbers are gone. Checking the source
3488
+ * before the run is the last moment where the fix is free.
3489
+ */
3490
+ 'ai4s-script-log-source': (policy, input, deps) => {
3491
+ if (input.action !== 'bash') return null;
3492
+ if (policy.config.script_log_check === false) return null;
3493
+ const scripts = analysisScriptTargets(input.command, {
3494
+ config: policy.config,
3495
+ cwd: input.cwd ?? null,
3496
+ isFile: deps.isFile,
3497
+ });
3498
+ for (const script of scripts) {
3499
+ // Notebooks and knitted reports keep their own output; see
3500
+ // `log_required_extensions`.
3501
+ if (!hasExtension(script, policy.config.log_required_extensions
3502
+ ?? DEFAULT_CONFIG.log_required_extensions)) continue;
3503
+ const text = typeof deps.readText === 'function' ? deps.readText(script) : null;
3504
+ // Unreadable source is not evidence of a missing log: fail open.
3505
+ if (typeof text !== 'string') continue;
3506
+ if (hasLogInitialization(text, script)) continue;
3507
+ const isR = /\.r(?:md)?$/i.test(script);
3508
+ return {
3509
+ code: 'AI4S_SCRIPT_LOG',
3510
+ reason: [
3511
+ '⛔ AI4S 域控 · W4 拦截:分析脚本没有日志初始化,跑完输出就只剩会话里的滚屏。',
3512
+ ` 脚本:${script}`,
3513
+ '',
3514
+ '给脚本加一段日志初始化,再跑:',
3515
+ isR
3516
+ ? ' R: log_file <- file.path("logs", paste0(basename(sys.frame(1)$ofile %||% "run"), ".log"))\n sink(log_file, split = TRUE); on.exit(close(log_file), add = TRUE)\n message(Sys.time(), " start")'
3517
+ : ' Py: import logging\n logging.basicConfig(filename="logs/run.log", level=logging.INFO,\n format="%(asctime)s %(levelname)s %(message)s")',
3518
+ '',
3519
+ '判定只看“有没有日志初始化”,不看写得对不对;这是能在跑前静态判定的一部分。',
3520
+ ].join('\n'),
3521
+ };
3522
+ }
3523
+ return null;
3524
+ },
3525
+
3526
+ /**
3527
+ * Layer 0: destructive shell operations are never taken on the agent's own
3528
+ * authority.
3529
+ *
3530
+ * Two tiers, and the difference between them is the whole design:
3531
+ *
3532
+ * guardrail (`severity: 'high'`) - unrecoverable. Deleting $HOME, the
3533
+ * cwd, a `..` escape, formatting a
3534
+ * disk, dd onto a raw device. NO grant
3535
+ * can reach these.
3536
+ * permission (`severity: 'confirm'`) - serious but survivable. The category's
3537
+ * tier decides allow / ask / deny.
3538
+ *
3539
+ * Hard (not subject to the block cap): a security rule must not stand down
3540
+ * because a session hit its block limit.
3541
+ */
3542
+ 'no-destructive-bash': (policy, input, deps) => {
3543
+ if (input.action !== 'bash') return null;
3544
+ const finding = shellDestructiveFinding(input, {
3545
+ config: policy.config,
3546
+ cwd: input.cwd ?? null,
3547
+ // Injected, not imported: a git repository root is unrecoverable even when
3548
+ // it is neither $HOME nor an ancestor of the cwd, but this file must stay
3549
+ // disk-free when a harness supplies no probe.
3550
+ isGitRepo: (dir) => deps?.fs?.exists?.(join(dir, '.git')) === true,
3551
+ });
3552
+ // ADR-015: a command aimed at the gate's own directories is not a tier.
3553
+ // Not in `bypass` (where the delete tier is off and it would simply run),
3554
+ // and not a question in `enforce` either - the thing being deleted is the
3555
+ // thing that asks. Answered ahead of the tiers, so the two modes agree;
3556
+ // `no-self-grant` covers it when this check is not loaded.
3557
+ //
3558
+ // Only when the general rule has nothing stronger to say: `rm -rf $HOME` is
3559
+ // a red line in its own right, and a home that happens to contain the gate
3560
+ // must not have that stated in weaker, indirect words.
3561
+ const owned = gateOwnedShellTarget(input, policy.config, deps);
3562
+ if (owned && finding?.severity !== 'high') return gateOwnedVerdict(owned);
3563
+ if (!finding) return null;
3564
+
3565
+ // ---- guardrail: not a permission, and no grant can reach it ----------
3566
+ if (finding.severity === 'high') {
3567
+ // The protected-worktree red line gets its own words (ADR-015). A generic
3568
+ // "irreversible, ask your user" would leave the agent to guess which part
3569
+ // of its command was the problem, and the obvious guess - `git stash` is
3570
+ // fine, `git checkout -- .` then - walks straight into the same line.
3571
+ if (finding.protectedRoot) {
3572
+ return {
3573
+ code: 'DESTRUCTIVE_BASH',
3574
+ reason: [
3575
+ '⛔ 动脑子铁律 · Layer 0 拦截:受保护工作区红线,任何授权、任何模式都不会放行。',
3576
+ ` 原因:${finding.why}`,
3577
+ ` 目录:${finding.protectedRoot}`,
3578
+ ` 命令:${finding.segment}`,
3579
+ '',
3580
+ '这个目录里「没提交的东西」不是待收拾的半成品,而是正在运行的服务赖以工作的状态',
3581
+ '(配置、凭据、会话)。把它们收走或还原,服务下一次读配置就回到出厂状态——',
3582
+ 'git 不报错,agent 当场往往也发现不了,等发现时服务已经掉线很久了。',
3583
+ '',
3584
+ '换办法:',
3585
+ ' · 只想看差异或旧版本 → git status / git diff / git show HEAD:<path>(只读,随便用)',
3586
+ ' · 想带着改动去别处比对 → git diff > <补丁文件>,或另 git worktree add / clone 一份',
3587
+ ' · 确实要清这个工作区 → 停下来,请主人亲手在终端执行',
3588
+ '',
3589
+ '受保护目录登记在 ~/.config/shipgate/machine-override.json 的',
3590
+ 'config.protected_worktrees,只能由主人修改;/gate list 可以看到生效清单。',
3591
+ ].join('\n'),
3592
+ };
3593
+ }
3594
+ return {
3595
+ code: 'DESTRUCTIVE_BASH',
3596
+ reason: [
3597
+ '⛔ 动脑子铁律 · Layer 0 拦截:这条命令不可恢复,任何授权都不会放行。',
3598
+ ` 原因:${finding.why}`,
3599
+ ` 命令:${finding.segment}`,
3600
+ '',
3601
+ '这一档是红线,不是权限:删 $HOME / 删 cwd / 含 .. 的路径 / 磁盘格式化 /',
3602
+ '裸设备写入 / 关机重启 / 受保护工作区里的 git 清场。没有任何 /gate grant 能打开它。',
3603
+ '',
3604
+ '确实要做,请主人手动在终端执行。',
3605
+ 'node_modules / dist / build / .venv 等构建产物的清理不受此限制。',
3606
+ ].join('\n'),
3607
+ };
3608
+ }
3609
+
3610
+ // ---- permission: the category's tier decides --------------------------
3611
+ const category = finding.category ?? 'delete';
3612
+
3613
+ // Bypass (ADR-013) turns the PERMISSION layer off - and only the permission
3614
+ // layer: research, secret, scope, contract and AI4S checks are untouched and
3615
+ // keep running in bypass. It sits AFTER the guardrail return above because
3616
+ // the red lines are not a permission; no mode can reach them.
3617
+ if (isDestructiveBypass(policy.config, deps?.state)) return null;
3618
+
3619
+ const tier = effectiveDestructiveTier(category, policy.config, deps?.state);
3620
+
3621
+ if (tier === 'deny') {
3622
+ return {
3623
+ code: 'DESTRUCTIVE_DENIED',
3624
+ reason: [
3625
+ `⛔ 门控拦截:「${category}」这一类操作已被设为拒绝。`,
3626
+ ` 原因:${finding.why}`,
3627
+ ` 命令:${finding.segment}`,
3628
+ '',
3629
+ `这是主人主动收紧的授权(policy 默认值,或 /gate deny ${category})。`,
3630
+ `要放开:/gate ask ${category}(改成每次询问)或 /gate grant ${category}(直接允许)。`,
3631
+ ].join('\n'),
3632
+ };
3633
+ }
3634
+
3635
+ if (tier === 'allow') return null; // granted: run it
3636
+
3637
+ // `destructive_confirm_mode: false` is the rollback switch. It restores the
3638
+ // pre-2026-11-05 behaviour, but only for the ask tier: the guardrail above
3639
+ // never depended on this switch.
3640
+ if (policy.config.destructive_confirm_mode === false) {
3641
+ return {
3642
+ code: 'DESTRUCTIVE_BASH',
3643
+ reason: [
3644
+ '⛔ 动脑子铁律 · Layer 0 拦截:破坏性命令不允许自动执行。',
3645
+ ` 原因:${finding.why}`,
3646
+ ` 命令:${finding.segment}`,
3647
+ '',
3648
+ '(destructive_confirm_mode 为 false:确认档也按硬拦处理)',
3649
+ '要恢复分级:把 policy.json 的 config.destructive_confirm_mode 设为 true。',
3650
+ ].join('\n'),
3651
+ };
3652
+ }
3653
+
3654
+ return {
3655
+ code: 'DESTRUCTIVE_CONFIRM',
3656
+ confirm: true,
3657
+ confirmCategory: category,
3658
+ reason: [
3659
+ `⚠️ 需要确认:「${category}」这一类操作会丢弃可恢复但重要的东西。`,
3660
+ ` 原因:${finding.why}`,
3661
+ ` 命令:${finding.segment}`,
3662
+ '',
3663
+ '交互模式会弹窗,可选「允许这一次」/「本会话允许这一类」/「拒绝」。',
3664
+ '无 UI 的自动化运行会直接执行并记一行日志。',
3665
+ '不可恢复的操作(删 $HOME / 删 cwd / 含 .. / 磁盘格式化 / 裸设备写入)仍被硬拦,没有授权口。',
3666
+ `想永久调整:/gate list 看当前档位,/gate grant ${category} 或 /gate deny ${category}。`,
3667
+ ].join('\n'),
3668
+ };
3669
+ },
3670
+
3671
+ /**
3672
+ * A grant must be given by the user, never taken by the agent.
3673
+ *
3674
+ * The permission tiers live in two files: the installed `policy.json` and the
3675
+ * machine-local `gate-policy.json`. If the agent could edit either one, every
3676
+ * tier above would be decorative - it would grant itself `allow` on `db-ddl`
3677
+ * and carry on. So the only supported way to change them is the `/gate`
3678
+ * command, which the user types; a write that carries `destructive_grants` is
3679
+ * refused here.
3680
+ *
3681
+ * ADR-015 adds the directory around those files. Refusing to edit a rule is
3682
+ * worth little while the file it is read from can be deleted, and under
3683
+ * `bypass` (ADR-013) that delete tier is exactly what is switched off:
3684
+ * `rm -rf` of the gate's own directory, or of any parent up to the agent's
3685
+ * home, ran unasked and took every rule - red lines included - with it.
3686
+ */
3687
+ 'no-self-grant': (policy, input, deps) => {
3688
+ const isGateFile = (p) => {
3689
+ const posix = String(p ?? '').replace(/\\/g, '/').toLowerCase();
3690
+ if (!posix) return false;
3691
+ return (
3692
+ posix.endsWith('/.config/shipgate/machine-override.json') ||
3693
+ // The truth source: writing the mode here is the same act as writing it
3694
+ // into an override, one step earlier. It must stay off-limits to tools
3695
+ // even though no rule reads the mode from the override any more - the
3696
+ // file a rule DOES read is the more valuable target, not the less.
3697
+ posix.endsWith('/.config/shipgate/gate-policy.json') ||
3698
+ posix.endsWith('/.config/agent-config-bridge/gate-policy.json') ||
3699
+ /\/extensions\/enforce-rules\/policy\.json$/.test(posix)
3700
+ );
3701
+ };
3702
+
3703
+ // The deployed engine, adapter and README are not grants files, and
3704
+ // editing one is the same act by other means.
3705
+ const gateDirs = gateDirsOf(deps);
3706
+ if (input.action === 'write') {
3707
+ if (!isGateFile(input.path)) {
3708
+ return isGateOwned(input.path, gateDirs) ? gateOwnedVerdict(input.path) : null;
3709
+ }
3710
+ // Only the grants block, the mode switch and the protected-worktree list
3711
+ // are protected: a user may still fix a typo in another field by hand,
3712
+ // and a tool that rewrites the whole file without touching any of them is
3713
+ // not self-granting.
3714
+ //
3715
+ // `destructive_mode` must be here too (ADR-013): writing
3716
+ // `{"config":{"destructive_mode":"bypass"}}` would silently turn off the
3717
+ // destructive permission layer for every future session - strictly worse
3718
+ // than granting itself one category, because it is permanent and global.
3719
+ //
3720
+ // `protected_worktrees` for the same reason, one step further (ADR-015):
3721
+ // it is the list that makes a red line out of `git stash`. An agent that
3722
+ // may delete its own directory from that list can un-protect the one
3723
+ // tree the red line exists for, and bypass is not even needed.
3724
+ if (
3725
+ typeof input.content === 'string' &&
3726
+ !/destructive_grants|destructive_mode|protected_worktrees/.test(input.content)
3727
+ ) {
3728
+ // …with one exception. A whole-file rewrite that leaves the list out
3729
+ // un-protects the tree without naming it. Grants and the mode may be
3730
+ // dropped that way (dropping them tightens the gate); the protected
3731
+ // list is a red line, and removing one is never a tightening.
3732
+ if (dropsProtectedList(input.content, input.path, deps?.fs)) {
3733
+ return {
3734
+ code: 'GATE_SELF_GRANT',
3735
+ reason: [
3736
+ '⛔ 门控自保护:agent 不能拆自己的红线。',
3737
+ ` 目标:${input.path}`,
3738
+ '',
3739
+ '这次写入会用一份不含受保护工作区清单(protected_worktrees)的内容覆盖整个文件,',
3740
+ '等于把受保护的目录从红线里摘出去。',
3741
+ '要增删受保护目录,请主人亲手改这个文件(/gate list 可以看到生效清单)。',
3742
+ ].join('\n'),
3743
+ };
3744
+ }
3745
+ return null;
3746
+ }
3747
+ return {
3748
+ code: 'GATE_SELF_GRANT',
3749
+ reason: [
3750
+ '⛔ 门控自保护:agent 不能给自己提权。',
3751
+ ` 目标:${input.path}`,
3752
+ '',
3753
+ '这次写入会改动破坏性操作的授权表(destructive_grants)、门控模式(destructive_mode)',
3754
+ '或受保护工作区清单(protected_worktrees)。',
3755
+ '三者只能由用户亲手改:',
3756
+ ' 1) 交互弹窗里选「本会话允许 <类别>」—— 只对当前会话有效;',
3757
+ ' 2) 敲 /gate grant <类别> —— 持久(写机器本地 machine-override.json 的授权档位);',
3758
+ ' 3) 敲 /gate deny <类别> —— 收紧;/gate list 查看当前档位;',
3759
+ ' 4) 敲 /gate mode bypass|enforce [时长] [session] —— 切换门控模式',
3760
+ ' (真源 ~/.config/shipgate/gate-policy.json,由 ShipGate CLI 写并同步到各 harness)。',
3761
+ '',
3762
+ '为什么不让 agent 写:如果 agent 能改授权表或模式开关,所有分级都变成装饰——',
3763
+ '它只要给自己 allow db-ddl 或 destructive_mode: bypass 就绕过了破坏性命令门控;',
3764
+ '能改受保护清单,就能把挡着自己的那条红线拆掉。',
3765
+ ].join('\n'),
3766
+ };
3767
+ }
3768
+
3769
+ if (input.action === 'bash') {
3770
+ const targets = shellWriteTargets(input, {
3771
+ config: policy.config,
3772
+ cwd: input.cwd ?? null,
3773
+ isFile: deps?.isFile,
3774
+ exists: deps?.exists,
3775
+ });
3776
+ const removing = typeof input.command === 'string' && shellUsesAny(input.command, GATE_REMOVAL_VERBS);
3777
+ let hit = targets.find((target) => isGateFile(target) || isGateOwned(target, gateDirs, removing));
3778
+ if (!hit && typeof input.command === 'string' && shellUsesAny(input.command, GATE_MOVE_VERBS)) {
3779
+ hit = gateOwnedShellTarget(input, policy.config, deps);
3780
+ }
3781
+ if (!hit) return null;
3782
+ if (!isGateFile(hit)) return gateOwnedVerdict(hit);
3783
+ return {
3784
+ code: 'GATE_SELF_GRANT',
3785
+ reason: [
3786
+ '⛔ 门控自保护:agent 不能给自己提权。',
3787
+ ` 目标:${hit}`,
3788
+ '',
3789
+ '用 shell 改写授权表同样不允许。授权只能由用户亲手给:',
3790
+ ' /gate grant <类别> / /gate ask <类别> / /gate deny <类别> / /gate list',
3791
+ '',
3792
+ '为什么不让 agent 写:如果 agent 能改授权表,所有分级都变成装饰。',
3793
+ ].join('\n'),
3794
+ };
3795
+ }
3796
+ return null;
3797
+ },
3798
+
3799
+ /** Don't read source before consulting the code graph. */
3800
+ 'graph-before-read': (policy, input, deps) => {
3801
+ if (input.action !== 'read') return null;
3802
+ const scope = scopeOf(input.path, { config: policy.config, exists: deps.exists });
3803
+ if (!scope.inScope) return null;
3804
+ if (deps.state.written.has(input.path)) return null;
3805
+ if (hasUnlock(deps.state, input.path, policy.config, deps.now)) return null;
3806
+ return {
3807
+ code: 'GRAPH_FIRST',
3808
+ reason: [
3809
+ '⛔ 三层铁律 · Layer 1 拦截:本次读取没有图谱依据。',
3810
+ ` 文件:${input.path}`,
3811
+ ` 依据:${scope.reason}(项目根:${scope.root ?? '未知'})`,
3812
+ '',
3813
+ '解除方式(二选一,都需要**成功且有内容**的图谱调用):',
3814
+ ' a) 针对本文件/本包查一次:search_graph / trace_path / get_code_snippet /',
3815
+ ' query_graph / get_architecture / search_code(查询里提到文件名或包名,',
3816
+ ' 命中后 30 分钟内该目标的读取都放行);',
3817
+ ' b) 任何一次有结果的图谱调用会给本会话一个 10 分钟的窗口。',
3818
+ '如果查询返回空结果,不算合规:先查 index_status / 重新索引,回到图谱重查;',
3819
+ '不允许“搜不到就直接 read”。',
3820
+ '本会话内你自己刚改过的文件不受此限制。',
3821
+ ].join('\n'),
3822
+ };
3823
+ },
3824
+
3825
+ /** The same rule for reads that arrive as bash commands (cat/grep/sed -n/…). */
3826
+ 'bash-graph-before-read': (policy, input, deps) => {
3827
+ if (input.action !== 'bash') return null;
3828
+ if (policy.config.bash_read_check === false) return null;
3829
+ const opts = {
3830
+ config: policy.config,
3831
+ cwd: input.cwd ?? null,
3832
+ isFile: deps.isFile,
3833
+ exists: deps.exists,
3834
+ };
3835
+ const targets = shellReadTargets(input, opts);
3836
+ const dirs = shellReadDirs(input, opts);
3837
+ if (targets.length === 0 && dirs.length === 0) return null;
3838
+
3839
+ const blockedFile = targets.find((target) => {
3840
+ const scope = scopeOf(target, { config: policy.config, exists: deps.exists });
3841
+ if (!scope.inScope) return false;
3842
+ if (deps.state.written.has(normalizePath(target))) return false;
3843
+ return !hasUnlock(deps.state, target, policy.config, deps.now);
3844
+ });
3845
+ const blockedDir = dirs.find((dir) => {
3846
+ if (deps.state.written.has(normalizePath(dir))) return false;
3847
+ return !hasUnlock(deps.state, dir, policy.config, deps.now);
3848
+ });
3849
+ if (!blockedFile && !blockedDir) return null;
3850
+
3851
+ return {
3852
+ code: 'GRAPH_FIRST_BASH',
3853
+ reason: [
3854
+ '⛔ 三层铁律 · Layer 1 拦截:用 bash 读源码和用 read 工具读源码是同一件事。',
3855
+ ` 命令:${String(input.command).slice(0, 200)}`,
3856
+ blockedFile ? ` 目标文件:${blockedFile}` : ` 目标目录:${blockedDir}`,
3857
+ targets.length > 1 || dirs.length > 1
3858
+ ? ` (共识别到 ${targets.length} 个文件、${dirs.length} 个目录,只列了第一个)`
3859
+ : '',
3860
+ '',
3861
+ '先查图谱(search_graph / trace_path / get_code_snippet / query_graph /',
3862
+ 'get_architecture / search_code),查询里提到该文件/包/目录,然后重试。',
3863
+ 'cat / grep -r / sed -n / git show / git diff / find -exec / xargs 都在范围内;',
3864
+ 'git status / ls / find 只列名字不受影响。',
3865
+ ]
3866
+ .filter(Boolean)
3867
+ .join('\n'),
3868
+ };
3869
+ },
3870
+
3871
+ /**
3872
+ * A read that the rule wants gated on an index existing at all.
3873
+ *
3874
+ * Opt-in, not default. codebase-memory's live index normally lives in the
3875
+ * tool's own data directory, not in `<repo>/.codebase-memory` (that marker
3876
+ * only exists when persistence was requested). Enabling this check on a
3877
+ * global index therefore blocks every read until the cap, and the v3 answer
3878
+ * is evidence instead: an empty graph result no longer counts as a signal, so
3879
+ * an unindexed project cannot buy a read window at all. Keep this check for
3880
+ * teams that do commit the persisted artifact.
3881
+ */
3882
+ 'index-before-read': (policy, input, deps) => {
3883
+ if (input.action !== 'read') return null;
3884
+ const scope = scopeOf(input.path, { config: policy.config, exists: deps.exists });
3885
+ if (!scope.inScope || !scope.root) return null;
3886
+ if (deps.state.written.has(input.path)) return null;
3887
+ const marker = join(scope.projectRoot ?? scope.root, policy.config.index_marker);
3888
+ if (deps.exists(marker)) return null;
3889
+ return {
3890
+ code: 'INDEX_FIRST',
3891
+ reason: [
3892
+ '⛔ 三层铁律 · Layer 2 拦截:该项目尚未建立 codebase-memory 索引。',
3893
+ ` 仓库:${scope.root}`,
3894
+ ` 缺少:${marker}`,
3895
+ '',
3896
+ `正确动作:先调用 index_repository(repo_path 取 ${scope.root};模式按规模选 full/moderate/fast)`,
3897
+ '建立索引与 embedding;索引完成后回到 Layer 1 查图谱(search_graph / trace_path /',
3898
+ 'get_code_snippet 等),最后才可直读。',
3899
+ '若你的索引是全局存储(没有 .codebase-memory 持久化产物),请从 policy.json 的',
3900
+ 'checks 里去掉本项:它无法验证全局索引,会误拦。',
3901
+ ].join('\n'),
3902
+ };
3903
+ },
3904
+
3905
+ /**
3906
+ * The index exists but the file is newer than anything inside it.
3907
+ *
3908
+ * v3 removes the "fresh graph signal" shortcut. A query against a stale index
3909
+ * is precisely the failure this check exists to catch: letting that query
3910
+ * stand the rule down made the check unreachable in practice. The session's
3911
+ * own writes remain exempt (they are always newer than the index they are
3912
+ * about to update), and the check still abstains when the marker or its
3913
+ * mtimes are unreadable.
3914
+ */
3915
+ 'index-freshness-before-read': (policy, input, deps) => {
3916
+ if (input.action !== 'read') return null;
3917
+ const scope = scopeOf(input.path, { config: policy.config, exists: deps.exists });
3918
+ if (!scope.inScope || !scope.root) return null;
3919
+ if (deps.state.written.has(input.path)) return null;
3920
+
3921
+ const mtime = deps.statMtime(input.path);
3922
+ if (!(mtime > 0)) return null; // vanished, unreadable, or a directory: abstain
3923
+
3924
+ // Prefer a real persisted marker when the indexer created one. Otherwise
3925
+ // fall back to the session's own successful index refresh: the default
3926
+ // codebase-memory index lives in a global data directory, so requiring a
3927
+ // repo-local marker made this check abstain on every normal project.
3928
+ const marker = join(scope.projectRoot ?? scope.root, policy.config.index_marker);
3929
+ let evidenceAt = 0;
3930
+ if (deps.exists(marker)) {
3931
+ evidenceAt = newestMtimeIn(marker, deps, deps.now, policy.config.index_mtime_ttl_ms);
3932
+ }
3933
+ if (!(evidenceAt > 0)) evidenceAt = deps.state.lastIndexRefreshAt ?? 0;
3934
+ if (!(evidenceAt > 0)) return null; // no evidence either way: abstain (graph rule still gates)
3935
+ if (mtime <= evidenceAt + policy.config.index_mtime_epsilon_ms) return null;
3936
+
3937
+ return {
3938
+ code: 'INDEX_STALE',
3939
+ reason: [
3940
+ '⛔ 三层铁律 · Layer 2 拦截:索引疑似过期——目标文件比索引新(embedding 落后于代码变更)。',
3941
+ ` 目标:${input.path}`,
3942
+ ` 所属已索引项目:${scope.root}`,
3943
+ '',
3944
+ '正确动作:先 detect_changes 检查影响范围,或 index_repository 重新索引;完成后回到',
3945
+ 'Layer 1 查图谱,最后才可直读。',
3946
+ '这次查询成功也不能代替索引更新:查的是旧图,读的是新代码。',
3947
+ '本会话内你自己刚改过的文件不受此拦截。',
3948
+ ].join('\n'),
3949
+ };
3950
+ },
3951
+
3952
+ /** Never write outside the paths the user declared writable. */
3953
+ 'no-write-outside': (policy, input, deps) => {
3954
+ if (input.action !== 'write' && input.action !== 'bash') return null;
3955
+ const allowed = policy.config.write_roots ?? [];
3956
+ if (allowed.length === 0) return null;
3957
+ const targets = input.action === 'write'
3958
+ ? [input.path].filter(Boolean)
3959
+ : shellWriteTargets(input, {
3960
+ config: policy.config,
3961
+ cwd: input.cwd ?? null,
3962
+ isFile: deps.isFile,
3963
+ exists: deps.exists,
3964
+ });
3965
+ if (targets.length === 0) return null;
3966
+ const outside = targets.filter((p) => !allowed.some((r) => withinRoot(r, p)));
3967
+ if (outside.length === 0) return null;
3968
+ return {
3969
+ code: 'WRITE_OUTSIDE',
3970
+ reason: [
3971
+ 'Blocked: writing outside the allowed roots.',
3972
+ ` path : ${outside[0]}`,
3973
+ outside.length > 1 ? ` (and ${outside.length - 1} more)` : '',
3974
+ ` allowed : ${allowed.join(', ')}`,
3975
+ '',
3976
+ 'Add the root to config.write_roots in the gate policy if this write is intended.',
3977
+ 'This also covers shell writes (redirection, tee, cp/mv, rm).',
3978
+ ]
3979
+ .filter(Boolean)
3980
+ .join('\n'),
3981
+ };
3982
+ },
3983
+
3984
+ /** Never let a credential-shaped string be written into a tracked file. */
3985
+ 'no-secret-write': (policy, input, deps) => {
3986
+ if (input.action !== 'write' && input.action !== 'bash') return null;
3987
+ const isBash = input.action === 'bash';
3988
+ if (isBash) {
3989
+ // Only scan when the command actually writes; `git commit -m "..."` is
3990
+ // not a file write and must not be judged as one.
3991
+ const writes = shellWriteTargets(input, {
3992
+ config: policy.config,
3993
+ cwd: input.cwd ?? null,
3994
+ isFile: deps.isFile,
3995
+ exists: deps.exists,
3996
+ });
3997
+ if (writes.length === 0) return null;
3998
+ }
3999
+ const text = input.content ?? (isBash ? input.command : '');
4000
+ if (typeof text !== 'string' || text === '') return null;
4001
+ const hits = scanForSecrets(text, policy.config);
4002
+ if (hits.length === 0) return null;
4003
+ return {
4004
+ code: 'SECRET_WRITE',
4005
+ reason: [
4006
+ 'Blocked: the content being written looks like it contains a real credential.',
4007
+ ...hits.slice(0, 5).map((h) => ` ${h}`),
4008
+ '',
4009
+ 'Replace it with a placeholder and keep the real value outside the repository.',
4010
+ isBash ? 'Shell writes (redirection, tee, sed -i) are covered by this rule too.' : '',
4011
+ ]
4012
+ .filter(Boolean)
4013
+ .join('\n'),
4014
+ };
4015
+ },
4016
+ };
4017
+
4018
+ /** Patterns that should never be committed. Deliberately the same families the
4019
+ * repository scanner uses, so the two cannot disagree about "what is a secret". */
4020
+ const SECRET_PATTERNS = [
4021
+ ['private key block', /-----BEGIN [A-Z ]*PRIVATE KEY-----/],
4022
+ ['api key assignment', /(api[_-]?key|apikey|token|secret|password|passwd)['"`]?\s*[:=]\s*["'`]?[A-Za-z0-9_\-]{16,}/i],
4023
+ ['long opaque token', /(^|[^A-Za-z0-9_+=])[A-Za-z0-9_+=]{40,}([^A-Za-z0-9_+=]|$)/],
4024
+ ];
4025
+
4026
+ /** A bare mailbox is not a credential. It only matters next to a credential field. */
4027
+ const EMAIL_ADDRESS = /[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/;
4028
+ const CREDENTIAL_FIELD = /(?:api[_-]?key|apikey|token|secret|password|passwd|credential)['"`]?\s*[:=]/i;
4029
+
4030
+ export const scanForSecrets = (text, config = DEFAULT_CONFIG) => {
4031
+ const allowed = config.secret_allow_patterns ?? [
4032
+ 'example\\.com',
4033
+ '127\\.0\\.0\\.1',
4034
+ '\\$\\{[A-Za-z_][A-Za-z0-9_]*\\}',
4035
+ '<[^<>\\s]+>',
4036
+ ];
4037
+ const allow = new RegExp(allowed.join('|'));
4038
+ const hits = [];
4039
+ for (const [label, re] of SECRET_PATTERNS) {
4040
+ const m = re.exec(text);
4041
+ if (m && !allow.test(m[0])) {
4042
+ const sample = m[0].length > 40 ? `${m[0].slice(0, 20)}…` : m[0];
4043
+ hits.push(`${label}: ${sample.replace(/\s+/g, ' ')}`);
4044
+ }
4045
+ }
4046
+ // v4: a mailbox alone is ordinary prose (READMEs, examples, contact info).
4047
+ // It is a credential signal only when a credential field sits next to it.
4048
+ const mail = EMAIL_ADDRESS.exec(text);
4049
+ if (mail && !allow.test(mail[0])) {
4050
+ const from = Math.max(0, mail.index - 40);
4051
+ const to = mail.index + mail[0].length + 40;
4052
+ const around = text.slice(from, to);
4053
+ if (CREDENTIAL_FIELD.test(around)) {
4054
+ const sample = mail[0].length > 40 ? `${mail[0].slice(0, 20)}…` : mail[0];
4055
+ hits.push(`credential email: ${sample}`);
4056
+ }
4057
+ }
4058
+ return hits;
4059
+ };
4060
+
4061
+ export const CHECK_NAMES = Object.keys(CHECKS);
4062
+
4063
+ /**
4064
+ * Checks that stay on after the per-session block cap.
4065
+ *
4066
+ * The cap exists so a mis-written research rule cannot brick an agent. It must
4067
+ * not also switch off safety: before v3, `shouldBlock` returned early once the
4068
+ * cap was reached, which turned 30 graph blocks into a free pass to write a
4069
+ * credential anywhere. Layer-0/1/2 checks are capped; the security checks are
4070
+ * not.
4071
+ */
4072
+ export const HARD_CHECKS = new Set([
4073
+ 'no-write-outside',
4074
+ 'no-secret-write',
4075
+ 'no-destructive-bash',
4076
+ // The self-grant guard protects the permission table itself. If it stood down
4077
+ // under the block cap, an agent could spend the cap and then write itself an
4078
+ // `allow` on `db-ddl`.
4079
+ 'no-self-grant',
4080
+ // ai-spec 契约门控:不得因拦截上限而失效——它守的是「不跑偏」,与安全同级。
4081
+ 'chg-contract-before-edit',
4082
+ ]);
4083
+
4084
+ // ---------------------------------------------------------------------------
4085
+ // Evaluation
4086
+ // ---------------------------------------------------------------------------
4087
+
4088
+ /**
4089
+ * Decide whether to block a normalized tool call.
4090
+ *
4091
+ * @param {object} args
4092
+ * @param {object} args.policy
4093
+ * @param {{action:string, path:string|null, tool:string, content?:string}} args.input
4094
+ * @param {object} args.state from newSessionState()
4095
+ * @param {(p:string)=>boolean} [args.exists] filesystem probe, injected
4096
+ * @param {object} [args.fs] full probe: {exists, isFile, statMtime, listDir}. Supersedes `exists`.
4097
+ * @param {number} [args.now]
4098
+ * @returns {{block: boolean, code: string|null, reason: string|null, capReached: boolean}}
4099
+ */
4100
+ export const shouldBlock = ({ policy, input, state, exists, fs, now = Date.now() }) => {
4101
+ const cap = policy.config.max_blocks_per_session;
4102
+ // v4: the cap is a sliding window, not a lifetime sentence. A long session
4103
+ // used to spend 30 blocks on ordinary reads and then lose every research rule
4104
+ // for the rest of its life.
4105
+ const resetMs = policy.config.block_cap_reset_ms ?? 0;
4106
+ if (resetMs > 0 && state.blocks > 0 && state.firstBlockAt > 0 && now - state.firstBlockAt > resetMs) {
4107
+ state.blocks = 0;
4108
+ state.firstBlockAt = 0;
4109
+ }
4110
+ const overCap = cap >= 0 && state.blocks >= cap;
4111
+
4112
+ // One probe object, so a check that needs more than `exists` can get it
4113
+ // without each check inventing its own seam. The flat `exists` shape stays
4114
+ // supported because it is what the unit tests and simpler harnesses pass.
4115
+ const probes = fs ?? { ...NO_FS, exists: typeof exists === 'function' ? exists : NO_FS.exists };
4116
+
4117
+ const enabled = new Set(policy.checks.length > 0 ? policy.checks : ['graph-before-read']);
4118
+ for (const name of enabled) {
4119
+ // After the cap, only the safety checks keep running. The research rules
4120
+ // stand down so a false positive cannot brick the session; hiding a secret
4121
+ // or deleting a tree has no such excuse.
4122
+ if (overCap && !HARD_CHECKS.has(name)) continue;
4123
+ const check = CHECKS[name];
4124
+ if (!check) continue; // unknown check names are ignored, not fatal
4125
+ const verdict = check(policy, input, { state, exists: probes.exists, fs: probes, ...probes, now });
4126
+ if (verdict) {
4127
+ // A confirmation is not a refusal: the call has not been denied, the user
4128
+ // has not been asked yet. Counting it against the block cap would let a
4129
+ // few ordinary deletes spend the session's rule budget, and reporting
4130
+ // `block: true` would stop the adapter from ever asking.
4131
+ if (verdict.confirm) {
4132
+ return {
4133
+ block: false,
4134
+ code: null,
4135
+ reason: null,
4136
+ capReached: overCap,
4137
+ confirm: true,
4138
+ confirmReason: verdict.reason ?? null,
4139
+ confirmCategory: verdict.confirmCategory ?? null,
4140
+ };
4141
+ }
4142
+ state.blocks += 1;
4143
+ if (!(state.firstBlockAt > 0)) state.firstBlockAt = now;
4144
+ return {
4145
+ block: true,
4146
+ code: verdict.code,
4147
+ reason: verdict.reason,
4148
+ capReached: false,
4149
+ confirm: false,
4150
+ confirmReason: null,
4151
+ confirmCategory: null,
4152
+ };
4153
+ }
4154
+ }
4155
+ return {
4156
+ block: false,
4157
+ code: null,
4158
+ reason: null,
4159
+ capReached: overCap,
4160
+ confirm: false,
4161
+ confirmReason: null,
4162
+ confirmCategory: null,
4163
+ };
4164
+ };
4165
+
4166
+ // ---------------------------------------------------------------------------
4167
+ // Turn-level anti-slack: "I'll do it later" is not a delivery
4168
+ // ---------------------------------------------------------------------------
4169
+
4170
+ /**
4171
+ * First-person deferrals about the current task. Kept deliberately narrow:
4172
+ * ordinary Q&A ("next you can run node --test") must not match, and text inside
4173
+ * code fences / blockquotes is documentation rather than a promise.
4174
+ */
4175
+ const SLACK_PATTERNS = [
4176
+ /(?:我|我们)\s*(?:先|暂时|暂且)\s*(?:不|不做|不处理|跳过|略过)/,
4177
+ /(?:稍后|后续|之后|下一轮|下次|明天|下周|下个版本)\s*(?:再|继续)\s*(?:做|补|实现|处理|完善|修复|跟进|优化)/,
4178
+ /(?:我|我们)\s*(?:会|将|准备|打算|计划)\s*(?:在)?\s*(?:稍后|后续|之后|下一轮|下次|明天|下周|下个版本)/,
4179
+ /(?:留待|留到|留给|放到)\s*(?:后续|下次|下一轮|之后)/,
4180
+ /(?:还有|仍有|留有|存在)\s*(?:TODO|FIXME|待办|未完成|占位)/,
4181
+ /\bI(?:'ll| will| am going to| plan to)\b[^.\n]{0,50}\b(?:later|next turn|afterwards|tomorrow|next week|next version)\b/i,
4182
+ /\b(?:leave|defer|deferring)\b[^.\n]{0,30}\b(?:for later|to the next|afterwards)\b/i,
4183
+ ];
4184
+
4185
+ /**
4186
+ * Decide whether an assistant reply is a deferral instead of a delivery.
4187
+ * @returns {{code:string, excerpt:string, reason:string}|null}
4188
+ */
4189
+ export const slackFinding = (text, config = DEFAULT_CONFIG) => {
4190
+ if (config.slack_check === false) return null;
4191
+ // CJK text is information-dense: "这个我稍后再补完。" is 9 characters and a
4192
+ // complete deferral. A 12-character floor (borrowed from English intuition)
4193
+ // made the rule miss exactly the short replies it exists to catch.
4194
+ if (typeof text !== 'string' || text.trim().length < 6) return null;
4195
+ const prose = text
4196
+ .replace(/```[\s\S]*?```/g, '')
4197
+ .replace(/`[^`\n]*`/g, '')
4198
+ .split('\n')
4199
+ .filter((line) => !/^\s*>/.test(line))
4200
+ .join('\n');
4201
+ if (prose.trim().length < 6) return null;
4202
+ const extra = (config.slack_patterns ?? [])
4203
+ .map((src) => {
4204
+ try {
4205
+ return new RegExp(src, 'i');
4206
+ } catch {
4207
+ return null;
4208
+ }
4209
+ })
4210
+ .filter(Boolean);
4211
+ for (const re of [...SLACK_PATTERNS, ...extra]) {
4212
+ const m = re.exec(prose);
4213
+ if (!m) continue;
4214
+ const at = Math.max(0, m.index - 10);
4215
+ const excerpt = prose.slice(at, m.index + m[0].length + 20).replace(/\s+/g, ' ').trim();
4216
+ return {
4217
+ code: 'NO_SLACK',
4218
+ excerpt,
4219
+ reason: [
4220
+ '⛔ 不偷懒铁律 · 轮次级拦截:检测到「把本任务留给以后」的承诺,而不是交付。',
4221
+ ` 命中:…${excerpt}…`,
4222
+ '',
4223
+ '这一轮必须二选一:',
4224
+ ' a) 直接调用工具把它做完(不要只复述计划);',
4225
+ ' b) 如果确实被外部条件阻塞(缺少凭据、服务不可用、需要用户决策),',
4226
+ ' 把阻塞点和已尝试的动作写清楚,并明确说明「这不是交付」。',
4227
+ '不要用「稍后再补 / 后续处理 / 先不实现」结束这一轮。',
4228
+ ].join('\n'),
4229
+ };
4230
+ }
4231
+ return null;
4232
+ };
4233
+
4234
+ /**
4235
+ * The per-turn nudge appended to the model's context.
4236
+ *
4237
+ * A gate that only says "no" teaches nothing; the reminder is what makes the
4238
+ * rule learnable. Returns null when the session is already compliant, so a
4239
+ * well-behaved session is not nagged.
4240
+ */
4241
+ export const reminderFor = (policy, state, now = Date.now()) => {
4242
+ // The base text and the profile text have different silences, on purpose.
4243
+ //
4244
+ // The base reminder teaches "ask the graph first", so a fresh graph signal means
4245
+ // it has been heard. The profile reminder teaches Worklog / log / result notes —
4246
+ // behaviours a graph query says nothing about — so it keeps being injected while
4247
+ // the domain is active. Silencing it after the first graph call would mean the
4248
+ // research rules are mentioned once per session and then never again.
4249
+ let base = null;
4250
+ if (policy.reminded) {
4251
+ // A session-wide signal silences the reminder, except while Layer 0 still has
4252
+ // a specific gap: the model has queried the graph but has not read the
4253
+ // project's conventions yet. Silence there would teach "query once, then act".
4254
+ const conventionsPending =
4255
+ policy.checks.includes('think-before-write') &&
4256
+ policy.config.require_conventions &&
4257
+ state.docReads.size === 0;
4258
+ if (!hasFreshSignal(state, policy.config.signal_ttl_ms, now) || conventionsPending) {
4259
+ base = policy.reminded;
4260
+ }
4261
+ }
4262
+ const profileReminder = profileFor(policy, state?.profile)?.reminder ?? '';
4263
+ const parts = [base, profileReminder].filter((t) => typeof t === 'string' && t !== '');
4264
+ return parts.length > 0 ? parts.join('\n\n') : null;
4265
+ };
4266
+
4267
+ export const globHelpers = { toPosix, posix };