dsh-clear-debug 0.0.0-stage → 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/checks.js ADDED
@@ -0,0 +1,322 @@
1
+ // Close-time checks: the structural comparison, the evidence pairing, and the
2
+ // discard verification, plus the normalizers the tool shares with them.
3
+
4
+ import { promises as fsp } from 'node:fs';
5
+ import { join } from 'node:path';
6
+ import { clip } from './invariants.js';
7
+ import { relativeToRoot, matchesTargets, isAlwaysWritable } from './paths.js';
8
+ import { branchTotal, fingerprint, setDelta, readText } from './fingerprint.js';
9
+
10
+ export function requireField(value, field, owner) {
11
+ const raw = value?.[field];
12
+ if (typeof raw !== 'string' || raw.trim() === '') {
13
+ throw new Error(`change_scope: ${owner}.${field} is required and must be a non-empty string.`);
14
+ }
15
+ return raw.trim();
16
+ }
17
+
18
+ export function normalizeObservation(value) {
19
+ if (value === undefined || value === null) return null;
20
+ if (typeof value !== 'object' || Array.isArray(value)) {
21
+ throw new Error('change_scope: "observation" must be an object with command, expected, actual, and site.');
22
+ }
23
+ return {
24
+ command: requireField(value, 'command', 'observation'),
25
+ expected: requireField(value, 'expected', 'observation'),
26
+ actual: requireField(value, 'actual', 'observation'),
27
+ site: requireField(value, 'site', 'observation'),
28
+ };
29
+ }
30
+
31
+ export function normalizeCause(value) {
32
+ if (value === undefined || value === null) return null;
33
+ if (typeof value !== 'object' || Array.isArray(value)) {
34
+ throw new Error('change_scope: "cause" must be an object with contract, class, and sweep.');
35
+ }
36
+ const contract = requireField(value, 'contract', 'cause');
37
+ const defectClass = requireField(value, 'class', 'cause');
38
+ const raw = value.sweep;
39
+ if (!Array.isArray(raw) || raw.length === 0) {
40
+ throw new Error(
41
+ 'change_scope: cause.sweep needs at least one entry — where else this defect class could live, '
42
+ + 'and your verdict for it. One entry is allowed only when you say why the class is contained there.',
43
+ );
44
+ }
45
+ const sweep = raw.map((entry, index) => {
46
+ if (!entry || typeof entry !== 'object' || Array.isArray(entry)) {
47
+ throw new Error(`change_scope: cause.sweep[${index}] must be an object with site and verdict.`);
48
+ }
49
+ return {
50
+ site: requireField(entry, 'site', `cause.sweep[${index}]`),
51
+ verdict: requireField(entry, 'verdict', `cause.sweep[${index}]`),
52
+ };
53
+ });
54
+ return { contract, class: defectClass, sweep };
55
+ }
56
+
57
+ export function escapeRegExp(value) {
58
+ return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
59
+ }
60
+
61
+ export function normalizeRetained(value) {
62
+ if (value === undefined || value === null) return null;
63
+ if (!Array.isArray(value)) {
64
+ throw new Error('change_scope: "retained" must be an array of { item, why } objects.');
65
+ }
66
+ return value.map((entry, index) => {
67
+ if (!entry || typeof entry !== 'object' || Array.isArray(entry)) {
68
+ throw new Error(`change_scope: retained[${index}] must be an object with item and why.`);
69
+ }
70
+ return {
71
+ item: requireField(entry, 'item', `retained[${index}]`),
72
+ why: requireField(entry, 'why', `retained[${index}]`),
73
+ };
74
+ });
75
+ }
76
+
77
+ export function normalizeVerification(value) {
78
+ if (value === undefined || value === null) return null;
79
+ if (typeof value !== 'object' || Array.isArray(value)) {
80
+ throw new Error('change_scope: "verification" must be an object with command and actual.');
81
+ }
82
+ return {
83
+ command: requireField(value, 'command', 'verification'),
84
+ actual: requireField(value, 'actual', 'verification'),
85
+ };
86
+ }
87
+
88
+ export function parseSite(value) {
89
+ const text = String(value ?? '').trim();
90
+ const match = /^(.*?):(\d+)$/.exec(text);
91
+ if (match) return { path: match[1], line: Number(match[2]) };
92
+ return { path: text, line: null };
93
+ }
94
+
95
+ export async function checkSite(root, site) {
96
+ if (!root) return null;
97
+ const parsed = parseSite(site);
98
+ if (parsed.path === '') return 'the site has no file path';
99
+ let text;
100
+ try {
101
+ text = await fsp.readFile(join(root, parsed.path), 'utf8');
102
+ } catch {
103
+ return `"${parsed.path}" does not exist in the workspace`;
104
+ }
105
+ if (parsed.line !== null) {
106
+ const total = text.split(/\r?\n/).length;
107
+ if (parsed.line < 1 || parsed.line > total) {
108
+ return `line ${parsed.line} is outside "${parsed.path}", which has ${total} lines`;
109
+ }
110
+ }
111
+ return null;
112
+ }
113
+
114
+ export function siteInAny(list, root, observation) {
115
+ const location = relativeToRoot(parseSite(observation.site).path, root);
116
+ return matchesTargets(location.relative, location.absolute, list);
117
+ }
118
+
119
+ export function evidenceFindings(scope, args) {
120
+ const findings = [];
121
+ const observation = scope.observation;
122
+ if (!observation) return findings;
123
+ const verification = normalizeVerification(args.verification);
124
+ if (!verification) {
125
+ findings.push(finding(
126
+ 'verification_missing', 'block',
127
+ 'No verification was given at close, though the declaration froze an observation to compare against.',
128
+ `Run the same step again and pass verification: { "command": ${JSON.stringify(observation.command)}, "actual": "..." }.`,
129
+ null,
130
+ ));
131
+ return findings;
132
+ }
133
+ if (verification.command !== observation.command) {
134
+ findings.push(finding(
135
+ 'verification_command_mismatch', 'block',
136
+ `The verification step differs from the observed step. before: "${clip(observation.command)}" / after: "${clip(verification.command)}".`,
137
+ 'Run the same step. A different step proves something else changed, not that this cause is gone.',
138
+ null,
139
+ ));
140
+ }
141
+ if (verification.actual !== observation.expected) {
142
+ findings.push(finding(
143
+ 'verification_unresolved', 'block',
144
+ `The verification reports "${clip(verification.actual)}", but the expectation frozen before the fix was "${clip(observation.expected)}".`,
145
+ 'Either the cause was not removed, or the expectation was wrong. Say which; do not restate the new value as the old expectation.',
146
+ null,
147
+ ));
148
+ }
149
+ return findings;
150
+ }
151
+
152
+ export async function discardFindings(scope, args) {
153
+ const findings = [];
154
+ const report = { checked: 0, unverified: [], retained: [] };
155
+ if (scope.mode !== 'rewrite') return { findings, report };
156
+ if (scope.touched.length === 0) {
157
+ findings.push(finding(
158
+ 'rewrite_without_edits', 'block',
159
+ 'The change is declared as a rewrite, but no file was edited inside this scope.',
160
+ 'A rewrite removes something. Edit inside the targets, or declare this as a fix instead.',
161
+ null,
162
+ ));
163
+ return { findings, report };
164
+ }
165
+ const retained = normalizeRetained(args.retained) ?? [];
166
+ const retainedItems = new Set(retained.map(entry => entry.item));
167
+ report.retained = [...retainedItems];
168
+ const texts = [];
169
+ if (scope.root) {
170
+ for (const relative of [...new Set(scope.touched)]) {
171
+ const text = await readText(scope.root, relative);
172
+ if (text !== null) texts.push({ relative, text });
173
+ }
174
+ }
175
+ for (const item of scope.discard ?? []) {
176
+ if (!/^[A-Za-z_$][\w$]*$/.test(item) || !scope.root) {
177
+ report.unverified.push(item);
178
+ continue;
179
+ }
180
+ report.checked += 1;
181
+ const matcher = new RegExp(`(?<![\\w$])${escapeRegExp(item)}(?![\\w$])`);
182
+ const found = texts.filter(entry => matcher.test(entry.text)).map(entry => entry.relative);
183
+ if (found.length === 0) continue;
184
+ if (retainedItems.has(item)) continue;
185
+ findings.push(finding(
186
+ 'discard_retained', 'block',
187
+ `"${item}" was declared for removal, but it still appears in ${found.join(', ')}.`,
188
+ 'Delete it, or list it in retained with the reason it had to stay. If it stayed, say so explicitly rather than letting the rewrite claim stand.',
189
+ found[0],
190
+ ));
191
+ }
192
+ return { findings, report };
193
+ }
194
+
195
+ export function finding(code, severity, detail, hint, file) {
196
+ return { code, severity, file: file ?? null, detail, hint };
197
+ }
198
+
199
+ export async function structuralReport(scope) {
200
+ const findings = [];
201
+ if (!scope.root) {
202
+ return {
203
+ available: false,
204
+ files: [],
205
+ findings,
206
+ note: 'The workspace directory could not be resolved, so structural comparison was skipped.',
207
+ };
208
+ }
209
+ const touched = [...new Set(scope.touched)];
210
+ const files = [];
211
+ for (const relative of touched) {
212
+ const before = scope.before[relative] ?? null;
213
+ const text = await readText(scope.root, relative);
214
+ const after = text === null ? { missing: true } : fingerprint(text, relative);
215
+ files.push({ path: relative, before, after });
216
+ }
217
+
218
+ for (const relative of touched) {
219
+ if (!matchesTargets(relative, false, scope.targets) && !isAlwaysWritable(relative)) {
220
+ findings.push(finding(
221
+ 'edited_outside_targets', 'block',
222
+ `"${relative}" was edited but is not among the declared targets.`,
223
+ 'Declare it with revise, or revert the edit. In quick depth the gate does not block, so this is reported at close instead.',
224
+ relative,
225
+ ));
226
+ }
227
+ if (matchesTargets(relative, false, scope.excluded)) {
228
+ findings.push(finding(
229
+ 'edited_excluded_path', 'block',
230
+ `"${relative}" is listed in excluded, so it was meant to stay untouched.`,
231
+ 'Either remove it from excluded with revise, or revert the edit.',
232
+ relative,
233
+ ));
234
+ }
235
+ }
236
+
237
+ const analyzed = files.filter(entry =>
238
+ entry.before && !entry.before.missing && entry.before.analyzed
239
+ && entry.after && !entry.after.missing && entry.after.analyzed);
240
+
241
+ let contractMoved = false;
242
+ let branchesAdded = false;
243
+ for (const entry of analyzed) {
244
+ const exportsDelta = setDelta(entry.before.exports, entry.after.exports);
245
+ const signaturesDelta = setDelta(entry.before.signatures, entry.after.signatures);
246
+ if (exportsDelta || signaturesDelta) {
247
+ contractMoved = true;
248
+ const parts = [];
249
+ if (exportsDelta) parts.push(`exports ${formatDelta(exportsDelta)}`);
250
+ if (signaturesDelta) parts.push(`signatures ${formatDelta(signaturesDelta)}`);
251
+ if (scope.contracts.length === 0) {
252
+ findings.push(finding(
253
+ 'contract_changed_undeclared', 'block',
254
+ `"${entry.path}" moved its public surface (${parts.join('; ')}) but the declaration names no contract change.`,
255
+ 'Either call revise with the contract this change may alter, or restore the surface and change only the implementation.',
256
+ entry.path,
257
+ ));
258
+ }
259
+ }
260
+ const beforeBranches = branchTotal(entry.before);
261
+ const afterBranches = branchTotal(entry.after);
262
+ if (afterBranches > beforeBranches && !(exportsDelta || signaturesDelta) && scope.mode !== 'feature') {
263
+ branchesAdded = true;
264
+ findings.push(finding(
265
+ 'branch_only_change', scope.depth === 'deep' ? 'block' : 'warn',
266
+ `"${entry.path}" gained ${afterBranches - beforeBranches} conditional(s) (if/case/catch) and moved no exported signature.`,
267
+ 'That is the shape of a symptom patch. Name what the new branch means: a contract the code now enforces, or an acknowledged containment.',
268
+ entry.path,
269
+ ));
270
+ }
271
+ }
272
+
273
+ if (scope.mode === 'rewrite' && analyzed.length > 0 && !contractMoved && !branchesAdded) {
274
+ const identical = analyzed.every(entry =>
275
+ setDelta(entry.before.exports, entry.after.exports) === null
276
+ && setDelta(entry.before.signatures, entry.after.signatures) === null
277
+ && branchTotal(entry.before) === branchTotal(entry.after));
278
+ if (identical) {
279
+ findings.push(finding(
280
+ 'rewrite_shape_unchanged', 'block',
281
+ `The change is declared as a rewrite, but ${analyzed.length === 1 ? 'the touched file kept' : 'every touched file kept'} its exports, exported signatures, and conditional count unchanged.`,
282
+ 'A rewrite must be re-derived, not inherited: state what was derived independently, or acknowledge that this was a local edit to an existing structure.',
283
+ null,
284
+ ));
285
+ }
286
+ }
287
+
288
+ return {
289
+ available: true,
290
+ files: files.map(entry => ({
291
+ path: entry.path,
292
+ before: entry.before && !entry.before.missing
293
+ ? { exports: entry.before.exports.length, signatures: entry.before.signatures.length, branches: branchTotal(entry.before), nonBlank: entry.before.nonBlank }
294
+ : null,
295
+ after: entry.after && !entry.after.missing
296
+ ? { exports: entry.after.exports.length, signatures: entry.after.signatures.length, branches: branchTotal(entry.after), nonBlank: entry.after.nonBlank }
297
+ : null,
298
+ })),
299
+ findings,
300
+ note: analyzed.length === 0
301
+ ? 'No touched file has a fingerprint in a language this version parses, so structure was not compared.'
302
+ : null,
303
+ };
304
+ }
305
+
306
+ export function formatDelta(delta) {
307
+ const parts = [];
308
+ if (delta.added.length > 0) parts.push(`+${delta.added.join(',+')}`);
309
+ if (delta.removed.length > 0) parts.push(`-${delta.removed.join(',-')}`);
310
+ return parts.join(' ');
311
+ }
312
+
313
+ export function formatFindings(findings, unacknowledged) {
314
+ return findings.map(entry => {
315
+ const mark = unacknowledged.includes(entry) ? '[blocking]' : '[acknowledged]';
316
+ return `${mark} ${entry.code}${entry.file ? ` (${entry.file})` : ''}\n ${entry.detail}\n ${entry.hint}`;
317
+ }).join('\n');
318
+ }
319
+
320
+ // ---------------------------------------------------------------------------
321
+ // Scope records
322
+
package/lib/config.js ADDED
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Resolved settings for one activation.
3
+ *
4
+ * The row's `config` is merged over these defaults in `apply`, and every reader
5
+ * calls `settings()` at use time rather than capturing values at import time, so
6
+ * a reload with a different patch takes effect without touching call sites.
7
+ */
8
+
9
+ export const DEFAULTS = {
10
+ stateDir: '.dsh/change-scope',
11
+ ledgerRepeatThreshold: 3,
12
+ ledgerMaxAgeDays: 180,
13
+ checkTimeoutMs: 30000,
14
+ preserveManualView: true,
15
+ };
16
+
17
+ let current = { ...DEFAULTS };
18
+
19
+ export function settings() {
20
+ return current;
21
+ }
22
+
23
+ export function applyConfig(config) {
24
+ const next = { ...DEFAULTS };
25
+ if (config && typeof config === 'object' && !Array.isArray(config)) {
26
+ const positive = value => typeof value === 'number' && Number.isFinite(value) && value > 0;
27
+ if (typeof config.stateDir === 'string' && config.stateDir.trim() !== '') {
28
+ next.stateDir = config.stateDir.trim().replace(/\\/g, '/').replace(/^\/+|\/+$/g, '');
29
+ }
30
+ if (positive(config.ledgerRepeatThreshold)) next.ledgerRepeatThreshold = Math.floor(config.ledgerRepeatThreshold);
31
+ if (positive(config.ledgerMaxAgeDays)) next.ledgerMaxAgeDays = Math.floor(config.ledgerMaxAgeDays);
32
+ if (positive(config.checkTimeoutMs)) next.checkTimeoutMs = Math.floor(config.checkTimeoutMs);
33
+ if (typeof config.preserveManualView === 'boolean') next.preserveManualView = config.preserveManualView;
34
+ }
35
+ current = next;
36
+ return current;
37
+ }
@@ -0,0 +1,127 @@
1
+ // Lexical structural fingerprint: what the public surface looks like, without
2
+ // pretending to understand the file.
3
+
4
+ import { promises as fsp } from 'node:fs';
5
+ import { join } from 'node:path';
6
+ import { extensionOf } from './paths.js';
7
+
8
+ const JS_FAMILY = new Set(['.js', '.mjs', '.cjs', '.jsx', '.ts', '.tsx', '.mts', '.cts', '.vue', '.svelte', '.astro']);
9
+
10
+ function arity(list) {
11
+ const trimmed = String(list ?? '').trim();
12
+ if (trimmed === '') return 0;
13
+ return trimmed.split(',').filter(part => part.trim() !== '').length;
14
+ }
15
+
16
+ export function branchTotal(fingerprintValue) {
17
+ const branches = fingerprintValue?.branches ?? {};
18
+ return (branches.if ?? 0) + (branches.case ?? 0) + (branches.catch ?? 0);
19
+ }
20
+
21
+ export function fingerprint(text, relative) {
22
+ const ext = extensionOf(relative);
23
+ const lines = text.split(/\r?\n/);
24
+ const exportsSet = new Set();
25
+ const signaturesSet = new Set();
26
+ let analyzed = true;
27
+
28
+ const each = (pattern, onMatch) => {
29
+ for (const match of text.matchAll(pattern)) onMatch(match);
30
+ };
31
+
32
+ if (JS_FAMILY.has(ext)) {
33
+ each(/export\s+(?:async\s+)?(?:function|class|const|let|var)\s+([A-Za-z_$][\w$]*)/g, match => exportsSet.add(match[1]));
34
+ each(/export\s+default\b/g, () => exportsSet.add('default'));
35
+ each(/export\s*\{([^}]*)\}/g, match => {
36
+ for (const part of match[1].split(',')) {
37
+ const name = part.trim().split(/\s+as\s+/i).pop();
38
+ if (name && name.trim() !== '') exportsSet.add(name.trim());
39
+ }
40
+ });
41
+ each(/module\.exports\s*=\s*\{([^}]*)\}/g, match => {
42
+ for (const part of match[1].split(',')) {
43
+ const name = part.trim().split(':')[0];
44
+ if (name && name.trim() !== '') exportsSet.add(name.trim());
45
+ }
46
+ });
47
+ each(/(?:export\s+)?(?:async\s+)?function\s+([A-Za-z_$][\w$]*)\s*\(([^)]*)\)/g, match => {
48
+ signaturesSet.add(`${match[1]}/${arity(match[2])}`);
49
+ });
50
+ each(/(?:export\s+)?(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*(?:async\s*)?\(([^)]*)\)\s*=>/g, match => {
51
+ signaturesSet.add(`${match[1]}/${arity(match[2])}`);
52
+ });
53
+ each(/\bclass\s+([A-Za-z_$][\w$]*)/g, match => signaturesSet.add(`${match[1]}/class`));
54
+ } else if (ext === '.py') {
55
+ each(/^(?:async\s+)?def\s+(\w+)\s*\(([^)]*)\)/gm, match => {
56
+ signaturesSet.add(`${match[1]}/${arity(match[2])}`);
57
+ if (!match[1].startsWith('_')) exportsSet.add(match[1]);
58
+ });
59
+ each(/^class\s+(\w+)/gm, match => {
60
+ signaturesSet.add(`${match[1]}/class`);
61
+ if (!match[1].startsWith('_')) exportsSet.add(match[1]);
62
+ });
63
+ } else if (ext === '.go') {
64
+ each(/^func\s+(?:\([^)]*\)\s*)?(\w+)\s*\(([^)]*)\)/gm, match => {
65
+ signaturesSet.add(`${match[1]}/${arity(match[2])}`);
66
+ if (/^[A-Z]/.test(match[1])) exportsSet.add(match[1]);
67
+ });
68
+ } else if (ext === '.rs') {
69
+ each(/^\s*pub\s+(?:async\s+)?fn\s+(\w+)\s*(?:<[^>]*>)?\s*\(([^)]*)\)/gm, match => {
70
+ signaturesSet.add(`${match[1]}/${arity(match[2])}`);
71
+ exportsSet.add(match[1]);
72
+ });
73
+ } else if (ext === '.java' || ext === '.cs' || ext === '.kt') {
74
+ each(/\b(?:public|private|protected|internal)\s+(?:static\s+)?(?:final\s+)?[\w<>[\],\s.]+\s+(\w+)\s*\(([^)]*)\)/g, match => {
75
+ signaturesSet.add(`${match[1]}/${arity(match[2])}`);
76
+ if (!text.includes(`private ${match[1]}`)) exportsSet.add(match[1]);
77
+ });
78
+ } else {
79
+ analyzed = false;
80
+ }
81
+
82
+ const signatures = [...signaturesSet]
83
+ .filter(entry => exportsSet.has(entry.slice(0, entry.lastIndexOf('/'))))
84
+ .sort();
85
+
86
+ return {
87
+ analyzed,
88
+ ext,
89
+ nonBlank: lines.filter(line => line.trim() !== '').length,
90
+ exports: [...exportsSet].sort(),
91
+ signatures,
92
+ branches: {
93
+ if: (text.match(/\bif\s*[(:]/g) ?? []).length,
94
+ case: (text.match(/\bcase\b/g) ?? []).length,
95
+ catch: (text.match(/\bcatch\b/g) ?? []).length,
96
+ },
97
+ };
98
+ }
99
+
100
+ export function setDelta(before, after) {
101
+ const left = new Set(before ?? []);
102
+ const right = new Set(after ?? []);
103
+ const added = [...right].filter(item => !left.has(item));
104
+ const removed = [...left].filter(item => !right.has(item));
105
+ if (added.length === 0 && removed.length === 0) return null;
106
+ return { added, removed };
107
+ }
108
+
109
+ export async function readText(root, relative) {
110
+ if (!root) return null;
111
+ try {
112
+ return await fsp.readFile(join(root, relative), 'utf8');
113
+ } catch {
114
+ return null;
115
+ }
116
+ }
117
+
118
+ export async function snapshotBefore(scope, relative) {
119
+ if (!scope.root) return;
120
+ if (scope.before[relative] !== undefined) return;
121
+ try {
122
+ const text = await readText(scope.root, relative);
123
+ scope.before[relative] = text === null ? { missing: true } : fingerprint(text, relative);
124
+ } catch {
125
+ scope.before[relative] = { missing: true };
126
+ }
127
+ }
package/lib/gate.js ADDED
@@ -0,0 +1,71 @@
1
+ // The edit gate: which tools are gated, which paths are exempt, and the two
2
+ // refusals that name the boundary instead of silently allowing the edit.
3
+
4
+ import { isGatedPath, matchesTargets, relativeToRoot } from './paths.js';
5
+ import { describeTargets, resolveScope, saveScope, workingDirectoryOf } from './scope-store.js';
6
+ import { snapshotBefore } from './fingerprint.js';
7
+
8
+ const GATED_TOOLS = new Set(['edit', 'write', 'apply_patch']);
9
+
10
+ function denialNoScope() {
11
+ return {
12
+ kind: 'deny',
13
+ reason:
14
+ 'Change-scope gate: no scope declaration exists for this session, so this source edit is blocked.\n'
15
+ + 'Before editing source: (1) investigate until you can name the first point where state departs '
16
+ + 'from intent and the defect class it belongs to, or the new contract for a rewrite; (2) ask the '
17
+ + 'user to authorize that boundary and choose a depth, described as consequences; (3) call '
18
+ + 'change_scope with action "declare" and the files as targets.\n'
19
+ + 'Files under .dsh/ and docs/INVARIANTS.md stay editable without a declaration. '
20
+ + 'Markdown and other non-source files are not gated.',
21
+ info: { name: 'ChangeScopeRequired', code: 'no_declaration' },
22
+ };
23
+ }
24
+
25
+ function denialOutside(relative, scope) {
26
+ const ceiling = scope.necessity.replace(/\s+/g, ' ').slice(0, 240);
27
+ return {
28
+ kind: 'deny',
29
+ reason:
30
+ `Change-scope gate: "${relative}" is outside the authorized targets of ${scope.id}.\n`
31
+ + `Authorized targets: ${describeTargets(scope)}\n`
32
+ + `Recorded reason for this boundary: ${ceiling}\n`
33
+ + 'Either edit inside the authorized targets, or — when the boundary itself cannot hold the cause — '
34
+ + 'surface that conflict to the user and call change_scope with action "revise", stating what moved '
35
+ + 'and why. Do not widen the scope silently.',
36
+ info: { name: 'ChangeScopeViolation', code: 'outside_targets' },
37
+ };
38
+ }
39
+
40
+ export function gate(ctx) {
41
+ return async (exec, next) => {
42
+ if (!GATED_TOOLS.has(exec.name)) return next();
43
+ const args = exec.arguments;
44
+ if (!args || typeof args !== 'object') return next();
45
+ const filePath = typeof args.file_path === 'string' ? args.file_path : '';
46
+ if (filePath === '') return next();
47
+ const agentId = exec.agent?.id ?? 'anonymous';
48
+ const cwd = workingDirectoryOf(ctx, exec.agent);
49
+ const scope = await resolveScope(cwd, agentId);
50
+ const location = relativeToRoot(filePath, scope?.root ?? cwd);
51
+ if (!isGatedPath(location.relative)) return next();
52
+ if (!scope || scope.closed) return denialNoScope();
53
+ if (scope.depth === 'deep' && !matchesTargets(location.relative, location.absolute, scope.targets)) {
54
+ return denialOutside(location.relative, scope);
55
+ }
56
+ let changed = false;
57
+ if (!scope.touched.includes(location.relative)) {
58
+ scope.touched.push(location.relative);
59
+ changed = true;
60
+ }
61
+ if (scope.before[location.relative] === undefined) {
62
+ await snapshotBefore(scope, location.relative);
63
+ changed = true;
64
+ }
65
+ if (changed) await saveScope(scope);
66
+ return next();
67
+ };
68
+ }
69
+
70
+ // ---------------------------------------------------------------------------
71
+