shipgate-cli 0.0.0-stage → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (122) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +258 -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 +1121 -0
  10. package/assets/gates/pi/policy.json +93 -0
  11. package/assets/gates/policy.js +4199 -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 +215 -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 +117 -0
  99. package/src/commands/ask.mjs +82 -0
  100. package/src/commands/deploy.mjs +589 -0
  101. package/src/commands/gates.mjs +83 -0
  102. package/src/commands/policy.mjs +67 -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/engines.mjs +182 -0
  111. package/src/lib/exec.mjs +80 -0
  112. package/src/lib/fsx.mjs +119 -0
  113. package/src/lib/gate.mjs +288 -0
  114. package/src/lib/log.mjs +31 -0
  115. package/src/lib/skills.mjs +347 -0
  116. package/src/lib/state.mjs +41 -0
  117. package/src/lib/update.mjs +67 -0
  118. package/src/version.mjs +14 -0
  119. package/templates/agents-snippet.md +82 -0
  120. package/templates/dev-profile.schema.json +119 -0
  121. package/templates/prd.json.example +64 -0
  122. package/templates/rule.json.example +28 -0
@@ -0,0 +1,1121 @@
1
+ /**
2
+ * pi adapter for the hard-gate policy.
3
+ *
4
+ * pi's extension API offers two points this gate needs:
5
+ * pi.on('tool_call', ...) -> { block: true, reason } (enforce)
6
+ * pi.on('context', ...) -> { messages } (remind each turn)
7
+ *
8
+ * Everything that decides *whether* to block lives in ../policy.js. This file
9
+ * only translates: pi event -> normalized input -> policy question -> pi result.
10
+ *
11
+ * Install: copy this directory to <pi agent dir>/extensions/enforce-rules/
12
+ * Installed by the bridge itself: bridge/lib/gates.js plans these files, so `adopt`
13
+ * snapshots them and `revoke` removes them again.
14
+ */
15
+
16
+ import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
17
+ import { dirname, join } from 'node:path';
18
+ import { fileURLToPath } from 'node:url';
19
+
20
+ import {
21
+ analysisScriptTargets,
22
+ applyMachineOverride,
23
+ DESTRUCTIVE_CATEGORIES,
24
+ DESTRUCTIVE_MODES,
25
+ destructiveModeRemainingMs,
26
+ effectiveDestructiveMode,
27
+ effectiveDestructiveTier,
28
+ isDestructiveBypass,
29
+ machineGateConfigPath,
30
+ bashReadTargets,
31
+ graphResultIsEvidence,
32
+ outputArtifactFindings,
33
+ powershellReadTargets,
34
+ profilePolicy,
35
+ recordIndexRefresh,
36
+ recordScriptRun,
37
+ shellReadTargets,
38
+ slackFinding,
39
+ isChgContract,
40
+ isConventionDoc,
41
+ loadPolicy,
42
+ machineProtectedListProblems,
43
+ newSessionState,
44
+ normalizePath,
45
+ normalizeProtectedWorktrees,
46
+ policyFromObject,
47
+ protectedRootOf,
48
+ recordCommandResult,
49
+ recordDocRead,
50
+ recordInspection,
51
+ recordInvestigation,
52
+ recordSignal,
53
+ recordUnlocks,
54
+ recordWrite,
55
+ reminderFor,
56
+ resetMtimeCache,
57
+ shouldBlock,
58
+ unlockTokensFromQualifiedName,
59
+ unlockTokensFromText,
60
+ } from '../policy.js';
61
+ import { classify } from '../classifier.js';
62
+
63
+ const HERE = dirname(fileURLToPath(import.meta.url));
64
+
65
+ /**
66
+ * The filesystem probe the policy consults.
67
+ *
68
+ * Everything here answers instead of throwing: a probe that throws turns a
69
+ * filesystem hiccup into a dead gate, and a gate that stops existing is the one
70
+ * failure this design is built to avoid. `listDir` and `statMtime` exist for
71
+ * the index-freshness rule; the plain `exists` is what scoping uses.
72
+ */
73
+ export const realFs = {
74
+ exists: (p) => existsSync(p),
75
+ isFile: (p) => {
76
+ try {
77
+ return statSync(p).isFile();
78
+ } catch {
79
+ return false;
80
+ }
81
+ },
82
+ isDirectory: (p) => {
83
+ try {
84
+ return statSync(p).isDirectory();
85
+ } catch {
86
+ return false;
87
+ }
88
+ },
89
+ statMtime: (p) => {
90
+ try {
91
+ return statSync(p).mtimeMs;
92
+ } catch {
93
+ return 0;
94
+ }
95
+ },
96
+ listDir: (dir) => {
97
+ try {
98
+ return readdirSync(dir);
99
+ } catch {
100
+ return [];
101
+ }
102
+ },
103
+ /**
104
+ * Source text of a file, for the AI4S "does the script log?" check.
105
+ * `null` (not a throw) when it cannot be read: an unreadable script is not
106
+ * evidence that its author forgot logging, so the check must abstain.
107
+ */
108
+ readText: (p) => {
109
+ try {
110
+ return readFileSync(p, 'utf8');
111
+ } catch {
112
+ return null;
113
+ }
114
+ },
115
+ /**
116
+ * ADR-015: the directories this gate is made of, for `no-self-grant` - where
117
+ * it is installed, and where its machine-local override lives. Only an
118
+ * INSTALLED gate counts: in a repository checkout the adapter's directory is
119
+ * source its author may edit. The two layouts tell themselves apart here -
120
+ * installed is `<gate dir>/pi/index.js` beside `<gate dir>/policy.json`; a
121
+ * checkout keeps its copy in this directory.
122
+ */
123
+ gateDirs: [
124
+ existsSync(join(HERE, '..', 'policy.json')) ? dirname(HERE) : null,
125
+ machineGateConfigPath() ? dirname(machineGateConfigPath()) : null,
126
+ ].filter(Boolean),
127
+ };
128
+
129
+ /**
130
+ * Where the policy JSON can live.
131
+ *
132
+ * Two layouts have to work, and getting this wrong fails SILENTLY (the gate
133
+ * falls back to fail-open), which is the worst possible failure mode for an
134
+ * enforcement point:
135
+ *
136
+ * repo checkout : bridge/gates/pi/policy.json <- next to this adapter
137
+ * installed : <gate dir>/pi/index.js
138
+ * <gate dir>/policy.json <- generated by the installer
139
+ *
140
+ * So the adapter-local file is checked first (developer layout), then the gate
141
+ * root (installed layout). A caller-supplied path always wins.
142
+ */
143
+ export const policyCandidates = (here, explicit) =>
144
+ [explicit, join(here, 'policy.json'), join(here, '..', 'policy.json')].filter(Boolean);
145
+
146
+ export const firstExistingPolicy = (here, explicit, exists = existsSync) => {
147
+ for (const candidate of policyCandidates(here, explicit)) {
148
+ if (exists(candidate)) return candidate;
149
+ }
150
+ return null;
151
+ };
152
+
153
+ /** Tool names that count as "the model consulted the code graph". */
154
+ const SIGNAL_TOOLS = [
155
+ 'search_graph',
156
+ 'trace_path',
157
+ 'get_code_snippet',
158
+ 'query_graph',
159
+ 'get_architecture',
160
+ 'search_code',
161
+ ];
162
+
163
+ /**
164
+ * Tool-name aliases. pi's own tools are read/write/edit/bash, but extensions
165
+ * and other harnesses reuse the same policy with `read_file`, `apply_patch`,
166
+ * `str_replace_editor` and friends. An unknown write tool used to fall through
167
+ * the adapter untouched — a silent bypass for Layer 0 and the secret rule.
168
+ */
169
+ const READ_TOOLS = new Set(['read', 'read_file', 'view', 'open_file']);
170
+ const WRITE_TOOLS = new Set([
171
+ 'write', 'edit', 'apply_patch', 'str_replace_editor', 'create_file', 'multi_edit', 'notebook_edit',
172
+ 'write_file', 'append_file', 'delete_file',
173
+ ]);
174
+
175
+ /** The path spelling a tool input uses, whichever harness it came from. */
176
+ const inputPath = (input) => input?.path ?? input?.file_path ?? null;
177
+
178
+ /** The text a write tool is about to insert, across the common schemas. */
179
+ const inputContent = (input) =>
180
+ [input?.content, input?.newText, input?.new_string, input?.patch, input?.text]
181
+ .find((v) => typeof v === 'string') ?? null;
182
+
183
+ const isSignalTool = (name) =>
184
+ SIGNAL_TOOLS.some((s) => name === s || name.endsWith(`_${s}`));
185
+
186
+ /**
187
+ * A `/gate mode` duration: `90s`, `30m`, `8h`, `2d`, or a bare number (hours).
188
+ *
189
+ * Returns `null` for anything else so the caller can refuse to write instead of
190
+ * guessing. A guessed expiry is worse than no expiry: the user believes the gate
191
+ * will tighten itself and it never does.
192
+ */
193
+ export const parseGateDurationMs = (text) => {
194
+ const m = /^(\d+(?:\.\d+)?)\s*(s|m|h|d)?$/i.exec(String(text ?? '').trim());
195
+ if (!m) return null;
196
+ const n = Number(m[1]);
197
+ if (!Number.isFinite(n) || n <= 0) return null;
198
+ const unit = (m[2] ?? 'h').toLowerCase();
199
+ return Math.round(n * { s: 1000, m: 60000, h: 3600000, d: 86400000 }[unit]);
200
+ };
201
+
202
+ /** Human form of a duration, for the mode banner. */
203
+ export const formatDurationMs = (ms) => {
204
+ const total = Math.max(0, Math.round(Number(ms) / 1000));
205
+ if (total >= 86400) {
206
+ const d = Math.floor(total / 86400);
207
+ const h = Math.floor((total % 86400) / 3600);
208
+ return h > 0 ? `${d}d${h}h` : `${d}d`;
209
+ }
210
+ if (total >= 3600) {
211
+ const h = Math.floor(total / 3600);
212
+ const m = Math.floor((total % 3600) / 60);
213
+ return m > 0 ? `${h}h${m}m` : `${h}h`;
214
+ }
215
+ if (total >= 60) return `${Math.floor(total / 60)}m`;
216
+ return `${Math.max(1, total)}s`;
217
+ };
218
+
219
+ /**
220
+ * Fallback when policy.json cannot be read.
221
+ *
222
+ * v4 fails CLOSED for the safety rules instead of returning `checks: []`.
223
+ * A malformed policy used to make the gate disappear silently — the one failure
224
+ * mode this whole design exists to prevent. Research rules stay off (they need
225
+ * reliable session state), but secrets, out-of-scope writes and destructive
226
+ * commands keep being enforced, and the session is told it is degraded.
227
+ */
228
+ const fallback = (why) => ({
229
+ policy: {
230
+ name: 'enforce-rules',
231
+ version: 1,
232
+ description: 'degraded safety-only policy because the policy file could not be read',
233
+ reminded:
234
+ `[system-reminder · 门控降级] policy.json 读取失败,完整规则已停用;` +
235
+ `安全底线仍在(凭据写入 / 越界写入 / 破坏性命令)。请修复:${why}`,
236
+ checks: ['no-write-outside', 'no-secret-write', 'no-destructive-bash'],
237
+ config: { max_blocks_per_session: 0, signal_ttl_ms: 0 },
238
+ },
239
+ error: why,
240
+ });
241
+
242
+ /** Append text to a pi message content, which is either a string or blocks. */
243
+ const appendText = (content, text) => {
244
+ if (typeof content === 'string') return `${content}\n\n${text}`;
245
+ if (Array.isArray(content)) return [...content, { type: 'text', text }];
246
+ return content; // unknown shape: leave it alone rather than corrupt it
247
+ };
248
+
249
+ export default function enforceRules(pi, options = {}) {
250
+ const resolved = firstExistingPolicy(HERE, options.policyPath ?? null);
251
+ const loaded = options.policy
252
+ ? policyFromObject(options.policy)
253
+ : resolved
254
+ ? loadPolicy(resolved)
255
+ : {
256
+ ok: false,
257
+ error:
258
+ `no policy file found; looked in:\n` +
259
+ policyCandidates(HERE, options.policyPath ?? null)
260
+ .map((c) => ` ${c}`)
261
+ .join('\n'),
262
+ };
263
+ const { policy: loadedPolicy, error } = loaded.ok
264
+ ? loaded
265
+ : fallback(`policy not loaded (${loaded.error})`);
266
+ /**
267
+ * A grant made through `/gate` lives in the machine-local override. Applying
268
+ * it here means the grant takes effect immediately instead of at the next
269
+ * `bridge apply` - and it keeps the installed `policy.json` and the live
270
+ * override from ever disagreeing about a tier.
271
+ */
272
+ const policy = applyMachineOverride(loadedPolicy);
273
+
274
+ const state = newSessionState();
275
+ /** Set once per session so the same advisory is not repeated. */
276
+ let noticedPolicyProblem = false;
277
+ /**
278
+ * Cache of the last classification, keyed by (cwd, prompt).
279
+ *
280
+ * `before_agent_start` can fire again for the same user request (retry,
281
+ * recovery, compaction). Re-classifying would spend another model round trip
282
+ * and - worse - could land on a different answer, silently switching the rule
283
+ * set mid-turn for reasons the user cannot see.
284
+ */
285
+ let lastClassified = { key: null, result: null };
286
+ /**
287
+ * The directory pi resolves a relative tool path against.
288
+ *
289
+ * pi's `read` schema accepts "relative or absolute" and resolves the relative
290
+ * form against the session directory, so a rule that only understands
291
+ * absolute paths would be dodged by spelling the same file relatively. The
292
+ * value is captured at session start and refreshed from `ctx` on every call,
293
+ * because `ctx.cwd` is not guaranteed on every event.
294
+ *
295
+ * Left null when nothing has ever supplied one: guessing here would scope a
296
+ * read into whatever directory the pi process happened to start in, which is
297
+ * a different repository. Without a cwd the path stays relative, the policy
298
+ * refuses it, and the gate is inert — the same behaviour as before this was
299
+ * fixed, and the honest floor.
300
+ */
301
+ let sessionCwd = null;
302
+ const cwdFor = (ctx) =>
303
+ typeof ctx?.cwd === 'string' && ctx.cwd ? ctx.cwd : sessionCwd;
304
+
305
+ pi.on('session_start', async (_event, ctx) => {
306
+ state.blocks = 0;
307
+ state.firstBlockAt = 0;
308
+ state.signals = 0;
309
+ state.lastIndexRefreshAt = 0;
310
+ state.slackContinues = 0;
311
+ state.written.clear();
312
+ state.unlocks.clear();
313
+ state.inspected.clear();
314
+ state.docReads.clear();
315
+ state.failedCommands.clear();
316
+ state.destructiveGrants.clear();
317
+ // A session override is memory-only by design, so a new session always starts
318
+ // from the global mode. Re-`session_start` also counts as a new session.
319
+ state.destructiveMode = null;
320
+ state.lastInvestigationAt = 0;
321
+ state.profile = policy.defaultProfile ?? 'general-dev';
322
+ state.profileSource = 'fallback';
323
+ state.scriptsRun.clear();
324
+ state.turnStart = 0;
325
+ lastClassified = { key: null, result: null };
326
+ if (typeof ctx?.cwd === 'string' && ctx.cwd) sessionCwd = ctx.cwd;
327
+ if (error) {
328
+ // A gate that cannot load its policy is OFF. Say so loudly: in a headless
329
+ // run there is no UI to notify, so this also goes to stderr. A silent
330
+ // no-op enforcement point is worse than no enforcement point at all,
331
+ // because everyone believes the rules are being enforced.
332
+ process.stderr.write(`[enforce-rules] DISABLED: ${error}\n`);
333
+ if (ctx?.hasUI && !noticedPolicyProblem) {
334
+ noticedPolicyProblem = true;
335
+ ctx.ui.notify(`enforce-rules: ${error}; gate is inactive`, 'warn');
336
+ }
337
+ return;
338
+ }
339
+ if (isDestructiveBypass(policy.config, state)) {
340
+ // Loud on purpose. A silent bypass is indistinguishable from a working gate,
341
+ // and ADR-012 already recorded that "too strict" replaced by "naked" is
342
+ // worse than leaving it alone. stderr too, because a headless run has no UI.
343
+ const source = state.destructiveMode ? '本会话覆盖' : '全局设置';
344
+ const left = destructiveModeRemainingMs(policy.config);
345
+ const line =
346
+ `[enforce-rules] 破坏性命令 BYPASS 生效(${source},${left === null ? '不过期' : `剩 ${formatDurationMs(left)}`}):` +
347
+ `删除/git 重写/force push/DDL 等不再询问或拦截,红线(删 $HOME / 删 cwd / 含 .. / 磁盘格式化 / 裸设备写入 / 关机 / 受保护工作区里的 git 清场)仍然拦。` +
348
+ ` 其他门控规则(图谱/思考/契约/AI4S/密钥/越界写入)不受影响。 收回:/gate mode enforce`;
349
+ process.stderr.write(`${line}\n`);
350
+ if (ctx?.hasUI) ctx.ui.notify(line, 'warn');
351
+ } else if (ctx?.hasUI) {
352
+ ctx.ui.notify(
353
+ `enforce-rules: ${policy.name} active (${policy.checks.join(', ') || 'no checks'})`,
354
+ 'info',
355
+ );
356
+ }
357
+ // ADR-015: the protected-worktree red line is only as good as the list
358
+ // behind it, and that list is hand-edited in a file on this machine. Say
359
+ // both halves while the model can still plan around them - the root the
360
+ // session stands in, and any entry that is being ignored. The refusal
361
+ // comes when the command does; this is the earlier, cheaper half.
362
+ const here = protectedRootOf(cwdFor(ctx), policy.config);
363
+ if (here) {
364
+ const line =
365
+ `[enforce-rules] 当前目录是受保护工作区:${here}\n` +
366
+ '[enforce-rules] 这里没提交的内容就是正在运行的状态(配置、凭据、会话)。' +
367
+ 'git stash / reset --hard / clean -f / checkout -- . 等清场命令是红线,任何授权、任何模式都拦;' +
368
+ 'git status / diff / show 等只读命令不受影响。';
369
+ process.stderr.write(`${line}\n`);
370
+ if (ctx?.hasUI) ctx.ui.notify(line, 'warn');
371
+ }
372
+ for (const { entry, why } of machineProtectedListProblems()) {
373
+ const line =
374
+ `[enforce-rules] 受保护工作区清单有一项被忽略(${why}):${entry} —— 这个目录现在不受保护。` +
375
+ '改成绝对路径后 /reload。';
376
+ process.stderr.write(`${line}\n`);
377
+ if (ctx?.hasUI) ctx.ui.notify(line, 'warn');
378
+ }
379
+ });
380
+
381
+ /**
382
+ * v5: classify the session's domain once per user turn.
383
+ *
384
+ * Deliberately HERE and not in `tool_call`. `tool_call` runs for every single
385
+ * tool invocation, so a model-backed judge there would add a network round trip
386
+ * to every read — the kind of latency that gets a gate uninstalled. This event
387
+ * fires once per user request, which is the right granularity for "what kind of
388
+ * work is this?"
389
+ *
390
+ * Runs started by `pi.sendMessage(..., { triggerTurn: true })` carry no prompt
391
+ * (`messageType === 'custom'`). They continue work the user already asked for,
392
+ * so the previous classification is kept instead of being re-derived from an
393
+ * empty prompt — which would always answer `general-dev`.
394
+ */
395
+ pi.on('before_agent_start', async (event, ctx) => {
396
+ const cwd = cwdFor(ctx) ?? '';
397
+ // A new user turn is the boundary the output checks (W2) compare mtimes to.
398
+ state.turnStart = Date.now();
399
+ if (event?.messageType === 'custom') return;
400
+ const prompt = typeof event?.prompt === 'string' ? event.prompt : '';
401
+ const key = `${cwd}\u0000${prompt}`;
402
+ if (lastClassified.key === key && lastClassified.result) {
403
+ state.profile = lastClassified.result.profile;
404
+ state.profileSource = lastClassified.result.source;
405
+ return;
406
+ }
407
+ const result = await classify({
408
+ cwd,
409
+ prompt,
410
+ fs: realFs,
411
+ policy,
412
+ // No judge is wired by default (`classifier.model_judge` is false), so T2
413
+ // is normally skipped. A host may inject one; tests always do not.
414
+ modelHint: typeof options.modelHint === 'function' ? options.modelHint : null,
415
+ });
416
+ lastClassified = { key, result };
417
+ state.profile = result.profile;
418
+ state.profileSource = result.source;
419
+ if (result.source !== 'fingerprint' && ctx?.hasUI) {
420
+ // A fingerprint hit is a fact, not news; the weaker verdicts are worth one
421
+ // line so a mis-classification is visible instead of silent.
422
+ ctx.ui.notify(`enforce-rules: domain ${result.profile} (${result.source})`, 'info');
423
+ }
424
+ });
425
+
426
+ pi.on('tool_call', async (event, ctx) => {
427
+ // MCP gateway: the real tool and its arguments live under input.tool/args.
428
+ // Before v4 the adapter returned early for every `mcp` call, so a proxied
429
+ // write/read/bash was silently exempt from every rule below.
430
+ const proxied =
431
+ event.toolName === 'mcp' && typeof event.input?.tool === 'string' ? event.input.tool : '';
432
+ const name = proxied || event.toolName;
433
+ const input = proxied ? (event.input?.args ?? {}) : event.input;
434
+ const shell = name === 'powershell' ? 'powershell' : 'bash';
435
+ const cwd = cwdFor(ctx);
436
+ // The profile decides the check LIST, never the signature: `shouldBlock`
437
+ // still receives `{policy, input, state, fs}`, so the rule layer never learns
438
+ // that domains exist (ADR-003 §strategy/adapter split).
439
+ const effective = profilePolicy(policy, state.profile);
440
+
441
+ // Remember what this session wrote: reading your own output is never a
442
+ // violation, and blocking it would make the gate fight normal development.
443
+ // The record happens only AFTER the checks pass. Recording first (as v2
444
+ // did) would put the target in `written` and exempt the very write that
445
+ // Layer 0 was supposed to question.
446
+ const writeLike =
447
+ WRITE_TOOLS.has(name) ||
448
+ (!READ_TOOLS.has(name) && typeof inputPath(input) === 'string' && typeof inputContent(input) === 'string');
449
+ if (writeLike) {
450
+ const path = normalizePath(inputPath(input), cwd);
451
+ const content = inputContent(input);
452
+ const verdict = shouldBlock({
453
+ policy: effective,
454
+ input: { action: 'write', path, tool: name, content },
455
+ state,
456
+ fs: realFs,
457
+ });
458
+ if (verdict.block) {
459
+ if (ctx?.hasUI) {
460
+ ctx.ui.notify(
461
+ `enforce-rules [${verdict.code}] block ${state.blocks}/${policy.config.max_blocks_per_session}`,
462
+ 'warn',
463
+ );
464
+ }
465
+ return { block: true, reason: verdict.reason };
466
+ }
467
+ recordWrite(state, path);
468
+ recordInvestigation(state);
469
+ return;
470
+ }
471
+
472
+ // Bash/PowerShell reads count as reads. `cat src/a.ts`, `grep x packages/…`,
473
+ // `sed -n '1,20p' file` and `Get-Content src/a.ts` are the same act as the
474
+ // `read` tool; leaving them ungated was the hole that made the gate
475
+ // cosmetic (2026-10-16). PowerShell was added in v4 because enabling that
476
+ // tool used to be a full bypass on Windows.
477
+ if (name === 'bash' || name === 'powershell') {
478
+ const command = typeof input?.command === 'string' ? input.command : '';
479
+ const verdict = shouldBlock({
480
+ policy: effective,
481
+ input: {
482
+ action: 'bash',
483
+ path: null,
484
+ tool: name,
485
+ shell,
486
+ command,
487
+ cwd,
488
+ },
489
+ state,
490
+ fs: realFs,
491
+ });
492
+ if (verdict.block) {
493
+ if (ctx?.hasUI) {
494
+ ctx.ui.notify(
495
+ `enforce-rules [${verdict.code}] block ${state.blocks}/${policy.config.max_blocks_per_session}`,
496
+ 'warn',
497
+ );
498
+ }
499
+ return { block: true, reason: verdict.reason };
500
+ }
501
+ // Three-tier permission model (CHG-20261105 v2): a `confirm` finding is
502
+ // not a refusal. pi itself does NOT ask before running a tool
503
+ // (`docs/security.md`: "it does not ask for approval before every tool
504
+ // call"), so the question has to come from here.
505
+ //
506
+ // Three options, not two: "allow once" and "allow this whole class for
507
+ // this session" are different promises, and collapsing them either
508
+ // nags on every file or silently grants more than the user meant.
509
+ if (verdict.confirm) {
510
+ const why = verdict.confirmReason ?? '破坏性命令需要确认';
511
+ const category = verdict.confirmCategory ?? 'delete';
512
+ if (ctx?.hasUI && typeof ctx.ui?.select === 'function') {
513
+ const options = [
514
+ '允许这一次',
515
+ `本会话允许「${category}」这一类`,
516
+ '拒绝',
517
+ ];
518
+ const choice = await ctx.ui.select(why, options);
519
+ if (choice === options[1]) {
520
+ state.destructiveGrants.set(category, 'allow');
521
+ ctx.ui.notify?.(
522
+ `enforce-rules: 本会话已允许「${category}」。收回:/gate deny ${category}`,
523
+ 'info',
524
+ );
525
+ } else if (choice !== options[0]) {
526
+ return { block: true, reason: `${why}\n\n用户拒绝了这次执行。` };
527
+ }
528
+ } else if (ctx?.hasUI && typeof ctx.ui?.confirm === 'function') {
529
+ // Older harness builds only expose a yes/no dialog.
530
+ const allowed = await ctx.ui.confirm('允许执行这条破坏性命令?', command);
531
+ if (!allowed) {
532
+ return { block: true, reason: `${why}\n\n用户拒绝了这次执行。` };
533
+ }
534
+ } else {
535
+ // No UI: an automated run already carries the user's authorization in
536
+ // its own invocation, and blocking there would make the gate
537
+ // unusable from scripts. Record the decision on stderr instead of
538
+ // waiting for a dialog that can never appear. The guardrail tier
539
+ // above still refuses, so nothing unrecoverable slips through here.
540
+ process.stderr.write(
541
+ `[enforce-rules] DESTRUCTIVE_CONFIRM auto-approved (no UI) [${category}]: ${command.slice(0, 200)}\n`,
542
+ );
543
+ }
544
+ }
545
+ // AI4S: remember the script this call is about to run. W1 uses the key set
546
+ // to ask for a Worklog only on the FIRST run of a given script, and the
547
+ // turn-end W4 check uses `startedAt` to date the log it expects.
548
+ for (const script of analysisScriptTargets(command, {
549
+ config: effective.config,
550
+ cwd,
551
+ isFile: realFs.isFile,
552
+ })) {
553
+ recordScriptRun(state, script);
554
+ }
555
+ return;
556
+ }
557
+
558
+ if (!READ_TOOLS.has(name)) return;
559
+
560
+ const verdict = shouldBlock({
561
+ policy: effective,
562
+ input: { action: 'read', path: normalizePath(inputPath(input), cwd), tool: name },
563
+ state,
564
+ fs: realFs,
565
+ });
566
+
567
+ if (verdict.block) {
568
+ if (ctx?.hasUI) {
569
+ ctx.ui.notify(
570
+ `enforce-rules [${verdict.code}] block ${state.blocks}/${policy.config.max_blocks_per_session}`,
571
+ 'warn',
572
+ );
573
+ }
574
+ return { block: true, reason: verdict.reason };
575
+ }
576
+
577
+ if (verdict.capReached && ctx?.hasUI && !noticedPolicyProblem) {
578
+ noticedPolicyProblem = true;
579
+ ctx.ui.notify(
580
+ 'enforce-rules: block cap reached for this window; research rules resume after the reset window',
581
+ 'warn',
582
+ );
583
+ }
584
+ return;
585
+ });
586
+
587
+ /** All string leaves of a tool input, so a query's arguments become unlocks. */
588
+ const inputStrings = (value, out = []) => {
589
+ if (typeof value === 'string') out.push(value);
590
+ else if (Array.isArray(value)) for (const item of value) inputStrings(item, out);
591
+ else if (value && typeof value === 'object') for (const item of Object.values(value)) inputStrings(item, out);
592
+ return out;
593
+ };
594
+
595
+ /** Text of a tool result, for the shape pi reports (`{content:[{text}]}`). */
596
+ const resultText = (result) => {
597
+ if (typeof result === 'string') return result;
598
+ if (!result || typeof result !== 'object') return '';
599
+ if (typeof result.text === 'string') return result.text;
600
+ if (Array.isArray(result.content)) {
601
+ return result.content
602
+ .map((block) => (typeof block === 'string' ? block : typeof block?.text === 'string' ? block.text : ''))
603
+ .join('\n');
604
+ }
605
+ return '';
606
+ };
607
+
608
+ pi.on('tool_result', async (event, ctx) => {
609
+ const cwd = cwdFor(ctx);
610
+ // Unwrap the MCP gateway once; every branch below works on the real tool.
611
+ const proxied =
612
+ event.toolName === 'mcp' && typeof event.input?.tool === 'string' ? event.input.tool : '';
613
+ const toolName = proxied || event.toolName;
614
+ const input = proxied ? (event.input?.args ?? {}) : event.input;
615
+ const command = typeof input?.command === 'string' ? input.command : '';
616
+ const shell = toolName === 'powershell' ? 'powershell' : 'bash';
617
+
618
+ if (event.isError) {
619
+ // A failed shell command feeds the blind-retry rule. A failed graph query
620
+ // must not record a signal — the model has learned nothing yet.
621
+ if (toolName === 'bash' || toolName === 'powershell') {
622
+ recordCommandResult(state, command, true);
623
+ }
624
+ return;
625
+ }
626
+
627
+ // A successful read is evidence about the exact file, which is what Layer 0
628
+ // needs before an edit. Convention documents additionally satisfy the
629
+ // "project conventions" question.
630
+ const path = normalizePath(inputPath(input), cwd);
631
+ if (READ_TOOLS.has(toolName) && path) {
632
+ recordInspection(state, path);
633
+ if (isConventionDoc(path, policy.config) || isChgContract(path, policy.config)) {
634
+ recordDocRead(state, path);
635
+ }
636
+ }
637
+
638
+ if (toolName === 'bash' || toolName === 'powershell') {
639
+ recordCommandResult(state, command, false);
640
+ for (const target of shellReadTargets({ command, shell }, {
641
+ config: policy.config,
642
+ cwd,
643
+ isFile: realFs.isFile,
644
+ exists: realFs.exists,
645
+ })) {
646
+ recordInspection(state, normalizePath(target));
647
+ }
648
+ // `cat CONTRIBUTING.md` satisfies the convention rule just like `read`.
649
+ for (const token of command.match(/"[^"]+"|'[^']+'|[^\s;&|]+/g) ?? []) {
650
+ const candidate = normalizePath(token.replace(/^["']|["']$/g, ''), cwd);
651
+ if (
652
+ candidate &&
653
+ (isConventionDoc(candidate, policy.config) || isChgContract(candidate, policy.config)) &&
654
+ realFs.isFile(candidate)
655
+ ) {
656
+ recordDocRead(state, candidate);
657
+ }
658
+ }
659
+ }
660
+
661
+ // A successful index refresh is Layer-2 evidence that works even when the
662
+ // index lives in a global data directory (no repo-local marker). Re-indexing
663
+ // also changes a marker's mtime, so a cached value must be dropped.
664
+ if (
665
+ toolName === 'index_repository' ||
666
+ toolName.endsWith('_index_repository') ||
667
+ toolName === 'detect_changes' ||
668
+ toolName.endsWith('_detect_changes')
669
+ ) {
670
+ resetMtimeCache();
671
+ recordIndexRefresh(state);
672
+ }
673
+
674
+ if (!isSignalTool(toolName)) return;
675
+
676
+ // A successful call is not enough: an empty result ("total":0) used to buy
677
+ // a full read window without telling the model anything. Only evidence
678
+ // counts; the policy can turn this off when a harness cannot see results.
679
+ // pi reports a tool result as `event.content` (plus optional
680
+ // `structuredContent`), not `event.result`. Prefer the legacy field when a
681
+ // harness supplies it, then the real pi event shape.
682
+ const resultBody = resultText(event.result ?? event);
683
+ if (!graphResultIsEvidence(resultBody, policy.config)) return;
684
+
685
+ const now = Date.now();
686
+ recordSignal(state, now);
687
+ // …and remember *what the query was about*: arguments plus the result text
688
+ // become scoped unlocks, so a query about one file/package never buys a
689
+ // free pass for the whole repository — but the file it named stays readable
690
+ // for `unlock_ttl_ms` without another round-trip.
691
+ recordUnlocks(state, unlockTokensFromText(inputStrings(input).join('\n')), now);
692
+ if (typeof input?.qualified_name === 'string') {
693
+ recordUnlocks(state, unlockTokensFromQualifiedName(input.qualified_name), now);
694
+ }
695
+ recordUnlocks(state, unlockTokensFromText(resultBody), now);
696
+ });
697
+
698
+ /**
699
+ * Turn-level anti-slack (v4).
700
+ *
701
+ * A tool-call gate cannot see a reply that does no work at all. `turn_end` is
702
+ * the boundary where the assistant's final text is available; returning
703
+ * `continue: true` asks for one more turn instead of handing a promise to the
704
+ * user as if it were a delivery. Bounded by `slack_max_continues` so a false
705
+ * positive cannot loop the agent forever.
706
+ */
707
+ pi.on('turn_end', async (event, ctx) => {
708
+ if (event.message?.role !== 'assistant') return;
709
+ const max = policy.config.slack_max_continues ?? 0;
710
+ if (max <= 0 || state.slackContinues >= max) return;
711
+
712
+ // AI4S output artifacts (W4 log file / W2 result README). Deliberately a
713
+ // `continue` and not a `deny`: both are discovered after the computation has
714
+ // finished, and one more turn is enough to fix them. Blocking a call that
715
+ // already completed would only break a finished analysis.
716
+ //
717
+ // `outputArtifactFindings` returns [] for a general-dev session (no result
718
+ // dirs, no scripts), so the cost on ordinary work is one Map lookup.
719
+ const effective = profilePolicy(policy, state.profile);
720
+ const artifacts = outputArtifactFindings({
721
+ policy: effective,
722
+ state,
723
+ fs: realFs,
724
+ cwd: cwdFor(ctx),
725
+ });
726
+ if (artifacts.length > 0) {
727
+ state.slackContinues += 1;
728
+ if (ctx?.hasUI) {
729
+ ctx.ui.notify(
730
+ `enforce-rules [${artifacts[0].code}] continue ${state.slackContinues}/${max}`,
731
+ 'warn',
732
+ );
733
+ }
734
+ return {
735
+ continue: true,
736
+ entries: [
737
+ ...(event.entries ?? []),
738
+ {
739
+ type: 'custom_message',
740
+ customType: 'enforce-rules-ai4s-output',
741
+ content: artifacts.map((f) => f.reason).join('\n\n'),
742
+ display: false,
743
+ },
744
+ ],
745
+ };
746
+ }
747
+
748
+ if (policy.config.slack_check === false) return;
749
+
750
+ const finding = slackFinding(resultText(event.message), policy.config);
751
+ if (!finding) return;
752
+
753
+ state.slackContinues += 1;
754
+ if (ctx?.hasUI) {
755
+ ctx.ui.notify(
756
+ `enforce-rules [${finding.code}] continue ${state.slackContinues}/${max}`,
757
+ 'warn',
758
+ );
759
+ }
760
+ return {
761
+ continue: true,
762
+ entries: [
763
+ ...(event.entries ?? []),
764
+ {
765
+ type: 'custom_message',
766
+ customType: 'enforce-rules-no-slack',
767
+ content: finding.reason,
768
+ display: false,
769
+ },
770
+ ],
771
+ };
772
+ });
773
+
774
+ /**
775
+ * `/gate` - the only supported way to change a permission tier.
776
+ *
777
+ * Deliberately a user-typed command and not a tool. A grant must be given by
778
+ * the user, never taken by the agent: the `no-self-grant` check refuses any
779
+ * write or shell redirect that carries `destructive_grants`, which closes the
780
+ * obvious "agent edits its own permission file" hole.
781
+ *
782
+ * Persistent grants go to the machine-local override, never to the installed
783
+ * `policy.json`: `bridge apply` regenerates that file, so a grant written
784
+ * there would be silently lost at the next apply.
785
+ */
786
+ // A harness build without `registerCommand` (or a test double) loses `/gate`,
787
+ // not enforcement. A missing capability must degrade one feature, never take
788
+ // the security layer down with it - the same rule the UI probes follow.
789
+ const registerGateCommand =
790
+ typeof pi.registerCommand === 'function' ? pi.registerCommand.bind(pi) : null;
791
+ registerGateCommand?.('gate', {
792
+ description:
793
+ '门控授权与模式:list / grant|ask|deny|reset|session <类别> / mode [bypass|enforce] [时长] [session]',
794
+ handler: async (args, ctx) => {
795
+ const notify = (text, level = 'info') => ctx?.ui?.notify?.(text, level);
796
+ const tokens = String(args ?? '').trim().split(/\s+/).filter(Boolean);
797
+ const sub = (tokens[0] ?? 'list').toLowerCase();
798
+ const category = tokens[1] ?? null;
799
+ const categories = Object.keys(DESTRUCTIVE_CATEGORIES);
800
+
801
+ /**
802
+ * The machine-local override, read once per command.
803
+ *
804
+ * Factored out because BOTH the grant path and the mode path write this
805
+ * file; two hand-rolled parsers is how one of them ends up silently
806
+ * dropping the other's keys.
807
+ */
808
+ const readGateDoc = () => {
809
+ const file = machineGateConfigPath();
810
+ if (!file) {
811
+ return { error: '无法定位机器本地配置目录(HOME / USERPROFILE 均未设置)。' };
812
+ }
813
+ let doc = {};
814
+ if (existsSync(file)) {
815
+ try {
816
+ doc = JSON.parse(readFileSync(file, 'utf8')) ?? {};
817
+ } catch (err) {
818
+ return { error: `${file} 不是合法 JSON,先修好它:${err.message}` };
819
+ }
820
+ }
821
+ if (!doc || typeof doc !== 'object' || Array.isArray(doc)) doc = {};
822
+ if (!doc.config || typeof doc.config !== 'object' || Array.isArray(doc.config)) doc.config = {};
823
+ return { file, doc };
824
+ };
825
+
826
+ const writeGateDoc = (file, doc) => {
827
+ try {
828
+ mkdirSync(dirname(file), { recursive: true });
829
+ writeFileSync(file, `${JSON.stringify(doc, null, 2)}\n`, 'utf8');
830
+ return null;
831
+ } catch (err) {
832
+ return `写入 ${file} 失败:${err.message}`;
833
+ }
834
+ };
835
+
836
+ /** Everything the mode banner and the picker need, in one read. */
837
+ const modeState = () => {
838
+ const merged = applyMachineOverride(policy);
839
+ const globalMode = DESTRUCTIVE_MODES.includes(merged.config.destructive_mode)
840
+ ? merged.config.destructive_mode
841
+ : 'enforce';
842
+ const sessionMode = DESTRUCTIVE_MODES.includes(state.destructiveMode)
843
+ ? state.destructiveMode
844
+ : null;
845
+ return {
846
+ merged,
847
+ globalMode,
848
+ until: Number(merged.config.destructive_mode_until ?? 0) || 0,
849
+ sessionMode,
850
+ effective: effectiveDestructiveMode(merged.config, state),
851
+ remaining: destructiveModeRemainingMs(merged.config),
852
+ };
853
+ };
854
+
855
+ /**
856
+ * The mode the destructive gate will actually apply, always stated first.
857
+ *
858
+ * ADR-013: a bypass nobody notices is the failure mode that makes the whole
859
+ * switch dangerous, so it is the first line of every report.
860
+ */
861
+ const modeLine = () => {
862
+ const m = modeState();
863
+ if (m.sessionMode) {
864
+ return `破坏性命令模式:${m.effective.toUpperCase()}(本会话覆盖 = ${m.sessionMode})`;
865
+ }
866
+ if (m.globalMode === 'bypass') {
867
+ if (m.remaining === null) return '破坏性命令模式:BYPASS(全局,不过期)';
868
+ if (m.remaining > 0) return `破坏性命令模式:BYPASS(全局,剩 ${formatDurationMs(m.remaining)})`;
869
+ return '破坏性命令模式:ENFORCE(全局 bypass 已到期)';
870
+ }
871
+ return '破坏性命令模式:ENFORCE(全局)';
872
+ };
873
+
874
+ const modeHelp = [
875
+ modeLine(),
876
+ ' 只影响破坏性指令(删除 / git 历史 / force push / DDL / 权限递归 / 杀进程 / 裸写);',
877
+ ' 图谱优先、思考前置、CHG 契约、AI4S、密钥与越界写入等其他门控不受影响。',
878
+ ' bypass 下仍然拦的红线:删 $HOME / 删 cwd / 含 .. 的路径 / 磁盘格式化 / 裸设备写入 / 关机重启 / 受保护工作区里的 git 清场。',
879
+ '',
880
+ ' /gate mode bypass 全局 bypass(持久,直到改回)',
881
+ ' /gate mode bypass 8h 全局 bypass,8 小时后自动回 enforce(s/m/h/d)',
882
+ ' /gate mode enforce 全局 enforce',
883
+ ' /gate mode bypass session 仅本会话 bypass(不写盘,重开会话失效)',
884
+ ' /gate mode enforce session 仅本会话 enforce(覆盖全局)',
885
+ ].join('\n');
886
+
887
+ const report = () => {
888
+ const { merged } = modeState();
889
+ const rows = categories.map((name) => {
890
+ const tier = effectiveDestructiveTier(name, merged.config, state);
891
+ const grant = merged.config.destructive_grants?.[name] ?? 'confirm';
892
+ const session = state.destructiveGrants.get(name);
893
+ return (
894
+ ` ${name.padEnd(18)} ${tier.padEnd(8)}(policy: ${grant}${session ? `,本会话: ${session}` : ''})\n` +
895
+ ` ${DESTRUCTIVE_CATEGORIES[name]}`
896
+ );
897
+ });
898
+ const protectedRoots = normalizeProtectedWorktrees(merged.config.protected_worktrees);
899
+ return [
900
+ modeLine(),
901
+ '',
902
+ '破坏性操作授权档位(allow=直接执行 / confirm=询问 / deny=拒绝)',
903
+ '',
904
+ ...rows,
905
+ '',
906
+ '红线(任何授权、任何模式都不放行):删 $HOME、删 cwd、含 .. 的路径、磁盘格式化、裸设备写入、关机重启。',
907
+ // Printed, not just configured: ADR-015's red line is only as good as
908
+ // the list behind it, and a typo in that file is otherwise invisible
909
+ // until the command it should have stopped has run.
910
+ protectedRoots.length > 0
911
+ ? `受保护工作区(同为红线,${protectedRoots.length} 个;其中的 git stash / reset --hard / clean -f / checkout -- . 等清场命令一律拦截):\n` +
912
+ protectedRoots.map((root) => ` ${root}`).join('\n')
913
+ : '受保护工作区(同为红线):未登记。登记方法见安装目录 README。',
914
+ '',
915
+ '调整:/gate grant <类别> 持久允许',
916
+ ' /gate ask <类别> 改为每次询问',
917
+ ' /gate deny <类别> 拒绝',
918
+ ' /gate reset <类别> 恢复默认',
919
+ ' /gate session <类别> 仅本会话允许',
920
+ ' /gate mode ... 破坏性命令模式(enforce / bypass,见 /gate mode)',
921
+ ].join('\n');
922
+ };
923
+
924
+ if (sub === 'list' || sub === 'status') {
925
+ notify(report());
926
+ return;
927
+ }
928
+
929
+ /**
930
+ * `/gate mode` - the switch that is not a category (ADR-013).
931
+ *
932
+ * Parsed as an order-independent token list so `/gate mode bypass 8h` and
933
+ * `/gate mode 8h bypass` mean the same thing, and so a typo refuses to write
934
+ * instead of silently setting something the user did not ask for.
935
+ */
936
+ if (sub === 'mode' || sub === 'bypass' || sub === 'enforce') {
937
+ const modeTokens = sub === 'mode' ? tokens.slice(1) : tokens;
938
+ let action = '';
939
+ let sessionScope = false;
940
+ let durationMs = null;
941
+
942
+ for (const word of modeTokens) {
943
+ const lower = word.toLowerCase();
944
+ if (DESTRUCTIVE_MODES.includes(lower)) {
945
+ action = lower;
946
+ continue;
947
+ }
948
+ if (lower === 'session' || lower === '本会话') {
949
+ sessionScope = true;
950
+ continue;
951
+ }
952
+ const parsed = parseGateDurationMs(word);
953
+ if (parsed === null) {
954
+ notify(
955
+ `看不懂「${word}」。\n\n${modeHelp}`,
956
+ 'warn',
957
+ );
958
+ return;
959
+ }
960
+ durationMs = parsed;
961
+ }
962
+ // `/gate mode 8h` is an unambiguous request for a bounded bypass.
963
+ if (!action && durationMs !== null) action = 'bypass';
964
+
965
+ if (!action) {
966
+ // No action: report, and offer a picker when the harness has one. The
967
+ // picker is the "选择这个 gate 的模式" path - a user should not have to
968
+ // remember the grammar to switch.
969
+ if (!(ctx?.hasUI && typeof ctx.ui?.select === 'function')) {
970
+ notify(`${modeHelp}\n\n${report()}`);
971
+ return;
972
+ }
973
+ const options = [
974
+ 'bypass:全局 8 小时(到期自动回 enforce)',
975
+ 'bypass:本会话(重开会话失效)',
976
+ 'bypass:全局(持久,直到我改回来)',
977
+ 'enforce:全局(清掉持久 bypass)',
978
+ 'enforce:本会话(覆盖全局)',
979
+ '只看当前状态,不改',
980
+ ];
981
+ const picked = await ctx.ui.select(modeHelp, options);
982
+ const index = options.indexOf(picked);
983
+ if (index === -1 || index === options.length - 1) {
984
+ notify(`${modeHelp}\n\n${report()}`);
985
+ return;
986
+ }
987
+ action = index >= 3 ? 'enforce' : 'bypass';
988
+ sessionScope = index === 1 || index === 4;
989
+ durationMs = index === 0 ? 8 * 60 * 60 * 1000 : null;
990
+ }
991
+
992
+ if (sessionScope && durationMs !== null) {
993
+ notify('会话内覆盖没有到期概念(会话结束即失效),请去掉时长。', 'warn');
994
+ return;
995
+ }
996
+
997
+ if (sessionScope) {
998
+ state.destructiveMode = action;
999
+ notify(
1000
+ action === 'bypass'
1001
+ ? `本会话已进入破坏性命令 bypass:除红线外不再询问或拦截(重开会话自动回 enforce,其他门控规则不变)。\n\n${modeHelp}`
1002
+ : `本会话已强制 enforce(覆盖全局设置)。\n\n${modeHelp}`,
1003
+ action === 'bypass' ? 'warn' : 'info',
1004
+ );
1005
+ return;
1006
+ }
1007
+
1008
+ const read = readGateDoc();
1009
+ if (read.error) {
1010
+ notify(read.error, 'error');
1011
+ return;
1012
+ }
1013
+ read.doc.config.destructive_mode = action;
1014
+ read.doc.config.destructive_mode_until =
1015
+ action === 'bypass' && durationMs ? Date.now() + durationMs : 0;
1016
+ const failure = writeGateDoc(read.file, read.doc);
1017
+ if (failure) {
1018
+ notify(failure, 'error');
1019
+ return;
1020
+ }
1021
+ // A fresh global decision outranks a stale session override; leaving it
1022
+ // in place would make this command look like it did nothing.
1023
+ state.destructiveMode = null;
1024
+ const expiry =
1025
+ action === 'bypass' && durationMs
1026
+ ? `,${formatDurationMs(durationMs)} 后自动回 enforce`
1027
+ : action === 'bypass'
1028
+ ? ',不过期'
1029
+ : '';
1030
+ notify(
1031
+ action === 'bypass'
1032
+ ? `破坏性命令已切到 BYPASS${expiry}(写入 ${read.file})。\n红线仍然拦;图谱/思考/契约/AI4S/密钥/越界写入等其他规则不受影响。\n收回:/gate mode enforce\n\n${modeHelp}`
1033
+ : `破坏性命令已切到 ENFORCE(写入 ${read.file}),授权档位恢复生效。\n\n${modeHelp}`,
1034
+ action === 'bypass' ? 'warn' : 'info',
1035
+ );
1036
+ return;
1037
+ }
1038
+
1039
+ if (!category || !categories.includes(category)) {
1040
+ notify(`未知类别:${category ?? '(空)'}\n可用:${categories.join(', ')}`, 'warn');
1041
+ return;
1042
+ }
1043
+
1044
+ if (sub === 'session') {
1045
+ state.destructiveGrants.set(category, 'allow');
1046
+ notify(`本会话已允许「${category}」(仅本会话,重开会话失效)。收回:/gate deny ${category}`);
1047
+ return;
1048
+ }
1049
+
1050
+ if (!['grant', 'ask', 'deny', 'reset'].includes(sub)) {
1051
+ notify(`未知子命令:${sub}\n\n${report()}`, 'warn');
1052
+ return;
1053
+ }
1054
+
1055
+ const file = machineGateConfigPath();
1056
+ if (!file) {
1057
+ notify('无法定位机器本地配置目录(HOME / USERPROFILE 均未设置)。', 'error');
1058
+ return;
1059
+ }
1060
+
1061
+ let doc = {};
1062
+ if (existsSync(file)) {
1063
+ try {
1064
+ doc = JSON.parse(readFileSync(file, 'utf8')) ?? {};
1065
+ } catch (err) {
1066
+ notify(`${file} 不是合法 JSON,先修好它:${err.message}`, 'error');
1067
+ return;
1068
+ }
1069
+ }
1070
+ if (!doc || typeof doc !== 'object' || Array.isArray(doc)) doc = {};
1071
+ if (!doc.config || typeof doc.config !== 'object' || Array.isArray(doc.config)) doc.config = {};
1072
+ if (
1073
+ !doc.config.destructive_grants ||
1074
+ typeof doc.config.destructive_grants !== 'object' ||
1075
+ Array.isArray(doc.config.destructive_grants)
1076
+ ) {
1077
+ doc.config.destructive_grants = {};
1078
+ }
1079
+
1080
+ if (sub === 'reset') {
1081
+ delete doc.config.destructive_grants[category];
1082
+ } else {
1083
+ doc.config.destructive_grants[category] =
1084
+ sub === 'grant' ? 'allow' : sub === 'ask' ? 'confirm' : 'deny';
1085
+ }
1086
+
1087
+ try {
1088
+ mkdirSync(dirname(file), { recursive: true });
1089
+ writeFileSync(file, `${JSON.stringify(doc, null, 2)}\n`, 'utf8');
1090
+ } catch (err) {
1091
+ notify(`写入 ${file} 失败:${err.message}`, 'error');
1092
+ return;
1093
+ }
1094
+
1095
+ const merged = applyMachineOverride(policy);
1096
+ notify(
1097
+ sub === 'reset'
1098
+ ? `「${category}」已恢复默认档位。\n\n${report()}`
1099
+ : `「${category}」已设为 ${merged.config.destructive_grants?.[category] ?? 'confirm'}(持久,写在 ${file})。\n\n${report()}`,
1100
+ );
1101
+ },
1102
+ });
1103
+
1104
+ pi.on('context', async (event) => {
1105
+ const reminder = reminderFor(policy, state);
1106
+ if (!reminder) return;
1107
+ const messages = event.messages;
1108
+ if (!Array.isArray(messages) || messages.length === 0) return;
1109
+
1110
+ const last = messages[messages.length - 1];
1111
+ if (last?.role === 'user') {
1112
+ messages[messages.length - 1] = {
1113
+ ...last,
1114
+ content: appendText(last.content, reminder),
1115
+ };
1116
+ } else {
1117
+ messages.push({ role: 'user', content: reminder });
1118
+ }
1119
+ return { messages };
1120
+ });
1121
+ }