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,767 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* DeepSeek Harness (dsh) adapter for the hard-gate policy.
|
|
3
|
+
*
|
|
4
|
+
* dsh is "everything is a plugin": a plugin is a module exporting `apply(ctx)`,
|
|
5
|
+
* and policy is expressed as listeners on documented extension points. This file
|
|
6
|
+
* is the same shape as the pi adapter: translate the harness event into the
|
|
7
|
+
* normalized question, ask ../policy.js, translate the answer back.
|
|
8
|
+
*
|
|
9
|
+
* Configure through the cordis plugin row, e.g.
|
|
10
|
+
*
|
|
11
|
+
* - insert:
|
|
12
|
+
* - id: enforce-rules
|
|
13
|
+
* # A bare home-relative path ('~/.dsh/plugins/...') does NOT resolve:
|
|
14
|
+
* # dsh's loader takes a module specifier, and a relative one is
|
|
15
|
+
* # anchored beside the patch file (~/.dsh/profiles/<profile>/). This is
|
|
16
|
+
* # the verified form; a file:// URL works too.
|
|
17
|
+
* name: '../../plugins/agent-config-gates/dsh/index.js'
|
|
18
|
+
* config:
|
|
19
|
+
* # policyPath is read with a plain fs call, so it must be absolute.
|
|
20
|
+
* policyPath: '/absolute/path/to/agent-config-gates/policy.json'
|
|
21
|
+
*
|
|
22
|
+
* ---------------------------------------------------------------------------
|
|
23
|
+
* Hook parity with the pi adapter (CHG-20261115-dsh-gate-parity)
|
|
24
|
+
* ---------------------------------------------------------------------------
|
|
25
|
+
*
|
|
26
|
+
* The previous revision recorded "dsh has no result hook and no turn-level
|
|
27
|
+
* injection" and turned three checks off in policy.json because of it. That was
|
|
28
|
+
* true of the dsh version it was written against and is FALSE of the installed
|
|
29
|
+
* one, so the checks are back:
|
|
30
|
+
*
|
|
31
|
+
* pi `tool_call` -> `tools/pre-execute` waterfall, deny/ask/next
|
|
32
|
+
* pi `tool_result` -> `tools/result` synchronous, frozen outcome
|
|
33
|
+
* pi `turn_end` -> `agent/turn-stopping` serial; object by steering
|
|
34
|
+
* pi `before_agent_start` -> `agent/pre-step` waterfall; sees claimed messages
|
|
35
|
+
* pi `context` (reminder) -> `agent.inject(message)`
|
|
36
|
+
* pi `ctx.ui.confirm` -> `{ kind: 'ask' }` + `ctx.approval`
|
|
37
|
+
*
|
|
38
|
+
* Sources (installed version, read 2026-11-15):
|
|
39
|
+
* docs/user/develop/framework/events.md tools/result signature
|
|
40
|
+
* docs/tool-execution-pipeline.md pipeline order
|
|
41
|
+
* docs/subsystems/tools.md PreToolDecision, ToolExecutionResult
|
|
42
|
+
* docs/subsystems/core.md agent/pre-step, agent/turn-stopping
|
|
43
|
+
* docs/subsystems/approval.md ctx.approval.effectivePolicy
|
|
44
|
+
* docs/subsystems/practices.md incremental-fold performance rule
|
|
45
|
+
*
|
|
46
|
+
* Two deliberate asymmetries REMAIN and are documented rather than hidden:
|
|
47
|
+
*
|
|
48
|
+
* - `agent/turn-stopping` hands over `{agent, turn, signal}` and no text, so
|
|
49
|
+
* the turn's final assistant text is folded incrementally from
|
|
50
|
+
* `session/event` (practices.md forbids rescanning the whole log there).
|
|
51
|
+
* - Steering and injection take a `UserMessage`, which this adapter cannot
|
|
52
|
+
* construct through the typed factory (`@deepseek-ai/dsh-llm` is not a
|
|
53
|
+
* declared dependency of this plugin). It therefore tries the documented
|
|
54
|
+
* shapes in order and, if every one is rejected, writes one stderr line
|
|
55
|
+
* instead of throwing: a gate that breaks a turn is worse than a gate that
|
|
56
|
+
* reports it could not act.
|
|
57
|
+
*
|
|
58
|
+
* Two harness details are matched here rather than assumed, because both were
|
|
59
|
+
* silent failures on Windows Desktop (2026-11-14):
|
|
60
|
+
*
|
|
61
|
+
* - the shell tool is named per platform (`bash` on POSIX presets, `pwsh` on
|
|
62
|
+
* the Windows one), so it must be matched as a set — an exact `'bash'`
|
|
63
|
+
* comparison disables every shell rule on Windows while the plugin row still
|
|
64
|
+
* reports `active`;
|
|
65
|
+
* - `ToolExecution` carries no `cwd`, so relative paths must be resolved
|
|
66
|
+
* against the Session's directory (the `workingDirectory` service), not
|
|
67
|
+
* against the directory the Desktop app happened to be launched from.
|
|
68
|
+
*/
|
|
69
|
+
|
|
70
|
+
import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
|
|
71
|
+
import { dirname, join } from 'node:path';
|
|
72
|
+
import { fileURLToPath } from 'node:url';
|
|
73
|
+
|
|
74
|
+
import {
|
|
75
|
+
analysisScriptTargets,
|
|
76
|
+
applyMachineOverride,
|
|
77
|
+
graphResultIsEvidence,
|
|
78
|
+
isChgContract,
|
|
79
|
+
isConventionDoc,
|
|
80
|
+
isDestructiveBypass,
|
|
81
|
+
loadPolicy,
|
|
82
|
+
machineGateConfigPath,
|
|
83
|
+
machineProtectedListProblems,
|
|
84
|
+
newSessionState,
|
|
85
|
+
normalizePath,
|
|
86
|
+
outputArtifactFindings,
|
|
87
|
+
policyFromObject,
|
|
88
|
+
profilePolicy,
|
|
89
|
+
recordCommandResult,
|
|
90
|
+
recordDocRead,
|
|
91
|
+
recordIndexRefresh,
|
|
92
|
+
recordInspection,
|
|
93
|
+
recordInvestigation,
|
|
94
|
+
recordScriptRun,
|
|
95
|
+
recordSignal,
|
|
96
|
+
recordUnlocks,
|
|
97
|
+
recordWrite,
|
|
98
|
+
reminderFor,
|
|
99
|
+
resetMtimeCache,
|
|
100
|
+
shellReadTargets,
|
|
101
|
+
shouldBlock,
|
|
102
|
+
slackFinding,
|
|
103
|
+
unlockTokensFromQualifiedName,
|
|
104
|
+
unlockTokensFromText,
|
|
105
|
+
} from '../policy.js';
|
|
106
|
+
import { classify } from '../classifier.js';
|
|
107
|
+
|
|
108
|
+
const HERE = dirname(fileURLToPath(import.meta.url));
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* Where the policy JSON can live. Same two layouts the pi adapter supports, and
|
|
112
|
+
* the same silent failure if it is got wrong: a missing file means the gate
|
|
113
|
+
* falls back to fail-open, i.e. it looks installed and enforces nothing.
|
|
114
|
+
*
|
|
115
|
+
* repo checkout : bridge/gates/dsh/policy.json
|
|
116
|
+
* installed : <gate dir>/dsh/index.js + <gate dir>/policy.json
|
|
117
|
+
*/
|
|
118
|
+
export const policyCandidates = (here, explicit) =>
|
|
119
|
+
[explicit, join(here, 'policy.json'), join(here, '..', 'policy.json')].filter(Boolean);
|
|
120
|
+
|
|
121
|
+
export const firstExistingPolicy = (here, explicit, exists = existsSync) => {
|
|
122
|
+
for (const candidate of policyCandidates(here, explicit)) {
|
|
123
|
+
if (exists(candidate)) return candidate;
|
|
124
|
+
}
|
|
125
|
+
return null;
|
|
126
|
+
};
|
|
127
|
+
|
|
128
|
+
export const name = 'enforce-rules';
|
|
129
|
+
|
|
130
|
+
/** The full probe set the policy expects, not just `exists`. */
|
|
131
|
+
const realFs = {
|
|
132
|
+
exists: (p) => existsSync(p),
|
|
133
|
+
isFile: (p) => {
|
|
134
|
+
try {
|
|
135
|
+
return statSync(p).isFile();
|
|
136
|
+
} catch {
|
|
137
|
+
return false;
|
|
138
|
+
}
|
|
139
|
+
},
|
|
140
|
+
isDirectory: (p) => {
|
|
141
|
+
try {
|
|
142
|
+
return statSync(p).isDirectory();
|
|
143
|
+
} catch {
|
|
144
|
+
return false;
|
|
145
|
+
}
|
|
146
|
+
},
|
|
147
|
+
statMtime: (p) => {
|
|
148
|
+
try {
|
|
149
|
+
return statSync(p).mtimeMs;
|
|
150
|
+
} catch {
|
|
151
|
+
return 0;
|
|
152
|
+
}
|
|
153
|
+
},
|
|
154
|
+
listDir: (dir) => {
|
|
155
|
+
try {
|
|
156
|
+
return readdirSync(dir);
|
|
157
|
+
} catch {
|
|
158
|
+
return [];
|
|
159
|
+
}
|
|
160
|
+
},
|
|
161
|
+
readText: (p) => {
|
|
162
|
+
try {
|
|
163
|
+
return readFileSync(p, 'utf8');
|
|
164
|
+
} catch {
|
|
165
|
+
return null;
|
|
166
|
+
}
|
|
167
|
+
},
|
|
168
|
+
/**
|
|
169
|
+
* ADR-015: the directories this gate is made of, for `no-self-grant`. Same
|
|
170
|
+
* rule as the pi adapter - only an installed gate (`<gate dir>/dsh/index.js`
|
|
171
|
+
* beside `<gate dir>/policy.json`) is protected, never a checkout.
|
|
172
|
+
*/
|
|
173
|
+
gateDirs: [
|
|
174
|
+
existsSync(join(HERE, '..', 'policy.json')) ? dirname(HERE) : null,
|
|
175
|
+
machineGateConfigPath() ? dirname(machineGateConfigPath()) : null,
|
|
176
|
+
].filter(Boolean),
|
|
177
|
+
};
|
|
178
|
+
|
|
179
|
+
/** Graph-query tool names that satisfy the "ask the graph first" rule. */
|
|
180
|
+
const SIGNAL_TOOLS = [
|
|
181
|
+
'search_graph',
|
|
182
|
+
'trace_path',
|
|
183
|
+
'get_code_snippet',
|
|
184
|
+
'query_graph',
|
|
185
|
+
'get_architecture',
|
|
186
|
+
'search_code',
|
|
187
|
+
];
|
|
188
|
+
|
|
189
|
+
const WRITE_TOOLS = new Set(['write', 'edit', 'apply_patch', 'str_replace_editor', 'create_file', 'multi_edit']);
|
|
190
|
+
const READ_TOOLS = new Set(['read', 'read_file', 'view', 'open_file']);
|
|
191
|
+
/**
|
|
192
|
+
* Tool names that run a shell command.
|
|
193
|
+
*
|
|
194
|
+
* dsh names the shell tool per platform: the POSIX presets mount `tool-bash`
|
|
195
|
+
* (tool name `bash`) and the Windows preset mounts `tool-pwsh` (tool name
|
|
196
|
+
* `pwsh`). An exact `toolName === 'bash'` test therefore left
|
|
197
|
+
* `no-destructive-bash`, `bash-graph-before-read` and the AI4S script tracking
|
|
198
|
+
* completely inactive on Windows while the plugin still reported `active` — the
|
|
199
|
+
* "installed, running, enforcing nothing" failure mode.
|
|
200
|
+
*/
|
|
201
|
+
const SHELL_TOOLS = new Set(['bash', 'pwsh', 'shell']);
|
|
202
|
+
|
|
203
|
+
/**
|
|
204
|
+
* The dialect a shell command is written in.
|
|
205
|
+
*
|
|
206
|
+
* The policy parses `Get-Content x` and `cat x` with different parsers
|
|
207
|
+
* (`shellOf(input)`), and the dsh adapter never told it which one applies — so a
|
|
208
|
+
* PowerShell command was parsed as bash, where `Get-Content` is not a read verb.
|
|
209
|
+
* `pwsh` must therefore declare itself, exactly as the pi adapter does for its
|
|
210
|
+
* `powershell` tool.
|
|
211
|
+
*/
|
|
212
|
+
const shellDialect = (toolName) => (toolName === 'pwsh' || toolName === 'powershell' ? 'powershell' : 'bash');
|
|
213
|
+
|
|
214
|
+
const isSignalTool = (toolName) => SIGNAL_TOOLS.some((s) => toolName === s || toolName.endsWith(`_${s}`));
|
|
215
|
+
|
|
216
|
+
/** Read one field out of an `unknown` args object without trusting its shape. */
|
|
217
|
+
const str = (args, key) => {
|
|
218
|
+
if (args && typeof args === 'object' && typeof args[key] === 'string') return args[key];
|
|
219
|
+
return null;
|
|
220
|
+
};
|
|
221
|
+
|
|
222
|
+
const argPath = (args) => str(args, 'file_path') ?? str(args, 'path');
|
|
223
|
+
const argContent = (args) =>
|
|
224
|
+
['content', 'new_string', 'newText', 'patch', 'text']
|
|
225
|
+
.map((key) => str(args, key))
|
|
226
|
+
.find((value) => value !== null) ?? null;
|
|
227
|
+
|
|
228
|
+
/** All string leaves of a tool input, so a query's arguments become unlocks. */
|
|
229
|
+
const inputStrings = (value, out = []) => {
|
|
230
|
+
if (typeof value === 'string') out.push(value);
|
|
231
|
+
else if (Array.isArray(value)) for (const item of value) inputStrings(item, out);
|
|
232
|
+
else if (value && typeof value === 'object') for (const item of Object.values(value)) inputStrings(item, out);
|
|
233
|
+
return out;
|
|
234
|
+
};
|
|
235
|
+
|
|
236
|
+
/**
|
|
237
|
+
* Model-facing text of a settled tool result.
|
|
238
|
+
*
|
|
239
|
+
* `ToolExecutionResult` is `{ isError, content, value? }` (docs/subsystems/tools.md).
|
|
240
|
+
* Only `content` is the projection the model saw; `value` is execution-local and
|
|
241
|
+
* deliberately omitted from durable events, so evidence is judged on `content` —
|
|
242
|
+
* the thing the model actually learned from.
|
|
243
|
+
*/
|
|
244
|
+
const resultText = (result) => {
|
|
245
|
+
if (!result || typeof result !== 'object') return '';
|
|
246
|
+
const blocks = Array.isArray(result.content) ? result.content : [];
|
|
247
|
+
return blocks
|
|
248
|
+
.map((block) => (typeof block === 'string' ? block : typeof block?.text === 'string' ? block.text : ''))
|
|
249
|
+
.join('\n');
|
|
250
|
+
};
|
|
251
|
+
|
|
252
|
+
/**
|
|
253
|
+
* Visible assistant text carried by one `assistant/message` session event.
|
|
254
|
+
*
|
|
255
|
+
* The event wraps the model stream (`expandAssistantStream` is the typed reader,
|
|
256
|
+
* but `@deepseek-ai/dsh-llm` is not a declared dependency here). Rather than
|
|
257
|
+
* depend on an unowned package the adapter collects the visible text blocks by
|
|
258
|
+
* shape: only `text` / `text-delta` count, so reasoning content never satisfies
|
|
259
|
+
* the anti-slack rule. Bounded in depth and length so a pathological event
|
|
260
|
+
* cannot stall a turn boundary.
|
|
261
|
+
*/
|
|
262
|
+
const assistantTextOf = (event) => {
|
|
263
|
+
const parts = [];
|
|
264
|
+
let budget = 20000;
|
|
265
|
+
const walk = (value, depth) => {
|
|
266
|
+
if (budget <= 0 || depth > 8 || parts.length > 400) return;
|
|
267
|
+
if (Array.isArray(value)) {
|
|
268
|
+
for (const item of value) walk(item, depth + 1);
|
|
269
|
+
return;
|
|
270
|
+
}
|
|
271
|
+
if (!value || typeof value !== 'object') return;
|
|
272
|
+
const kind = value.type;
|
|
273
|
+
if ((kind === 'text' || kind === 'text-delta') && typeof value.text === 'string') {
|
|
274
|
+
parts.push(value.text);
|
|
275
|
+
budget -= value.text.length;
|
|
276
|
+
return;
|
|
277
|
+
}
|
|
278
|
+
for (const item of Object.values(value)) walk(item, depth + 1);
|
|
279
|
+
};
|
|
280
|
+
walk(event?.data, 0);
|
|
281
|
+
return parts.join('');
|
|
282
|
+
};
|
|
283
|
+
|
|
284
|
+
/** Concatenated text of the messages a pre-step has already claimed for entry. */
|
|
285
|
+
const messagesText = (messages) => {
|
|
286
|
+
if (!Array.isArray(messages)) return '';
|
|
287
|
+
const parts = [];
|
|
288
|
+
for (const message of messages) {
|
|
289
|
+
if (typeof message?.content === 'string') {
|
|
290
|
+
parts.push(message.content);
|
|
291
|
+
continue;
|
|
292
|
+
}
|
|
293
|
+
if (!Array.isArray(message?.content)) continue;
|
|
294
|
+
for (const block of message.content) {
|
|
295
|
+
if (typeof block === 'string') parts.push(block);
|
|
296
|
+
else if (block?.type === 'text' && typeof block.text === 'string') parts.push(block.text);
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
return parts.join('\n');
|
|
300
|
+
};
|
|
301
|
+
|
|
302
|
+
let messageSeq = 0;
|
|
303
|
+
const newMessageId = () => `enforce-rules-${Date.now().toString(36)}-${(messageSeq += 1).toString(36)}`;
|
|
304
|
+
|
|
305
|
+
/**
|
|
306
|
+
* Candidate `UserMessage` shapes for `agent.inject` / `agent.steer`.
|
|
307
|
+
*
|
|
308
|
+
* `session.md` says a message is "one identified, immutable role/source/content
|
|
309
|
+
* value", and `MessageSourceMap` is a merge-extensible sum type where "each
|
|
310
|
+
* producer declares its own kind" and consumers "fall through unknown kinds" —
|
|
311
|
+
* so `{ kind: 'enforce-rules' }` is the semantically correct source; the extra
|
|
312
|
+
* shapes exist only because the exact id requirement is not verifiable from the
|
|
313
|
+
* documents alone. First one that the harness accepts wins.
|
|
314
|
+
*/
|
|
315
|
+
const messageCandidates = (text) => [
|
|
316
|
+
{ role: 'user', messageId: newMessageId(), content: [{ type: 'text', text }], source: { kind: 'enforce-rules' } },
|
|
317
|
+
{ role: 'user', content: [{ type: 'text', text }], source: { kind: 'enforce-rules' } },
|
|
318
|
+
{ role: 'user', content: [{ type: 'text', text }], source: { kind: 'user' } },
|
|
319
|
+
];
|
|
320
|
+
|
|
321
|
+
/**
|
|
322
|
+
* Deliver one message through `agent[method]`, trying the documented shapes.
|
|
323
|
+
*
|
|
324
|
+
* Never throws: this runs inside `agent/turn-stopping`, which is awaited on the
|
|
325
|
+
* turn boundary — a throw there would fail the turn. Returning `false` lets the
|
|
326
|
+
* caller report that the gate could not act, which is the honest outcome.
|
|
327
|
+
*/
|
|
328
|
+
const deliver = (agent, method, text) => {
|
|
329
|
+
if (!agent || typeof agent[method] !== 'function' || typeof text !== 'string' || text === '') return false;
|
|
330
|
+
for (const message of messageCandidates(text)) {
|
|
331
|
+
try {
|
|
332
|
+
agent[method](message);
|
|
333
|
+
return true;
|
|
334
|
+
} catch {
|
|
335
|
+
// Try the next documented shape; report only if all of them fail.
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
return false;
|
|
339
|
+
};
|
|
340
|
+
|
|
341
|
+
export function apply(ctx, config = {}) {
|
|
342
|
+
// An inline `policy` object lets a host inject configuration; `policyPath`
|
|
343
|
+
// keeps the file-based route for real deployments.
|
|
344
|
+
const resolved =
|
|
345
|
+
typeof config.policyPath === 'string'
|
|
346
|
+
? config.policyPath
|
|
347
|
+
: firstExistingPolicy(HERE, null);
|
|
348
|
+
const loaded = config.policy
|
|
349
|
+
? policyFromObject(config.policy)
|
|
350
|
+
: resolved
|
|
351
|
+
? loadPolicy(resolved)
|
|
352
|
+
: {
|
|
353
|
+
ok: false,
|
|
354
|
+
error:
|
|
355
|
+
'no policy file found; looked in:\n' +
|
|
356
|
+
policyCandidates(HERE, null)
|
|
357
|
+
.map((c) => ` ${c}`)
|
|
358
|
+
.join('\n'),
|
|
359
|
+
};
|
|
360
|
+
const policy = applyMachineOverride(
|
|
361
|
+
loaded.ok
|
|
362
|
+
? loaded.policy
|
|
363
|
+
: {
|
|
364
|
+
name: 'enforce-rules',
|
|
365
|
+
version: 1,
|
|
366
|
+
description: 'fallback: policy unreadable, gate inactive',
|
|
367
|
+
reminded: '',
|
|
368
|
+
checks: [],
|
|
369
|
+
config: { max_blocks_per_session: 0, signal_ttl_ms: 0 },
|
|
370
|
+
},
|
|
371
|
+
);
|
|
372
|
+
|
|
373
|
+
if (!loaded.ok) {
|
|
374
|
+
// Fail open, loudly. A gate that bricks the agent because of a typo in a
|
|
375
|
+
// JSON file is worse than an unenforced rule — but a gate that is silently
|
|
376
|
+
// off is worse still, because everyone assumes it is working.
|
|
377
|
+
const message = `enforce-rules: DISABLED (${loaded.error})`;
|
|
378
|
+
ctx.logger?.warn?.(message);
|
|
379
|
+
process.stderr.write(`${message}\n`);
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
const state = newSessionState();
|
|
383
|
+
|
|
384
|
+
/**
|
|
385
|
+
* ADR-013: the destructive gate's mode is read from the same config both paths
|
|
386
|
+
* already share, so dsh needs no command channel to obey it. It does need to
|
|
387
|
+
* SAY it, because a silent bypass on this harness is invisible.
|
|
388
|
+
*/
|
|
389
|
+
if (isDestructiveBypass(policy.config, state)) {
|
|
390
|
+
const line =
|
|
391
|
+
'[enforce-rules] 破坏性命令 BYPASS 生效(全局):删除/git 重写/force push/DDL 等不再询问或拦截;' +
|
|
392
|
+
'红线(删 $HOME / 删 cwd / 含 .. / 磁盘格式化 / 裸设备写入 / 关机 / 受保护工作区里的 git 清场)仍然拦。' +
|
|
393
|
+
'其他门控规则不受影响。收回:编辑 policy.json 或机器本地 gate-policy.json。';
|
|
394
|
+
ctx.logger?.warn?.(line);
|
|
395
|
+
process.stderr.write(`${line}\n`);
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
/**
|
|
399
|
+
* ADR-015: an entry of the machine-local protected-worktree list that is
|
|
400
|
+
* being ignored protects nothing, and nothing else would ever say so. dsh has
|
|
401
|
+
* no session cwd at load time, so it cannot announce "you are standing in
|
|
402
|
+
* one" the way pi does; the refusal still applies to every command.
|
|
403
|
+
*/
|
|
404
|
+
for (const { entry, why } of machineProtectedListProblems()) {
|
|
405
|
+
const line =
|
|
406
|
+
`[enforce-rules] 受保护工作区清单有一项被忽略(${why}):${entry} —— 这个目录现在不受保护。` +
|
|
407
|
+
'改成绝对路径后重新加载。';
|
|
408
|
+
ctx.logger?.warn?.(line);
|
|
409
|
+
process.stderr.write(`${line}\n`);
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
/**
|
|
413
|
+
* v5: classify lazily, on the first tool event.
|
|
414
|
+
*
|
|
415
|
+
* Kept as a fallback for harness builds without `agent/pre-step`; when that
|
|
416
|
+
* hook is present the classification happens at the turn start with the real
|
|
417
|
+
* user prompt (see that listener), which is the accurate moment.
|
|
418
|
+
*/
|
|
419
|
+
let classified = false;
|
|
420
|
+
|
|
421
|
+
/** The last `agent/pre-step` prompt we classified, and the turn it belonged to. */
|
|
422
|
+
let lastPreStepKey = null;
|
|
423
|
+
|
|
424
|
+
/**
|
|
425
|
+
* The final assistant text of each session, folded incrementally.
|
|
426
|
+
*
|
|
427
|
+
* `agent/turn-stopping` receives `{agent, turn, signal}` only, so the text the
|
|
428
|
+
* anti-slack rule needs is not in the hook payload. `docs/subsystems/practices.md`
|
|
429
|
+
* forbids rescanning `session.events` on `session/event`, and an incremental
|
|
430
|
+
* fold is exactly the allowed alternative: one map write per assistant message.
|
|
431
|
+
*/
|
|
432
|
+
const lastAssistantText = new Map();
|
|
433
|
+
|
|
434
|
+
/**
|
|
435
|
+
* The directory this call's relative paths resolve against.
|
|
436
|
+
*
|
|
437
|
+
* `exec.cwd` is not part of dsh's `ToolExecution`, so the previous
|
|
438
|
+
* `process.cwd()` fallback judged every relative path against the directory
|
|
439
|
+
* the Desktop app was launched from — a different project than the Session's.
|
|
440
|
+
*/
|
|
441
|
+
const cwdOf = (exec) => {
|
|
442
|
+
if (typeof exec?.cwd === 'string' && exec.cwd) return exec.cwd;
|
|
443
|
+
const session = exec?.agent?.session;
|
|
444
|
+
const service = ctx.get?.('workingDirectory');
|
|
445
|
+
if (session !== undefined && service && typeof service.get === 'function') {
|
|
446
|
+
try {
|
|
447
|
+
const directory = service.get(session);
|
|
448
|
+
if (typeof directory === 'string' && directory) return directory;
|
|
449
|
+
} catch {
|
|
450
|
+
// A wrong cwd is worse than an explicit fallback: fall through.
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
if (typeof config.cwd === 'string' && config.cwd) return config.cwd;
|
|
454
|
+
return process.cwd();
|
|
455
|
+
};
|
|
456
|
+
|
|
457
|
+
/**
|
|
458
|
+
* Whether returning `ask` would actually reach a human.
|
|
459
|
+
*
|
|
460
|
+
* `PreToolDecision.ask` runs the call only after `ctx.approval` answers
|
|
461
|
+
* `allowed-once`; a `never` policy or a missing service means "deny". Turning
|
|
462
|
+
* every recoverable delete into a hard denial because approvals happen to be
|
|
463
|
+
* disabled is the "gate bricks the agent" failure this design avoids, so the
|
|
464
|
+
* question is only asked when it can be answered.
|
|
465
|
+
*/
|
|
466
|
+
const approvalUsable = (exec) => {
|
|
467
|
+
const service = ctx.get?.('approval');
|
|
468
|
+
const session = exec?.agent?.session;
|
|
469
|
+
if (!service || session === undefined || typeof service.effectivePolicy !== 'function') return false;
|
|
470
|
+
try {
|
|
471
|
+
return service.effectivePolicy(session) === 'ask';
|
|
472
|
+
} catch {
|
|
473
|
+
return false;
|
|
474
|
+
}
|
|
475
|
+
};
|
|
476
|
+
|
|
477
|
+
// -------------------------------------------------------------------------
|
|
478
|
+
// Turn boundary: fold the assistant text the anti-slack rule will read.
|
|
479
|
+
// -------------------------------------------------------------------------
|
|
480
|
+
ctx.on('session/event', (session, event) => {
|
|
481
|
+
try {
|
|
482
|
+
if (!event || event.type !== 'assistant/message') return;
|
|
483
|
+
const text = assistantTextOf(event);
|
|
484
|
+
if (text) lastAssistantText.set(session, text);
|
|
485
|
+
} catch {
|
|
486
|
+
// An observation listener must never break the session.
|
|
487
|
+
}
|
|
488
|
+
});
|
|
489
|
+
|
|
490
|
+
// -------------------------------------------------------------------------
|
|
491
|
+
// Turn start: turnStart, domain classification, per-turn reminder.
|
|
492
|
+
// -------------------------------------------------------------------------
|
|
493
|
+
ctx.on('agent/pre-step', async (payload, next) => {
|
|
494
|
+
try {
|
|
495
|
+
const agent = payload?.agent;
|
|
496
|
+
const cwd = cwdOf({ agent });
|
|
497
|
+
const turn = payload?.turn;
|
|
498
|
+
const key = `${cwd}\u0000${turn}`;
|
|
499
|
+
const firstOfTurn = key !== lastPreStepKey;
|
|
500
|
+
|
|
501
|
+
if (firstOfTurn) {
|
|
502
|
+
lastPreStepKey = key;
|
|
503
|
+
// A new turn is the boundary the output checks (W2) compare mtimes to.
|
|
504
|
+
state.turnStart = Date.now();
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
if (!classified) {
|
|
508
|
+
classified = true;
|
|
509
|
+
const result = await classify({
|
|
510
|
+
cwd,
|
|
511
|
+
prompt: messagesText(payload?.messages),
|
|
512
|
+
fs: realFs,
|
|
513
|
+
policy,
|
|
514
|
+
modelHint: typeof config.modelHint === 'function' ? config.modelHint : null,
|
|
515
|
+
});
|
|
516
|
+
state.profile = result.profile;
|
|
517
|
+
state.profileSource = result.source;
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
if (firstOfTurn) {
|
|
521
|
+
const reminder = reminderFor(policy, state);
|
|
522
|
+
if (reminder && !deliver(agent, 'inject', reminder)) {
|
|
523
|
+
process.stderr.write('[enforce-rules] 提醒注入失败:agent.inject 拒绝所有已知消息形状\n');
|
|
524
|
+
}
|
|
525
|
+
}
|
|
526
|
+
} catch (err) {
|
|
527
|
+
process.stderr.write(`[enforce-rules] agent/pre-step observer failed: ${err?.message ?? err}\n`);
|
|
528
|
+
}
|
|
529
|
+
return next();
|
|
530
|
+
});
|
|
531
|
+
|
|
532
|
+
// -------------------------------------------------------------------------
|
|
533
|
+
// Tool result: the only truthful source of "what the model learned".
|
|
534
|
+
// -------------------------------------------------------------------------
|
|
535
|
+
ctx.on('tools/result', (exec, result) => {
|
|
536
|
+
try {
|
|
537
|
+
const toolName = String(exec?.name ?? '');
|
|
538
|
+
const args = exec?.arguments;
|
|
539
|
+
const cwd = cwdOf(exec);
|
|
540
|
+
const command = str(args, 'command') ?? '';
|
|
541
|
+
const failed = result?.isError === true;
|
|
542
|
+
|
|
543
|
+
if (failed) {
|
|
544
|
+
// A failed shell command feeds the blind-retry rule. A failed graph query
|
|
545
|
+
// must not record a signal — the model has learned nothing yet.
|
|
546
|
+
if (SHELL_TOOLS.has(toolName)) recordCommandResult(state, command, true);
|
|
547
|
+
return;
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
// A successful read is evidence about the exact file, which is what Layer 0
|
|
551
|
+
// needs before an edit. Convention documents additionally satisfy the
|
|
552
|
+
// "project conventions" question.
|
|
553
|
+
const path = normalizePath(argPath(args), cwd);
|
|
554
|
+
if (READ_TOOLS.has(toolName) && path) {
|
|
555
|
+
recordInspection(state, path);
|
|
556
|
+
if (isConventionDoc(path, policy.config) || isChgContract(path, policy.config)) {
|
|
557
|
+
recordDocRead(state, path);
|
|
558
|
+
}
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
if (SHELL_TOOLS.has(toolName)) {
|
|
562
|
+
recordCommandResult(state, command, false);
|
|
563
|
+
const shell = shellDialect(toolName);
|
|
564
|
+
for (const target of shellReadTargets(
|
|
565
|
+
{ command, shell },
|
|
566
|
+
{ config: policy.config, cwd, isFile: realFs.isFile, exists: realFs.exists },
|
|
567
|
+
)) {
|
|
568
|
+
recordInspection(state, normalizePath(target));
|
|
569
|
+
}
|
|
570
|
+
// `cat CONTRIBUTING.md` satisfies the convention rule just like `read`.
|
|
571
|
+
for (const token of command.match(/"[^"]+"|'[^']+'|[^\s;&|]+/g) ?? []) {
|
|
572
|
+
const candidate = normalizePath(token.replace(/^["']|["']$/g, ''), cwd);
|
|
573
|
+
if (
|
|
574
|
+
candidate &&
|
|
575
|
+
(isConventionDoc(candidate, policy.config) || isChgContract(candidate, policy.config)) &&
|
|
576
|
+
realFs.isFile(candidate)
|
|
577
|
+
) {
|
|
578
|
+
recordDocRead(state, candidate);
|
|
579
|
+
}
|
|
580
|
+
}
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
// A successful index refresh is Layer-2 evidence that works even when the
|
|
584
|
+
// index lives in a global data directory (no repo-local marker). Re-indexing
|
|
585
|
+
// also changes a marker's mtime, so a cached value must be dropped.
|
|
586
|
+
if (/(?:^|_)index_repository$/.test(toolName) || /(?:^|_)detect_changes$/.test(toolName)) {
|
|
587
|
+
resetMtimeCache();
|
|
588
|
+
recordIndexRefresh(state);
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
if (!isSignalTool(toolName)) return;
|
|
592
|
+
|
|
593
|
+
// A successful call is not enough: an empty result ("total":0) used to buy
|
|
594
|
+
// a full read window without telling the model anything. Only evidence counts.
|
|
595
|
+
const body = resultText(result);
|
|
596
|
+
if (!graphResultIsEvidence(body, policy.config)) return;
|
|
597
|
+
|
|
598
|
+
const now = Date.now();
|
|
599
|
+
recordSignal(state, now);
|
|
600
|
+
// …and remember *what the query was about*: arguments plus the result text
|
|
601
|
+
// become scoped unlocks, so a query about one file never buys a free pass
|
|
602
|
+
// for the whole repository.
|
|
603
|
+
recordUnlocks(state, unlockTokensFromText(inputStrings(args).join('\n')), now);
|
|
604
|
+
if (typeof args?.qualified_name === 'string') {
|
|
605
|
+
recordUnlocks(state, unlockTokensFromQualifiedName(args.qualified_name), now);
|
|
606
|
+
}
|
|
607
|
+
recordUnlocks(state, unlockTokensFromText(body), now);
|
|
608
|
+
} catch (err) {
|
|
609
|
+
process.stderr.write(`[enforce-rules] tools/result observer failed: ${err?.message ?? err}\n`);
|
|
610
|
+
}
|
|
611
|
+
});
|
|
612
|
+
|
|
613
|
+
// -------------------------------------------------------------------------
|
|
614
|
+
// Turn close: the anti-slack gate. A promise is not a delivery.
|
|
615
|
+
// -------------------------------------------------------------------------
|
|
616
|
+
ctx.on('agent/turn-stopping', async (payload) => {
|
|
617
|
+
try {
|
|
618
|
+
const max = policy.config.slack_max_continues ?? 0;
|
|
619
|
+
if (max <= 0 || state.slackContinues >= max) return;
|
|
620
|
+
|
|
621
|
+
const agent = payload?.agent;
|
|
622
|
+
if (!agent || typeof agent.steer !== 'function') return;
|
|
623
|
+
|
|
624
|
+
const effective = profilePolicy(policy, state.profile);
|
|
625
|
+
|
|
626
|
+
// AI4S output artifacts (W4 log file / W2 result README). Both are
|
|
627
|
+
// discovered after the computation has finished, and one more turn is
|
|
628
|
+
// enough to fix them — `outputArtifactFindings` returns [] for a
|
|
629
|
+
// general-dev session, so ordinary work pays one Map lookup.
|
|
630
|
+
const artifacts = outputArtifactFindings({
|
|
631
|
+
policy: effective,
|
|
632
|
+
state,
|
|
633
|
+
fs: realFs,
|
|
634
|
+
cwd: cwdOf({ agent }),
|
|
635
|
+
});
|
|
636
|
+
if (artifacts.length > 0) {
|
|
637
|
+
if (deliver(agent, 'steer', artifacts.map((f) => f.reason).join('\n\n'))) {
|
|
638
|
+
state.slackContinues += 1;
|
|
639
|
+
} else {
|
|
640
|
+
process.stderr.write('[enforce-rules] AI4S 产出物缺失,但 agent.steer 不可用,本轮放弃续跑\n');
|
|
641
|
+
}
|
|
642
|
+
return;
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
if (policy.config.slack_check === false) return;
|
|
646
|
+
|
|
647
|
+
const text = lastAssistantText.get(agent.session);
|
|
648
|
+
if (!text) return;
|
|
649
|
+
const finding = slackFinding(text, policy.config);
|
|
650
|
+
if (!finding) return;
|
|
651
|
+
|
|
652
|
+
if (deliver(agent, 'steer', finding.reason)) {
|
|
653
|
+
state.slackContinues += 1;
|
|
654
|
+
} else {
|
|
655
|
+
process.stderr.write('[enforce-rules] 检测到拖延承诺,但 agent.steer 不可用,本轮放弃续跑\n');
|
|
656
|
+
}
|
|
657
|
+
} catch (err) {
|
|
658
|
+
// `agent/turn-stopping` is awaited on the boundary: never throw from here.
|
|
659
|
+
process.stderr.write(`[enforce-rules] agent/turn-stopping observer failed: ${err?.message ?? err}\n`);
|
|
660
|
+
}
|
|
661
|
+
});
|
|
662
|
+
|
|
663
|
+
// -------------------------------------------------------------------------
|
|
664
|
+
// Pre-execute: allow / deny / ask. Never records a graph signal.
|
|
665
|
+
// -------------------------------------------------------------------------
|
|
666
|
+
ctx.on('tools/pre-execute', async (exec, next) => {
|
|
667
|
+
const toolName = String(exec?.name ?? '');
|
|
668
|
+
const args = exec?.arguments;
|
|
669
|
+
const cwd = cwdOf(exec);
|
|
670
|
+
|
|
671
|
+
if (!classified) {
|
|
672
|
+
// Fallback only: `agent/pre-step` normally classifies with the real prompt
|
|
673
|
+
// before any tool runs. This keeps the profile sane on builds without it.
|
|
674
|
+
classified = true;
|
|
675
|
+
const result = await classify({
|
|
676
|
+
cwd,
|
|
677
|
+
prompt: '',
|
|
678
|
+
fs: realFs,
|
|
679
|
+
policy,
|
|
680
|
+
modelHint: typeof config.modelHint === 'function' ? config.modelHint : null,
|
|
681
|
+
});
|
|
682
|
+
state.profile = result.profile;
|
|
683
|
+
state.profileSource = result.source;
|
|
684
|
+
}
|
|
685
|
+
|
|
686
|
+
const effective = profilePolicy(policy, state.profile);
|
|
687
|
+
|
|
688
|
+
if (WRITE_TOOLS.has(toolName)) {
|
|
689
|
+
const path = normalizePath(argPath(args), cwd);
|
|
690
|
+
const verdict = shouldBlock({
|
|
691
|
+
policy: effective,
|
|
692
|
+
input: { action: 'write', path, tool: toolName, content: argContent(args) },
|
|
693
|
+
state,
|
|
694
|
+
fs: realFs,
|
|
695
|
+
});
|
|
696
|
+
if (verdict.block) return { kind: 'deny', reason: verdict.reason };
|
|
697
|
+
// Record only after the gate allows: a blocked write is not a file this
|
|
698
|
+
// session may later read back freely.
|
|
699
|
+
recordWrite(state, path);
|
|
700
|
+
recordInvestigation(state);
|
|
701
|
+
return next();
|
|
702
|
+
}
|
|
703
|
+
|
|
704
|
+
if (READ_TOOLS.has(toolName)) {
|
|
705
|
+
const path = normalizePath(argPath(args), cwd);
|
|
706
|
+
const verdict = shouldBlock({
|
|
707
|
+
policy: effective,
|
|
708
|
+
input: { action: 'read', path, tool: toolName },
|
|
709
|
+
state,
|
|
710
|
+
fs: realFs,
|
|
711
|
+
});
|
|
712
|
+
if (verdict.block) return { kind: 'deny', reason: verdict.reason };
|
|
713
|
+
// Layer 0 only: "did this session read before editing". Recorded at
|
|
714
|
+
// admission on purpose — a file the gate let through has been inspected
|
|
715
|
+
// for the purposes of the edit rule, and keeping it here means Layer 0
|
|
716
|
+
// still works if the result hook is ever unavailable. Layer 1 (the graph
|
|
717
|
+
//通行证) is NOT recorded here; see `tools/result`.
|
|
718
|
+
recordInspection(state, path);
|
|
719
|
+
return next();
|
|
720
|
+
}
|
|
721
|
+
|
|
722
|
+
if (SHELL_TOOLS.has(toolName)) {
|
|
723
|
+
const command = str(args, 'command') ?? '';
|
|
724
|
+
const verdict = shouldBlock({
|
|
725
|
+
policy: effective,
|
|
726
|
+
input: { action: 'bash', path: null, tool: toolName, command, cwd, shell: shellDialect(toolName) },
|
|
727
|
+
state,
|
|
728
|
+
fs: realFs,
|
|
729
|
+
});
|
|
730
|
+
if (verdict.block) return { kind: 'deny', reason: verdict.reason };
|
|
731
|
+
|
|
732
|
+
// Three-tier destructive policy (CHG-20261105): a `confirm` finding is not
|
|
733
|
+
// a refusal. dsh can ask — `{kind:'ask'}` routes through `ctx.approval` —
|
|
734
|
+
// but only when an approval channel can actually answer; otherwise the
|
|
735
|
+
// call proceeds exactly as before and says so on stderr. That keeps a
|
|
736
|
+
// recoverable delete working in headless/unattended runs without
|
|
737
|
+
// pretending it was reviewed. The `high` tier above still denies.
|
|
738
|
+
if (verdict.confirm) {
|
|
739
|
+
const why = verdict.confirmReason ?? '破坏性命令需要确认';
|
|
740
|
+
if (approvalUsable(exec)) {
|
|
741
|
+
return { kind: 'ask', reason: why, displayReason: { en: why, 'zh-CN': why } };
|
|
742
|
+
}
|
|
743
|
+
process.stderr.write(
|
|
744
|
+
`[enforce-rules] DESTRUCTIVE_CONFIRM auto-approved (no approval channel): ${command.slice(0, 200)}\n`,
|
|
745
|
+
);
|
|
746
|
+
}
|
|
747
|
+
|
|
748
|
+
// AI4S: remember the script this call runs (W1 first-run test, W4 log date).
|
|
749
|
+
for (const script of analysisScriptTargets(command, {
|
|
750
|
+
config: effective.config,
|
|
751
|
+
cwd,
|
|
752
|
+
isFile: realFs.isFile,
|
|
753
|
+
})) {
|
|
754
|
+
recordScriptRun(state, script);
|
|
755
|
+
}
|
|
756
|
+
return next();
|
|
757
|
+
}
|
|
758
|
+
|
|
759
|
+
// NOTE: a graph query is deliberately NOT recorded here. `recordSignal` now
|
|
760
|
+
// lives in the `tools/result` listener, where the outcome can be judged — an
|
|
761
|
+
// admission-time signal lets `{"total":0}` buy a read window, which is the
|
|
762
|
+
// hole ADR-006 recorded.
|
|
763
|
+
return next();
|
|
764
|
+
});
|
|
765
|
+
}
|
|
766
|
+
|
|
767
|
+
export const inject = ['tools'];
|