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.
- package/LICENSE +21 -0
- package/README.md +258 -2
- package/agents/context-builder.md +158 -0
- package/agents/debug-executor.md +234 -0
- package/assets/gates/classifier.js +245 -0
- package/assets/gates/dsh/index.js +767 -0
- package/assets/gates/dsh/policy.json +93 -0
- package/assets/gates/index.js +3 -0
- package/assets/gates/pi/index.js +1121 -0
- package/assets/gates/pi/policy.json +93 -0
- package/assets/gates/policy.js +4199 -0
- package/assets/gates/profiles/ai4s-dry-lab.json +64 -0
- package/assets/gates/profiles/ai4s-quant.json +36 -0
- package/assets/pi-extensions/auto-continue.ts +176 -0
- package/assets/pi-extensions/goal-mode.ts +313 -0
- package/bin/shipgate.mjs +9 -0
- package/commands/ai-spec.md +9 -0
- package/commands/api-first.md +33 -0
- package/commands/code-review.md +7 -0
- package/commands/codebase-context.md +19 -0
- package/commands/debug-ui.md +147 -0
- package/commands/debug.md +101 -0
- package/commands/dev-env-scan.md +18 -0
- package/commands/dev-host-init.md +28 -0
- package/commands/discover-skill-opportunities.md +33 -0
- package/commands/fork-sync.md +17 -0
- package/commands/gh-actions.md +26 -0
- package/commands/goal-driven-development.md +7 -0
- package/commands/intent-grill.md +7 -0
- package/commands/iteration-manager.md +7 -0
- package/commands/loop-engineer.md +21 -0
- package/commands/nodejs-npm-auto-release.md +12 -0
- package/commands/prd.md +7 -0
- package/commands/project-health-audit.md +7 -0
- package/commands/ralph-yolo.md +346 -0
- package/commands/ralph.md +226 -0
- package/commands/security-audit.md +7 -0
- package/commands/ux-experience-audit.md +133 -0
- package/docs/ARCHITECTURE.md +63 -0
- package/docs/GATES.md +106 -0
- package/docs/HARNESS.md +215 -0
- package/package.json +48 -4
- package/references/ADR-FORMAT.md +67 -0
- package/references/CONTEXT-FORMAT.md +62 -0
- package/references/mcp-config-template.json +54 -0
- package/scripts/fix-skill-frontmatter.mjs +66 -0
- package/scripts/migrate-skillpack.mjs +257 -0
- package/skills/ai-spec/SKILL.md +90 -0
- package/skills/api-first-modular/SKILL.md +411 -0
- package/skills/code-debugger/SKILL.md +379 -0
- package/skills/code-review/SKILL.md +62 -0
- package/skills/codebase-context/SKILL.md +139 -0
- package/skills/debug-ui/SKILL.md +220 -0
- package/skills/dev-env-scan/SKILL.md +147 -0
- package/skills/dev-host-init/SKILL.md +198 -0
- package/skills/dev-host-init/scripts/fill-placeholders.py +226 -0
- package/skills/dev-host-init/scripts/host-scan.ps1 +159 -0
- package/skills/dev-host-init/scripts/host-scan.sh +201 -0
- package/skills/dev-host-init/scripts/render-now.py +488 -0
- package/skills/dev-host-init/scripts/tools-catalog.py +229 -0
- package/skills/dev-host-init/templates/graph-first-gate.ts +291 -0
- package/skills/dev-host-init/templates/host-injection.template.md +725 -0
- package/skills/discover-skill-opportunities/SKILL.md +145 -0
- package/skills/discover-skill-opportunities/references/accounting-finance-ops.md +24 -0
- package/skills/discover-skill-opportunities/references/business-consulting.md +24 -0
- package/skills/discover-skill-opportunities/references/evidence-and-privacy.md +39 -0
- package/skills/discover-skill-opportunities/references/finance-investment.md +24 -0
- package/skills/discover-skill-opportunities/references/legal-and-compliance.md +24 -0
- package/skills/discover-skill-opportunities/references/output-contract.md +75 -0
- package/skills/discover-skill-opportunities/references/product-and-operations.md +24 -0
- package/skills/discover-skill-opportunities/references/quant-trading.md +24 -0
- package/skills/discover-skill-opportunities/references/scientific-research.md +24 -0
- package/skills/discover-skill-opportunities/references/scoring-rubric.md +45 -0
- package/skills/discover-skill-opportunities/references/session-skill-review.md +78 -0
- package/skills/discover-skill-opportunities/references/software-development.md +24 -0
- package/skills/fork-sync/SKILL.md +86 -0
- package/skills/gh-actions-architect/SKILL.md +395 -0
- package/skills/goal-driven-development/SKILL.md +132 -0
- package/skills/intent-grill/SKILL.md +46 -0
- package/skills/iteration-manager/SKILL.md +53 -0
- package/skills/loop-engineer/SKILL.md +108 -0
- package/skills/nodejs-npm-auto-release/SKILL.md +141 -0
- package/skills/prd/SKILL.md +63 -0
- package/skills/project-health-audit/SKILL.md +64 -0
- package/skills/ralph/SKILL.md +329 -0
- package/skills/ralph-yolo/SKILL.md +623 -0
- package/skills/security-audit/SKILL.md +114 -0
- package/skills/security-audit/references/audit-checklist.md +135 -0
- package/skills/security-audit/references/evidence-conventions.md +54 -0
- package/skills/security-audit/references/findings-schema.md +37 -0
- package/skills/security-audit/references/stack-signatures.md +66 -0
- package/skills/shipgate/SKILL.md +40 -0
- package/skills/shipgate-install/SKILL.md +87 -0
- package/skills/shipgate-quality/SKILL.md +80 -0
- package/skills/shipgate-security/SKILL.md +97 -0
- package/skills/shipgate-spec/SKILL.md +67 -0
- package/skills/ux-experience-audit/SKILL.md +202 -0
- package/src/cli.mjs +117 -0
- package/src/commands/ask.mjs +82 -0
- package/src/commands/deploy.mjs +589 -0
- package/src/commands/gates.mjs +83 -0
- package/src/commands/policy.mjs +67 -0
- package/src/gates/quality.mjs +123 -0
- package/src/gates/security.mjs +92 -0
- package/src/gates/ship.mjs +74 -0
- package/src/gates/spec.mjs +88 -0
- package/src/harness/index.mjs +203 -0
- package/src/inject/render.mjs +75 -0
- package/src/lib/cfg.mjs +66 -0
- package/src/lib/engines.mjs +182 -0
- package/src/lib/exec.mjs +80 -0
- package/src/lib/fsx.mjs +119 -0
- package/src/lib/gate.mjs +288 -0
- package/src/lib/log.mjs +31 -0
- package/src/lib/skills.mjs +347 -0
- package/src/lib/state.mjs +41 -0
- package/src/lib/update.mjs +67 -0
- package/src/version.mjs +14 -0
- package/templates/agents-snippet.md +82 -0
- package/templates/dev-profile.schema.json +119 -0
- package/templates/prd.json.example +64 -0
- package/templates/rule.json.example +28 -0
|
@@ -0,0 +1,4199 @@
|
|
|
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
|
+
'要更新门控:改 agent-config-bridge 仓库源码 → node --test → node bridge/cli.js apply。',
|
|
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
|
+
* The bridge writes this same file when it generates `policy.json`, so a grant
|
|
2099
|
+
* made here survives `apply` (which regenerates `policy.json`) instead of being
|
|
2100
|
+
* overwritten by it. Deliberately outside every repository: a permission is a
|
|
2101
|
+
* property of the machine and its user, not of the code being worked on.
|
|
2102
|
+
*/
|
|
2103
|
+
export const machineGateConfigPath = (home = null) => {
|
|
2104
|
+
const base = home ?? process.env.HOME ?? process.env.USERPROFILE ?? '';
|
|
2105
|
+
return base ? join(base, '.config', 'agent-config-bridge', 'gate-policy.json') : null;
|
|
2106
|
+
};
|
|
2107
|
+
|
|
2108
|
+
/**
|
|
2109
|
+
* The machine-local override as written, or null when absent or unparsable.
|
|
2110
|
+
*
|
|
2111
|
+
* One reader for the file: `applyMachineOverride` merges it, and
|
|
2112
|
+
* `machineProtectedListProblems` reports what the merge had to drop.
|
|
2113
|
+
*/
|
|
2114
|
+
const readMachineOverride = (home = null) => {
|
|
2115
|
+
const file = machineGateConfigPath(home);
|
|
2116
|
+
if (!file) return null;
|
|
2117
|
+
try {
|
|
2118
|
+
return JSON.parse(readFileSync(file, 'utf8'));
|
|
2119
|
+
} catch {
|
|
2120
|
+
return null;
|
|
2121
|
+
}
|
|
2122
|
+
};
|
|
2123
|
+
|
|
2124
|
+
/**
|
|
2125
|
+
* Entries of the machine-local `protected_worktrees` that are being ignored
|
|
2126
|
+
* (ADR-015). The list is a red line that exists only for as long as it is
|
|
2127
|
+
* right, and it is maintained by hand; a relative path in it silently protects
|
|
2128
|
+
* nothing. An adapter prints these when a session starts.
|
|
2129
|
+
*/
|
|
2130
|
+
export const machineProtectedListProblems = (home = null) => {
|
|
2131
|
+
const raw = readMachineOverride(home)?.config?.protected_worktrees;
|
|
2132
|
+
return raw === undefined || raw === null ? [] : droppedProtectedWorktrees(raw);
|
|
2133
|
+
};
|
|
2134
|
+
|
|
2135
|
+
/**
|
|
2136
|
+
* Merge the machine-local `config` override into a loaded policy.
|
|
2137
|
+
*
|
|
2138
|
+
* The bridge already does this at install time, but a grant must take effect the
|
|
2139
|
+
* moment the user makes it, not at the next `apply`. Reading it here keeps one
|
|
2140
|
+
* source of truth for both paths: the installed `policy.json` and the live
|
|
2141
|
+
* override never disagree about a tier.
|
|
2142
|
+
*/
|
|
2143
|
+
export const applyMachineOverride = (policy, home = null) => {
|
|
2144
|
+
if (!machineGateConfigPath(home)) return policy;
|
|
2145
|
+
// Absent or unreadable: the shipped policy stands. A broken override must
|
|
2146
|
+
// not disable the gate, and it must not silently reset grants either.
|
|
2147
|
+
const parsed = readMachineOverride(home);
|
|
2148
|
+
const override = parsed?.config;
|
|
2149
|
+
if (!override || typeof override !== 'object' || Array.isArray(override)) return policy;
|
|
2150
|
+
|
|
2151
|
+
const config = { ...policy.config, ...override };
|
|
2152
|
+
// Grants merge per key. Replacing the object wholesale would make a single
|
|
2153
|
+
// granted category reset the other six to "not configured".
|
|
2154
|
+
const grants = { ...(policy.config.destructive_grants ?? {}) };
|
|
2155
|
+
if (override.destructive_grants && typeof override.destructive_grants === 'object') {
|
|
2156
|
+
for (const [name, tier] of Object.entries(override.destructive_grants)) {
|
|
2157
|
+
if (
|
|
2158
|
+
Object.prototype.hasOwnProperty.call(DESTRUCTIVE_CATEGORIES, name) &&
|
|
2159
|
+
DESTRUCTIVE_TIERS.includes(tier)
|
|
2160
|
+
) {
|
|
2161
|
+
grants[name] = tier;
|
|
2162
|
+
}
|
|
2163
|
+
}
|
|
2164
|
+
}
|
|
2165
|
+
config.destructive_grants = grants;
|
|
2166
|
+
// The mode keys come from a hand-editable file, so they get the same
|
|
2167
|
+
// sanitization `normalizePolicy` applies. Without this a typo like
|
|
2168
|
+
// `"destructive_mode": "Bypass "` would merge straight into the live config and
|
|
2169
|
+
// silently decide the mode by string inequality.
|
|
2170
|
+
config.destructive_mode = normalizeDestructiveMode(config.destructive_mode);
|
|
2171
|
+
config.destructive_mode_until = normalizeDestructiveModeUntil(config.destructive_mode_until);
|
|
2172
|
+
// The protected-worktree list lives in this same file. It is a red line, so a
|
|
2173
|
+
// malformed value may not reach the classifier raw.
|
|
2174
|
+
config.protected_worktrees = normalizeProtectedWorktrees(config.protected_worktrees);
|
|
2175
|
+
return { ...policy, config };
|
|
2176
|
+
};
|
|
2177
|
+
|
|
2178
|
+
/**
|
|
2179
|
+
* Detect a destructive shell operation that must not run unattended.
|
|
2180
|
+
*
|
|
2181
|
+
* This is Layer 0 in mechanical form: the thinking rule says "know the root
|
|
2182
|
+
* cause and the impact before you act", and a recursive delete / hard reset /
|
|
2183
|
+
* force push is the class of action where acting first is unrecoverable. The
|
|
2184
|
+
* rule is intentionally narrow: build directories (`node_modules`, `dist`, …)
|
|
2185
|
+
* and temp directories remain disposable, so routine cleanup is not blocked.
|
|
2186
|
+
*
|
|
2187
|
+
* @returns {{why: string, segment: string, severity: 'high'|'confirm'}|null}
|
|
2188
|
+
*/
|
|
2189
|
+
/**
|
|
2190
|
+
* Host-level destructive verbs, matched against the analysed command head.
|
|
2191
|
+
*
|
|
2192
|
+
* `mkfs` needs a suffix family so `mkfs.ext4` / `mkfs.xfs` are covered, and
|
|
2193
|
+
* `diskpart.exe` needs its extension; everything else is an exact verb, because a
|
|
2194
|
+
* prefix silently swallows unrelated programs. That is exactly how `format` used to
|
|
2195
|
+
* eat PowerShell's read-only `Format-Table` / `Format-List` / `Format-Wide` /
|
|
2196
|
+
* `Format-Custom` / `Format-Hex` cmdlets: `format` + `-table` matched `/^format/`,
|
|
2197
|
+
* so every `... | Format-Table` inspection pipeline was reported as disk formatting.
|
|
2198
|
+
* `format` is therefore an exact verb now, and `format-volume` — the one cmdlet in
|
|
2199
|
+
* that family that really wipes a volume — is named explicitly so the tightening
|
|
2200
|
+
* does not open a hole.
|
|
2201
|
+
*/
|
|
2202
|
+
const HOST_DESTRUCTIVE_VERB =
|
|
2203
|
+
/^(?:mkfs(?:\.[a-z0-9]+)?|fdisk|parted|diskpart(?:\.exe)?|format(?:\.(?:com|exe))?|format-volume)$/;
|
|
2204
|
+
|
|
2205
|
+
/**
|
|
2206
|
+
* Raw block devices, where `dd of=` is unrecoverable rather than merely risky.
|
|
2207
|
+
*
|
|
2208
|
+
* Matched by device family, not by a prefix on the whole path: `/dev/sda` and
|
|
2209
|
+
* `/dev/nvme0n1` are devices, `/dev/shm/x` is memory-backed scratch and a plain
|
|
2210
|
+
* file target is a permission the user may grant.
|
|
2211
|
+
*/
|
|
2212
|
+
const RAW_DEVICE =
|
|
2213
|
+
/^\/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;
|
|
2214
|
+
|
|
2215
|
+
/**
|
|
2216
|
+
* Clients that take a SQL statement as an argument.
|
|
2217
|
+
*
|
|
2218
|
+
* `psql -c "drop database prod"` runs the identical statement a bare
|
|
2219
|
+
* `drop database prod` would. The DDL pattern below is anchored at the verb, so
|
|
2220
|
+
* before this list existed the single category that starts at `deny` could be
|
|
2221
|
+
* bypassed by typing a client name in front of the statement.
|
|
2222
|
+
*
|
|
2223
|
+
* Scanned only for these verbs on purpose: matching the pattern anywhere in
|
|
2224
|
+
* every command would also fire on `echo "drop table x"` and on documentation
|
|
2225
|
+
* quotes, which is the class of false positive that gets a gate uninstalled.
|
|
2226
|
+
*/
|
|
2227
|
+
const DB_CLIENTS = new Set([
|
|
2228
|
+
'psql', 'pgcli', 'mysql', 'mysqlsh', 'mariadb', 'sqlite3', 'sqlcmd', 'clickhouse-client',
|
|
2229
|
+
'cockroach', 'duckdb', 'usql',
|
|
2230
|
+
]);
|
|
2231
|
+
|
|
2232
|
+
/** A DDL statement appears anywhere in the payload (used for client arguments). */
|
|
2233
|
+
const DDL_ANYWHERE = /(?:^|[\s'"`(])(?:drop\s+(?:table|database|schema)|truncate\s+table)\b/;
|
|
2234
|
+
|
|
2235
|
+
/**
|
|
2236
|
+
* mongo shells express the same act in JavaScript (`db.dropDatabase()`) rather
|
|
2237
|
+
* than SQL, so the SQL pattern above cannot see it.
|
|
2238
|
+
*/
|
|
2239
|
+
const MONGO_DROP = /\.(?:dropdatabase|dropcollection|drop)\s*\(/i;
|
|
2240
|
+
|
|
2241
|
+
/**
|
|
2242
|
+
* Normalise `config.protected_worktrees` (see DEFAULT_CONFIG for what it is).
|
|
2243
|
+
*
|
|
2244
|
+
* A kept entry is a non-empty string, `~` expanded, absolute, without a
|
|
2245
|
+
* trailing separator. Everything else is dropped rather than guessed at: a
|
|
2246
|
+
* relative path would resolve against whatever directory the session happens
|
|
2247
|
+
* to sit in and so protect the wrong tree, and a number is a typo. Dropping is
|
|
2248
|
+
* the visible failure (`/gate list` prints the list that actually took
|
|
2249
|
+
* effect); guessing would be the invisible one.
|
|
2250
|
+
*/
|
|
2251
|
+
export const normalizeProtectedWorktrees = (raw) => {
|
|
2252
|
+
const entries = Array.isArray(raw) ? raw : typeof raw === 'string' ? [raw] : [];
|
|
2253
|
+
const home = process.env.HOME ?? process.env.USERPROFILE ?? null;
|
|
2254
|
+
const out = [];
|
|
2255
|
+
for (const entry of entries) {
|
|
2256
|
+
if (typeof entry !== 'string') continue;
|
|
2257
|
+
let value = entry.trim();
|
|
2258
|
+
if (!value) continue;
|
|
2259
|
+
if (value === '~' || /^~[\\/]/.test(value)) {
|
|
2260
|
+
if (!home) continue;
|
|
2261
|
+
value = value === '~' ? home : join(home, value.slice(2));
|
|
2262
|
+
}
|
|
2263
|
+
if (!isAbsolute(value)) continue;
|
|
2264
|
+
const resolved = normalize(value).replace(/[\\/]+$/, '');
|
|
2265
|
+
if (resolved && !out.includes(resolved)) out.push(resolved);
|
|
2266
|
+
}
|
|
2267
|
+
return out;
|
|
2268
|
+
};
|
|
2269
|
+
|
|
2270
|
+
/**
|
|
2271
|
+
* Hand-written entries `normalizeProtectedWorktrees` had to drop, each with the
|
|
2272
|
+
* reason (ADR-015).
|
|
2273
|
+
*
|
|
2274
|
+
* Every dropped entry is a directory its owner believes is protected and is
|
|
2275
|
+
* not. Returning them lets an adapter say so when a session starts, instead of
|
|
2276
|
+
* leaving the typo to be found by the command it should have stopped. Blank
|
|
2277
|
+
* entries are not reported: they protect nothing and claim nothing.
|
|
2278
|
+
*/
|
|
2279
|
+
export const droppedProtectedWorktrees = (raw) => {
|
|
2280
|
+
const entries = Array.isArray(raw) ? raw : [raw];
|
|
2281
|
+
const out = [];
|
|
2282
|
+
for (const entry of entries) {
|
|
2283
|
+
if (typeof entry !== 'string') {
|
|
2284
|
+
if (entry !== undefined && entry !== null) out.push({ entry: String(entry), why: '不是字符串' });
|
|
2285
|
+
continue;
|
|
2286
|
+
}
|
|
2287
|
+
const value = entry.trim();
|
|
2288
|
+
if (!value || isAbsolute(value)) continue;
|
|
2289
|
+
if (value === '~' || /^~[\\/]/.test(value)) {
|
|
2290
|
+
if (process.env.HOME ?? process.env.USERPROFILE ?? null) continue;
|
|
2291
|
+
out.push({ entry: value, why: '~ 展不开(HOME / USERPROFILE 都没设)' });
|
|
2292
|
+
continue;
|
|
2293
|
+
}
|
|
2294
|
+
out.push({ entry: value, why: '不是绝对路径' });
|
|
2295
|
+
}
|
|
2296
|
+
return out;
|
|
2297
|
+
};
|
|
2298
|
+
|
|
2299
|
+
/**
|
|
2300
|
+
* git's own options, i.e. the ones that may sit between `git` and the
|
|
2301
|
+
* subcommand: `git -C <dir> stash`, `git --work-tree=<dir> reset --hard`.
|
|
2302
|
+
*
|
|
2303
|
+
* They matter here because two of them MOVE the command into another
|
|
2304
|
+
* repository without a `cd`. A rule that reads the subcommand off the first
|
|
2305
|
+
* argument sees neither `git -C elsewhere stash` nor `git -C elsewhere reset
|
|
2306
|
+
* --hard` - which was true of every git rule in this file until 2026-11-25.
|
|
2307
|
+
* The lists are the OPTIONS section of `git --help`; a token that is in none
|
|
2308
|
+
* of them is the subcommand.
|
|
2309
|
+
*/
|
|
2310
|
+
const GIT_OPTIONS_TAKING_AN_OPERAND = new Set([
|
|
2311
|
+
'-C', '-c', '--git-dir', '--work-tree', '--namespace', '--exec-path', '--super-prefix',
|
|
2312
|
+
]);
|
|
2313
|
+
const GIT_OPTIONS_STANDING_ALONE = new Set([
|
|
2314
|
+
'-p', '-P', '--paginate', '--no-pager', '--bare', '--literal-pathspecs', '--glob-pathspecs',
|
|
2315
|
+
'--noglob-pathspecs', '--icase-pathspecs', '--no-replace-objects', '--no-optional-locks',
|
|
2316
|
+
]);
|
|
2317
|
+
const GIT_OPTIONS_WRITTEN_WITH_EQUALS = new Set([
|
|
2318
|
+
'--git-dir', '--work-tree', '--namespace', '--super-prefix', '--exec-path', '--config-env',
|
|
2319
|
+
]);
|
|
2320
|
+
|
|
2321
|
+
/**
|
|
2322
|
+
* Split a `git` argument list into the subcommand, its arguments, and the
|
|
2323
|
+
* directory git will run in once `-C` / `--work-tree` have been applied.
|
|
2324
|
+
*
|
|
2325
|
+
* `dir` is `null` when that directory cannot be known statically (it started
|
|
2326
|
+
* out unknown and a relative `-C` followed, or the operand was `$VAR`). The
|
|
2327
|
+
* caller must read that as "is this a protected worktree? - unanswered", and
|
|
2328
|
+
* must not turn it into a claim either way.
|
|
2329
|
+
*/
|
|
2330
|
+
const gitInvocation = (values, cwd) => {
|
|
2331
|
+
let dir = typeof cwd === 'string' && cwd !== '' ? cwd : null;
|
|
2332
|
+
let i = 0;
|
|
2333
|
+
// `-C` is cumulative and relative to the previous `-C`, exactly as in git.
|
|
2334
|
+
const moveTo = (operand) => {
|
|
2335
|
+
if (typeof operand !== 'string' || operand === '') {
|
|
2336
|
+
dir = null;
|
|
2337
|
+
return;
|
|
2338
|
+
}
|
|
2339
|
+
if (dir === null && !isAbsolute(operand)) {
|
|
2340
|
+
dir = null;
|
|
2341
|
+
return;
|
|
2342
|
+
}
|
|
2343
|
+
const resolved = resolveShellPath(operand, dir);
|
|
2344
|
+
dir = resolved === null ? null : normalize(resolved);
|
|
2345
|
+
};
|
|
2346
|
+
while (i < values.length) {
|
|
2347
|
+
const value = values[i];
|
|
2348
|
+
if (GIT_OPTIONS_TAKING_AN_OPERAND.has(value)) {
|
|
2349
|
+
if (value === '-C' || value === '--work-tree') moveTo(values[i + 1]);
|
|
2350
|
+
i += 2;
|
|
2351
|
+
continue;
|
|
2352
|
+
}
|
|
2353
|
+
if (GIT_OPTIONS_STANDING_ALONE.has(value)) {
|
|
2354
|
+
i += 1;
|
|
2355
|
+
continue;
|
|
2356
|
+
}
|
|
2357
|
+
const equals = value.indexOf('=');
|
|
2358
|
+
if (equals > 2 && GIT_OPTIONS_WRITTEN_WITH_EQUALS.has(value.slice(0, equals))) {
|
|
2359
|
+
if (value.startsWith('--work-tree=')) moveTo(value.slice('--work-tree='.length));
|
|
2360
|
+
i += 1;
|
|
2361
|
+
continue;
|
|
2362
|
+
}
|
|
2363
|
+
break;
|
|
2364
|
+
}
|
|
2365
|
+
return {
|
|
2366
|
+
sub: i < values.length ? commandBase(values[i]) : '',
|
|
2367
|
+
rest: values.slice(i + 1),
|
|
2368
|
+
dir,
|
|
2369
|
+
};
|
|
2370
|
+
};
|
|
2371
|
+
|
|
2372
|
+
/**
|
|
2373
|
+
* The protected worktree `dir` sits in, or null. A PARENT of a protected root
|
|
2374
|
+
* is not itself protected: a command reaches into the root from there by
|
|
2375
|
+
* naming it (`git -C <root> ...`), and `gitInvocation` has already resolved
|
|
2376
|
+
* that to `dir`.
|
|
2377
|
+
*/
|
|
2378
|
+
export const protectedRootOf = (dir, config) => {
|
|
2379
|
+
if (!dir) return null;
|
|
2380
|
+
const target = normalize(String(dir).replace(/\\/g, '/'));
|
|
2381
|
+
return normalizeProtectedWorktrees(config.protected_worktrees).find((root) => withinRoot(root, target)) ?? null;
|
|
2382
|
+
};
|
|
2383
|
+
|
|
2384
|
+
/**
|
|
2385
|
+
* Whether `content` replaces the gate file wholesale while leaving out the
|
|
2386
|
+
* protected-worktree list the file on disk still carries.
|
|
2387
|
+
*
|
|
2388
|
+
* Recognised by shape - `content` parses as a JSON object, i.e. it is a whole
|
|
2389
|
+
* document and not a fragment - because a fragment cannot be judged: an edit
|
|
2390
|
+
* that rewrites one line says nothing about the lines it leaves alone. With no
|
|
2391
|
+
* readable file behind the path there is nothing being dropped.
|
|
2392
|
+
*/
|
|
2393
|
+
const dropsProtectedList = (content, path, fs) => {
|
|
2394
|
+
let doc;
|
|
2395
|
+
try {
|
|
2396
|
+
doc = JSON.parse(content);
|
|
2397
|
+
} catch {
|
|
2398
|
+
return false;
|
|
2399
|
+
}
|
|
2400
|
+
if (!doc || typeof doc !== 'object' || Array.isArray(doc)) return false;
|
|
2401
|
+
let current = null;
|
|
2402
|
+
try {
|
|
2403
|
+
current = fs?.readText?.(path) ?? null;
|
|
2404
|
+
} catch {
|
|
2405
|
+
current = null;
|
|
2406
|
+
}
|
|
2407
|
+
return typeof current === 'string' && /protected_worktrees/.test(current);
|
|
2408
|
+
};
|
|
2409
|
+
|
|
2410
|
+
/**
|
|
2411
|
+
* Whether a git subcommand discards or replaces the working tree's uncommitted
|
|
2412
|
+
* content, and how the gate treats it OUTSIDE a protected worktree.
|
|
2413
|
+
*
|
|
2414
|
+
* `permission: true` - irreversibly destroys uncommitted work, the way
|
|
2415
|
+
* `reset --hard` does. A `git-history` confirmation in an
|
|
2416
|
+
* ordinary repository (ADR-012).
|
|
2417
|
+
* `permission: false` - reversible there, so an ordinary repository does not
|
|
2418
|
+
* ask: `git stash` keeps what it removes, `--autostash`
|
|
2419
|
+
* puts it back, `git rm` is how a file is retired. Only a
|
|
2420
|
+
* protected worktree makes these a red line, because
|
|
2421
|
+
* there "removed from the working tree" already IS the
|
|
2422
|
+
* outage, whatever becomes of the saved copy.
|
|
2423
|
+
*
|
|
2424
|
+
* Read-only and history commands never match - `status`, `diff`, `log`, `add`,
|
|
2425
|
+
* `commit`, `show HEAD:<path>` leave the working tree alone - and neither does
|
|
2426
|
+
* anything that only puts state back (`stash pop` / `apply` / `branch`).
|
|
2427
|
+
*/
|
|
2428
|
+
const gitWorktreeWipe = (sub, rest) => {
|
|
2429
|
+
// Flags after `--` belong to the pathspec, not to the command.
|
|
2430
|
+
const pathspecAt = rest.indexOf('--');
|
|
2431
|
+
const opts = pathspecAt >= 0 ? rest.slice(0, pathspecAt) : rest;
|
|
2432
|
+
if (opts.includes('-h') || opts.includes('--help')) return null;
|
|
2433
|
+
const short = (letter) =>
|
|
2434
|
+
opts.some((v) => v.length > 1 && v[0] === '-' && v[1] !== '-' && [...v].slice(1).includes(letter));
|
|
2435
|
+
const long = (name) => opts.includes(name);
|
|
2436
|
+
const dryRun = short('n') || long('--dry-run');
|
|
2437
|
+
|
|
2438
|
+
switch (sub) {
|
|
2439
|
+
case 'stash': {
|
|
2440
|
+
// `git stash [-p|-S|-k|-q|-u|-a|-m <msg>] [--] [<pathspec>…]` is a push;
|
|
2441
|
+
// the subcommand word is optional, so the first non-option token is only
|
|
2442
|
+
// an action when it is one of these.
|
|
2443
|
+
const action = opts[0];
|
|
2444
|
+
if (['list', 'show', 'pop', 'apply', 'branch', 'create', 'store'].includes(action)) return null;
|
|
2445
|
+
if (action === 'drop' || action === 'clear') {
|
|
2446
|
+
return { why: `git stash ${action}`, permission: true };
|
|
2447
|
+
}
|
|
2448
|
+
return { why: 'git stash removes uncommitted changes from the working tree', permission: false };
|
|
2449
|
+
}
|
|
2450
|
+
case 'reset':
|
|
2451
|
+
if (long('--hard')) return { why: 'git reset --hard discards uncommitted work', permission: true };
|
|
2452
|
+
if (long('--merge')) return { why: 'git reset --merge discards uncommitted work', permission: true };
|
|
2453
|
+
return null;
|
|
2454
|
+
case 'clean':
|
|
2455
|
+
if (dryRun) return null;
|
|
2456
|
+
return short('f') || long('--force')
|
|
2457
|
+
? { why: 'git clean --force deletes untracked files', permission: true }
|
|
2458
|
+
: null;
|
|
2459
|
+
case 'checkout':
|
|
2460
|
+
if (short('f') || long('--force')) {
|
|
2461
|
+
return { why: 'git checkout --force discards uncommitted work', permission: true };
|
|
2462
|
+
}
|
|
2463
|
+
if (rest.includes('--') || rest.includes('.') || long('--ours') || long('--theirs')) {
|
|
2464
|
+
return { why: 'git checkout -- . discards uncommitted work', permission: true };
|
|
2465
|
+
}
|
|
2466
|
+
return null;
|
|
2467
|
+
case 'restore': {
|
|
2468
|
+
// `--staged` alone touches the index only; `--staged --worktree` does not.
|
|
2469
|
+
const stagedOnly = (long('--staged') || short('S')) && !(long('--worktree') || short('W'));
|
|
2470
|
+
return stagedOnly ? null : { why: 'git restore discards uncommitted work', permission: true };
|
|
2471
|
+
}
|
|
2472
|
+
case 'switch':
|
|
2473
|
+
return short('f') || long('--force') || long('--discard-changes')
|
|
2474
|
+
? { why: 'git switch --force discards uncommitted work', permission: true }
|
|
2475
|
+
: null;
|
|
2476
|
+
case 'read-tree':
|
|
2477
|
+
return long('--reset')
|
|
2478
|
+
? { why: 'git read-tree --reset overwrites the index and working tree', permission: true }
|
|
2479
|
+
: null;
|
|
2480
|
+
case 'checkout-index':
|
|
2481
|
+
return short('f') || long('--force')
|
|
2482
|
+
? { why: 'git checkout-index --force overwrites working tree files', permission: true }
|
|
2483
|
+
: null;
|
|
2484
|
+
case 'update-ref':
|
|
2485
|
+
return (short('d') || long('--delete')) && rest.some((v) => v === 'refs/stash' || v.startsWith('refs/stash/'))
|
|
2486
|
+
? { why: 'git update-ref -d refs/stash destroys every saved stash', permission: true }
|
|
2487
|
+
: null;
|
|
2488
|
+
case 'rm':
|
|
2489
|
+
return long('--cached') || dryRun
|
|
2490
|
+
? null
|
|
2491
|
+
: { why: 'git rm deletes tracked files from the working tree', permission: false };
|
|
2492
|
+
default:
|
|
2493
|
+
if (['pull', 'fetch', 'rebase', 'merge', 'revert', 'cherry-pick', 'am'].includes(sub) && long('--autostash')) {
|
|
2494
|
+
return { why: `git ${sub} --autostash stashes uncommitted changes before it runs`, permission: false };
|
|
2495
|
+
}
|
|
2496
|
+
return null;
|
|
2497
|
+
}
|
|
2498
|
+
};
|
|
2499
|
+
|
|
2500
|
+
export const bashDestructiveFinding = (command, { config = DEFAULT_CONFIG, cwd = null, isGitRepo = null } = {}, depth = 0) => {
|
|
2501
|
+
if (typeof command !== 'string' || command === '' || depth > 2) return null;
|
|
2502
|
+
const allow = (config.destructive_allow_patterns ?? []).some((src) => {
|
|
2503
|
+
try {
|
|
2504
|
+
return new RegExp(src).test(command);
|
|
2505
|
+
} catch {
|
|
2506
|
+
return false;
|
|
2507
|
+
}
|
|
2508
|
+
});
|
|
2509
|
+
if (allow) return null;
|
|
2510
|
+
|
|
2511
|
+
let activeCwd = cwd;
|
|
2512
|
+
// Quote-aware on purpose. A plain split tore `bash -c "cd <dir> && git stash"`
|
|
2513
|
+
// into `bash -c "cd <dir>` and `git stash"`, so the nested shell was never
|
|
2514
|
+
// entered AND the torn-off half read as an unknown subcommand: nothing was
|
|
2515
|
+
// found, in any directory (ADR-015).
|
|
2516
|
+
for (const segment of splitShellSegments(command)) {
|
|
2517
|
+
if (!segment.trim()) continue;
|
|
2518
|
+
const tokens = shellTokens(segment);
|
|
2519
|
+
if (tokens.length === 0) continue;
|
|
2520
|
+
const { verb, args } = parseCommandHead(tokens);
|
|
2521
|
+
if (!verb) continue;
|
|
2522
|
+
const values = args.map((a) => a.value);
|
|
2523
|
+
/**
|
|
2524
|
+
* `high` - a guardrail: unrecoverable, and no grant can reach it.
|
|
2525
|
+
* `confirm` - a permission: the category's tier decides allow/ask/deny.
|
|
2526
|
+
*
|
|
2527
|
+
* `high` is the default on purpose: a branch that forgets to pass a
|
|
2528
|
+
* severity keeps the un-grantable behaviour instead of silently becoming a
|
|
2529
|
+
* question the user can click through.
|
|
2530
|
+
*
|
|
2531
|
+
* `protectedRoot` is set only by the protected-worktree red line (ADR-015),
|
|
2532
|
+
* so the check can explain that one in its own words.
|
|
2533
|
+
*/
|
|
2534
|
+
const finding = (why, severity = 'high', category = null, protectedRoot = null) => ({
|
|
2535
|
+
why,
|
|
2536
|
+
segment: segment.trim().slice(0, 200),
|
|
2537
|
+
severity,
|
|
2538
|
+
category,
|
|
2539
|
+
protectedRoot,
|
|
2540
|
+
});
|
|
2541
|
+
|
|
2542
|
+
if (['cd', 'pushd', 'set-location', 'sl', 'chdir'].includes(verb)) {
|
|
2543
|
+
const target = args.find((a) => a.quoted || !a.value.startsWith('-'));
|
|
2544
|
+
const resolved = target ? resolveShellPath(target.value, activeCwd) : null;
|
|
2545
|
+
if (resolved) activeCwd = resolved;
|
|
2546
|
+
continue;
|
|
2547
|
+
}
|
|
2548
|
+
|
|
2549
|
+
// Recursively inspect a nested shell: `bash -c 'git reset --hard'`.
|
|
2550
|
+
if (['sh', 'bash', 'zsh', 'dash', 'ksh', 'cmd', 'powershell', 'pwsh'].includes(verb)) {
|
|
2551
|
+
const flagAt = values.findIndex((v) => ['-c', '/c', '/C', '-Command', '-command'].includes(v));
|
|
2552
|
+
if (flagAt >= 0 && values[flagAt + 1]) {
|
|
2553
|
+
const nested = bashDestructiveFinding(
|
|
2554
|
+
values.slice(flagAt + 1).join(' '),
|
|
2555
|
+
{ config, cwd: activeCwd, isGitRepo },
|
|
2556
|
+
depth + 1,
|
|
2557
|
+
);
|
|
2558
|
+
if (nested) return nested;
|
|
2559
|
+
}
|
|
2560
|
+
continue;
|
|
2561
|
+
}
|
|
2562
|
+
|
|
2563
|
+
if (verb === 'rm' || verb === 'rmdir' || verb === 'unlink') {
|
|
2564
|
+
const recursive = values.some((v) => /^-[a-z]*[rR]/.test(v) || v === '--recursive');
|
|
2565
|
+
const force = values.some((v) => /^-[a-z]*f/.test(v) || v === '--force');
|
|
2566
|
+
const targets = values.filter((v) => !v.startsWith('-'));
|
|
2567
|
+
const dangerous = targets.filter((t) => !isDisposablePath(t, activeCwd, config));
|
|
2568
|
+
if (dangerous.length > 0 && (recursive || force || targets.length > 1)) {
|
|
2569
|
+
// One unrecoverable target is enough to make the whole command high:
|
|
2570
|
+
// `rm -rf scratch.txt $HOME` must not become a question.
|
|
2571
|
+
const severity = dangerous.some((t) => unrecoverableTarget(t, activeCwd, isGitRepo))
|
|
2572
|
+
? 'high'
|
|
2573
|
+
: 'confirm';
|
|
2574
|
+
return finding(
|
|
2575
|
+
`${verb} ${recursive ? 'recursive ' : ''}${force ? 'forced ' : ''}on ${dangerous[0]}`,
|
|
2576
|
+
severity,
|
|
2577
|
+
'delete',
|
|
2578
|
+
);
|
|
2579
|
+
}
|
|
2580
|
+
}
|
|
2581
|
+
|
|
2582
|
+
if (verb === 'git') {
|
|
2583
|
+
const { sub, rest, dir } = gitInvocation(values, activeCwd);
|
|
2584
|
+
const wipe = gitWorktreeWipe(sub, rest);
|
|
2585
|
+
if (wipe) {
|
|
2586
|
+
// ---- red line: a protected worktree ------------------------------
|
|
2587
|
+
// First, and before any permission logic, for the same reason the
|
|
2588
|
+
// `severity === 'high'` return sits ahead of the bypass check in
|
|
2589
|
+
// `no-destructive-bash`: in this directory "uncommitted" means "in
|
|
2590
|
+
// use", so removing it is an outage whether or not a copy survives in
|
|
2591
|
+
// a stash. See `gitWorktreeWipe` for why plain `git stash` is a red
|
|
2592
|
+
// line here and nothing at all everywhere else.
|
|
2593
|
+
const root = protectedRootOf(dir, config);
|
|
2594
|
+
if (root) {
|
|
2595
|
+
return finding(wipe.why, 'high', 'git-history', root);
|
|
2596
|
+
}
|
|
2597
|
+
if (wipe.permission) return finding(wipe.why, 'confirm', 'git-history');
|
|
2598
|
+
}
|
|
2599
|
+
|
|
2600
|
+
// Every git branch below is a *permission*, not a guardrail: discarding
|
|
2601
|
+
// local work or rewriting a branch you own is a normal thing to want, and
|
|
2602
|
+
// the user can grant it (`/gate grant git-history`). The guardrail tier is
|
|
2603
|
+
// reserved for things no grant can undo.
|
|
2604
|
+
if (sub === 'push' && rest.some((v) => v === '--force' || v === '--force-with-lease' || /^-f$/.test(v))) {
|
|
2605
|
+
return finding('git push --force rewrites shared history', 'confirm', 'git-force-push');
|
|
2606
|
+
}
|
|
2607
|
+
if (sub === 'branch' && rest.some((v) => /^-[a-zA-Z]*D/.test(v) || v === '--delete')) {
|
|
2608
|
+
return finding('git branch --delete removes a branch', 'confirm', 'git-history');
|
|
2609
|
+
}
|
|
2610
|
+
if (['filter-branch', 'filter-repo'].includes(sub)) {
|
|
2611
|
+
return finding(`git ${sub} rewrites history`, 'confirm', 'git-history');
|
|
2612
|
+
}
|
|
2613
|
+
}
|
|
2614
|
+
|
|
2615
|
+
if (verb === 'find' && values.includes('-delete')) {
|
|
2616
|
+
const root = values.find((v) => !v.startsWith('-')) ?? '.';
|
|
2617
|
+
if (!isDisposablePath(root, activeCwd, config)) {
|
|
2618
|
+
return finding(`find ${root} -delete`, targetSeverity(root, activeCwd, isGitRepo), 'delete');
|
|
2619
|
+
}
|
|
2620
|
+
}
|
|
2621
|
+
|
|
2622
|
+
if (verb === 'dd' && values.some((v) => v.startsWith('of='))) {
|
|
2623
|
+
const target = values.find((v) => v.startsWith('of=')).slice(3);
|
|
2624
|
+
if (['/dev/null', 'nul'].includes(target.toLowerCase())) return null;
|
|
2625
|
+
// Writing to a raw device is a guardrail: there is no "undo" for it. A
|
|
2626
|
+
// plain file is a permission the user may grant.
|
|
2627
|
+
if (RAW_DEVICE.test(target)) return finding(`dd of=${target} writes a raw device`);
|
|
2628
|
+
if (!isDisposablePath(target, activeCwd, config)) {
|
|
2629
|
+
return finding(`dd of=${target}`, 'confirm', 'raw-write');
|
|
2630
|
+
}
|
|
2631
|
+
}
|
|
2632
|
+
|
|
2633
|
+
if (HOST_DESTRUCTIVE_VERB.test(verb) || ['shutdown', 'reboot', 'poweroff', 'halt'].includes(verb)) {
|
|
2634
|
+
return finding(`${verb} is a host-level destructive command`);
|
|
2635
|
+
}
|
|
2636
|
+
if (verb === 'init' && ['0', '6'].includes(values[0])) return finding('init 0/6 shuts the machine down');
|
|
2637
|
+
if (verb === 'taskkill' && values.some((v) => v.toLowerCase() === '/f')) {
|
|
2638
|
+
return finding('taskkill /F forcibly terminates processes', 'confirm', 'process-kill');
|
|
2639
|
+
}
|
|
2640
|
+
|
|
2641
|
+
if (['del', 'erase'].includes(verb) && values.some((v) => ['/s', '/q', '/f'].includes(v.toLowerCase()))) {
|
|
2642
|
+
const target = values.find((v) => !v.startsWith('-') && !v.startsWith('/'));
|
|
2643
|
+
return finding(`${verb} deletes files recursively`, targetSeverity(target, activeCwd, isGitRepo), 'delete');
|
|
2644
|
+
}
|
|
2645
|
+
if (['rd', 'rmdir'].includes(verb) && values.some((v) => v.toLowerCase() === '/s')) {
|
|
2646
|
+
const target = values.find((v) => !v.startsWith('-') && !v.startsWith('/'));
|
|
2647
|
+
return finding(`${verb} /s deletes a tree`, targetSeverity(target, activeCwd, isGitRepo), 'delete');
|
|
2648
|
+
}
|
|
2649
|
+
if (verb === 'remove-item' && values.some((v) => v.toLowerCase().startsWith('-recurse'))) {
|
|
2650
|
+
const target = values.find((v) => !v.startsWith('-'));
|
|
2651
|
+
if (!target || !isDisposablePath(target, activeCwd, config)) {
|
|
2652
|
+
return finding('Remove-Item -Recurse', targetSeverity(target, activeCwd, isGitRepo), 'delete');
|
|
2653
|
+
}
|
|
2654
|
+
}
|
|
2655
|
+
if (verb === 'stop-computer') return finding('Stop-Computer shuts the machine down');
|
|
2656
|
+
|
|
2657
|
+
if (['chmod', 'chown', 'chgrp'].includes(verb) && values.some((v) => /^-[a-z]*R/.test(v))) {
|
|
2658
|
+
const target = values.filter((v) => !v.startsWith('-')).pop();
|
|
2659
|
+
if (target && !isDisposablePath(target, activeCwd, config)) {
|
|
2660
|
+
return finding(`${verb} -R on ${target}`, targetSeverity(target, activeCwd, isGitRepo), 'perm-recursive');
|
|
2661
|
+
}
|
|
2662
|
+
}
|
|
2663
|
+
|
|
2664
|
+
const sql = `${verb} ${values.join(' ')}`.toLowerCase();
|
|
2665
|
+
if (/^(?:drop\s+(?:table|database|schema)|truncate\s+table)\b/.test(sql)) {
|
|
2666
|
+
return finding('destructive SQL', 'confirm', 'db-ddl');
|
|
2667
|
+
}
|
|
2668
|
+
|
|
2669
|
+
// The same statement passed to a database client's flag is still DDL.
|
|
2670
|
+
if (DB_CLIENTS.has(verb) && DDL_ANYWHERE.test(values.join(' ').toLowerCase())) {
|
|
2671
|
+
return finding(`destructive SQL via ${verb}`, 'confirm', 'db-ddl');
|
|
2672
|
+
}
|
|
2673
|
+
if (['mongo', 'mongosh'].includes(verb) && MONGO_DROP.test(values.join(' '))) {
|
|
2674
|
+
return finding(`destructive MongoDB drop via ${verb}`, 'confirm', 'db-ddl');
|
|
2675
|
+
}
|
|
2676
|
+
}
|
|
2677
|
+
return null;
|
|
2678
|
+
};
|
|
2679
|
+
|
|
2680
|
+
|
|
2681
|
+
// ---------------------------------------------------------------------------
|
|
2682
|
+
// PowerShell: the same read/write semantics, different verb names
|
|
2683
|
+
// ---------------------------------------------------------------------------
|
|
2684
|
+
|
|
2685
|
+
const PS_READ_VERBS = new Set([
|
|
2686
|
+
'get-content', 'gc', 'cat', 'type', 'select-string', 'sls', 'format-hex', 'fhx',
|
|
2687
|
+
'get-item', 'gi', 'get-itemproperty', 'gp', 'resolve-path', 'rvpa', 'get-filehash',
|
|
2688
|
+
]);
|
|
2689
|
+
const PS_SCAN_VERBS = new Set(['get-childitem', 'gci', 'ls', 'dir']);
|
|
2690
|
+
const PS_WRITE_VERBS = new Set([
|
|
2691
|
+
'set-content', 'sc', 'add-content', 'ac', 'out-file', 'tee-object', 'tee',
|
|
2692
|
+
'new-item', 'ni', 'copy-item', 'cpi', 'cp', 'copy', 'move-item', 'mi', 'mv', 'move',
|
|
2693
|
+
'rename-item', 'rni', 'ren', 'remove-item', 'ri', 'rm', 'del', 'erase', 'rmdir',
|
|
2694
|
+
'clear-content', 'clc', 'export-csv', 'export-clixml', 'set-item', 'si',
|
|
2695
|
+
]);
|
|
2696
|
+
/** Flags whose next token is a path. */
|
|
2697
|
+
const PS_PATH_FLAGS = new Set(['-path', '-filepath', '-literalpath', '-destination', '-outfile', '-target', '-name']);
|
|
2698
|
+
/** Flags whose next token is a value (content, encoding, pattern), never a path. */
|
|
2699
|
+
const PS_VALUE_FLAGS = new Set([
|
|
2700
|
+
'-value', '-encoding', '-delimiter', '-pattern', '-inputobject', '-width', '-totalcount',
|
|
2701
|
+
'-head', '-tail', '-first', '-last', '-replace', '-credential', '-pipelinevariable',
|
|
2702
|
+
'-filter', '-include', '-exclude', '-erroraction', '-warningaction', '-verbose',
|
|
2703
|
+
]);
|
|
2704
|
+
/** Verbs where every operand after the first is a destination. */
|
|
2705
|
+
const PS_MULTI_PATH_VERBS = new Set(['copy-item', 'cpi', 'cp', 'copy', 'move-item', 'mi', 'mv', 'move', 'rename-item', 'rni', 'ren']);
|
|
2706
|
+
|
|
2707
|
+
const psFlag = (value) => String(value).toLowerCase().split(':')[0];
|
|
2708
|
+
|
|
2709
|
+
/**
|
|
2710
|
+
* Static parser for the PowerShell shapes that overlap with file work.
|
|
2711
|
+
*
|
|
2712
|
+
* Like the bash parser this is deliberately conservative: it understands the
|
|
2713
|
+
* common read/write/scan verbs and `-Path`-style flags, and skips anything it
|
|
2714
|
+
* cannot resolve. It never executes a command.
|
|
2715
|
+
*/
|
|
2716
|
+
const parsePowerShell = (
|
|
2717
|
+
command,
|
|
2718
|
+
{ config = DEFAULT_CONFIG, cwd = null, isFile = defaultIsFile, exists = () => false } = {},
|
|
2719
|
+
) => {
|
|
2720
|
+
const files = [];
|
|
2721
|
+
const dirs = [];
|
|
2722
|
+
const writes = [];
|
|
2723
|
+
if (typeof command !== 'string' || command === '') return { files, dirs, writes };
|
|
2724
|
+
let activeCwd = cwd;
|
|
2725
|
+
|
|
2726
|
+
const pushFile = (raw) => {
|
|
2727
|
+
const candidate = resolveShellPath(raw, activeCwd);
|
|
2728
|
+
if (!candidate || !isCodeFile(candidate, config) || isExcluded(candidate, config)) return;
|
|
2729
|
+
if (isFile(candidate)) files.push(candidate);
|
|
2730
|
+
};
|
|
2731
|
+
const pushDir = (raw) => {
|
|
2732
|
+
const candidate = resolveShellPath(raw, activeCwd);
|
|
2733
|
+
if (!candidate || !exists(candidate)) return;
|
|
2734
|
+
const scope = scopeOf(join(candidate, '.gate-probe.ts'), { config, exists });
|
|
2735
|
+
if (scope.inScope) dirs.push(candidate);
|
|
2736
|
+
};
|
|
2737
|
+
const pushWrite = (raw) => {
|
|
2738
|
+
const candidate = resolveShellPath(raw, activeCwd);
|
|
2739
|
+
if (!candidate) return;
|
|
2740
|
+
const base = candidate.replace(/\\/g, '/').split('/').pop()?.toLowerCase();
|
|
2741
|
+
if (['/dev/null', 'nul', '/dev/stdout', '/dev/stderr'].includes(base)) return;
|
|
2742
|
+
writes.push(candidate);
|
|
2743
|
+
};
|
|
2744
|
+
|
|
2745
|
+
for (const rawSegment of splitShellSegments(command)) {
|
|
2746
|
+
const segment = rawSegment.trim();
|
|
2747
|
+
if (!segment) continue;
|
|
2748
|
+
const tokens = shellTokens(segment);
|
|
2749
|
+
if (tokens.length === 0) continue;
|
|
2750
|
+
const { verb, args } = parseCommandHead(tokens);
|
|
2751
|
+
if (!verb) continue;
|
|
2752
|
+
|
|
2753
|
+
// Nested invocation: `powershell -Command "Get-Content x"`.
|
|
2754
|
+
if (['powershell', 'pwsh'].includes(verb)) {
|
|
2755
|
+
const at = args.findIndex((a) => ['-c', '-command', '/c'].includes(a.value.toLowerCase()));
|
|
2756
|
+
if (at >= 0 && args[at + 1]) {
|
|
2757
|
+
const nested = args.slice(at + 1).map((a) => a.raw).join(' ');
|
|
2758
|
+
const inner = parsePowerShell(nested, { config, cwd: activeCwd, isFile, exists });
|
|
2759
|
+
files.push(...inner.files);
|
|
2760
|
+
dirs.push(...inner.dirs);
|
|
2761
|
+
writes.push(...inner.writes);
|
|
2762
|
+
}
|
|
2763
|
+
continue;
|
|
2764
|
+
}
|
|
2765
|
+
|
|
2766
|
+
if (verb === 'cd' || verb === 'set-location' || verb === 'sl') {
|
|
2767
|
+
const target = args.find((a) => a.quoted || !a.value.startsWith('-'));
|
|
2768
|
+
const resolved = target ? resolveShellPath(target.value, activeCwd) : null;
|
|
2769
|
+
if (resolved) activeCwd = resolved;
|
|
2770
|
+
continue;
|
|
2771
|
+
}
|
|
2772
|
+
|
|
2773
|
+
// Redirection: `... > file`, `... >> file`, `2> file`.
|
|
2774
|
+
for (const m of segment.matchAll(/(?:^|\s)(?:\d?>>?)\s*("[^"]+"|'[^']+'|\S+)/g)) {
|
|
2775
|
+
pushWrite(m[1]);
|
|
2776
|
+
}
|
|
2777
|
+
|
|
2778
|
+
const isRead = PS_READ_VERBS.has(verb);
|
|
2779
|
+
const isScan = PS_SCAN_VERBS.has(verb);
|
|
2780
|
+
const isWrite = PS_WRITE_VERBS.has(verb);
|
|
2781
|
+
if (!isRead && !isScan && !isWrite) continue;
|
|
2782
|
+
|
|
2783
|
+
const operands = [];
|
|
2784
|
+
for (let i = 0; i < args.length; i += 1) {
|
|
2785
|
+
const value = args[i].value;
|
|
2786
|
+
if (!args[i].quoted && value.startsWith('-')) {
|
|
2787
|
+
const flag = psFlag(value);
|
|
2788
|
+
if (PS_PATH_FLAGS.has(flag) && args[i + 1]) {
|
|
2789
|
+
operands.push(args[i + 1].value);
|
|
2790
|
+
i += 1;
|
|
2791
|
+
} else if (PS_VALUE_FLAGS.has(flag) && args[i + 1]) {
|
|
2792
|
+
i += 1;
|
|
2793
|
+
}
|
|
2794
|
+
continue;
|
|
2795
|
+
}
|
|
2796
|
+
operands.push(value);
|
|
2797
|
+
}
|
|
2798
|
+
|
|
2799
|
+
if (isScan) {
|
|
2800
|
+
pushDir(operands[0] ?? activeCwd ?? '.');
|
|
2801
|
+
continue;
|
|
2802
|
+
}
|
|
2803
|
+
|
|
2804
|
+
if (isRead) {
|
|
2805
|
+
// Positional `Select-String <pattern> <path>`: the first operand is the pattern.
|
|
2806
|
+
const hasPathFlag = args.some((a) => PS_PATH_FLAGS.has(psFlag(a.value)));
|
|
2807
|
+
const start = (verb === 'select-string' || verb === 'sls') && !hasPathFlag ? 1 : 0;
|
|
2808
|
+
for (const p of operands.slice(start)) pushFile(p);
|
|
2809
|
+
continue;
|
|
2810
|
+
}
|
|
2811
|
+
|
|
2812
|
+
if (PS_MULTI_PATH_VERBS.has(verb)) {
|
|
2813
|
+
const [source, ...dests] = operands;
|
|
2814
|
+
if (source) pushFile(source);
|
|
2815
|
+
for (const d of dests) pushWrite(d);
|
|
2816
|
+
continue;
|
|
2817
|
+
}
|
|
2818
|
+
|
|
2819
|
+
// Set-Content / Out-File / New-Item / Remove-Item: first operand is the path,
|
|
2820
|
+
// later operands are content or values and must not be judged as paths.
|
|
2821
|
+
if (operands[0]) pushWrite(operands[0]);
|
|
2822
|
+
}
|
|
2823
|
+
|
|
2824
|
+
const unique = (list) => [...new Set(list)];
|
|
2825
|
+
return { files: unique(files), dirs: unique(dirs), writes: unique(writes) };
|
|
2826
|
+
};
|
|
2827
|
+
|
|
2828
|
+
export const powershellReadTargets = (command, opts = {}) => parsePowerShell(command, opts).files;
|
|
2829
|
+
export const powershellReadDirs = (command, opts = {}) => parsePowerShell(command, opts).dirs;
|
|
2830
|
+
export const powershellWriteTargets = (command, opts = {}) => parsePowerShell(command, opts).writes;
|
|
2831
|
+
|
|
2832
|
+
export const powershellDestructiveFinding = (command, opts = {}) => {
|
|
2833
|
+
const base = bashDestructiveFinding(command, opts);
|
|
2834
|
+
if (base) return base; // Remove-Item -Recurse / del /s are already covered there
|
|
2835
|
+
const { config = DEFAULT_CONFIG, cwd = null } = opts;
|
|
2836
|
+
for (const segment of splitShellSegments(command)) {
|
|
2837
|
+
const tokens = shellTokens(segment);
|
|
2838
|
+
if (tokens.length === 0) continue;
|
|
2839
|
+
const { verb, args } = parseCommandHead(tokens);
|
|
2840
|
+
if (verb !== 'clear-content' && verb !== 'clc') continue;
|
|
2841
|
+
const target = args.map((a) => a.value).find((v) => !v.startsWith('-'));
|
|
2842
|
+
if (target && !isDisposablePath(target, cwd, config)) {
|
|
2843
|
+
return {
|
|
2844
|
+
why: `${verb} wipes file contents`,
|
|
2845
|
+
segment: segment.trim().slice(0, 200),
|
|
2846
|
+
severity: targetSeverity(target, cwd, opts.isGitRepo ?? null),
|
|
2847
|
+
};
|
|
2848
|
+
}
|
|
2849
|
+
}
|
|
2850
|
+
return null;
|
|
2851
|
+
};
|
|
2852
|
+
|
|
2853
|
+
/** Shell-agnostic dispatch: one seam so every check handles both shells. */
|
|
2854
|
+
const shellOf = (input) => (input?.shell === 'powershell' ? 'powershell' : 'bash');
|
|
2855
|
+
export const shellReadTargets = (input, opts = {}) =>
|
|
2856
|
+
shellOf(input) === 'powershell' ? powershellReadTargets(input.command, opts) : bashReadTargets(input.command, opts);
|
|
2857
|
+
export const shellReadDirs = (input, opts = {}) =>
|
|
2858
|
+
shellOf(input) === 'powershell' ? powershellReadDirs(input.command, opts) : bashReadDirs(input.command, opts);
|
|
2859
|
+
export const shellWriteTargets = (input, opts = {}) =>
|
|
2860
|
+
shellOf(input) === 'powershell' ? powershellWriteTargets(input.command, opts) : bashWriteTargets(input.command, opts);
|
|
2861
|
+
export const shellDestructiveFinding = (input, opts = {}) =>
|
|
2862
|
+
shellOf(input) === 'powershell'
|
|
2863
|
+
? powershellDestructiveFinding(input.command, opts)
|
|
2864
|
+
: bashDestructiveFinding(input.command, opts);
|
|
2865
|
+
|
|
2866
|
+
// ---------------------------------------------------------------------------
|
|
2867
|
+
// Index freshness
|
|
2868
|
+
// ---------------------------------------------------------------------------
|
|
2869
|
+
|
|
2870
|
+
/**
|
|
2871
|
+
* The filesystem facts a check may consult, injected so the rule layer stays
|
|
2872
|
+
* unit-testable off-harness (a harness with a virtual or remote filesystem can
|
|
2873
|
+
* still be policed, and the test suite needs no disk).
|
|
2874
|
+
*
|
|
2875
|
+
* Each probe is TOTAL: it answers, it never throws. A probe that can throw
|
|
2876
|
+
* turns a filesystem hiccup into a dead gate, and a gate that stops existing is
|
|
2877
|
+
* the one failure this whole design is built to avoid.
|
|
2878
|
+
*/
|
|
2879
|
+
const NO_FS = {
|
|
2880
|
+
exists: () => false,
|
|
2881
|
+
isFile: () => false,
|
|
2882
|
+
isDirectory: () => false,
|
|
2883
|
+
statMtime: () => 0,
|
|
2884
|
+
listDir: () => [],
|
|
2885
|
+
readText: () => null,
|
|
2886
|
+
};
|
|
2887
|
+
|
|
2888
|
+
/** Newest mtime inside a directory, or 0 when it cannot be read. */
|
|
2889
|
+
export const newestMtimeIn = (dir, fs, now = Date.now(), ttlMs = 0) => {
|
|
2890
|
+
const hit = mtimeCache.get(dir);
|
|
2891
|
+
// `now >= hit.at` rather than trusting the clock: a backwards clock must not
|
|
2892
|
+
// make a stale answer look fresh. Keeping the comparison on the arguments
|
|
2893
|
+
// (instead of calling Date.now() in here) is what makes the TTL testable
|
|
2894
|
+
// without fake timers.
|
|
2895
|
+
if (hit && now >= hit.at && now - hit.at <= ttlMs) return hit.mtime;
|
|
2896
|
+
|
|
2897
|
+
let newest = 0;
|
|
2898
|
+
for (const name of fs.listDir(dir)) {
|
|
2899
|
+
const m = fs.statMtime(join(dir, name));
|
|
2900
|
+
if (m > newest) newest = m;
|
|
2901
|
+
}
|
|
2902
|
+
mtimeCache.set(dir, { at: now, mtime: newest });
|
|
2903
|
+
return newest;
|
|
2904
|
+
};
|
|
2905
|
+
|
|
2906
|
+
/**
|
|
2907
|
+
* Module-level on purpose: this caches a fact about the disk, not about a
|
|
2908
|
+
* session's permissions, so a per-session reset must not clear it. Exported for
|
|
2909
|
+
* tests; not part of the policy contract.
|
|
2910
|
+
*/
|
|
2911
|
+
export const resetMtimeCache = () => mtimeCache.clear();
|
|
2912
|
+
|
|
2913
|
+
/**
|
|
2914
|
+
* AI4S turn-end findings: W4 (run half) + W2.
|
|
2915
|
+
*
|
|
2916
|
+
* Both are OUTPUT-shape problems, and output problems are discovered after the
|
|
2917
|
+
* computation. That is why they are findings for a `continue` (one more turn to
|
|
2918
|
+
* fix) rather than denials: blocking a call that already finished teaches
|
|
2919
|
+
* nothing and breaks a completed analysis.
|
|
2920
|
+
*
|
|
2921
|
+
* Returns `[]` when there is nothing to judge. In particular it returns `[]`
|
|
2922
|
+
* when the session never recorded a turn start: without a boundary there is no
|
|
2923
|
+
* "this turn's output", and judging the whole history would flag every old
|
|
2924
|
+
* directory on the machine.
|
|
2925
|
+
*
|
|
2926
|
+
* @param {object} args
|
|
2927
|
+
* @param {object} args.policy normalized (profile-applied) policy
|
|
2928
|
+
* @param {object} args.state session state from newSessionState()
|
|
2929
|
+
* @param {object} args.fs probe set: {exists, isFile, statMtime, listDir, readText}
|
|
2930
|
+
* @param {string} [args.cwd] session directory the relative result dirs hang off
|
|
2931
|
+
* @param {number} [args.now]
|
|
2932
|
+
* @returns {Array<{code:string, reason:string, path:string}>}
|
|
2933
|
+
*/
|
|
2934
|
+
export const outputArtifactFindings = ({ policy, state, fs, cwd = null, now = Date.now() } = {}) => {
|
|
2935
|
+
const config = policy?.config ?? DEFAULT_CONFIG;
|
|
2936
|
+
const probes = { ...NO_FS, ...(fs ?? {}) };
|
|
2937
|
+
const since = Number.isFinite(state?.turnStart) ? state.turnStart : 0;
|
|
2938
|
+
if (since <= 0) return [];
|
|
2939
|
+
// See `artifact_mtime_epsilon_ms`: file timestamps and Date.now() disagree by a
|
|
2940
|
+
// few milliseconds in both directions, so every comparison below is tolerant.
|
|
2941
|
+
const epsilon = Number.isFinite(config.artifact_mtime_epsilon_ms)
|
|
2942
|
+
? config.artifact_mtime_epsilon_ms
|
|
2943
|
+
: DEFAULT_CONFIG.artifact_mtime_epsilon_ms;
|
|
2944
|
+
const findings = [];
|
|
2945
|
+
|
|
2946
|
+
// --- W4 (run half): every script started this turn must have left a log ----
|
|
2947
|
+
if (config.script_log_check !== false && state?.scriptsRun instanceof Map) {
|
|
2948
|
+
for (const [script, info] of state.scriptsRun) {
|
|
2949
|
+
const startedAt = Number.isFinite(info?.startedAt) ? info.startedAt : 0;
|
|
2950
|
+
if (startedAt < since) continue; // an earlier turn already answered for it
|
|
2951
|
+
if (!hasExtension(script, config.log_required_extensions
|
|
2952
|
+
?? DEFAULT_CONFIG.log_required_extensions)) continue;
|
|
2953
|
+
// Two accepted spellings: `run.R.log` (what the W4 remediation suggests)
|
|
2954
|
+
// and `run.log` (what most pipelines write). Accepting only one would turn
|
|
2955
|
+
// a formatting preference into a blocked turn.
|
|
2956
|
+
const stem = script.replace(/\.[^./\\]+$/, '');
|
|
2957
|
+
const candidates = [`${script}.log`, `${stem}.log`];
|
|
2958
|
+
const log = candidates.find(
|
|
2959
|
+
(p) => probes.isFile(p) && probes.statMtime(p) >= startedAt - epsilon,
|
|
2960
|
+
);
|
|
2961
|
+
if (log) continue;
|
|
2962
|
+
findings.push({
|
|
2963
|
+
code: 'AI4S_SCRIPT_LOG_MISSING',
|
|
2964
|
+
path: script,
|
|
2965
|
+
reason: [
|
|
2966
|
+
'⛔ AI4S 域控 · W4 提醒:本轮跑过的脚本没有留下日志文件。',
|
|
2967
|
+
` 脚本:${script}`,
|
|
2968
|
+
` 期待:${candidates.join(' 或 ')}(mtime 不早于启动时刻)`,
|
|
2969
|
+
'',
|
|
2970
|
+
'把输出重定向到日志(如 `Rscript run.R 2>&1 | tee run.R.log`),',
|
|
2971
|
+
'或让脚本自己 sink / logging 写文件。日志是这几月后唯一能复核的现场。',
|
|
2972
|
+
].join('\n'),
|
|
2973
|
+
});
|
|
2974
|
+
}
|
|
2975
|
+
}
|
|
2976
|
+
|
|
2977
|
+
// --- W2: a result subdirectory touched this turn needs a note --------------
|
|
2978
|
+
const resultDirs = Array.isArray(config.result_dirs) ? config.result_dirs : [];
|
|
2979
|
+
const prefix = String(config.readme_prefix ?? DEFAULT_CONFIG.readme_prefix).toLowerCase();
|
|
2980
|
+
if (resultDirs.length > 0 && prefix !== '' && typeof cwd === 'string' && cwd !== '') {
|
|
2981
|
+
for (const rel of resultDirs) {
|
|
2982
|
+
if (typeof rel !== 'string' || rel === '') continue;
|
|
2983
|
+
const dir = normalizePath(join(cwd, rel));
|
|
2984
|
+
if (!probes.exists(dir)) continue;
|
|
2985
|
+
for (const child of probes.listDir(dir)) {
|
|
2986
|
+
const childPath = normalizePath(join(dir, child));
|
|
2987
|
+
// "Touched this turn" is derived from the newest mtime INSIDE the entry,
|
|
2988
|
+
// so a plain file in `results/` is skipped without needing an extra
|
|
2989
|
+
// isDirectory probe: a file has no entries, hence no mtime, hence 0.
|
|
2990
|
+
const newest = newestMtimeIn(childPath, probes, now, 0);
|
|
2991
|
+
if (newest < since - epsilon) continue;
|
|
2992
|
+
const annotated = probes.listDir(childPath)
|
|
2993
|
+
.some((name) => String(name).toLowerCase().startsWith(prefix));
|
|
2994
|
+
if (annotated) continue;
|
|
2995
|
+
findings.push({
|
|
2996
|
+
code: 'AI4S_RESULT_README',
|
|
2997
|
+
path: childPath,
|
|
2998
|
+
reason: [
|
|
2999
|
+
'⛔ AI4S 域控 · W2 提醒:本轮更新的结果目录没有说明文件。',
|
|
3000
|
+
` 目录:${childPath}`,
|
|
3001
|
+
` 期待:目录下有一个以 ${config.readme_prefix ?? DEFAULT_CONFIG.readme_prefix} 开头的文件`,
|
|
3002
|
+
'',
|
|
3003
|
+
'写一句:这个目录是什么、用哪个脚本跑的、关键参数、怎么读。',
|
|
3004
|
+
'半年后打开 results/ 的人(包括你自己)靠它才知道哪张图是什么。',
|
|
3005
|
+
].join('\n'),
|
|
3006
|
+
});
|
|
3007
|
+
}
|
|
3008
|
+
}
|
|
3009
|
+
}
|
|
3010
|
+
|
|
3011
|
+
return findings;
|
|
3012
|
+
};
|
|
3013
|
+
|
|
3014
|
+
// ---------------------------------------------------------------------------
|
|
3015
|
+
// Checks
|
|
3016
|
+
// ---------------------------------------------------------------------------
|
|
3017
|
+
|
|
3018
|
+
/**
|
|
3019
|
+
* Verbs whose operands mention a script but do not execute it.
|
|
3020
|
+
*
|
|
3021
|
+
* `cat annotate.R` is reading the script, and demanding a Worklog for it would
|
|
3022
|
+
* make the rule hate its own debugging: the model must be free to open the file
|
|
3023
|
+
* to see what it is about to run.
|
|
3024
|
+
*/
|
|
3025
|
+
const SKIP_SCRIPT_VERBS = new Set([
|
|
3026
|
+
...BASH_READ_VERBS,
|
|
3027
|
+
'ls', 'dir', 'vdir', 'tree', 'find', 'echo', 'printf', 'test', '[', 'stat',
|
|
3028
|
+
'du', 'df', 'which', 'type', 'command', 'open', 'xdg-open', 'git', 'file',
|
|
3029
|
+
'grep', 'rg', 'diff', 'cmp',
|
|
3030
|
+
]);
|
|
3031
|
+
|
|
3032
|
+
/** Does `file` end with one of `exts`? Case-insensitive, list may be undefined. */
|
|
3033
|
+
const hasExtension = (file, exts) => {
|
|
3034
|
+
const lower = String(file ?? '').toLowerCase();
|
|
3035
|
+
return (Array.isArray(exts) ? exts : []).some((e) => lower.endsWith(String(e).toLowerCase()));
|
|
3036
|
+
};
|
|
3037
|
+
|
|
3038
|
+
/**
|
|
3039
|
+
* Analysis scripts a shell command would EXECUTE.
|
|
3040
|
+
*
|
|
3041
|
+
* Only existing files with an analysis extension count, and only when the verb
|
|
3042
|
+
* is an executor — a path-shaped argument is not a run. Kept deliberately
|
|
3043
|
+
* conservative: a false positive here asks for a Worklog update, a false
|
|
3044
|
+
* negative skips one rule set, and the second is the cheaper mistake.
|
|
3045
|
+
*/
|
|
3046
|
+
export const analysisScriptTargets = (
|
|
3047
|
+
command,
|
|
3048
|
+
{ config = DEFAULT_CONFIG, cwd = null, isFile = defaultIsFile } = {},
|
|
3049
|
+
) => {
|
|
3050
|
+
if (typeof command !== 'string' || command === '') return [];
|
|
3051
|
+
const exts = (config.script_extensions ?? DEFAULT_CONFIG.script_extensions)
|
|
3052
|
+
.map((e) => String(e).toLowerCase());
|
|
3053
|
+
if (exts.length === 0) return [];
|
|
3054
|
+
const found = [];
|
|
3055
|
+
for (const rawSegment of splitShellSegments(command)) {
|
|
3056
|
+
const segment = rawSegment.trim();
|
|
3057
|
+
if (segment === '') continue;
|
|
3058
|
+
const tokens = shellTokens(segment);
|
|
3059
|
+
if (tokens.length === 0) continue;
|
|
3060
|
+
const { verb, args } = parseCommandHead(tokens);
|
|
3061
|
+
if (!verb || SKIP_SCRIPT_VERBS.has(verb)) continue;
|
|
3062
|
+
for (const arg of args) {
|
|
3063
|
+
const value = arg?.value;
|
|
3064
|
+
if (typeof value !== 'string' || value === '' || value.startsWith('-')) continue;
|
|
3065
|
+
const lowerValue = value.toLowerCase();
|
|
3066
|
+
if (!exts.some((ext) => lowerValue.endsWith(ext))) continue;
|
|
3067
|
+
const resolved = resolveShellPath(value, cwd);
|
|
3068
|
+
if (!resolved || !isFile(resolved)) continue;
|
|
3069
|
+
found.push(resolved);
|
|
3070
|
+
}
|
|
3071
|
+
}
|
|
3072
|
+
return [...new Set(found)];
|
|
3073
|
+
};
|
|
3074
|
+
|
|
3075
|
+
/**
|
|
3076
|
+
* Remember that this session started an analysis script.
|
|
3077
|
+
*
|
|
3078
|
+
* `startedAt` is refreshed on every run (the turn-end check dates the expected
|
|
3079
|
+
* `.log` against the latest one), while the KEY's presence is what makes W1 a
|
|
3080
|
+
* "first run only" rule — a long pipeline must not be interrupted by a Worklog
|
|
3081
|
+
* demand before every step.
|
|
3082
|
+
*/
|
|
3083
|
+
export const recordScriptRun = (state, scriptPath, now = Date.now()) => {
|
|
3084
|
+
const norm = normalizePath(scriptPath);
|
|
3085
|
+
if (!norm || !(state?.scriptsRun instanceof Map)) return;
|
|
3086
|
+
state.scriptsRun.set(norm, { startedAt: now });
|
|
3087
|
+
};
|
|
3088
|
+
|
|
3089
|
+
/** R: `sink()` / `Sys.time()` / log4r / logger / futile.logger. */
|
|
3090
|
+
const R_LOG_INIT = /\bsink\s*\(|\bSys\.time\s*\(|\blog4r\b|\blogger\s*::|\bfutile\.logger/;
|
|
3091
|
+
/** Python: the logging module (or loguru), which is the only portable answer. */
|
|
3092
|
+
const PY_LOG_INIT = /\blogging\s*\.|\bFileHandler\b|\bbasicConfig\s*\(|\bloguru\b/;
|
|
3093
|
+
|
|
3094
|
+
/**
|
|
3095
|
+
* Does this script set up a log sink of its own?
|
|
3096
|
+
*
|
|
3097
|
+
* Static and shallow ON PURPOSE: the question is "did the author remember to
|
|
3098
|
+
* leave a trace", not "is the logging correct". A deep answer is not decidable
|
|
3099
|
+
* without running the script, and a rule that cannot be checked is worse than no
|
|
3100
|
+
* rule.
|
|
3101
|
+
*/
|
|
3102
|
+
export const hasLogInitialization = (text, scriptPath = '') => {
|
|
3103
|
+
if (typeof text !== 'string') return false;
|
|
3104
|
+
const ext = String(scriptPath).toLowerCase();
|
|
3105
|
+
if (ext.endsWith('.r') || ext.endsWith('.rmd')) return R_LOG_INIT.test(text);
|
|
3106
|
+
if (ext.endsWith('.py') || ext.endsWith('.ipynb')) return PY_LOG_INIT.test(text);
|
|
3107
|
+
return R_LOG_INIT.test(text) || PY_LOG_INIT.test(text);
|
|
3108
|
+
};
|
|
3109
|
+
|
|
3110
|
+
/**
|
|
3111
|
+
* A check answers one question about one tool call and returns either null
|
|
3112
|
+
* (abstain) or a `{ code, reason }` denial.
|
|
3113
|
+
*
|
|
3114
|
+
* `input` is the normalized shape every adapter produces:
|
|
3115
|
+
* { action: 'read'|'write'|'bash'|'other', path: string|null, tool: string }
|
|
3116
|
+
*
|
|
3117
|
+
* `deps` carries what a check may need from the running harness:
|
|
3118
|
+
* { exists(dir): boolean, state, now: number }
|
|
3119
|
+
*
|
|
3120
|
+
* CASCADE ORDER
|
|
3121
|
+
* -------------
|
|
3122
|
+
* `shouldBlock` stops at the FIRST check that returns a verdict, so the order
|
|
3123
|
+
* of the policy's `checks` array decides which layer speaks. The shipped
|
|
3124
|
+
* policies list the two Layer-2 checks BEFORE `graph-before-read`, because:
|
|
3125
|
+
*
|
|
3126
|
+
* - an unindexed repository must hear "build the index first", not
|
|
3127
|
+
* "the index exists, query the graph" — with the reverse order Layer 2 is
|
|
3128
|
+
* unreachable and the Layer-1 wording is simply false;
|
|
3129
|
+
* - the reverse order was tried once, on the theory that Layer 2 would
|
|
3130
|
+
* re-block a session right after its first graph query. It would not: both
|
|
3131
|
+
* Layer-2 checks short-circuit on a fresh signal, exactly like
|
|
3132
|
+
* `graph-before-read`. The theory was wrong and the order it produced hid
|
|
3133
|
+
* the index rules on every unindexed repository.
|
|
3134
|
+
*
|
|
3135
|
+
* A policy that lists only `graph-before-read` remains valid and means "always
|
|
3136
|
+
* ask the graph first"; the cascade is a property of the array, not the code.
|
|
3137
|
+
*/
|
|
3138
|
+
const CHECKS = {
|
|
3139
|
+
/**
|
|
3140
|
+
* Layer 0: do not overwrite a file you have never looked at.
|
|
3141
|
+
*
|
|
3142
|
+
* The v2 gate only policed reads. A model could query the graph about one
|
|
3143
|
+
* file, then edit any other file in the repository without ever opening it —
|
|
3144
|
+
* mechanical action, which is exactly what the first rule forbids. This check
|
|
3145
|
+
* demands evidence about the *specific* target: a successful read of that
|
|
3146
|
+
* file or a scoped graph unlock that named it. A fresh session-wide signal is
|
|
3147
|
+
* deliberately NOT enough (that is the "I queried once" hole in a new coat).
|
|
3148
|
+
*
|
|
3149
|
+
* New files are exempt from target evidence: there is nothing to inspect yet,
|
|
3150
|
+
* and requiring a graph hit would brick the first file in an empty repo. The
|
|
3151
|
+
* convention check still applies to them.
|
|
3152
|
+
*/
|
|
3153
|
+
/**
|
|
3154
|
+
* ai-spec Layer 0.5:改代码前必须核对该改动对应的立项 CHG 契约。
|
|
3155
|
+
*
|
|
3156
|
+
* 与 `think-before-write` 的分工:
|
|
3157
|
+
* - `think-before-write` 管「你看过这个文件吗」(图层/证据)
|
|
3158
|
+
* - 本检查管「这个改动属于哪个 CHG、那个 CHG 契约齐全吗」(契约/范围)
|
|
3159
|
+
*
|
|
3160
|
+
* 两者都过,才允许改代码。缺前者 = 篡改;缺后者 = 跑偏。
|
|
3161
|
+
*/
|
|
3162
|
+
'chg-contract-before-edit': (policy, input, deps) => {
|
|
3163
|
+
if (input.action !== 'write') return null;
|
|
3164
|
+
const config = policy.config;
|
|
3165
|
+
if (config.require_chg_contract === false) return null;
|
|
3166
|
+
|
|
3167
|
+
const norm = normalizePath(input.path);
|
|
3168
|
+
const scope = scopeOf(norm, { config, exists: deps.exists });
|
|
3169
|
+
if (!scope.inScope || !scope.root) return null;
|
|
3170
|
+
// 只约束代码:改文档 / 数据 / 台账不要求 CHG 契约。
|
|
3171
|
+
if (!isCodeFile(norm, config)) return null;
|
|
3172
|
+
// 可选收窄:只在真正受 CHG 治理的目录里要求契约。
|
|
3173
|
+
const scopeGlobs = (config.chg_contract_scope_globs ?? []).map((g) => String(g).toLowerCase());
|
|
3174
|
+
if (scopeGlobs.length > 0 && !matchesAnyGlob(toPosix(norm).toLowerCase(), scopeGlobs)) return null;
|
|
3175
|
+
|
|
3176
|
+
// 项目适用性:不用 CHG 体系的项目(如以 ADR 管理的仓库)不该被这条拦死。
|
|
3177
|
+
// 判据取文件系统事实:`tasks/` 存在且含 `CHG-*` 子目录,才认为本项目采纳了 CHG。
|
|
3178
|
+
// 不跳过的后果:任何不用 CHG 的仓库都改不了代码 —— 死锁。
|
|
3179
|
+
const projectRoot = scope.projectRoot ?? scope.root;
|
|
3180
|
+
const tasksDir = join(projectRoot, 'tasks');
|
|
3181
|
+
if (!deps.exists(tasksDir)) return null;
|
|
3182
|
+
if (typeof deps.listDir === 'function') {
|
|
3183
|
+
const entries = deps.listDir(tasksDir) ?? [];
|
|
3184
|
+
if (!entries.some((name) => /^CHG-/i.test(String(name)))) return null;
|
|
3185
|
+
}
|
|
3186
|
+
|
|
3187
|
+
// 本会话读过的契约,且必须属于**当前项目**:读别的仓库的 CHG 不算数。
|
|
3188
|
+
// v5 少了这层过滤 —— 读 A 仓库的 SPEC.md 可以解锁 B 仓库的代码改动。
|
|
3189
|
+
const dirs = new Set();
|
|
3190
|
+
for (const p of deps.state.docReads ?? []) {
|
|
3191
|
+
const read = normalizePath(p);
|
|
3192
|
+
if (!withinRoot(projectRoot, read)) continue;
|
|
3193
|
+
const dir = chgDirOf(read, config);
|
|
3194
|
+
if (dir) dirs.add(dir);
|
|
3195
|
+
}
|
|
3196
|
+
if (dirs.size === 0) {
|
|
3197
|
+
return {
|
|
3198
|
+
code: 'CHG_CONTRACT',
|
|
3199
|
+
reason: [
|
|
3200
|
+
'⛔ ai-spec 门控:改代码前没有核对**本项目**的立项 CHG 契约。',
|
|
3201
|
+
` 目标:${norm}`,
|
|
3202
|
+
` 项目:${projectRoot}`,
|
|
3203
|
+
' 缺口:本会话没有读过本项目 tasks/CHG-*/ 下的任何 SPEC / PRD / TRACEABILITY。',
|
|
3204
|
+
'',
|
|
3205
|
+
'先做(按序,缺一不可):',
|
|
3206
|
+
' 1) 定位本次开发属于哪个 CHG:ls tasks/CHG-*/(按 date-slug 判定)',
|
|
3207
|
+
' 2) 读它的四件套(至少 SPEC + PRD):',
|
|
3208
|
+
' read tasks/CHG-<id>/SPEC.md # 目标 / 独占文件 / 验收断言 / 绝不做什么',
|
|
3209
|
+
' read tasks/CHG-<id>/PRD.md # 承诺什么、不承诺什么',
|
|
3210
|
+
' read tasks/CHG-<id>/TRACEABILITY.md # 每条 AC 的证据在哪',
|
|
3211
|
+
' 3) 五问自检再动手:',
|
|
3212
|
+
' · 这个改动属于哪个 CHG?(答不出 = 不许改)',
|
|
3213
|
+
' · 该 CHG 四件套齐全吗?(缺哪件就先补,缺料不许开工)',
|
|
3214
|
+
' · 目标文件在该 CHG 的「独占文件」清单里吗?(不在 = 可能越界)',
|
|
3215
|
+
' · 改完哪条 AC 会从红变绿?(答不出 = 没有验收目标)',
|
|
3216
|
+
' · 是先用第一性原理判了根因,还是照症状打补丁?',
|
|
3217
|
+
'',
|
|
3218
|
+
'注意:读别的仓库的 CHG 不算数,本规则按项目绑定。',
|
|
3219
|
+
'',
|
|
3220
|
+
'开发中发现的问题必须当场修,不许留给「后续」;',
|
|
3221
|
+
'收尾必须让该 CHG 的预定功能目标达成,而不是「大部分做完」。',
|
|
3222
|
+
'',
|
|
3223
|
+
'这条不是建议:未核对契约的代码改动一律拒绝。',
|
|
3224
|
+
].join('\n'),
|
|
3225
|
+
};
|
|
3226
|
+
}
|
|
3227
|
+
|
|
3228
|
+
// 读过 ≠ 契约成立。缺 PRD / 缺 TRACEABILITY / SPEC 塞的是空壳 / 还是 draft,
|
|
3229
|
+
// 都不能支撑开工。v5 只看「碰过文件」,于是「写一个 SPEC.md → 读它 → 改代码」
|
|
3230
|
+
// 全流程畅通,而 PRD 与 TRACEABILITY 根本不存在。
|
|
3231
|
+
const gaps = [];
|
|
3232
|
+
for (const dir of dirs) {
|
|
3233
|
+
const audit = auditChgContract(dir, config, deps);
|
|
3234
|
+
if (audit.ok) return null;
|
|
3235
|
+
gaps.push({ dir, problems: audit.problems });
|
|
3236
|
+
}
|
|
3237
|
+
|
|
3238
|
+
const prefix = `${toPosix(projectRoot)}/`;
|
|
3239
|
+
return {
|
|
3240
|
+
code: 'CHG_CONTRACT_INCOMPLETE',
|
|
3241
|
+
reason: [
|
|
3242
|
+
'⛔ ai-spec 门控:本次改动对应的 CHG 契约**不成立**。',
|
|
3243
|
+
` 目标:${norm}`,
|
|
3244
|
+
'',
|
|
3245
|
+
'本会话读过的契约,没有一个能支撑开工:',
|
|
3246
|
+
...gaps.flatMap(({ dir, problems }) => [
|
|
3247
|
+
` · ${toPosix(dir).replace(prefix, '')}`,
|
|
3248
|
+
...problems.map((p) => ` ✗ ${p}`),
|
|
3249
|
+
]),
|
|
3250
|
+
'',
|
|
3251
|
+
'「读过一份文件」不等于「立项完成」。补齐后再改代码:',
|
|
3252
|
+
' 1) 缺 PRD.md → 写清承诺什么、不承诺什么、判定口径',
|
|
3253
|
+
' 2) 缺 TRACEABILITY.md → 每条验收断言对应哪个产物、怎么验',
|
|
3254
|
+
' 3) SPEC.md 没有验收判据 → 至少写一节「验收断言 / AC」',
|
|
3255
|
+
' 4) status 是 draft → 先把 SPEC 改到 approved,或确认这不是本次要做的 CHG',
|
|
3256
|
+
'',
|
|
3257
|
+
'这条不是建议:契约不成立时,代码改动一律拒绝。',
|
|
3258
|
+
].join('\n'),
|
|
3259
|
+
};
|
|
3260
|
+
},
|
|
3261
|
+
|
|
3262
|
+
'think-before-write': (policy, input, deps) => {
|
|
3263
|
+
if (input.action !== 'write' && input.action !== 'bash') return null;
|
|
3264
|
+
const config = policy.config;
|
|
3265
|
+
if (config.require_target_evidence === false && config.require_conventions === false) return null;
|
|
3266
|
+
|
|
3267
|
+
const targets = input.action === 'write'
|
|
3268
|
+
? [input.path]
|
|
3269
|
+
: bashWriteTargets(input.command, {
|
|
3270
|
+
config,
|
|
3271
|
+
cwd: input.cwd ?? null,
|
|
3272
|
+
isFile: deps.isFile,
|
|
3273
|
+
exists: deps.exists,
|
|
3274
|
+
});
|
|
3275
|
+
if (targets.length === 0) return null;
|
|
3276
|
+
|
|
3277
|
+
const roots = new Set();
|
|
3278
|
+
for (const target of targets) {
|
|
3279
|
+
if (!target) continue;
|
|
3280
|
+
const norm = normalizePath(target);
|
|
3281
|
+
const scope = scopeOf(norm, { config, exists: deps.exists });
|
|
3282
|
+
if (!scope.inScope || !scope.root) continue;
|
|
3283
|
+
roots.add(scope.projectRoot ?? scope.root);
|
|
3284
|
+
if (config.require_target_evidence !== false) {
|
|
3285
|
+
if (deps.state.written.has(norm)) continue;
|
|
3286
|
+
// A directory or a path that does not exist yet: nothing to inspect.
|
|
3287
|
+
if (!deps.isFile(norm)) continue;
|
|
3288
|
+
if (hasFreshInspection(deps.state, norm, config, deps.now)) continue;
|
|
3289
|
+
if (hasScopedUnlock(deps.state, norm, config, deps.now)) continue;
|
|
3290
|
+
return {
|
|
3291
|
+
code: 'THINK_TARGET',
|
|
3292
|
+
reason: [
|
|
3293
|
+
'⛔ 动脑子铁律 · Layer 0 拦截:动手前没有看过这个文件。',
|
|
3294
|
+
` 目标:${norm}`,
|
|
3295
|
+
` 工具:${input.tool ?? input.action}`,
|
|
3296
|
+
' 证据缺口:本会话既没有成功读取过它,也没有一次图谱查询点名过它。',
|
|
3297
|
+
'',
|
|
3298
|
+
'先做(任一即可):',
|
|
3299
|
+
' a) read 这个文件(read 本身通过 Layer 1 后即可);',
|
|
3300
|
+
' b) search_graph / get_code_snippet / trace_path / query_graph 查询并命中它',
|
|
3301
|
+
' (命中后 30 分钟内该目标可改)。',
|
|
3302
|
+
'然后重试。不要在没看代码、没判根因的情况下直接改。',
|
|
3303
|
+
'',
|
|
3304
|
+
'顺手过一遍五问:项目约定?环境现状?字面背后的真实需求?任务目的?产出价值?',
|
|
3305
|
+
].join('\n'),
|
|
3306
|
+
};
|
|
3307
|
+
}
|
|
3308
|
+
}
|
|
3309
|
+
|
|
3310
|
+
if (config.require_conventions) {
|
|
3311
|
+
for (const root of roots) {
|
|
3312
|
+
const docs = (config.convention_files ?? []).filter((name) => deps.exists(join(root, name)));
|
|
3313
|
+
if (docs.length === 0) continue;
|
|
3314
|
+
const read = [...deps.state.docReads].some(
|
|
3315
|
+
(p) => withinRoot(root, p) && isConventionDoc(p, config),
|
|
3316
|
+
);
|
|
3317
|
+
if (read) continue;
|
|
3318
|
+
return {
|
|
3319
|
+
code: 'THINK_CONVENTIONS',
|
|
3320
|
+
reason: [
|
|
3321
|
+
'⛔ 动脑子铁律 · Layer 0 拦截:还没读项目约定就要改代码。',
|
|
3322
|
+
` 仓库:${root}`,
|
|
3323
|
+
` 存在的约定文件:${docs.join(', ')}`,
|
|
3324
|
+
'',
|
|
3325
|
+
'先 read 其中一个(AGENTS.md / CLAUDE.md / CONTRIBUTING.md / .cursorrules),',
|
|
3326
|
+
'确认架构、约定和当前状态后再动手。没有约定文件的仓库不触发这条。',
|
|
3327
|
+
].join('\n'),
|
|
3328
|
+
};
|
|
3329
|
+
}
|
|
3330
|
+
}
|
|
3331
|
+
return null;
|
|
3332
|
+
},
|
|
3333
|
+
|
|
3334
|
+
/**
|
|
3335
|
+
* Layer 0: a failing command repeated verbatim is not debugging, it is
|
|
3336
|
+
* flailing. After `max_identical_failures` failures the model must do
|
|
3337
|
+
* something investigative (read, graph query, or a real edit) before running
|
|
3338
|
+
* the same command again. The evidence timestamp, not a timer, is what opens
|
|
3339
|
+
* it — "wait a bit and retry" is still mechanical.
|
|
3340
|
+
*/
|
|
3341
|
+
'no-blind-retry': (policy, input, deps) => {
|
|
3342
|
+
if (input.action !== 'bash') return null;
|
|
3343
|
+
const config = policy.config;
|
|
3344
|
+
const key = normalizeCommand(input.command);
|
|
3345
|
+
if (!key) return null;
|
|
3346
|
+
const rec = deps.state.failedCommands.get(key);
|
|
3347
|
+
if (!rec || rec.count < config.max_identical_failures) return null;
|
|
3348
|
+
if (deps.now - rec.lastAt > config.retry_window_ms) return null;
|
|
3349
|
+
if (deps.state.lastInvestigationAt >= rec.lastAt) return null;
|
|
3350
|
+
return {
|
|
3351
|
+
code: 'BLIND_RETRY',
|
|
3352
|
+
reason: [
|
|
3353
|
+
'⛔ 动脑子铁律 · Layer 0 拦截:同一条命令已经失败 ' + rec.count + ' 次,仍要原样重试。',
|
|
3354
|
+
` 命令:${String(input.command).slice(0, 200)}`,
|
|
3355
|
+
'',
|
|
3356
|
+
'先判根因,再重试。做下面任一动作即可解除:',
|
|
3357
|
+
' - 读失败输出对应的代码(read / get_code_snippet);',
|
|
3358
|
+
' - 查图谱(search_graph / trace_path / query_graph);',
|
|
3359
|
+
' - 做出真正的修改(write / edit)。',
|
|
3360
|
+
'不要靠“再跑一次看看”推进。',
|
|
3361
|
+
].join('\n'),
|
|
3362
|
+
};
|
|
3363
|
+
},
|
|
3364
|
+
|
|
3365
|
+
/**
|
|
3366
|
+
* AI4S W1: an analysis script may not be the first thing that runs after a
|
|
3367
|
+
* long gap — the Worklog has to be fresher than `worklog_ttl_ms`.
|
|
3368
|
+
*
|
|
3369
|
+
* Only the FIRST run of a given script in a session is judged: a stepwise
|
|
3370
|
+
* pipeline (`01_qc.R`, `02_annotate.R`, …) would otherwise demand a Worklog
|
|
3371
|
+
* edit before every step, which turns the rule into a tax and gets it disabled.
|
|
3372
|
+
*
|
|
3373
|
+
* Blocking BEFORE the run is the whole point: nothing has been computed yet, so
|
|
3374
|
+
* the fix (write down the plan) costs one edit. After the run it is a
|
|
3375
|
+
* retrospective entry nobody reads.
|
|
3376
|
+
*/
|
|
3377
|
+
'ai4s-worklog-before-run': (policy, input, deps) => {
|
|
3378
|
+
if (input.action !== 'bash') return null;
|
|
3379
|
+
const config = policy.config;
|
|
3380
|
+
const firstRun = analysisScriptTargets(input.command, {
|
|
3381
|
+
config,
|
|
3382
|
+
cwd: input.cwd ?? null,
|
|
3383
|
+
isFile: deps.isFile,
|
|
3384
|
+
}).find((script) => !deps.state.scriptsRun.has(normalizePath(script)));
|
|
3385
|
+
if (!firstRun) return null;
|
|
3386
|
+
|
|
3387
|
+
const norm = normalizePath(firstRun);
|
|
3388
|
+
// The Worklog lives at the project root, which the path itself tells us: a
|
|
3389
|
+
// script outside any repository cannot be judged, and guessing a root would
|
|
3390
|
+
// scope the rule to whatever directory the agent happened to start in.
|
|
3391
|
+
const root = scopeOf(norm, { config, exists: deps.exists }).projectRoot
|
|
3392
|
+
?? findRepoRoot(norm, deps.exists);
|
|
3393
|
+
if (!root) return null; // unknown project: fail open, see ADR-011 §fail-open
|
|
3394
|
+
|
|
3395
|
+
const rel = config.worklog_path ?? DEFAULT_CONFIG.worklog_path;
|
|
3396
|
+
const worklog = normalizePath(join(root, rel));
|
|
3397
|
+
const ttl = Number.isFinite(config.worklog_ttl_ms)
|
|
3398
|
+
? config.worklog_ttl_ms
|
|
3399
|
+
: DEFAULT_CONFIG.worklog_ttl_ms;
|
|
3400
|
+
const mtime = typeof deps.statMtime === 'function' ? deps.statMtime(worklog) : 0;
|
|
3401
|
+
if (mtime > 0 && deps.now - mtime <= ttl) return null;
|
|
3402
|
+
|
|
3403
|
+
const age = mtime > 0 ? Math.round((deps.now - mtime) / 60000) : null;
|
|
3404
|
+
return {
|
|
3405
|
+
code: 'AI4S_WORKLOG',
|
|
3406
|
+
reason: [
|
|
3407
|
+
'⛔ AI4S 域控 · W1 拦截:跑分析脚本之前没有一份新鲜的 Worklog。',
|
|
3408
|
+
` 脚本:${norm}`,
|
|
3409
|
+
` Worklog:${worklog}${age === null ? '(不存在)' : `(最后更新 ${age} 分钟前)`}`,
|
|
3410
|
+
` 窗口:${Math.round(ttl / 60000)} 分钟`,
|
|
3411
|
+
'',
|
|
3412
|
+
'先把这一轮要做的事写进 Worklog(目标 / 输入数据 / 关键参数 / 预期产出),再跑:',
|
|
3413
|
+
` - 要做什么、为什么这么做;`,
|
|
3414
|
+
` - 输入数据与筛选条件;`,
|
|
3415
|
+
' - 预期产出的目录与文件;',
|
|
3416
|
+
' - 已知风险与回退方式。',
|
|
3417
|
+
'这不是形式主义:Worklog 是几个月后唯一能回答“当时为什么这么跑”的记录。',
|
|
3418
|
+
].join('\n'),
|
|
3419
|
+
};
|
|
3420
|
+
},
|
|
3421
|
+
|
|
3422
|
+
/**
|
|
3423
|
+
* AI4S W4 (run half): the script itself must set up a log sink.
|
|
3424
|
+
*
|
|
3425
|
+
* Static and cheap. A run whose output lives only in the agent's scrollback is
|
|
3426
|
+
* unrecoverable — the session ends, the numbers are gone. Checking the source
|
|
3427
|
+
* before the run is the last moment where the fix is free.
|
|
3428
|
+
*/
|
|
3429
|
+
'ai4s-script-log-source': (policy, input, deps) => {
|
|
3430
|
+
if (input.action !== 'bash') return null;
|
|
3431
|
+
if (policy.config.script_log_check === false) return null;
|
|
3432
|
+
const scripts = analysisScriptTargets(input.command, {
|
|
3433
|
+
config: policy.config,
|
|
3434
|
+
cwd: input.cwd ?? null,
|
|
3435
|
+
isFile: deps.isFile,
|
|
3436
|
+
});
|
|
3437
|
+
for (const script of scripts) {
|
|
3438
|
+
// Notebooks and knitted reports keep their own output; see
|
|
3439
|
+
// `log_required_extensions`.
|
|
3440
|
+
if (!hasExtension(script, policy.config.log_required_extensions
|
|
3441
|
+
?? DEFAULT_CONFIG.log_required_extensions)) continue;
|
|
3442
|
+
const text = typeof deps.readText === 'function' ? deps.readText(script) : null;
|
|
3443
|
+
// Unreadable source is not evidence of a missing log: fail open.
|
|
3444
|
+
if (typeof text !== 'string') continue;
|
|
3445
|
+
if (hasLogInitialization(text, script)) continue;
|
|
3446
|
+
const isR = /\.r(?:md)?$/i.test(script);
|
|
3447
|
+
return {
|
|
3448
|
+
code: 'AI4S_SCRIPT_LOG',
|
|
3449
|
+
reason: [
|
|
3450
|
+
'⛔ AI4S 域控 · W4 拦截:分析脚本没有日志初始化,跑完输出就只剩会话里的滚屏。',
|
|
3451
|
+
` 脚本:${script}`,
|
|
3452
|
+
'',
|
|
3453
|
+
'给脚本加一段日志初始化,再跑:',
|
|
3454
|
+
isR
|
|
3455
|
+
? ' 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")'
|
|
3456
|
+
: ' Py: import logging\n logging.basicConfig(filename="logs/run.log", level=logging.INFO,\n format="%(asctime)s %(levelname)s %(message)s")',
|
|
3457
|
+
'',
|
|
3458
|
+
'判定只看“有没有日志初始化”,不看写得对不对;这是能在跑前静态判定的一部分。',
|
|
3459
|
+
].join('\n'),
|
|
3460
|
+
};
|
|
3461
|
+
}
|
|
3462
|
+
return null;
|
|
3463
|
+
},
|
|
3464
|
+
|
|
3465
|
+
/**
|
|
3466
|
+
* Layer 0: destructive shell operations are never taken on the agent's own
|
|
3467
|
+
* authority.
|
|
3468
|
+
*
|
|
3469
|
+
* Two tiers, and the difference between them is the whole design:
|
|
3470
|
+
*
|
|
3471
|
+
* guardrail (`severity: 'high'`) - unrecoverable. Deleting $HOME, the
|
|
3472
|
+
* cwd, a `..` escape, formatting a
|
|
3473
|
+
* disk, dd onto a raw device. NO grant
|
|
3474
|
+
* can reach these.
|
|
3475
|
+
* permission (`severity: 'confirm'`) - serious but survivable. The category's
|
|
3476
|
+
* tier decides allow / ask / deny.
|
|
3477
|
+
*
|
|
3478
|
+
* Hard (not subject to the block cap): a security rule must not stand down
|
|
3479
|
+
* because a session hit its block limit.
|
|
3480
|
+
*/
|
|
3481
|
+
'no-destructive-bash': (policy, input, deps) => {
|
|
3482
|
+
if (input.action !== 'bash') return null;
|
|
3483
|
+
const finding = shellDestructiveFinding(input, {
|
|
3484
|
+
config: policy.config,
|
|
3485
|
+
cwd: input.cwd ?? null,
|
|
3486
|
+
// Injected, not imported: a git repository root is unrecoverable even when
|
|
3487
|
+
// it is neither $HOME nor an ancestor of the cwd, but this file must stay
|
|
3488
|
+
// disk-free when a harness supplies no probe.
|
|
3489
|
+
isGitRepo: (dir) => deps?.fs?.exists?.(join(dir, '.git')) === true,
|
|
3490
|
+
});
|
|
3491
|
+
// ADR-015: a command aimed at the gate's own directories is not a tier.
|
|
3492
|
+
// Not in `bypass` (where the delete tier is off and it would simply run),
|
|
3493
|
+
// and not a question in `enforce` either - the thing being deleted is the
|
|
3494
|
+
// thing that asks. Answered ahead of the tiers, so the two modes agree;
|
|
3495
|
+
// `no-self-grant` covers it when this check is not loaded.
|
|
3496
|
+
//
|
|
3497
|
+
// Only when the general rule has nothing stronger to say: `rm -rf $HOME` is
|
|
3498
|
+
// a red line in its own right, and a home that happens to contain the gate
|
|
3499
|
+
// must not have that stated in weaker, indirect words.
|
|
3500
|
+
const owned = gateOwnedShellTarget(input, policy.config, deps);
|
|
3501
|
+
if (owned && finding?.severity !== 'high') return gateOwnedVerdict(owned);
|
|
3502
|
+
if (!finding) return null;
|
|
3503
|
+
|
|
3504
|
+
// ---- guardrail: not a permission, and no grant can reach it ----------
|
|
3505
|
+
if (finding.severity === 'high') {
|
|
3506
|
+
// The protected-worktree red line gets its own words (ADR-015). A generic
|
|
3507
|
+
// "irreversible, ask your user" would leave the agent to guess which part
|
|
3508
|
+
// of its command was the problem, and the obvious guess - `git stash` is
|
|
3509
|
+
// fine, `git checkout -- .` then - walks straight into the same line.
|
|
3510
|
+
if (finding.protectedRoot) {
|
|
3511
|
+
return {
|
|
3512
|
+
code: 'DESTRUCTIVE_BASH',
|
|
3513
|
+
reason: [
|
|
3514
|
+
'⛔ 动脑子铁律 · Layer 0 拦截:受保护工作区红线,任何授权、任何模式都不会放行。',
|
|
3515
|
+
` 原因:${finding.why}`,
|
|
3516
|
+
` 目录:${finding.protectedRoot}`,
|
|
3517
|
+
` 命令:${finding.segment}`,
|
|
3518
|
+
'',
|
|
3519
|
+
'这个目录里「没提交的东西」不是待收拾的半成品,而是正在运行的服务赖以工作的状态',
|
|
3520
|
+
'(配置、凭据、会话)。把它们收走或还原,服务下一次读配置就回到出厂状态——',
|
|
3521
|
+
'git 不报错,agent 当场往往也发现不了,等发现时服务已经掉线很久了。',
|
|
3522
|
+
'',
|
|
3523
|
+
'换办法:',
|
|
3524
|
+
' · 只想看差异或旧版本 → git status / git diff / git show HEAD:<path>(只读,随便用)',
|
|
3525
|
+
' · 想带着改动去别处比对 → git diff > <补丁文件>,或另 git worktree add / clone 一份',
|
|
3526
|
+
' · 确实要清这个工作区 → 停下来,请主人亲手在终端执行',
|
|
3527
|
+
'',
|
|
3528
|
+
'受保护目录登记在 ~/.config/agent-config-bridge/gate-policy.json 的',
|
|
3529
|
+
'config.protected_worktrees,只能由主人修改;/gate list 可以看到生效清单。',
|
|
3530
|
+
].join('\n'),
|
|
3531
|
+
};
|
|
3532
|
+
}
|
|
3533
|
+
return {
|
|
3534
|
+
code: 'DESTRUCTIVE_BASH',
|
|
3535
|
+
reason: [
|
|
3536
|
+
'⛔ 动脑子铁律 · Layer 0 拦截:这条命令不可恢复,任何授权都不会放行。',
|
|
3537
|
+
` 原因:${finding.why}`,
|
|
3538
|
+
` 命令:${finding.segment}`,
|
|
3539
|
+
'',
|
|
3540
|
+
'这一档是红线,不是权限:删 $HOME / 删 cwd / 含 .. 的路径 / 磁盘格式化 /',
|
|
3541
|
+
'裸设备写入 / 关机重启 / 受保护工作区里的 git 清场。没有任何 /gate grant 能打开它。',
|
|
3542
|
+
'',
|
|
3543
|
+
'确实要做,请主人手动在终端执行。',
|
|
3544
|
+
'node_modules / dist / build / .venv 等构建产物的清理不受此限制。',
|
|
3545
|
+
].join('\n'),
|
|
3546
|
+
};
|
|
3547
|
+
}
|
|
3548
|
+
|
|
3549
|
+
// ---- permission: the category's tier decides --------------------------
|
|
3550
|
+
const category = finding.category ?? 'delete';
|
|
3551
|
+
|
|
3552
|
+
// Bypass (ADR-013) turns the PERMISSION layer off - and only the permission
|
|
3553
|
+
// layer: research, secret, scope, contract and AI4S checks are untouched and
|
|
3554
|
+
// keep running in bypass. It sits AFTER the guardrail return above because
|
|
3555
|
+
// the red lines are not a permission; no mode can reach them.
|
|
3556
|
+
if (isDestructiveBypass(policy.config, deps?.state)) return null;
|
|
3557
|
+
|
|
3558
|
+
const tier = effectiveDestructiveTier(category, policy.config, deps?.state);
|
|
3559
|
+
|
|
3560
|
+
if (tier === 'deny') {
|
|
3561
|
+
return {
|
|
3562
|
+
code: 'DESTRUCTIVE_DENIED',
|
|
3563
|
+
reason: [
|
|
3564
|
+
`⛔ 门控拦截:「${category}」这一类操作已被设为拒绝。`,
|
|
3565
|
+
` 原因:${finding.why}`,
|
|
3566
|
+
` 命令:${finding.segment}`,
|
|
3567
|
+
'',
|
|
3568
|
+
`这是主人主动收紧的授权(policy 默认值,或 /gate deny ${category})。`,
|
|
3569
|
+
`要放开:/gate ask ${category}(改成每次询问)或 /gate grant ${category}(直接允许)。`,
|
|
3570
|
+
].join('\n'),
|
|
3571
|
+
};
|
|
3572
|
+
}
|
|
3573
|
+
|
|
3574
|
+
if (tier === 'allow') return null; // granted: run it
|
|
3575
|
+
|
|
3576
|
+
// `destructive_confirm_mode: false` is the rollback switch. It restores the
|
|
3577
|
+
// pre-2026-11-05 behaviour, but only for the ask tier: the guardrail above
|
|
3578
|
+
// never depended on this switch.
|
|
3579
|
+
if (policy.config.destructive_confirm_mode === false) {
|
|
3580
|
+
return {
|
|
3581
|
+
code: 'DESTRUCTIVE_BASH',
|
|
3582
|
+
reason: [
|
|
3583
|
+
'⛔ 动脑子铁律 · Layer 0 拦截:破坏性命令不允许自动执行。',
|
|
3584
|
+
` 原因:${finding.why}`,
|
|
3585
|
+
` 命令:${finding.segment}`,
|
|
3586
|
+
'',
|
|
3587
|
+
'(destructive_confirm_mode 为 false:确认档也按硬拦处理)',
|
|
3588
|
+
'要恢复分级:把 policy.json 的 config.destructive_confirm_mode 设为 true。',
|
|
3589
|
+
].join('\n'),
|
|
3590
|
+
};
|
|
3591
|
+
}
|
|
3592
|
+
|
|
3593
|
+
return {
|
|
3594
|
+
code: 'DESTRUCTIVE_CONFIRM',
|
|
3595
|
+
confirm: true,
|
|
3596
|
+
confirmCategory: category,
|
|
3597
|
+
reason: [
|
|
3598
|
+
`⚠️ 需要确认:「${category}」这一类操作会丢弃可恢复但重要的东西。`,
|
|
3599
|
+
` 原因:${finding.why}`,
|
|
3600
|
+
` 命令:${finding.segment}`,
|
|
3601
|
+
'',
|
|
3602
|
+
'交互模式会弹窗,可选「允许这一次」/「本会话允许这一类」/「拒绝」。',
|
|
3603
|
+
'无 UI 的自动化运行会直接执行并记一行日志。',
|
|
3604
|
+
'不可恢复的操作(删 $HOME / 删 cwd / 含 .. / 磁盘格式化 / 裸设备写入)仍被硬拦,没有授权口。',
|
|
3605
|
+
`想永久调整:/gate list 看当前档位,/gate grant ${category} 或 /gate deny ${category}。`,
|
|
3606
|
+
].join('\n'),
|
|
3607
|
+
};
|
|
3608
|
+
},
|
|
3609
|
+
|
|
3610
|
+
/**
|
|
3611
|
+
* A grant must be given by the user, never taken by the agent.
|
|
3612
|
+
*
|
|
3613
|
+
* The permission tiers live in two files: the installed `policy.json` and the
|
|
3614
|
+
* machine-local `gate-policy.json`. If the agent could edit either one, every
|
|
3615
|
+
* tier above would be decorative - it would grant itself `allow` on `db-ddl`
|
|
3616
|
+
* and carry on. So the only supported way to change them is the `/gate`
|
|
3617
|
+
* command, which the user types; a write that carries `destructive_grants` is
|
|
3618
|
+
* refused here.
|
|
3619
|
+
*
|
|
3620
|
+
* ADR-015 adds the directory around those files. Refusing to edit a rule is
|
|
3621
|
+
* worth little while the file it is read from can be deleted, and under
|
|
3622
|
+
* `bypass` (ADR-013) that delete tier is exactly what is switched off:
|
|
3623
|
+
* `rm -rf` of the gate's own directory, or of any parent up to the agent's
|
|
3624
|
+
* home, ran unasked and took every rule - red lines included - with it.
|
|
3625
|
+
*/
|
|
3626
|
+
'no-self-grant': (policy, input, deps) => {
|
|
3627
|
+
const isGateFile = (p) => {
|
|
3628
|
+
const posix = String(p ?? '').replace(/\\/g, '/').toLowerCase();
|
|
3629
|
+
if (!posix) return false;
|
|
3630
|
+
return (
|
|
3631
|
+
posix.endsWith('/.config/agent-config-bridge/gate-policy.json') ||
|
|
3632
|
+
/\/extensions\/enforce-rules\/policy\.json$/.test(posix)
|
|
3633
|
+
);
|
|
3634
|
+
};
|
|
3635
|
+
|
|
3636
|
+
// The deployed engine, adapter and README are not grants files, and
|
|
3637
|
+
// editing one is the same act by other means.
|
|
3638
|
+
const gateDirs = gateDirsOf(deps);
|
|
3639
|
+
if (input.action === 'write') {
|
|
3640
|
+
if (!isGateFile(input.path)) {
|
|
3641
|
+
return isGateOwned(input.path, gateDirs) ? gateOwnedVerdict(input.path) : null;
|
|
3642
|
+
}
|
|
3643
|
+
// Only the grants block, the mode switch and the protected-worktree list
|
|
3644
|
+
// are protected: a user may still fix a typo in another field by hand,
|
|
3645
|
+
// and a tool that rewrites the whole file without touching any of them is
|
|
3646
|
+
// not self-granting.
|
|
3647
|
+
//
|
|
3648
|
+
// `destructive_mode` must be here too (ADR-013): writing
|
|
3649
|
+
// `{"config":{"destructive_mode":"bypass"}}` would silently turn off the
|
|
3650
|
+
// destructive permission layer for every future session - strictly worse
|
|
3651
|
+
// than granting itself one category, because it is permanent and global.
|
|
3652
|
+
//
|
|
3653
|
+
// `protected_worktrees` for the same reason, one step further (ADR-015):
|
|
3654
|
+
// it is the list that makes a red line out of `git stash`. An agent that
|
|
3655
|
+
// may delete its own directory from that list can un-protect the one
|
|
3656
|
+
// tree the red line exists for, and bypass is not even needed.
|
|
3657
|
+
if (
|
|
3658
|
+
typeof input.content === 'string' &&
|
|
3659
|
+
!/destructive_grants|destructive_mode|protected_worktrees/.test(input.content)
|
|
3660
|
+
) {
|
|
3661
|
+
// …with one exception. A whole-file rewrite that leaves the list out
|
|
3662
|
+
// un-protects the tree without naming it. Grants and the mode may be
|
|
3663
|
+
// dropped that way (dropping them tightens the gate); the protected
|
|
3664
|
+
// list is a red line, and removing one is never a tightening.
|
|
3665
|
+
if (dropsProtectedList(input.content, input.path, deps?.fs)) {
|
|
3666
|
+
return {
|
|
3667
|
+
code: 'GATE_SELF_GRANT',
|
|
3668
|
+
reason: [
|
|
3669
|
+
'⛔ 门控自保护:agent 不能拆自己的红线。',
|
|
3670
|
+
` 目标:${input.path}`,
|
|
3671
|
+
'',
|
|
3672
|
+
'这次写入会用一份不含受保护工作区清单(protected_worktrees)的内容覆盖整个文件,',
|
|
3673
|
+
'等于把受保护的目录从红线里摘出去。',
|
|
3674
|
+
'要增删受保护目录,请主人亲手改这个文件(/gate list 可以看到生效清单)。',
|
|
3675
|
+
].join('\n'),
|
|
3676
|
+
};
|
|
3677
|
+
}
|
|
3678
|
+
return null;
|
|
3679
|
+
}
|
|
3680
|
+
return {
|
|
3681
|
+
code: 'GATE_SELF_GRANT',
|
|
3682
|
+
reason: [
|
|
3683
|
+
'⛔ 门控自保护:agent 不能给自己提权。',
|
|
3684
|
+
` 目标:${input.path}`,
|
|
3685
|
+
'',
|
|
3686
|
+
'这次写入会改动破坏性操作的授权表(destructive_grants)、门控模式(destructive_mode)',
|
|
3687
|
+
'或受保护工作区清单(protected_worktrees)。',
|
|
3688
|
+
'三者只能由用户亲手改:',
|
|
3689
|
+
' 1) 交互弹窗里选「本会话允许 <类别>」—— 只对当前会话有效;',
|
|
3690
|
+
' 2) 敲 /gate grant <类别> —— 持久(写机器本地 gate-policy.json);',
|
|
3691
|
+
' 3) 敲 /gate deny <类别> —— 收紧;/gate list 查看当前档位;',
|
|
3692
|
+
' 4) 敲 /gate mode bypass|enforce [时长] [session] —— 切换门控模式。',
|
|
3693
|
+
'',
|
|
3694
|
+
'为什么不让 agent 写:如果 agent 能改授权表或模式开关,所有分级都变成装饰——',
|
|
3695
|
+
'它只要给自己 allow db-ddl 或 destructive_mode: bypass 就绕过了破坏性命令门控;',
|
|
3696
|
+
'能改受保护清单,就能把挡着自己的那条红线拆掉。',
|
|
3697
|
+
].join('\n'),
|
|
3698
|
+
};
|
|
3699
|
+
}
|
|
3700
|
+
|
|
3701
|
+
if (input.action === 'bash') {
|
|
3702
|
+
const targets = shellWriteTargets(input, {
|
|
3703
|
+
config: policy.config,
|
|
3704
|
+
cwd: input.cwd ?? null,
|
|
3705
|
+
isFile: deps?.isFile,
|
|
3706
|
+
exists: deps?.exists,
|
|
3707
|
+
});
|
|
3708
|
+
const removing = typeof input.command === 'string' && shellUsesAny(input.command, GATE_REMOVAL_VERBS);
|
|
3709
|
+
let hit = targets.find((target) => isGateFile(target) || isGateOwned(target, gateDirs, removing));
|
|
3710
|
+
if (!hit && typeof input.command === 'string' && shellUsesAny(input.command, GATE_MOVE_VERBS)) {
|
|
3711
|
+
hit = gateOwnedShellTarget(input, policy.config, deps);
|
|
3712
|
+
}
|
|
3713
|
+
if (!hit) return null;
|
|
3714
|
+
if (!isGateFile(hit)) return gateOwnedVerdict(hit);
|
|
3715
|
+
return {
|
|
3716
|
+
code: 'GATE_SELF_GRANT',
|
|
3717
|
+
reason: [
|
|
3718
|
+
'⛔ 门控自保护:agent 不能给自己提权。',
|
|
3719
|
+
` 目标:${hit}`,
|
|
3720
|
+
'',
|
|
3721
|
+
'用 shell 改写授权表同样不允许。授权只能由用户亲手给:',
|
|
3722
|
+
' /gate grant <类别> / /gate ask <类别> / /gate deny <类别> / /gate list',
|
|
3723
|
+
'',
|
|
3724
|
+
'为什么不让 agent 写:如果 agent 能改授权表,所有分级都变成装饰。',
|
|
3725
|
+
].join('\n'),
|
|
3726
|
+
};
|
|
3727
|
+
}
|
|
3728
|
+
return null;
|
|
3729
|
+
},
|
|
3730
|
+
|
|
3731
|
+
/** Don't read source before consulting the code graph. */
|
|
3732
|
+
'graph-before-read': (policy, input, deps) => {
|
|
3733
|
+
if (input.action !== 'read') return null;
|
|
3734
|
+
const scope = scopeOf(input.path, { config: policy.config, exists: deps.exists });
|
|
3735
|
+
if (!scope.inScope) return null;
|
|
3736
|
+
if (deps.state.written.has(input.path)) return null;
|
|
3737
|
+
if (hasUnlock(deps.state, input.path, policy.config, deps.now)) return null;
|
|
3738
|
+
return {
|
|
3739
|
+
code: 'GRAPH_FIRST',
|
|
3740
|
+
reason: [
|
|
3741
|
+
'⛔ 三层铁律 · Layer 1 拦截:本次读取没有图谱依据。',
|
|
3742
|
+
` 文件:${input.path}`,
|
|
3743
|
+
` 依据:${scope.reason}(项目根:${scope.root ?? '未知'})`,
|
|
3744
|
+
'',
|
|
3745
|
+
'解除方式(二选一,都需要**成功且有内容**的图谱调用):',
|
|
3746
|
+
' a) 针对本文件/本包查一次:search_graph / trace_path / get_code_snippet /',
|
|
3747
|
+
' query_graph / get_architecture / search_code(查询里提到文件名或包名,',
|
|
3748
|
+
' 命中后 30 分钟内该目标的读取都放行);',
|
|
3749
|
+
' b) 任何一次有结果的图谱调用会给本会话一个 10 分钟的窗口。',
|
|
3750
|
+
'如果查询返回空结果,不算合规:先查 index_status / 重新索引,回到图谱重查;',
|
|
3751
|
+
'不允许“搜不到就直接 read”。',
|
|
3752
|
+
'本会话内你自己刚改过的文件不受此限制。',
|
|
3753
|
+
].join('\n'),
|
|
3754
|
+
};
|
|
3755
|
+
},
|
|
3756
|
+
|
|
3757
|
+
/** The same rule for reads that arrive as bash commands (cat/grep/sed -n/…). */
|
|
3758
|
+
'bash-graph-before-read': (policy, input, deps) => {
|
|
3759
|
+
if (input.action !== 'bash') return null;
|
|
3760
|
+
if (policy.config.bash_read_check === false) return null;
|
|
3761
|
+
const opts = {
|
|
3762
|
+
config: policy.config,
|
|
3763
|
+
cwd: input.cwd ?? null,
|
|
3764
|
+
isFile: deps.isFile,
|
|
3765
|
+
exists: deps.exists,
|
|
3766
|
+
};
|
|
3767
|
+
const targets = shellReadTargets(input, opts);
|
|
3768
|
+
const dirs = shellReadDirs(input, opts);
|
|
3769
|
+
if (targets.length === 0 && dirs.length === 0) return null;
|
|
3770
|
+
|
|
3771
|
+
const blockedFile = targets.find((target) => {
|
|
3772
|
+
const scope = scopeOf(target, { config: policy.config, exists: deps.exists });
|
|
3773
|
+
if (!scope.inScope) return false;
|
|
3774
|
+
if (deps.state.written.has(normalizePath(target))) return false;
|
|
3775
|
+
return !hasUnlock(deps.state, target, policy.config, deps.now);
|
|
3776
|
+
});
|
|
3777
|
+
const blockedDir = dirs.find((dir) => {
|
|
3778
|
+
if (deps.state.written.has(normalizePath(dir))) return false;
|
|
3779
|
+
return !hasUnlock(deps.state, dir, policy.config, deps.now);
|
|
3780
|
+
});
|
|
3781
|
+
if (!blockedFile && !blockedDir) return null;
|
|
3782
|
+
|
|
3783
|
+
return {
|
|
3784
|
+
code: 'GRAPH_FIRST_BASH',
|
|
3785
|
+
reason: [
|
|
3786
|
+
'⛔ 三层铁律 · Layer 1 拦截:用 bash 读源码和用 read 工具读源码是同一件事。',
|
|
3787
|
+
` 命令:${String(input.command).slice(0, 200)}`,
|
|
3788
|
+
blockedFile ? ` 目标文件:${blockedFile}` : ` 目标目录:${blockedDir}`,
|
|
3789
|
+
targets.length > 1 || dirs.length > 1
|
|
3790
|
+
? ` (共识别到 ${targets.length} 个文件、${dirs.length} 个目录,只列了第一个)`
|
|
3791
|
+
: '',
|
|
3792
|
+
'',
|
|
3793
|
+
'先查图谱(search_graph / trace_path / get_code_snippet / query_graph /',
|
|
3794
|
+
'get_architecture / search_code),查询里提到该文件/包/目录,然后重试。',
|
|
3795
|
+
'cat / grep -r / sed -n / git show / git diff / find -exec / xargs 都在范围内;',
|
|
3796
|
+
'git status / ls / find 只列名字不受影响。',
|
|
3797
|
+
]
|
|
3798
|
+
.filter(Boolean)
|
|
3799
|
+
.join('\n'),
|
|
3800
|
+
};
|
|
3801
|
+
},
|
|
3802
|
+
|
|
3803
|
+
/**
|
|
3804
|
+
* A read that the rule wants gated on an index existing at all.
|
|
3805
|
+
*
|
|
3806
|
+
* Opt-in, not default. codebase-memory's live index normally lives in the
|
|
3807
|
+
* tool's own data directory, not in `<repo>/.codebase-memory` (that marker
|
|
3808
|
+
* only exists when persistence was requested). Enabling this check on a
|
|
3809
|
+
* global index therefore blocks every read until the cap, and the v3 answer
|
|
3810
|
+
* is evidence instead: an empty graph result no longer counts as a signal, so
|
|
3811
|
+
* an unindexed project cannot buy a read window at all. Keep this check for
|
|
3812
|
+
* teams that do commit the persisted artifact.
|
|
3813
|
+
*/
|
|
3814
|
+
'index-before-read': (policy, input, deps) => {
|
|
3815
|
+
if (input.action !== 'read') return null;
|
|
3816
|
+
const scope = scopeOf(input.path, { config: policy.config, exists: deps.exists });
|
|
3817
|
+
if (!scope.inScope || !scope.root) return null;
|
|
3818
|
+
if (deps.state.written.has(input.path)) return null;
|
|
3819
|
+
const marker = join(scope.projectRoot ?? scope.root, policy.config.index_marker);
|
|
3820
|
+
if (deps.exists(marker)) return null;
|
|
3821
|
+
return {
|
|
3822
|
+
code: 'INDEX_FIRST',
|
|
3823
|
+
reason: [
|
|
3824
|
+
'⛔ 三层铁律 · Layer 2 拦截:该项目尚未建立 codebase-memory 索引。',
|
|
3825
|
+
` 仓库:${scope.root}`,
|
|
3826
|
+
` 缺少:${marker}`,
|
|
3827
|
+
'',
|
|
3828
|
+
`正确动作:先调用 index_repository(repo_path 取 ${scope.root};模式按规模选 full/moderate/fast)`,
|
|
3829
|
+
'建立索引与 embedding;索引完成后回到 Layer 1 查图谱(search_graph / trace_path /',
|
|
3830
|
+
'get_code_snippet 等),最后才可直读。',
|
|
3831
|
+
'若你的索引是全局存储(没有 .codebase-memory 持久化产物),请从 policy.json 的',
|
|
3832
|
+
'checks 里去掉本项:它无法验证全局索引,会误拦。',
|
|
3833
|
+
].join('\n'),
|
|
3834
|
+
};
|
|
3835
|
+
},
|
|
3836
|
+
|
|
3837
|
+
/**
|
|
3838
|
+
* The index exists but the file is newer than anything inside it.
|
|
3839
|
+
*
|
|
3840
|
+
* v3 removes the "fresh graph signal" shortcut. A query against a stale index
|
|
3841
|
+
* is precisely the failure this check exists to catch: letting that query
|
|
3842
|
+
* stand the rule down made the check unreachable in practice. The session's
|
|
3843
|
+
* own writes remain exempt (they are always newer than the index they are
|
|
3844
|
+
* about to update), and the check still abstains when the marker or its
|
|
3845
|
+
* mtimes are unreadable.
|
|
3846
|
+
*/
|
|
3847
|
+
'index-freshness-before-read': (policy, input, deps) => {
|
|
3848
|
+
if (input.action !== 'read') return null;
|
|
3849
|
+
const scope = scopeOf(input.path, { config: policy.config, exists: deps.exists });
|
|
3850
|
+
if (!scope.inScope || !scope.root) return null;
|
|
3851
|
+
if (deps.state.written.has(input.path)) return null;
|
|
3852
|
+
|
|
3853
|
+
const mtime = deps.statMtime(input.path);
|
|
3854
|
+
if (!(mtime > 0)) return null; // vanished, unreadable, or a directory: abstain
|
|
3855
|
+
|
|
3856
|
+
// Prefer a real persisted marker when the indexer created one. Otherwise
|
|
3857
|
+
// fall back to the session's own successful index refresh: the default
|
|
3858
|
+
// codebase-memory index lives in a global data directory, so requiring a
|
|
3859
|
+
// repo-local marker made this check abstain on every normal project.
|
|
3860
|
+
const marker = join(scope.projectRoot ?? scope.root, policy.config.index_marker);
|
|
3861
|
+
let evidenceAt = 0;
|
|
3862
|
+
if (deps.exists(marker)) {
|
|
3863
|
+
evidenceAt = newestMtimeIn(marker, deps, deps.now, policy.config.index_mtime_ttl_ms);
|
|
3864
|
+
}
|
|
3865
|
+
if (!(evidenceAt > 0)) evidenceAt = deps.state.lastIndexRefreshAt ?? 0;
|
|
3866
|
+
if (!(evidenceAt > 0)) return null; // no evidence either way: abstain (graph rule still gates)
|
|
3867
|
+
if (mtime <= evidenceAt + policy.config.index_mtime_epsilon_ms) return null;
|
|
3868
|
+
|
|
3869
|
+
return {
|
|
3870
|
+
code: 'INDEX_STALE',
|
|
3871
|
+
reason: [
|
|
3872
|
+
'⛔ 三层铁律 · Layer 2 拦截:索引疑似过期——目标文件比索引新(embedding 落后于代码变更)。',
|
|
3873
|
+
` 目标:${input.path}`,
|
|
3874
|
+
` 所属已索引项目:${scope.root}`,
|
|
3875
|
+
'',
|
|
3876
|
+
'正确动作:先 detect_changes 检查影响范围,或 index_repository 重新索引;完成后回到',
|
|
3877
|
+
'Layer 1 查图谱,最后才可直读。',
|
|
3878
|
+
'这次查询成功也不能代替索引更新:查的是旧图,读的是新代码。',
|
|
3879
|
+
'本会话内你自己刚改过的文件不受此拦截。',
|
|
3880
|
+
].join('\n'),
|
|
3881
|
+
};
|
|
3882
|
+
},
|
|
3883
|
+
|
|
3884
|
+
/** Never write outside the paths the user declared writable. */
|
|
3885
|
+
'no-write-outside': (policy, input, deps) => {
|
|
3886
|
+
if (input.action !== 'write' && input.action !== 'bash') return null;
|
|
3887
|
+
const allowed = policy.config.write_roots ?? [];
|
|
3888
|
+
if (allowed.length === 0) return null;
|
|
3889
|
+
const targets = input.action === 'write'
|
|
3890
|
+
? [input.path].filter(Boolean)
|
|
3891
|
+
: shellWriteTargets(input, {
|
|
3892
|
+
config: policy.config,
|
|
3893
|
+
cwd: input.cwd ?? null,
|
|
3894
|
+
isFile: deps.isFile,
|
|
3895
|
+
exists: deps.exists,
|
|
3896
|
+
});
|
|
3897
|
+
if (targets.length === 0) return null;
|
|
3898
|
+
const outside = targets.filter((p) => !allowed.some((r) => withinRoot(r, p)));
|
|
3899
|
+
if (outside.length === 0) return null;
|
|
3900
|
+
return {
|
|
3901
|
+
code: 'WRITE_OUTSIDE',
|
|
3902
|
+
reason: [
|
|
3903
|
+
'Blocked: writing outside the allowed roots.',
|
|
3904
|
+
` path : ${outside[0]}`,
|
|
3905
|
+
outside.length > 1 ? ` (and ${outside.length - 1} more)` : '',
|
|
3906
|
+
` allowed : ${allowed.join(', ')}`,
|
|
3907
|
+
'',
|
|
3908
|
+
'Add the root to config.write_roots in the gate policy if this write is intended.',
|
|
3909
|
+
'This also covers shell writes (redirection, tee, cp/mv, rm).',
|
|
3910
|
+
]
|
|
3911
|
+
.filter(Boolean)
|
|
3912
|
+
.join('\n'),
|
|
3913
|
+
};
|
|
3914
|
+
},
|
|
3915
|
+
|
|
3916
|
+
/** Never let a credential-shaped string be written into a tracked file. */
|
|
3917
|
+
'no-secret-write': (policy, input, deps) => {
|
|
3918
|
+
if (input.action !== 'write' && input.action !== 'bash') return null;
|
|
3919
|
+
const isBash = input.action === 'bash';
|
|
3920
|
+
if (isBash) {
|
|
3921
|
+
// Only scan when the command actually writes; `git commit -m "..."` is
|
|
3922
|
+
// not a file write and must not be judged as one.
|
|
3923
|
+
const writes = shellWriteTargets(input, {
|
|
3924
|
+
config: policy.config,
|
|
3925
|
+
cwd: input.cwd ?? null,
|
|
3926
|
+
isFile: deps.isFile,
|
|
3927
|
+
exists: deps.exists,
|
|
3928
|
+
});
|
|
3929
|
+
if (writes.length === 0) return null;
|
|
3930
|
+
}
|
|
3931
|
+
const text = input.content ?? (isBash ? input.command : '');
|
|
3932
|
+
if (typeof text !== 'string' || text === '') return null;
|
|
3933
|
+
const hits = scanForSecrets(text, policy.config);
|
|
3934
|
+
if (hits.length === 0) return null;
|
|
3935
|
+
return {
|
|
3936
|
+
code: 'SECRET_WRITE',
|
|
3937
|
+
reason: [
|
|
3938
|
+
'Blocked: the content being written looks like it contains a real credential.',
|
|
3939
|
+
...hits.slice(0, 5).map((h) => ` ${h}`),
|
|
3940
|
+
'',
|
|
3941
|
+
'Replace it with a placeholder and keep the real value outside the repository.',
|
|
3942
|
+
isBash ? 'Shell writes (redirection, tee, sed -i) are covered by this rule too.' : '',
|
|
3943
|
+
]
|
|
3944
|
+
.filter(Boolean)
|
|
3945
|
+
.join('\n'),
|
|
3946
|
+
};
|
|
3947
|
+
},
|
|
3948
|
+
};
|
|
3949
|
+
|
|
3950
|
+
/** Patterns that should never be committed. Deliberately the same families the
|
|
3951
|
+
* repository scanner uses, so the two cannot disagree about "what is a secret". */
|
|
3952
|
+
const SECRET_PATTERNS = [
|
|
3953
|
+
['private key block', /-----BEGIN [A-Z ]*PRIVATE KEY-----/],
|
|
3954
|
+
['api key assignment', /(api[_-]?key|apikey|token|secret|password|passwd)['"`]?\s*[:=]\s*["'`]?[A-Za-z0-9_\-]{16,}/i],
|
|
3955
|
+
['long opaque token', /(^|[^A-Za-z0-9_+=])[A-Za-z0-9_+=]{40,}([^A-Za-z0-9_+=]|$)/],
|
|
3956
|
+
];
|
|
3957
|
+
|
|
3958
|
+
/** A bare mailbox is not a credential. It only matters next to a credential field. */
|
|
3959
|
+
const EMAIL_ADDRESS = /[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/;
|
|
3960
|
+
const CREDENTIAL_FIELD = /(?:api[_-]?key|apikey|token|secret|password|passwd|credential)['"`]?\s*[:=]/i;
|
|
3961
|
+
|
|
3962
|
+
export const scanForSecrets = (text, config = DEFAULT_CONFIG) => {
|
|
3963
|
+
const allowed = config.secret_allow_patterns ?? [
|
|
3964
|
+
'example\\.com',
|
|
3965
|
+
'127\\.0\\.0\\.1',
|
|
3966
|
+
'\\$\\{[A-Za-z_][A-Za-z0-9_]*\\}',
|
|
3967
|
+
'<[^<>\\s]+>',
|
|
3968
|
+
];
|
|
3969
|
+
const allow = new RegExp(allowed.join('|'));
|
|
3970
|
+
const hits = [];
|
|
3971
|
+
for (const [label, re] of SECRET_PATTERNS) {
|
|
3972
|
+
const m = re.exec(text);
|
|
3973
|
+
if (m && !allow.test(m[0])) {
|
|
3974
|
+
const sample = m[0].length > 40 ? `${m[0].slice(0, 20)}…` : m[0];
|
|
3975
|
+
hits.push(`${label}: ${sample.replace(/\s+/g, ' ')}`);
|
|
3976
|
+
}
|
|
3977
|
+
}
|
|
3978
|
+
// v4: a mailbox alone is ordinary prose (READMEs, examples, contact info).
|
|
3979
|
+
// It is a credential signal only when a credential field sits next to it.
|
|
3980
|
+
const mail = EMAIL_ADDRESS.exec(text);
|
|
3981
|
+
if (mail && !allow.test(mail[0])) {
|
|
3982
|
+
const from = Math.max(0, mail.index - 40);
|
|
3983
|
+
const to = mail.index + mail[0].length + 40;
|
|
3984
|
+
const around = text.slice(from, to);
|
|
3985
|
+
if (CREDENTIAL_FIELD.test(around)) {
|
|
3986
|
+
const sample = mail[0].length > 40 ? `${mail[0].slice(0, 20)}…` : mail[0];
|
|
3987
|
+
hits.push(`credential email: ${sample}`);
|
|
3988
|
+
}
|
|
3989
|
+
}
|
|
3990
|
+
return hits;
|
|
3991
|
+
};
|
|
3992
|
+
|
|
3993
|
+
export const CHECK_NAMES = Object.keys(CHECKS);
|
|
3994
|
+
|
|
3995
|
+
/**
|
|
3996
|
+
* Checks that stay on after the per-session block cap.
|
|
3997
|
+
*
|
|
3998
|
+
* The cap exists so a mis-written research rule cannot brick an agent. It must
|
|
3999
|
+
* not also switch off safety: before v3, `shouldBlock` returned early once the
|
|
4000
|
+
* cap was reached, which turned 30 graph blocks into a free pass to write a
|
|
4001
|
+
* credential anywhere. Layer-0/1/2 checks are capped; the security checks are
|
|
4002
|
+
* not.
|
|
4003
|
+
*/
|
|
4004
|
+
export const HARD_CHECKS = new Set([
|
|
4005
|
+
'no-write-outside',
|
|
4006
|
+
'no-secret-write',
|
|
4007
|
+
'no-destructive-bash',
|
|
4008
|
+
// The self-grant guard protects the permission table itself. If it stood down
|
|
4009
|
+
// under the block cap, an agent could spend the cap and then write itself an
|
|
4010
|
+
// `allow` on `db-ddl`.
|
|
4011
|
+
'no-self-grant',
|
|
4012
|
+
// ai-spec 契约门控:不得因拦截上限而失效——它守的是「不跑偏」,与安全同级。
|
|
4013
|
+
'chg-contract-before-edit',
|
|
4014
|
+
]);
|
|
4015
|
+
|
|
4016
|
+
// ---------------------------------------------------------------------------
|
|
4017
|
+
// Evaluation
|
|
4018
|
+
// ---------------------------------------------------------------------------
|
|
4019
|
+
|
|
4020
|
+
/**
|
|
4021
|
+
* Decide whether to block a normalized tool call.
|
|
4022
|
+
*
|
|
4023
|
+
* @param {object} args
|
|
4024
|
+
* @param {object} args.policy
|
|
4025
|
+
* @param {{action:string, path:string|null, tool:string, content?:string}} args.input
|
|
4026
|
+
* @param {object} args.state from newSessionState()
|
|
4027
|
+
* @param {(p:string)=>boolean} [args.exists] filesystem probe, injected
|
|
4028
|
+
* @param {object} [args.fs] full probe: {exists, isFile, statMtime, listDir}. Supersedes `exists`.
|
|
4029
|
+
* @param {number} [args.now]
|
|
4030
|
+
* @returns {{block: boolean, code: string|null, reason: string|null, capReached: boolean}}
|
|
4031
|
+
*/
|
|
4032
|
+
export const shouldBlock = ({ policy, input, state, exists, fs, now = Date.now() }) => {
|
|
4033
|
+
const cap = policy.config.max_blocks_per_session;
|
|
4034
|
+
// v4: the cap is a sliding window, not a lifetime sentence. A long session
|
|
4035
|
+
// used to spend 30 blocks on ordinary reads and then lose every research rule
|
|
4036
|
+
// for the rest of its life.
|
|
4037
|
+
const resetMs = policy.config.block_cap_reset_ms ?? 0;
|
|
4038
|
+
if (resetMs > 0 && state.blocks > 0 && state.firstBlockAt > 0 && now - state.firstBlockAt > resetMs) {
|
|
4039
|
+
state.blocks = 0;
|
|
4040
|
+
state.firstBlockAt = 0;
|
|
4041
|
+
}
|
|
4042
|
+
const overCap = cap >= 0 && state.blocks >= cap;
|
|
4043
|
+
|
|
4044
|
+
// One probe object, so a check that needs more than `exists` can get it
|
|
4045
|
+
// without each check inventing its own seam. The flat `exists` shape stays
|
|
4046
|
+
// supported because it is what the unit tests and simpler harnesses pass.
|
|
4047
|
+
const probes = fs ?? { ...NO_FS, exists: typeof exists === 'function' ? exists : NO_FS.exists };
|
|
4048
|
+
|
|
4049
|
+
const enabled = new Set(policy.checks.length > 0 ? policy.checks : ['graph-before-read']);
|
|
4050
|
+
for (const name of enabled) {
|
|
4051
|
+
// After the cap, only the safety checks keep running. The research rules
|
|
4052
|
+
// stand down so a false positive cannot brick the session; hiding a secret
|
|
4053
|
+
// or deleting a tree has no such excuse.
|
|
4054
|
+
if (overCap && !HARD_CHECKS.has(name)) continue;
|
|
4055
|
+
const check = CHECKS[name];
|
|
4056
|
+
if (!check) continue; // unknown check names are ignored, not fatal
|
|
4057
|
+
const verdict = check(policy, input, { state, exists: probes.exists, fs: probes, ...probes, now });
|
|
4058
|
+
if (verdict) {
|
|
4059
|
+
// A confirmation is not a refusal: the call has not been denied, the user
|
|
4060
|
+
// has not been asked yet. Counting it against the block cap would let a
|
|
4061
|
+
// few ordinary deletes spend the session's rule budget, and reporting
|
|
4062
|
+
// `block: true` would stop the adapter from ever asking.
|
|
4063
|
+
if (verdict.confirm) {
|
|
4064
|
+
return {
|
|
4065
|
+
block: false,
|
|
4066
|
+
code: null,
|
|
4067
|
+
reason: null,
|
|
4068
|
+
capReached: overCap,
|
|
4069
|
+
confirm: true,
|
|
4070
|
+
confirmReason: verdict.reason ?? null,
|
|
4071
|
+
confirmCategory: verdict.confirmCategory ?? null,
|
|
4072
|
+
};
|
|
4073
|
+
}
|
|
4074
|
+
state.blocks += 1;
|
|
4075
|
+
if (!(state.firstBlockAt > 0)) state.firstBlockAt = now;
|
|
4076
|
+
return {
|
|
4077
|
+
block: true,
|
|
4078
|
+
code: verdict.code,
|
|
4079
|
+
reason: verdict.reason,
|
|
4080
|
+
capReached: false,
|
|
4081
|
+
confirm: false,
|
|
4082
|
+
confirmReason: null,
|
|
4083
|
+
confirmCategory: null,
|
|
4084
|
+
};
|
|
4085
|
+
}
|
|
4086
|
+
}
|
|
4087
|
+
return {
|
|
4088
|
+
block: false,
|
|
4089
|
+
code: null,
|
|
4090
|
+
reason: null,
|
|
4091
|
+
capReached: overCap,
|
|
4092
|
+
confirm: false,
|
|
4093
|
+
confirmReason: null,
|
|
4094
|
+
confirmCategory: null,
|
|
4095
|
+
};
|
|
4096
|
+
};
|
|
4097
|
+
|
|
4098
|
+
// ---------------------------------------------------------------------------
|
|
4099
|
+
// Turn-level anti-slack: "I'll do it later" is not a delivery
|
|
4100
|
+
// ---------------------------------------------------------------------------
|
|
4101
|
+
|
|
4102
|
+
/**
|
|
4103
|
+
* First-person deferrals about the current task. Kept deliberately narrow:
|
|
4104
|
+
* ordinary Q&A ("next you can run node --test") must not match, and text inside
|
|
4105
|
+
* code fences / blockquotes is documentation rather than a promise.
|
|
4106
|
+
*/
|
|
4107
|
+
const SLACK_PATTERNS = [
|
|
4108
|
+
/(?:我|我们)\s*(?:先|暂时|暂且)\s*(?:不|不做|不处理|跳过|略过)/,
|
|
4109
|
+
/(?:稍后|后续|之后|下一轮|下次|明天|下周|下个版本)\s*(?:再|继续)\s*(?:做|补|实现|处理|完善|修复|跟进|优化)/,
|
|
4110
|
+
/(?:我|我们)\s*(?:会|将|准备|打算|计划)\s*(?:在)?\s*(?:稍后|后续|之后|下一轮|下次|明天|下周|下个版本)/,
|
|
4111
|
+
/(?:留待|留到|留给|放到)\s*(?:后续|下次|下一轮|之后)/,
|
|
4112
|
+
/(?:还有|仍有|留有|存在)\s*(?:TODO|FIXME|待办|未完成|占位)/,
|
|
4113
|
+
/\bI(?:'ll| will| am going to| plan to)\b[^.\n]{0,50}\b(?:later|next turn|afterwards|tomorrow|next week|next version)\b/i,
|
|
4114
|
+
/\b(?:leave|defer|deferring)\b[^.\n]{0,30}\b(?:for later|to the next|afterwards)\b/i,
|
|
4115
|
+
];
|
|
4116
|
+
|
|
4117
|
+
/**
|
|
4118
|
+
* Decide whether an assistant reply is a deferral instead of a delivery.
|
|
4119
|
+
* @returns {{code:string, excerpt:string, reason:string}|null}
|
|
4120
|
+
*/
|
|
4121
|
+
export const slackFinding = (text, config = DEFAULT_CONFIG) => {
|
|
4122
|
+
if (config.slack_check === false) return null;
|
|
4123
|
+
// CJK text is information-dense: "这个我稍后再补完。" is 9 characters and a
|
|
4124
|
+
// complete deferral. A 12-character floor (borrowed from English intuition)
|
|
4125
|
+
// made the rule miss exactly the short replies it exists to catch.
|
|
4126
|
+
if (typeof text !== 'string' || text.trim().length < 6) return null;
|
|
4127
|
+
const prose = text
|
|
4128
|
+
.replace(/```[\s\S]*?```/g, '')
|
|
4129
|
+
.replace(/`[^`\n]*`/g, '')
|
|
4130
|
+
.split('\n')
|
|
4131
|
+
.filter((line) => !/^\s*>/.test(line))
|
|
4132
|
+
.join('\n');
|
|
4133
|
+
if (prose.trim().length < 6) return null;
|
|
4134
|
+
const extra = (config.slack_patterns ?? [])
|
|
4135
|
+
.map((src) => {
|
|
4136
|
+
try {
|
|
4137
|
+
return new RegExp(src, 'i');
|
|
4138
|
+
} catch {
|
|
4139
|
+
return null;
|
|
4140
|
+
}
|
|
4141
|
+
})
|
|
4142
|
+
.filter(Boolean);
|
|
4143
|
+
for (const re of [...SLACK_PATTERNS, ...extra]) {
|
|
4144
|
+
const m = re.exec(prose);
|
|
4145
|
+
if (!m) continue;
|
|
4146
|
+
const at = Math.max(0, m.index - 10);
|
|
4147
|
+
const excerpt = prose.slice(at, m.index + m[0].length + 20).replace(/\s+/g, ' ').trim();
|
|
4148
|
+
return {
|
|
4149
|
+
code: 'NO_SLACK',
|
|
4150
|
+
excerpt,
|
|
4151
|
+
reason: [
|
|
4152
|
+
'⛔ 不偷懒铁律 · 轮次级拦截:检测到「把本任务留给以后」的承诺,而不是交付。',
|
|
4153
|
+
` 命中:…${excerpt}…`,
|
|
4154
|
+
'',
|
|
4155
|
+
'这一轮必须二选一:',
|
|
4156
|
+
' a) 直接调用工具把它做完(不要只复述计划);',
|
|
4157
|
+
' b) 如果确实被外部条件阻塞(缺少凭据、服务不可用、需要用户决策),',
|
|
4158
|
+
' 把阻塞点和已尝试的动作写清楚,并明确说明「这不是交付」。',
|
|
4159
|
+
'不要用「稍后再补 / 后续处理 / 先不实现」结束这一轮。',
|
|
4160
|
+
].join('\n'),
|
|
4161
|
+
};
|
|
4162
|
+
}
|
|
4163
|
+
return null;
|
|
4164
|
+
};
|
|
4165
|
+
|
|
4166
|
+
/**
|
|
4167
|
+
* The per-turn nudge appended to the model's context.
|
|
4168
|
+
*
|
|
4169
|
+
* A gate that only says "no" teaches nothing; the reminder is what makes the
|
|
4170
|
+
* rule learnable. Returns null when the session is already compliant, so a
|
|
4171
|
+
* well-behaved session is not nagged.
|
|
4172
|
+
*/
|
|
4173
|
+
export const reminderFor = (policy, state, now = Date.now()) => {
|
|
4174
|
+
// The base text and the profile text have different silences, on purpose.
|
|
4175
|
+
//
|
|
4176
|
+
// The base reminder teaches "ask the graph first", so a fresh graph signal means
|
|
4177
|
+
// it has been heard. The profile reminder teaches Worklog / log / result notes —
|
|
4178
|
+
// behaviours a graph query says nothing about — so it keeps being injected while
|
|
4179
|
+
// the domain is active. Silencing it after the first graph call would mean the
|
|
4180
|
+
// research rules are mentioned once per session and then never again.
|
|
4181
|
+
let base = null;
|
|
4182
|
+
if (policy.reminded) {
|
|
4183
|
+
// A session-wide signal silences the reminder, except while Layer 0 still has
|
|
4184
|
+
// a specific gap: the model has queried the graph but has not read the
|
|
4185
|
+
// project's conventions yet. Silence there would teach "query once, then act".
|
|
4186
|
+
const conventionsPending =
|
|
4187
|
+
policy.checks.includes('think-before-write') &&
|
|
4188
|
+
policy.config.require_conventions &&
|
|
4189
|
+
state.docReads.size === 0;
|
|
4190
|
+
if (!hasFreshSignal(state, policy.config.signal_ttl_ms, now) || conventionsPending) {
|
|
4191
|
+
base = policy.reminded;
|
|
4192
|
+
}
|
|
4193
|
+
}
|
|
4194
|
+
const profileReminder = profileFor(policy, state?.profile)?.reminder ?? '';
|
|
4195
|
+
const parts = [base, profileReminder].filter((t) => typeof t === 'string' && t !== '');
|
|
4196
|
+
return parts.length > 0 ? parts.join('\n\n') : null;
|
|
4197
|
+
};
|
|
4198
|
+
|
|
4199
|
+
export const globHelpers = { toPosix, posix };
|