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