dsh-clear-debug 0.0.0-stage → 0.1.0
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 +64 -2
- package/cordis.patch.yml +3 -0
- package/docs/DETAIL.md +184 -0
- package/icon.svg +6 -0
- package/index.js +872 -0
- package/lib/checks.js +322 -0
- package/lib/config.js +37 -0
- package/lib/fingerprint.js +127 -0
- package/lib/gate.js +71 -0
- package/lib/invariants.js +231 -0
- package/lib/paths.js +101 -0
- package/lib/scope-store.js +205 -0
- package/lib/session.js +114 -0
- package/lib/site-history.js +63 -0
- package/locale/en.json +7 -0
- package/locale/zh.json +7 -0
- package/package.json +56 -3
package/index.js
ADDED
|
@@ -0,0 +1,872 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Change scope.
|
|
3
|
+
*
|
|
4
|
+
* One rule: a declaration must exist before a source edit, and every edit must
|
|
5
|
+
* fall inside it. The declaration records why the scope is sufficient, who
|
|
6
|
+
* authorized it, and which depth applies; the gate enforces the targets. On
|
|
7
|
+
* closure the plugin compares each touched file's public surface against the
|
|
8
|
+
* snapshot taken just before its first edit, so a claim of "rewrite" that
|
|
9
|
+
* changed nothing structural, or a "fix" that only added conditionals, has to
|
|
10
|
+
* be acknowledged rather than silently passed.
|
|
11
|
+
*
|
|
12
|
+
* State lives in memory, keyed by agent session. It is a derived cache: the
|
|
13
|
+
* declaration is announced in the conversation by the tool call itself, so a
|
|
14
|
+
* resumed session can re-declare cheaply. Nothing here is durable truth.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import { promises as fsp } from 'node:fs';
|
|
18
|
+
import { join } from 'node:path';
|
|
19
|
+
import { clip, readInvariantStore, renderInvariants, writeInvariantStore, upsertInvariant, verifyInvariants, INVARIANTS_RELATIVE, INVARIANTS_JSON } from './lib/invariants.js';
|
|
20
|
+
import { identicalCause, askedBeforeDeclare, askedBeforeClose, evidenceInLog } from './lib/session.js';
|
|
21
|
+
import { DEFAULTS as DEFAULT_SETTINGS, applyConfig, settings } from './lib/config.js';
|
|
22
|
+
import Schema from '@deepseek-ai/schemastery';
|
|
23
|
+
import { recordFixed, recordRefuted, siteHistory, fileOf } from './lib/site-history.js';
|
|
24
|
+
import { normPath, isAbsolutePath, extensionOf, relativeToRoot, matchesPattern, matchesTargets, isAlwaysWritable, isGatedPath } from './lib/paths.js';
|
|
25
|
+
import { branchTotal, fingerprint, setDelta, readText, snapshotBefore } from './lib/fingerprint.js';
|
|
26
|
+
import { gate } from './lib/gate.js';
|
|
27
|
+
import { requireField, normalizeObservation, normalizeCause, escapeRegExp, normalizeRetained, normalizeVerification, parseSite, checkSite, siteInAny, evidenceFindings, discardFindings, finding, structuralReport, formatDelta, formatFindings } from './lib/checks.js';
|
|
28
|
+
import { scopes, describeTargets, emptyScope, publicView, saveScope, resolveScope, requireString, optionalStringArray, requireEnum, sessionOf, workingDirectoryOf, MODES, DEPTHS, AUTHORIZATIONS } from './lib/scope-store.js';
|
|
29
|
+
|
|
30
|
+
const TOOL_NAME = 'change_scope';
|
|
31
|
+
const LEDGER_RELATIVE = '.dsh/ledger.json';
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
// Paths written through DSH's own filesystem service, with the time seen. A
|
|
35
|
+
// change with no entry here never passed through DSH at all — an editor, an
|
|
36
|
+
// external script, or a shell command — which is the only attribution available.
|
|
37
|
+
const serviceWrites = new Map();
|
|
38
|
+
|
|
39
|
+
function noteServiceWrite(target) {
|
|
40
|
+
const path = typeof target === 'string'
|
|
41
|
+
? target
|
|
42
|
+
: (target?.path ?? target?.filePath ?? target?.name);
|
|
43
|
+
if (typeof path === 'string' && path !== '') {
|
|
44
|
+
serviceWrites.set(normPath(path).toLowerCase(), Date.now());
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const PROTOCOL = `## Change scope protocol
|
|
49
|
+
|
|
50
|
+
When the user reports a bug symptom, or asks to rewrite or replace part of the code, investigate before editing, and record a scope before the first source edit.
|
|
51
|
+
|
|
52
|
+
1. Investigate first. For a bug, locate the first point where observed state departs from the state the code intends, then name the defect class that point belongs to. For a rewrite, derive the new contract and boundaries without using the current implementation as a reason. Only then do you know the minimal sufficient scope.
|
|
53
|
+
2. Confirm the route with the user as an actual question — the cause you believe, the files it would touch, and whether that matches what they see — then ask for a depth, described as consequences rather than abstract sizes: what stays untouched, which callers change, whether old and new coexist. \`deep\` is a commitment, not a stricter checkbox: it requires the cause dossier below, and it means you stop looking for the smallest change that silences the symptom. \`quick\` is only for a single-point, single-file change whose complete causal chain you can state now.
|
|
54
|
+
3. Call \`change_scope\` with action "declare". Its \`targets\` are the files you may edit; the gate denies \`edit\` and \`write\` outside them.
|
|
55
|
+
4. A deep fix must also carry \`observation\`: the step that reproduces the symptom, the value the code intends at the divergence, the value it actually produces, and the site. The expectation is frozen there and cannot be revised afterwards. \`expected\` and \`actual\` must differ, the site must exist, and the site must lie inside \`targets\` — a scope cannot explain a place it is not allowed to change, and \`revise\` may not detach the two.
|
|
56
|
+
5. A deep fix or rewrite must carry \`cause\` as well: the contract that should always be true at the divergence (or the new contract, for a rewrite), the defect class that point belongs to, and \`sweep\` — at least one other place that class could live, each with a verdict. This is the pivot: without it, \`deep\` is only a stricter gate on the same patching strategy.
|
|
57
|
+
6. A deep rewrite must also declare \`discard\`: what must no longer exist afterwards. At close each identifier in \`discard\` is searched in the files you touched; one that is still there is refused unless you list it in \`retained\` with the reason it stayed. A rewrite is a claim about what disappears, not a claim about what you looked at.
|
|
58
|
+
7. When an observation contradicts your diagnosis, do not patch around it: call \`change_scope\` with action "rediagnose", carrying \`reason\` (what the old cause got wrong), \`evidence\` (the observation that contradicts it), and the replacement \`cause\`. The gate records the refutation and keeps the symptom observation frozen. Re-diagnosing is a step forward, not a failed fix.
|
|
59
|
+
8. Never widen the scope silently. If the authorized boundary cannot hold the cause, say so and call \`change_scope\` with action "revise".
|
|
60
|
+
9. Before closing, ask the user once whether the result matches what they actually see. Then call \`change_scope\` with action "close", carrying \`verification\` — the same step again, with what it now produces — and the single invariant the fix established. An invariant nothing can check is a comment: prefer one a test, a type, or an assertion can hold.
|
|
61
|
+
|
|
62
|
+
Close refuses when the shape contradicts the declared mode (a rewrite that moved no export and no exported signature; a fix that only added conditionals without moving a contract; a file edited outside the targets), and when the verification is missing, uses a different step than the observation, or reports something other than the frozen expectation. Refusal is not a verdict: call close again with \`acknowledge\` listing the codes and an \`acknowledgeReason\` saying what you actually did and why.
|
|
63
|
+
|
|
64
|
+
A declaration is not a plan and not a restatement of the request. It names the smallest set of files whose change removes the cause, and states why that set is sufficient.`;
|
|
65
|
+
|
|
66
|
+
// ---------------------------------------------------------------------------
|
|
67
|
+
// Paths
|
|
68
|
+
|
|
69
|
+
async function recordFindings(root, scope, findings) {
|
|
70
|
+
if (!root) return [];
|
|
71
|
+
const path = join(root, LEDGER_RELATIVE);
|
|
72
|
+
let entries = [];
|
|
73
|
+
try {
|
|
74
|
+
const parsed = JSON.parse(await fsp.readFile(path, 'utf8'));
|
|
75
|
+
if (Array.isArray(parsed)) entries = parsed;
|
|
76
|
+
} catch {
|
|
77
|
+
entries = [];
|
|
78
|
+
}
|
|
79
|
+
const cutoff = Date.now() - settings().ledgerMaxAgeDays * 86400000;
|
|
80
|
+
entries = entries.filter(entry => typeof entry.at === 'number' && entry.at >= cutoff);
|
|
81
|
+
const at = Date.now();
|
|
82
|
+
for (const item of findings) {
|
|
83
|
+
entries.push({ at, code: item.code, site: item.file ?? '(scope)', severity: item.severity, mode: scope.mode, depth: scope.depth });
|
|
84
|
+
}
|
|
85
|
+
if (scope.depth === 'quick') {
|
|
86
|
+
entries.push({ at, code: 'quick_scope', site: scope.targets[0] ?? '(scope)', severity: 'info', mode: scope.mode, depth: 'quick' });
|
|
87
|
+
}
|
|
88
|
+
try {
|
|
89
|
+
await fsp.mkdir(join(root, '.dsh'), { recursive: true });
|
|
90
|
+
await fsp.writeFile(path, `${JSON.stringify(entries, null, 2)}\n`, 'utf8');
|
|
91
|
+
} catch {
|
|
92
|
+
return [];
|
|
93
|
+
}
|
|
94
|
+
const counts = new Map();
|
|
95
|
+
for (const entry of entries) {
|
|
96
|
+
const key = `${entry.code}|${entry.site}`;
|
|
97
|
+
counts.set(key, (counts.get(key) ?? 0) + 1);
|
|
98
|
+
}
|
|
99
|
+
return [...counts.entries()]
|
|
100
|
+
.filter(([, count]) => count >= settings().ledgerRepeatThreshold)
|
|
101
|
+
.map(([key, count]) => {
|
|
102
|
+
const [code, site] = key.split('|');
|
|
103
|
+
return { code, site, count };
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
// ---------------------------------------------------------------------------
|
|
108
|
+
// Tool
|
|
109
|
+
|
|
110
|
+
async function runGitLog(subprocess, root, file) {
|
|
111
|
+
const executable = await subprocess.resolveExecutable('git');
|
|
112
|
+
const controller = new AbortController();
|
|
113
|
+
const timer = setTimeout(() => controller.abort(), 5000);
|
|
114
|
+
try {
|
|
115
|
+
const handle = subprocess.spawn({
|
|
116
|
+
argv: [executable, 'log', '--oneline', '-5', '--', file],
|
|
117
|
+
cwd: root,
|
|
118
|
+
stdio: { stdin: 'ignore', stdout: { maxBytes: 20000 }, stderr: { maxBytes: 20000 } },
|
|
119
|
+
graceMs: 1000,
|
|
120
|
+
signal: controller.signal,
|
|
121
|
+
});
|
|
122
|
+
const outcome = await handle.done;
|
|
123
|
+
if (outcome.exitCode !== 0) return [];
|
|
124
|
+
const text = handle.collected?.stdout?.readFrom(0)?.text ?? '';
|
|
125
|
+
return text.split(/\r?\n/).map(line => line.trim()).filter(Boolean).slice(0, 5);
|
|
126
|
+
} finally {
|
|
127
|
+
clearTimeout(timer);
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
async function briefSite(ctx, root, site) {
|
|
132
|
+
if (!root || !site) return null;
|
|
133
|
+
const file = fileOf(site);
|
|
134
|
+
const history = await siteHistory(root, site);
|
|
135
|
+
const store = await readInvariantStore(root);
|
|
136
|
+
const invariants = store
|
|
137
|
+
.filter(entry => entry.status === 'active'
|
|
138
|
+
&& ((entry.statement ?? '').toLowerCase().includes(file)
|
|
139
|
+
|| (entry.why ?? '').toLowerCase().includes(file)))
|
|
140
|
+
.map(entry => ({ key: entry.key, statement: entry.statement, check: entry.check ?? null }));
|
|
141
|
+
let commits = null;
|
|
142
|
+
let gitNote = null;
|
|
143
|
+
const subprocess = ctx.get?.('subprocess');
|
|
144
|
+
let isRepo = false;
|
|
145
|
+
try {
|
|
146
|
+
await fsp.stat(join(root, '.git'));
|
|
147
|
+
isRepo = true;
|
|
148
|
+
} catch {
|
|
149
|
+
isRepo = false;
|
|
150
|
+
}
|
|
151
|
+
if (!subprocess?.spawn) {
|
|
152
|
+
gitNote = 'the subprocess service is unavailable, so recent commits were not read';
|
|
153
|
+
} else if (!isRepo) {
|
|
154
|
+
gitNote = 'this workspace is not a git repository, so there is no commit history to read';
|
|
155
|
+
} else {
|
|
156
|
+
try {
|
|
157
|
+
commits = await runGitLog(subprocess, root, file);
|
|
158
|
+
if (commits.length === 0) gitNote = 'no commits touch this file, or it is not tracked';
|
|
159
|
+
} catch (error) {
|
|
160
|
+
commits = [];
|
|
161
|
+
gitNote = clip(String(error?.message ?? error));
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
return {
|
|
165
|
+
file,
|
|
166
|
+
attributed: history?.attributed ?? 0,
|
|
167
|
+
refuted: (history?.refuted ?? []).slice(-3),
|
|
168
|
+
fixed: (history?.fixed ?? []).slice(-3),
|
|
169
|
+
invariants,
|
|
170
|
+
hint: invariants.length > 0
|
|
171
|
+
? 'Active invariants already constrain this file; a diagnosis that contradicts one is probably wrong.'
|
|
172
|
+
: null,
|
|
173
|
+
commits,
|
|
174
|
+
gitNote,
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
function buildTool(ctx) {
|
|
179
|
+
return {
|
|
180
|
+
name: TOOL_NAME,
|
|
181
|
+
description:
|
|
182
|
+
'Declare, revise, inspect, or close the authorized scope of a code change. '
|
|
183
|
+
+ 'Call it with action "declare" after investigating and before the first source edit; '
|
|
184
|
+
+ 'its targets are the only files the edit gate accepts. Call action "close" when the '
|
|
185
|
+
+ 'change is complete, carrying the one invariant the fix established, which this tool '
|
|
186
|
+
+ 'appends to docs/INVARIANTS.md. Close also compares each touched file with its state '
|
|
187
|
+
+ 'before your first edit and refuses a shape that contradicts the declared mode — a '
|
|
188
|
+
+ 'rewrite with an unchanged public surface, or a fix that only added conditionals. '
|
|
189
|
+
+ 'A deep fix must carry observation at declare and verification at close: the expectation is '
|
|
190
|
+
+ 'frozen before the fix and compared with what the same step produces afterwards. '
|
|
191
|
+
+ 'Pass acknowledge with the reported codes and acknowledgeReason to proceed deliberately.',
|
|
192
|
+
parameters: {
|
|
193
|
+
type: 'object',
|
|
194
|
+
additionalProperties: false,
|
|
195
|
+
required: ['action'],
|
|
196
|
+
properties: {
|
|
197
|
+
action: {
|
|
198
|
+
type: 'string',
|
|
199
|
+
enum: ['declare', 'revise', 'rediagnose', 'status', 'verify', 'close'],
|
|
200
|
+
description:
|
|
201
|
+
'declare: record a new scope. revise: replace fields of the active scope. '
|
|
202
|
+
+ 'rediagnose: refute the current cause with contradicting evidence and replace it — '
|
|
203
|
+
+ 'this is a first-class step, not a failed patch. status: read the active scope and '
|
|
204
|
+
+ 'its findings. verify: run every executable invariant check and record the result. '
|
|
205
|
+
+ 'close: end it, check the change shape, and sediment its invariant.',
|
|
206
|
+
},
|
|
207
|
+
mode: {
|
|
208
|
+
type: 'string',
|
|
209
|
+
enum: MODES,
|
|
210
|
+
description: 'fix: a defect. rewrite: replacing part of the code. feature: new behavior.',
|
|
211
|
+
},
|
|
212
|
+
depth: {
|
|
213
|
+
type: 'string',
|
|
214
|
+
enum: DEPTHS,
|
|
215
|
+
description:
|
|
216
|
+
'deep: the gate enforces the targets and the close check blocks. quick: for a '
|
|
217
|
+
+ 'single-point, single-file change whose full causal chain you can state now; it '
|
|
218
|
+
+ 'records and warns but does not block.',
|
|
219
|
+
},
|
|
220
|
+
necessity: {
|
|
221
|
+
type: 'string',
|
|
222
|
+
description:
|
|
223
|
+
'Why this target set is the minimal sufficient scope: the first point where state '
|
|
224
|
+
+ 'departs from intent (for a fix), or the new contract and boundaries (for a rewrite).',
|
|
225
|
+
},
|
|
226
|
+
authorization: {
|
|
227
|
+
type: 'string',
|
|
228
|
+
enum: AUTHORIZATIONS,
|
|
229
|
+
description: 'user: the user authorized this scope. assumed: you chose it because the user declined to decide.',
|
|
230
|
+
},
|
|
231
|
+
targets: {
|
|
232
|
+
type: 'array',
|
|
233
|
+
items: { type: 'string' },
|
|
234
|
+
description: 'Workspace-relative file globs the change may edit, such as "src/parser/**" or "src/store.ts". When an observation is declared, its site must fall inside these.',
|
|
235
|
+
},
|
|
236
|
+
contracts: {
|
|
237
|
+
type: 'array',
|
|
238
|
+
items: { type: 'string' },
|
|
239
|
+
description: 'Contracts this change may alter, such as a type, an invariant, or a function signature. Moving an export without naming one here is refused at close.',
|
|
240
|
+
},
|
|
241
|
+
excluded: {
|
|
242
|
+
type: 'array',
|
|
243
|
+
items: { type: 'string' },
|
|
244
|
+
description: 'Paths deliberately left untouched; editing one is reported at close.',
|
|
245
|
+
},
|
|
246
|
+
invariant: {
|
|
247
|
+
type: 'string',
|
|
248
|
+
description: 'On close: the one invariant the change established, phrased so a test, type, or assertion can check it.',
|
|
249
|
+
},
|
|
250
|
+
invariantKey: {
|
|
251
|
+
type: 'string',
|
|
252
|
+
description: 'On close: the stable key of this invariant. Reusing a key replaces the earlier entry instead of appending; it defaults to the contract in cause, slugified.',
|
|
253
|
+
},
|
|
254
|
+
invariantCheck: {
|
|
255
|
+
type: 'string',
|
|
256
|
+
description: 'On close: the command, test, or assertion that would fail if this invariant broke. Without it the entry is recorded as low trust.',
|
|
257
|
+
},
|
|
258
|
+
reason: {
|
|
259
|
+
type: 'string',
|
|
260
|
+
description: 'On close: why no invariant could be established, for example a containment change whose cause is upstream.',
|
|
261
|
+
},
|
|
262
|
+
cause: {
|
|
263
|
+
type: 'object',
|
|
264
|
+
additionalProperties: false,
|
|
265
|
+
required: ['contract', 'class', 'sweep'],
|
|
266
|
+
description:
|
|
267
|
+
'On declare, required for a deep fix: the pivot from patching to root-cause work. Name the contract '
|
|
268
|
+
+ 'that broke, the defect class it belongs to, and where else that class could live. Without it, '
|
|
269
|
+
+ '"deep" is only a stricter gate on the same patching strategy.',
|
|
270
|
+
properties: {
|
|
271
|
+
contract: { type: 'string', description: 'What should always be true at the divergence: the contract that was violated.' },
|
|
272
|
+
class: { type: 'string', description: 'The defect class this cause belongs to, such as "cross-module contract drift".' },
|
|
273
|
+
sweep: {
|
|
274
|
+
type: 'array',
|
|
275
|
+
description: 'At least one other place the class could appear, each with a verdict. A single entry is allowed only if it says why the class is contained.',
|
|
276
|
+
items: {
|
|
277
|
+
type: 'object',
|
|
278
|
+
additionalProperties: false,
|
|
279
|
+
required: ['site', 'verdict'],
|
|
280
|
+
properties: {
|
|
281
|
+
site: { type: 'string', description: 'A path, a module, a caller, or a search pattern.' },
|
|
282
|
+
verdict: { type: 'string', description: 'Why it is the same class, or why it is safe.' },
|
|
283
|
+
},
|
|
284
|
+
},
|
|
285
|
+
},
|
|
286
|
+
},
|
|
287
|
+
},
|
|
288
|
+
discard: {
|
|
289
|
+
type: 'array',
|
|
290
|
+
items: { type: 'string' },
|
|
291
|
+
description:
|
|
292
|
+
'On declare, required for a deep rewrite: what must no longer exist afterwards — symbols you are '
|
|
293
|
+
+ 'deleting, behaviors you are replacing. Identifiers are searched in the touched files at close; '
|
|
294
|
+
+ 'one that is still there is refused unless it is listed in retained with a reason.',
|
|
295
|
+
},
|
|
296
|
+
retained: {
|
|
297
|
+
type: 'array',
|
|
298
|
+
items: {
|
|
299
|
+
type: 'object',
|
|
300
|
+
additionalProperties: false,
|
|
301
|
+
required: ['item', 'why'],
|
|
302
|
+
properties: {
|
|
303
|
+
item: { type: 'string', description: 'A discard entry that was deliberately kept.' },
|
|
304
|
+
why: { type: 'string', description: 'Why it had to stay.' },
|
|
305
|
+
},
|
|
306
|
+
},
|
|
307
|
+
description: 'On close: discards you deliberately kept, each with its reason.',
|
|
308
|
+
},
|
|
309
|
+
observation: {
|
|
310
|
+
type: 'object',
|
|
311
|
+
additionalProperties: false,
|
|
312
|
+
required: ['command', 'expected', 'actual', 'site'],
|
|
313
|
+
description:
|
|
314
|
+
'On declare, required for a deep fix: the step that reproduces the symptom, the value the code '
|
|
315
|
+
+ 'intends, the value it actually produces, and where the divergence is visible. expected and '
|
|
316
|
+
+ 'actual must differ, the site must exist, and the expectation is frozen — revise cannot change it.',
|
|
317
|
+
properties: {
|
|
318
|
+
command: { type: 'string', description: 'The step that reproduces the symptom, preferably an executable command.' },
|
|
319
|
+
expected: { type: 'string', description: 'What the code intends to produce at the site.' },
|
|
320
|
+
actual: { type: 'string', description: 'What it actually produces now. Must differ from expected.' },
|
|
321
|
+
site: { type: 'string', description: 'Where the divergence is visible, as "path" or "path:line", relative to the workspace. It must exist and must fall inside targets.' },
|
|
322
|
+
},
|
|
323
|
+
},
|
|
324
|
+
evidence: {
|
|
325
|
+
type: 'object',
|
|
326
|
+
additionalProperties: false,
|
|
327
|
+
required: ['command', 'expected', 'actual', 'site'],
|
|
328
|
+
description:
|
|
329
|
+
'On rediagnose: the observation that contradicts the current cause. Same shape as observation; '
|
|
330
|
+
+ 'expected and actual must differ, and the site must lie inside the targets.',
|
|
331
|
+
properties: {
|
|
332
|
+
command: { type: 'string' },
|
|
333
|
+
expected: { type: 'string' },
|
|
334
|
+
actual: { type: 'string' },
|
|
335
|
+
site: { type: 'string' },
|
|
336
|
+
},
|
|
337
|
+
},
|
|
338
|
+
verification: {
|
|
339
|
+
type: 'object',
|
|
340
|
+
additionalProperties: false,
|
|
341
|
+
required: ['command', 'actual'],
|
|
342
|
+
description:
|
|
343
|
+
'On close, required when the declaration carries an observation: the same step again, with what '
|
|
344
|
+
+ 'it now produces. The command must match the observation exactly, and actual must equal the '
|
|
345
|
+
+ 'expectation frozen before the fix.',
|
|
346
|
+
properties: {
|
|
347
|
+
command: { type: 'string', description: 'The same step recorded in observation.command.' },
|
|
348
|
+
actual: { type: 'string', description: 'What the step now produces; it must equal observation.expected.' },
|
|
349
|
+
},
|
|
350
|
+
},
|
|
351
|
+
acknowledge: {
|
|
352
|
+
type: 'array',
|
|
353
|
+
items: { type: 'string' },
|
|
354
|
+
description: 'On close: the finding codes you are deliberately accepting, for example "branch_only_change".',
|
|
355
|
+
},
|
|
356
|
+
acknowledgeReason: {
|
|
357
|
+
type: 'string',
|
|
358
|
+
description: 'On close: what you actually did and why the observed shape is the right one.',
|
|
359
|
+
},
|
|
360
|
+
},
|
|
361
|
+
},
|
|
362
|
+
output: {
|
|
363
|
+
schema: {
|
|
364
|
+
type: 'object',
|
|
365
|
+
properties: {
|
|
366
|
+
ok: { type: 'boolean' },
|
|
367
|
+
declarationId: { type: 'string' },
|
|
368
|
+
depth: { type: 'string' },
|
|
369
|
+
mode: { type: 'string' },
|
|
370
|
+
targets: { type: 'array', items: { type: 'string' } },
|
|
371
|
+
touched: { type: 'array', items: { type: 'string' } },
|
|
372
|
+
findings: { type: 'array' },
|
|
373
|
+
invariantFile: { type: 'string' },
|
|
374
|
+
closed: { type: 'boolean' },
|
|
375
|
+
message: { type: 'string' },
|
|
376
|
+
},
|
|
377
|
+
additionalProperties: true,
|
|
378
|
+
},
|
|
379
|
+
render(args, value) {
|
|
380
|
+
return [{ type: 'text', text: JSON.stringify(value, null, 2) }];
|
|
381
|
+
},
|
|
382
|
+
},
|
|
383
|
+
async execute(args, exec) {
|
|
384
|
+
const agent = exec.agent;
|
|
385
|
+
const agentId = agent?.id ?? 'anonymous';
|
|
386
|
+
const cwd = workingDirectoryOf(ctx, agent);
|
|
387
|
+
const action = requireEnum(args.action, ['declare', 'revise', 'rediagnose', 'status', 'verify', 'close'], 'action');
|
|
388
|
+
const current = await resolveScope(cwd, agentId);
|
|
389
|
+
|
|
390
|
+
if (action === 'verify') {
|
|
391
|
+
return await verifyInvariants(ctx, cwd);
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
if (action === 'status') {
|
|
395
|
+
if (!current) {
|
|
396
|
+
return { ok: true, message: 'No scope declaration is active for this session.' };
|
|
397
|
+
}
|
|
398
|
+
const report = await structuralReport(current);
|
|
399
|
+
return { ok: true, ...publicView(current), structure: report };
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
if (action === 'declare') {
|
|
403
|
+
if (current && !current.closed) {
|
|
404
|
+
throw new Error(
|
|
405
|
+
`change_scope: a scope is already active (${current.id}). Use action "revise" to change it, `
|
|
406
|
+
+ 'or "close" it before declaring a new one.',
|
|
407
|
+
);
|
|
408
|
+
}
|
|
409
|
+
const mode = requireEnum(args.mode, MODES, 'mode', 'fix');
|
|
410
|
+
const depth = requireEnum(args.depth, DEPTHS, 'depth', 'deep');
|
|
411
|
+
const necessity = requireString(args, 'necessity');
|
|
412
|
+
const targets = optionalStringArray(args, 'targets') ?? [];
|
|
413
|
+
if (targets.length === 0) {
|
|
414
|
+
throw new Error(
|
|
415
|
+
'change_scope: "targets" is required on declare. Name the files the change may edit, '
|
|
416
|
+
+ 'or use action "revise" later — the gate does not accept an empty declaration.',
|
|
417
|
+
);
|
|
418
|
+
}
|
|
419
|
+
const observation = normalizeObservation(args.observation);
|
|
420
|
+
const cause = normalizeCause(args.cause);
|
|
421
|
+
const discard = optionalStringArray(args, 'discard') ?? [];
|
|
422
|
+
const contracts = optionalStringArray(args, 'contracts') ?? [];
|
|
423
|
+
const excluded = optionalStringArray(args, 'excluded') ?? [];
|
|
424
|
+
if (mode === 'fix' && depth === 'deep' && !observation) {
|
|
425
|
+
throw new Error(
|
|
426
|
+
'change_scope: a deep fix must declare an observation before editing — observation.command '
|
|
427
|
+
+ '(the step that reproduces), observation.expected, observation.actual, and observation.site. '
|
|
428
|
+
+ 'Without it the declaration records an intention to change something, not evidence that a '
|
|
429
|
+
+ 'divergence was located.',
|
|
430
|
+
);
|
|
431
|
+
}
|
|
432
|
+
if (observation) {
|
|
433
|
+
if (observation.expected === observation.actual) {
|
|
434
|
+
throw new Error(
|
|
435
|
+
'change_scope: observation.expected and observation.actual are identical, so the observation '
|
|
436
|
+
+ 'shows no divergence. Record what the code intends and what it actually produces; if they '
|
|
437
|
+
+ 'match, the site is not where the defect lives.',
|
|
438
|
+
);
|
|
439
|
+
}
|
|
440
|
+
const siteProblem = await checkSite(cwd, observation.site);
|
|
441
|
+
if (siteProblem) {
|
|
442
|
+
throw new Error(`change_scope: observation.site is not credible — ${siteProblem}.`);
|
|
443
|
+
}
|
|
444
|
+
if (!siteInAny(targets, cwd, observation)) {
|
|
445
|
+
throw new Error(
|
|
446
|
+
`change_scope: observation.site "${observation.site}" is outside the declared targets `
|
|
447
|
+
+ `(${targets.join(', ')}). An observation about a place you are not authorized to change cannot `
|
|
448
|
+
+ 'justify this scope: add that path to targets, or point the observation at the divergence you '
|
|
449
|
+
+ 'intend to fix.',
|
|
450
|
+
);
|
|
451
|
+
}
|
|
452
|
+
if (excluded.length > 0 && siteInAny(excluded, cwd, observation)) {
|
|
453
|
+
throw new Error(
|
|
454
|
+
`change_scope: observation.site "${observation.site}" is listed in excluded, so this scope both `
|
|
455
|
+
+ 'points at it and promises not to touch it.',
|
|
456
|
+
);
|
|
457
|
+
}
|
|
458
|
+
}
|
|
459
|
+
if ((mode === 'fix' || mode === 'rewrite') && depth === 'deep' && !cause) {
|
|
460
|
+
throw new Error(
|
|
461
|
+
'change_scope: a deep fix or rewrite must declare cause before editing — cause.contract (what '
|
|
462
|
+
+ 'should always be true at the divergence, or the new contract for a rewrite), cause.class (the '
|
|
463
|
+
+ 'defect class), and cause.sweep (where else that class could live, with a verdict for each). '
|
|
464
|
+
+ 'Declaring deep is a commitment to stop looking for the smallest change that silences the symptom.',
|
|
465
|
+
);
|
|
466
|
+
}
|
|
467
|
+
if (mode === 'rewrite' && depth === 'deep' && discard.length === 0) {
|
|
468
|
+
throw new Error(
|
|
469
|
+
'change_scope: a deep rewrite must declare "discard" — what must no longer exist afterwards, as '
|
|
470
|
+
+ 'symbols you are deleting or behaviors you are replacing. Without it there is no claim to check, '
|
|
471
|
+
+ 'and "rewrite" degenerates into a local edit with a larger label.',
|
|
472
|
+
);
|
|
473
|
+
}
|
|
474
|
+
const askedUser = depth === 'deep' ? askedBeforeDeclare(sessionOf(ctx, agent)) : null;
|
|
475
|
+
if (askedUser === false) {
|
|
476
|
+
throw new Error(
|
|
477
|
+
'change_scope: confirm the route with the user before declaring a deep change. Ask once — the '
|
|
478
|
+
+ 'cause you believe, the files it would touch, and whether that matches what they actually see — '
|
|
479
|
+
+ 'then declare. The question is not ceremony: the user is the cheapest oracle for a wrong '
|
|
480
|
+
+ 'attribution, and asking makes reversing it cheap for both sides.',
|
|
481
|
+
);
|
|
482
|
+
}
|
|
483
|
+
const briefing = await briefSite(ctx, cwd, observation?.site);
|
|
484
|
+
const watch = {};
|
|
485
|
+
for (const pattern of targets) {
|
|
486
|
+
if (/[*?]/.test(pattern)) continue;
|
|
487
|
+
try {
|
|
488
|
+
watch[pattern] = (await fsp.stat(join(cwd, pattern))).mtimeMs;
|
|
489
|
+
} catch {
|
|
490
|
+
watch[pattern] = null;
|
|
491
|
+
}
|
|
492
|
+
}
|
|
493
|
+
let prior = null;
|
|
494
|
+
if (current && current.closed) {
|
|
495
|
+
const priorSite = current.observation?.site ?? null;
|
|
496
|
+
if (priorSite && observation && priorSite === observation.site) {
|
|
497
|
+
if (identicalCause(current.cause, cause)) {
|
|
498
|
+
throw new Error(
|
|
499
|
+
`change_scope: this session already declared a change at ${priorSite}, and that diagnosis `
|
|
500
|
+
+ 'closed. Declaring the same contract and class again repeats it. Say what the earlier '
|
|
501
|
+
+ 'diagnosis got wrong — change cause.contract or cause.class — before declaring again.',
|
|
502
|
+
);
|
|
503
|
+
}
|
|
504
|
+
prior = {
|
|
505
|
+
declarationId: current.id,
|
|
506
|
+
site: priorSite,
|
|
507
|
+
contract: current.cause?.contract ?? null,
|
|
508
|
+
class: current.cause?.class ?? null,
|
|
509
|
+
};
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
const next = emptyScope(agentId, cwd);
|
|
513
|
+
next.mode = mode;
|
|
514
|
+
next.depth = depth;
|
|
515
|
+
next.necessity = necessity;
|
|
516
|
+
next.targets = targets;
|
|
517
|
+
next.contracts = contracts;
|
|
518
|
+
next.excluded = excluded;
|
|
519
|
+
next.observation = observation;
|
|
520
|
+
next.cause = cause;
|
|
521
|
+
next.discard = discard;
|
|
522
|
+
next.prior = prior;
|
|
523
|
+
next.watch = watch;
|
|
524
|
+
next.authorization = requireEnum(args.authorization, AUTHORIZATIONS, 'authorization', 'assumed');
|
|
525
|
+
scopes.set(agentId, next);
|
|
526
|
+
await saveScope(next);
|
|
527
|
+
return {
|
|
528
|
+
ok: true,
|
|
529
|
+
declarationId: next.id,
|
|
530
|
+
mode: next.mode,
|
|
531
|
+
depth: next.depth,
|
|
532
|
+
targets: next.targets,
|
|
533
|
+
observation: next.observation,
|
|
534
|
+
cause: next.cause,
|
|
535
|
+
discard: next.discard,
|
|
536
|
+
prior: next.prior,
|
|
537
|
+
briefing,
|
|
538
|
+
askedUser: askedUser === null ? 'unverified' : askedUser,
|
|
539
|
+
message: depth === 'deep'
|
|
540
|
+
? 'Declared. Deep scope: edit and write are now refused outside the targets, and close checks the change shape. Keep the boundary honest and revise it explicitly rather than widening it silently.'
|
|
541
|
+
: 'Declared, quick depth: the gate records but does not block, and close warns instead of refusing. Prefer deep when the cause crosses a file or a contract.',
|
|
542
|
+
};
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
if (action === 'revise') {
|
|
546
|
+
if (!current) {
|
|
547
|
+
throw new Error('change_scope: no active scope to revise. Call action "declare" first.');
|
|
548
|
+
}
|
|
549
|
+
if (args.observation !== undefined) {
|
|
550
|
+
throw new Error(
|
|
551
|
+
'change_scope: the observation is frozen at declare. Revise may move targets, contracts, '
|
|
552
|
+
+ 'excluded, mode, depth, necessity, and authorization, but not the expected value — '
|
|
553
|
+
+ 'changing it after the fix would make the comparison meaningless.',
|
|
554
|
+
);
|
|
555
|
+
}
|
|
556
|
+
const before = publicView(current);
|
|
557
|
+
const targets = optionalStringArray(args, 'targets');
|
|
558
|
+
const contracts = optionalStringArray(args, 'contracts');
|
|
559
|
+
const excluded = optionalStringArray(args, 'excluded');
|
|
560
|
+
if (current.observation && (targets || excluded)) {
|
|
561
|
+
const nextTargets = targets ?? current.targets;
|
|
562
|
+
const nextExcluded = excluded ?? current.excluded;
|
|
563
|
+
if (!siteInAny(nextTargets, current.root, current.observation)) {
|
|
564
|
+
throw new Error(
|
|
565
|
+
`change_scope: this revision would move the observation site "${current.observation.site}" `
|
|
566
|
+
+ 'outside the targets. The observation is frozen, so a scope may not stop containing the place '
|
|
567
|
+
+ 'it explains — keep that path in targets, or close and declare again.',
|
|
568
|
+
);
|
|
569
|
+
}
|
|
570
|
+
if (nextExcluded.length > 0 && siteInAny(nextExcluded, current.root, current.observation)) {
|
|
571
|
+
throw new Error(
|
|
572
|
+
`change_scope: this revision would add the observation site "${current.observation.site}" `
|
|
573
|
+
+ 'to excluded, so the scope would both point at it and promise not to touch it.',
|
|
574
|
+
);
|
|
575
|
+
}
|
|
576
|
+
}
|
|
577
|
+
if (targets) current.targets = targets;
|
|
578
|
+
if (contracts) current.contracts = contracts;
|
|
579
|
+
if (excluded) current.excluded = excluded;
|
|
580
|
+
if (args.necessity !== undefined) current.necessity = requireString(args, 'necessity');
|
|
581
|
+
if (args.depth !== undefined) current.depth = requireEnum(args.depth, DEPTHS, 'depth');
|
|
582
|
+
if (args.mode !== undefined) current.mode = requireEnum(args.mode, MODES, 'mode');
|
|
583
|
+
if (args.authorization !== undefined) {
|
|
584
|
+
current.authorization = requireEnum(args.authorization, AUTHORIZATIONS, 'authorization');
|
|
585
|
+
}
|
|
586
|
+
if (args.cause !== undefined) current.cause = normalizeCause(args.cause);
|
|
587
|
+
if (args.discard !== undefined) current.discard = optionalStringArray(args, 'discard') ?? [];
|
|
588
|
+
current.revisions.push({ at: Date.now(), before, reason: args.reason ?? null });
|
|
589
|
+
await saveScope(current);
|
|
590
|
+
return {
|
|
591
|
+
ok: true,
|
|
592
|
+
declarationId: current.id,
|
|
593
|
+
depth: current.depth,
|
|
594
|
+
targets: current.targets,
|
|
595
|
+
message: `Revised (revision ${current.revisions.length}). The previous boundary is recorded.`,
|
|
596
|
+
};
|
|
597
|
+
}
|
|
598
|
+
|
|
599
|
+
if (action === 'rediagnose') {
|
|
600
|
+
if (!current) {
|
|
601
|
+
throw new Error('change_scope: no active scope to rediagnose. Call action "declare" first.');
|
|
602
|
+
}
|
|
603
|
+
if (current.closed) {
|
|
604
|
+
throw new Error('change_scope: this scope is already closed; declare a new one instead of rediagnosing it.');
|
|
605
|
+
}
|
|
606
|
+
const reason = requireString(args, 'reason');
|
|
607
|
+
const evidence = normalizeObservation(args.evidence);
|
|
608
|
+
if (!evidence) {
|
|
609
|
+
throw new Error(
|
|
610
|
+
'change_scope: rediagnose needs "evidence" — the observation that contradicts the current cause. '
|
|
611
|
+
+ 'Changing the diagnosis without new data is guessing again, not re-diagnosing.',
|
|
612
|
+
);
|
|
613
|
+
}
|
|
614
|
+
if (evidence.expected === evidence.actual) {
|
|
615
|
+
throw new Error('change_scope: evidence.expected and evidence.actual are identical, so it contradicts nothing.');
|
|
616
|
+
}
|
|
617
|
+
const evidenceProblem = await checkSite(cwd, evidence.site);
|
|
618
|
+
if (evidenceProblem) {
|
|
619
|
+
throw new Error(`change_scope: evidence.site is not credible — ${evidenceProblem}.`);
|
|
620
|
+
}
|
|
621
|
+
if (!siteInAny(current.targets, cwd, evidence)) {
|
|
622
|
+
throw new Error(
|
|
623
|
+
`change_scope: evidence.site "${evidence.site}" is outside the declared targets (${current.targets.join(', ')}).`,
|
|
624
|
+
);
|
|
625
|
+
}
|
|
626
|
+
const replacement = normalizeCause(args.cause);
|
|
627
|
+
if (!replacement) {
|
|
628
|
+
throw new Error('change_scope: rediagnose needs the replacement "cause" dossier.');
|
|
629
|
+
}
|
|
630
|
+
if (identicalCause(current.cause, replacement)) {
|
|
631
|
+
throw new Error(
|
|
632
|
+
'change_scope: the replacement cause has the same contract and class as the current one. '
|
|
633
|
+
+ 'That is the same diagnosis; say what is actually different.',
|
|
634
|
+
);
|
|
635
|
+
}
|
|
636
|
+
const refutedCause = current.cause;
|
|
637
|
+
current.refuted = [...(current.refuted ?? []), { at: Date.now(), reason, evidence, cause: refutedCause }];
|
|
638
|
+
current.cause = replacement;
|
|
639
|
+
await recordRefuted(cwd, current.observation?.site, {
|
|
640
|
+
declarationId: current.id,
|
|
641
|
+
contract: refutedCause?.contract ?? null,
|
|
642
|
+
class: refutedCause?.class ?? null,
|
|
643
|
+
reason,
|
|
644
|
+
});
|
|
645
|
+
await saveScope(current);
|
|
646
|
+
return {
|
|
647
|
+
ok: true,
|
|
648
|
+
declarationId: current.id,
|
|
649
|
+
refuted: current.refuted.length,
|
|
650
|
+
refutedCause,
|
|
651
|
+
cause: replacement,
|
|
652
|
+
message:
|
|
653
|
+
`Recorded: the previous cause "${refutedCause?.contract ?? '(none)'}" was refuted by an observation `
|
|
654
|
+
+ `at ${evidence.site} — actual "${clip(evidence.actual)}" against expected "${clip(evidence.expected)}". `
|
|
655
|
+
+ `This is diagnosis ${current.refuted.length + 1} for this scope, not a failed patch. The symptom `
|
|
656
|
+
+ 'observation is unchanged; close still verifies against it.',
|
|
657
|
+
};
|
|
658
|
+
}
|
|
659
|
+
|
|
660
|
+
// close
|
|
661
|
+
if (!current) {
|
|
662
|
+
throw new Error('change_scope: no active scope to close.');
|
|
663
|
+
}
|
|
664
|
+
const invariant = typeof args.invariant === 'string' && args.invariant.trim() !== ''
|
|
665
|
+
? args.invariant.trim()
|
|
666
|
+
: undefined;
|
|
667
|
+
const reason = typeof args.reason === 'string' && args.reason.trim() !== ''
|
|
668
|
+
? args.reason.trim()
|
|
669
|
+
: undefined;
|
|
670
|
+
if (!invariant && !reason) {
|
|
671
|
+
throw new Error(
|
|
672
|
+
'change_scope: close needs "invariant" — the one contract this change established — '
|
|
673
|
+
+ 'or "reason" when the change was containment and established none.',
|
|
674
|
+
);
|
|
675
|
+
}
|
|
676
|
+
|
|
677
|
+
const report = await structuralReport(current);
|
|
678
|
+
report.findings.push(...evidenceFindings(current, args));
|
|
679
|
+
const discardCheck = await discardFindings(current, args);
|
|
680
|
+
report.findings.push(...discardCheck.findings);
|
|
681
|
+
const askedBeforeClosing = current.depth === 'deep' ? askedBeforeClose(sessionOf(ctx, agent)) : null;
|
|
682
|
+
if (askedBeforeClosing === false) {
|
|
683
|
+
report.findings.push(finding(
|
|
684
|
+
'user_confirmation_missing', 'block',
|
|
685
|
+
'No question to the user was asked after the declaration, so the result was never checked against what they actually see.',
|
|
686
|
+
'Ask once before closing — what changed, and what the same step now produces — then close again. The user is the only oracle for whether the fix matches reality.',
|
|
687
|
+
null,
|
|
688
|
+
));
|
|
689
|
+
}
|
|
690
|
+
const verificationCommand = typeof args.verification?.command === 'string' ? args.verification.command : '';
|
|
691
|
+
const verificationActual = typeof args.verification?.actual === 'string' ? args.verification.actual : '';
|
|
692
|
+
const evidence = current.observation && verificationCommand
|
|
693
|
+
? evidenceInLog(sessionOf(ctx, agent), verificationCommand, verificationActual)
|
|
694
|
+
: null;
|
|
695
|
+
if (evidence && (!evidence.commandSeen || !evidence.outputMatched)) {
|
|
696
|
+
report.findings.push(finding(
|
|
697
|
+
'evidence_not_in_log', 'block',
|
|
698
|
+
evidence.commandSeen
|
|
699
|
+
? 'The verification command appears in the log, but no result for it contains the value that was reported.'
|
|
700
|
+
: 'The verification command appears in no tool call after the declaration.',
|
|
701
|
+
'Run the command in this session so its output is committed, then close again with what it actually printed. A reported value that is not in the log was not observed.',
|
|
702
|
+
null,
|
|
703
|
+
));
|
|
704
|
+
}
|
|
705
|
+
for (const [relative, before] of Object.entries(current.watch ?? {})) {
|
|
706
|
+
// Ungated paths are never recorded in touched, so watching them is a false positive.
|
|
707
|
+
if (!isGatedPath(relative)) continue;
|
|
708
|
+
if (current.touched.includes(relative)) continue;
|
|
709
|
+
let after = null;
|
|
710
|
+
try {
|
|
711
|
+
after = (await fsp.stat(join(current.root, relative))).mtimeMs;
|
|
712
|
+
} catch {
|
|
713
|
+
after = null;
|
|
714
|
+
}
|
|
715
|
+
if (before === after) continue;
|
|
716
|
+
const key = normPath(join(current.root, relative)).toLowerCase();
|
|
717
|
+
const seenAt = serviceWrites.get(key);
|
|
718
|
+
const throughDsh = typeof seenAt === 'number' && seenAt >= current.declaredAt;
|
|
719
|
+
report.findings.push(finding(
|
|
720
|
+
'changed_outside_gate', throughDsh ? 'block' : 'warn',
|
|
721
|
+
throughDsh
|
|
722
|
+
? `"${relative}" was written through DSH but outside the gate, so a tool or plugin changed it without a declaration.`
|
|
723
|
+
: `"${relative}" changed outside DSH entirely — an editor, an external script, or a shell command. If the user made this change it stands; if you did, say so.`,
|
|
724
|
+
throughDsh
|
|
725
|
+
? 'Someone used DSH to write this file while the scope was open. Name it, or revert it before closing.'
|
|
726
|
+
: 'Ask the user whether they edited it. A change made outside DSH is not this scope\'s work and is not a bypass — but it must not be counted as one either.',
|
|
727
|
+
relative,
|
|
728
|
+
));
|
|
729
|
+
}
|
|
730
|
+
const repeats = await recordFindings(cwd, current, report.findings);
|
|
731
|
+
const acknowledged = Array.isArray(args.acknowledge) ? args.acknowledge.map(item => String(item)) : [];
|
|
732
|
+
const acknowledgeReason = typeof args.acknowledgeReason === 'string' && args.acknowledgeReason.trim() !== ''
|
|
733
|
+
? args.acknowledgeReason.trim()
|
|
734
|
+
: undefined;
|
|
735
|
+
const blocking = report.findings.filter(entry => entry.severity === 'block');
|
|
736
|
+
const unacknowledged = blocking.filter(entry => !acknowledged.includes(entry.code));
|
|
737
|
+
if (unacknowledged.length > 0 || (blocking.length > 0 && !acknowledgeReason)) {
|
|
738
|
+
const header = unacknowledged.length > 0
|
|
739
|
+
? 'change_scope: close refused — the change shape contradicts the declaration.'
|
|
740
|
+
: 'change_scope: close refused — acknowledging a finding needs acknowledgeReason.';
|
|
741
|
+
throw new Error(
|
|
742
|
+
`${header}\n\n${formatFindings(report.findings, unacknowledged)}\n\n`
|
|
743
|
+
+ 'Do one of these:\n'
|
|
744
|
+
+ '- Fix the change so the shape matches, or call revise to correct the declaration.\n'
|
|
745
|
+
+ '- Or call close again with acknowledge listing the codes you accept and acknowledgeReason '
|
|
746
|
+
+ 'stating what you actually did and why this shape is the right outcome.',
|
|
747
|
+
);
|
|
748
|
+
}
|
|
749
|
+
|
|
750
|
+
const invariantCheck = typeof args.invariantCheck === 'string' && args.invariantCheck.trim() !== ''
|
|
751
|
+
? args.invariantCheck.trim()
|
|
752
|
+
: undefined;
|
|
753
|
+
let invariantFile = null;
|
|
754
|
+
let invariantKeyValue = null;
|
|
755
|
+
let invariantPreserved = null;
|
|
756
|
+
if (invariant) {
|
|
757
|
+
try {
|
|
758
|
+
const stored = await upsertInvariant(cwd, current, invariant, invariantCheck, args.invariantKey);
|
|
759
|
+
invariantFile = stored?.file ?? null;
|
|
760
|
+
invariantKeyValue = stored?.key ?? null;
|
|
761
|
+
invariantPreserved = stored?.preserved ?? null;
|
|
762
|
+
} catch (error) {
|
|
763
|
+
invariantFile = null;
|
|
764
|
+
current.closed = { at: Date.now(), invariant, reason: reason ?? null, writeError: String(error) };
|
|
765
|
+
}
|
|
766
|
+
}
|
|
767
|
+
current.closed = current.closed ?? { at: Date.now(), invariant: invariant ?? null, reason: reason ?? null };
|
|
768
|
+
await saveScope(current);
|
|
769
|
+
await recordFixed(cwd, current.observation?.site, {
|
|
770
|
+
declarationId: current.id,
|
|
771
|
+
mode: current.mode,
|
|
772
|
+
contract: current.cause?.contract ?? null,
|
|
773
|
+
invariantKey: invariantKeyValue,
|
|
774
|
+
});
|
|
775
|
+
const touched = [...new Set(current.touched)];
|
|
776
|
+
const warnings = report.findings.filter(entry => entry.severity === 'warn').map(entry => entry.code);
|
|
777
|
+
return {
|
|
778
|
+
ok: true,
|
|
779
|
+
summary: [
|
|
780
|
+
`Change scope ${current.id} — ${current.mode}, ${current.depth}`,
|
|
781
|
+
current.observation
|
|
782
|
+
? `Site: ${current.observation.site} — actual "${clip(current.observation.actual)}", expected "${clip(current.observation.expected)}"`
|
|
783
|
+
: 'Site: none recorded',
|
|
784
|
+
current.cause ? `Contract: ${clip(current.cause.contract)}` : 'Contract: none',
|
|
785
|
+
current.cause ? `Defect class: ${clip(current.cause.class)}` : 'Defect class: none',
|
|
786
|
+
current.cause ? `Swept: ${current.cause.sweep.map(item => item.site).join(', ')}` : 'Swept: none',
|
|
787
|
+
verificationCommand
|
|
788
|
+
? `Verified: "${clip(verificationCommand)}" → "${clip(verificationActual)}"`
|
|
789
|
+
: 'Verified: not applicable',
|
|
790
|
+
evidence
|
|
791
|
+
? `Log evidence: ${evidence.commandSeen ? 'command found' : 'command missing'}, ${evidence.outputMatched ? 'output matches' : 'output not found'}`
|
|
792
|
+
: 'Log evidence: not checked',
|
|
793
|
+
`Touched: ${[...new Set(current.touched)].join(', ') || 'none'}`,
|
|
794
|
+
`Findings: ${report.findings.length === 0 ? 'none' : report.findings.map(item => item.code).join(', ')}`,
|
|
795
|
+
`Invariant: ${invariantKeyValue ?? 'none'}`,
|
|
796
|
+
].join('\n'),
|
|
797
|
+
evidence,
|
|
798
|
+
declarationId: current.id,
|
|
799
|
+
mode: current.mode,
|
|
800
|
+
depth: current.depth,
|
|
801
|
+
targets: current.targets,
|
|
802
|
+
touched,
|
|
803
|
+
findings: report.findings,
|
|
804
|
+
invariantFile: invariantFile ?? '',
|
|
805
|
+
invariantKey: invariantKeyValue ?? '',
|
|
806
|
+
invariantPreserved: invariantPreserved ?? '',
|
|
807
|
+
cause: current.cause,
|
|
808
|
+
discards: discardCheck.report,
|
|
809
|
+
repeats,
|
|
810
|
+
askedUser: askedBeforeClosing === null ? 'unverified' : askedBeforeClosing,
|
|
811
|
+
closed: true,
|
|
812
|
+
message: invariant
|
|
813
|
+
? (invariantFile
|
|
814
|
+
? `Closed. The invariant was recorded in ${INVARIANTS_RELATIVE} and ${INVARIANTS_JSON}; a changed statement under the same key replaces the earlier entry.`
|
|
815
|
+
: `Closed. The workspace directory could not be resolved, so record the invariant manually in ${INVARIANTS_JSON}.`)
|
|
816
|
+
: 'Closed as containment. Say so in the final report instead of calling it a root fix.',
|
|
817
|
+
warnings,
|
|
818
|
+
acknowledged,
|
|
819
|
+
};
|
|
820
|
+
},
|
|
821
|
+
};
|
|
822
|
+
}
|
|
823
|
+
|
|
824
|
+
// ---------------------------------------------------------------------------
|
|
825
|
+
// Gate
|
|
826
|
+
|
|
827
|
+
export const inject = ['tools', 'systemPrompt', 'agents', 'workingDirectory'];
|
|
828
|
+
|
|
829
|
+
export const Config = Schema.object({
|
|
830
|
+
stateDir: Schema.string().default(DEFAULT_SETTINGS.stateDir)
|
|
831
|
+
.description('Workspace-relative directory for per-session scope records.'),
|
|
832
|
+
ledgerRepeatThreshold: Schema.natural().default(DEFAULT_SETTINGS.ledgerRepeatThreshold)
|
|
833
|
+
.description('How many times one finding code may hit the same site before close reports it under repeats.'),
|
|
834
|
+
ledgerMaxAgeDays: Schema.natural().default(DEFAULT_SETTINGS.ledgerMaxAgeDays)
|
|
835
|
+
.description('Ledger rows older than this are dropped when the ledger is rewritten.'),
|
|
836
|
+
checkTimeoutMs: Schema.natural().default(DEFAULT_SETTINGS.checkTimeoutMs)
|
|
837
|
+
.description('How long one invariant check may run before it is aborted.'),
|
|
838
|
+
preserveManualView: Schema.boolean().default(DEFAULT_SETTINGS.preserveManualView)
|
|
839
|
+
.description('Copy a hand-written docs/INVARIANTS.md to docs/INVARIANTS.manual.md before the first generated render.'),
|
|
840
|
+
});
|
|
841
|
+
|
|
842
|
+
export function apply(ctx, config) {
|
|
843
|
+
applyConfig(config);
|
|
844
|
+
const disposers = [];
|
|
845
|
+
disposers.push(ctx.tools.register(buildTool(ctx)));
|
|
846
|
+
disposers.push(ctx.systemPrompt.section({
|
|
847
|
+
name: 'change-scope',
|
|
848
|
+
order: 900,
|
|
849
|
+
text: PROTOCOL,
|
|
850
|
+
}));
|
|
851
|
+
ctx.on('tools/pre-execute', gate(ctx));
|
|
852
|
+
ctx.on('fs/edit-intent', (target, _actor, next) => {
|
|
853
|
+
noteServiceWrite(target);
|
|
854
|
+
return next();
|
|
855
|
+
});
|
|
856
|
+
ctx.on('fs/write-intent', (target, _actor, next) => {
|
|
857
|
+
noteServiceWrite(target);
|
|
858
|
+
return next();
|
|
859
|
+
});
|
|
860
|
+
ctx.on('agent/disposed', ({ agent }) => {
|
|
861
|
+
if (agent) scopes.delete(agent.id);
|
|
862
|
+
});
|
|
863
|
+
return () => {
|
|
864
|
+
for (const dispose of disposers) {
|
|
865
|
+
try {
|
|
866
|
+
dispose();
|
|
867
|
+
} catch {
|
|
868
|
+
// A registration already gone is not a failure to report.
|
|
869
|
+
}
|
|
870
|
+
}
|
|
871
|
+
};
|
|
872
|
+
}
|