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
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Invariant store: keyed entries in docs/invariants.json, a generated
|
|
3
|
+
* docs/INVARIANTS.md view, and the runner that executes each check through
|
|
4
|
+
* the host subprocess service.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { promises as fsp } from 'node:fs';
|
|
8
|
+
import { join } from 'node:path';
|
|
9
|
+
import { settings } from './config.js';
|
|
10
|
+
|
|
11
|
+
export const INVARIANTS_RELATIVE = 'docs/INVARIANTS.md';
|
|
12
|
+
export const INVARIANTS_JSON = 'docs/invariants.json';
|
|
13
|
+
|
|
14
|
+
function slugify(value) {
|
|
15
|
+
const text = String(value ?? '').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '');
|
|
16
|
+
return text.slice(0, 60) || 'invariant';
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export async function readInvariantStore(root) {
|
|
20
|
+
try {
|
|
21
|
+
const parsed = JSON.parse(await fsp.readFile(join(root, INVARIANTS_JSON), 'utf8'));
|
|
22
|
+
return Array.isArray(parsed) ? parsed : [];
|
|
23
|
+
} catch {
|
|
24
|
+
return [];
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function renderInvariants(entries) {
|
|
29
|
+
const active = entries.filter(entry => entry.status === 'active');
|
|
30
|
+
const retired = entries.filter(entry => entry.status !== 'active');
|
|
31
|
+
const lines = [
|
|
32
|
+
'# Invariants',
|
|
33
|
+
'',
|
|
34
|
+
'Generated from `docs/invariants.json` — that file is the source of truth. Close a scope to add or replace an entry; this file is rewritten each time.',
|
|
35
|
+
'',
|
|
36
|
+
];
|
|
37
|
+
for (const entry of active) {
|
|
38
|
+
lines.push(`## ${entry.key}`, '');
|
|
39
|
+
lines.push(`- Invariant: ${entry.statement}`);
|
|
40
|
+
lines.push(entry.check
|
|
41
|
+
? `- Check: \`${entry.check}\``
|
|
42
|
+
: '- Check: none — low trust, nothing fails when this breaks');
|
|
43
|
+
if (entry.lastResult) {
|
|
44
|
+
const exit = typeof entry.lastExit === 'number' ? ` (exit ${entry.lastExit})` : '';
|
|
45
|
+
lines.push(`- Last run: ${entry.lastResult}${exit} on ${entry.lastRun ?? 'unknown date'}`);
|
|
46
|
+
}
|
|
47
|
+
lines.push(`- Why it matters: ${entry.why}`);
|
|
48
|
+
lines.push(`- Established: ${entry.establishedAt} by ${entry.scopeId}`);
|
|
49
|
+
lines.push('');
|
|
50
|
+
}
|
|
51
|
+
if (retired.length > 0) {
|
|
52
|
+
lines.push('## Retired', '');
|
|
53
|
+
for (const entry of retired) {
|
|
54
|
+
const target = entry.supersededBy ? ` → see ${entry.supersededBy}` : '';
|
|
55
|
+
lines.push(`- **${entry.key}** (${entry.status} ${entry.retiredAt ?? ''}) — ${entry.statement}${target}`);
|
|
56
|
+
}
|
|
57
|
+
lines.push('');
|
|
58
|
+
}
|
|
59
|
+
return lines.join('\n');
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
async function preserveHandWrittenView(root) {
|
|
63
|
+
if (!settings().preserveManualView) return null;
|
|
64
|
+
const target = join(root, INVARIANTS_RELATIVE);
|
|
65
|
+
let existing;
|
|
66
|
+
try {
|
|
67
|
+
existing = await fsp.readFile(target, 'utf8');
|
|
68
|
+
} catch {
|
|
69
|
+
return null;
|
|
70
|
+
}
|
|
71
|
+
if (existing.trim() === '') return null;
|
|
72
|
+
if (existing.includes('Generated from `docs/invariants.json`')) return null;
|
|
73
|
+
const backup = join(root, 'docs', 'INVARIANTS.manual.md');
|
|
74
|
+
try {
|
|
75
|
+
await fsp.access(backup);
|
|
76
|
+
return backup;
|
|
77
|
+
} catch {
|
|
78
|
+
await fsp.writeFile(backup, existing, 'utf8');
|
|
79
|
+
return backup;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export async function writeInvariantStore(root, entries) {
|
|
84
|
+
await fsp.mkdir(join(root, 'docs'), { recursive: true });
|
|
85
|
+
await fsp.writeFile(join(root, INVARIANTS_JSON), `${JSON.stringify(entries, null, 2)}\n`, 'utf8');
|
|
86
|
+
// Never destroy a view the plugin did not write: keep the original once, then render.
|
|
87
|
+
const preserved = await preserveHandWrittenView(root);
|
|
88
|
+
await fsp.writeFile(join(root, INVARIANTS_RELATIVE), `${renderInvariants(entries)}\n`, 'utf8');
|
|
89
|
+
return { file: join(root, INVARIANTS_RELATIVE), preserved };
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export async function upsertInvariant(root, scope, invariant, check, keyHint) {
|
|
93
|
+
if (!root) return null;
|
|
94
|
+
const entries = await readInvariantStore(root);
|
|
95
|
+
const stamp = new Date().toISOString().slice(0, 10);
|
|
96
|
+
const key = slugify(keyHint || scope.cause?.contract || invariant);
|
|
97
|
+
const current = entries.find(entry => entry.key === key && entry.status === 'active');
|
|
98
|
+
if (current && current.statement === invariant) {
|
|
99
|
+
if (check) current.check = check;
|
|
100
|
+
current.updatedAt = stamp;
|
|
101
|
+
} else {
|
|
102
|
+
if (current) {
|
|
103
|
+
current.status = 'superseded';
|
|
104
|
+
current.retiredAt = stamp;
|
|
105
|
+
current.supersededBy = key;
|
|
106
|
+
}
|
|
107
|
+
entries.push({
|
|
108
|
+
key,
|
|
109
|
+
statement: invariant,
|
|
110
|
+
check: check ?? null,
|
|
111
|
+
why: scope.necessity.replace(/\s+/g, ' ').slice(0, 200),
|
|
112
|
+
status: 'active',
|
|
113
|
+
establishedAt: stamp,
|
|
114
|
+
scopeId: scope.id,
|
|
115
|
+
supersedes: current ? `${key}@${current.establishedAt}` : null,
|
|
116
|
+
retiredAt: null,
|
|
117
|
+
supersededBy: null,
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
const written = await writeInvariantStore(root, entries);
|
|
121
|
+
return { key, file: written.file, preserved: written.preserved };
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
async function runCheck(subprocess, root, check) {
|
|
125
|
+
// The check is split on whitespace: no shell, no quoting, predictable on every platform.
|
|
126
|
+
const argv = check.trim().split(/\s+/).filter(Boolean);
|
|
127
|
+
if (argv.length === 0) throw new Error('empty check');
|
|
128
|
+
// The host process is itself a node executable, so a check written as "node ..."
|
|
129
|
+
// works on a desktop install where PATH carries no node. Every other bare name
|
|
130
|
+
// still goes through the provider's executable lookup.
|
|
131
|
+
const head = argv[0].toLowerCase();
|
|
132
|
+
const executable = head === 'node' || head === 'node.exe'
|
|
133
|
+
? process.execPath
|
|
134
|
+
: await subprocess.resolveExecutable(argv[0]);
|
|
135
|
+
const controller = new AbortController();
|
|
136
|
+
const timer = setTimeout(() => controller.abort(), settings().checkTimeoutMs);
|
|
137
|
+
try {
|
|
138
|
+
const handle = subprocess.spawn({
|
|
139
|
+
argv: [executable, ...argv.slice(1)],
|
|
140
|
+
cwd: root,
|
|
141
|
+
stdio: {
|
|
142
|
+
stdin: 'ignore',
|
|
143
|
+
stdout: { maxBytes: 200000 },
|
|
144
|
+
stderr: { maxBytes: 200000 },
|
|
145
|
+
},
|
|
146
|
+
graceMs: 2000,
|
|
147
|
+
signal: controller.signal,
|
|
148
|
+
});
|
|
149
|
+
const outcome = await handle.done;
|
|
150
|
+
const stdout = handle.collected?.stdout?.readFrom(0)?.text ?? '';
|
|
151
|
+
const stderr = handle.collected?.stderr?.readFrom(0)?.text ?? '';
|
|
152
|
+
const exitCode = typeof outcome?.exitCode === 'number' ? outcome.exitCode : 1;
|
|
153
|
+
return { exitCode, detail: clip(stderr || stdout || '') };
|
|
154
|
+
} finally {
|
|
155
|
+
clearTimeout(timer);
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
export async function verifyInvariants(ctx, root) {
|
|
160
|
+
if (!root) {
|
|
161
|
+
return { ok: false, checked: 0, passed: 0, failed: 0, unchecked: 0, results: [], message: 'The workspace directory could not be resolved, so no check could run.' };
|
|
162
|
+
}
|
|
163
|
+
const entries = await readInvariantStore(root);
|
|
164
|
+
const active = entries.filter(entry => entry.status === 'active');
|
|
165
|
+
const subprocess = ctx.get?.('subprocess');
|
|
166
|
+
const stamp = new Date().toISOString().slice(0, 10);
|
|
167
|
+
const results = [];
|
|
168
|
+
let passed = 0;
|
|
169
|
+
let failed = 0;
|
|
170
|
+
let unchecked = 0;
|
|
171
|
+
let unavailable = 0;
|
|
172
|
+
|
|
173
|
+
for (const entry of active) {
|
|
174
|
+
if (!entry.check) {
|
|
175
|
+
unchecked += 1;
|
|
176
|
+
results.push({ key: entry.key, check: null, status: 'unchecked', exitCode: null, detail: '' });
|
|
177
|
+
continue;
|
|
178
|
+
}
|
|
179
|
+
if (!subprocess?.spawn) {
|
|
180
|
+
unavailable += 1;
|
|
181
|
+
results.push({ key: entry.key, check: entry.check, status: 'unavailable', exitCode: null, detail: 'the subprocess service is not available in this profile' });
|
|
182
|
+
continue;
|
|
183
|
+
}
|
|
184
|
+
try {
|
|
185
|
+
const run = await runCheck(subprocess, root, entry.check);
|
|
186
|
+
entry.lastRun = stamp;
|
|
187
|
+
entry.lastExit = run.exitCode;
|
|
188
|
+
entry.lastResult = run.exitCode === 0 ? 'passed' : 'failed';
|
|
189
|
+
if (run.exitCode === 0) passed += 1;
|
|
190
|
+
else failed += 1;
|
|
191
|
+
results.push({
|
|
192
|
+
key: entry.key,
|
|
193
|
+
check: entry.check,
|
|
194
|
+
status: entry.lastResult,
|
|
195
|
+
exitCode: run.exitCode,
|
|
196
|
+
detail: run.exitCode === 0 ? '' : run.detail,
|
|
197
|
+
});
|
|
198
|
+
} catch (error) {
|
|
199
|
+
entry.lastRun = stamp;
|
|
200
|
+
entry.lastResult = 'error';
|
|
201
|
+
delete entry.lastExit;
|
|
202
|
+
failed += 1;
|
|
203
|
+
results.push({
|
|
204
|
+
key: entry.key,
|
|
205
|
+
check: entry.check,
|
|
206
|
+
status: 'error',
|
|
207
|
+
exitCode: null,
|
|
208
|
+
detail: clip(String(error?.message ?? error)),
|
|
209
|
+
});
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
await writeInvariantStore(root, entries);
|
|
214
|
+
return {
|
|
215
|
+
ok: failed === 0 && unavailable === 0,
|
|
216
|
+
checked: passed + failed,
|
|
217
|
+
passed,
|
|
218
|
+
failed,
|
|
219
|
+
unchecked,
|
|
220
|
+
unavailable,
|
|
221
|
+
results,
|
|
222
|
+
message: failed === 0
|
|
223
|
+
? `All ${passed} executable invariant check(s) hold; ${unchecked} entr${unchecked === 1 ? 'y has' : 'ies have'} no check.`
|
|
224
|
+
: `${failed} invariant check(s) failed. A recorded invariant that no longer holds is worse than none.`,
|
|
225
|
+
};
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
export function clip(value) {
|
|
230
|
+
return value.replace(/\s+/g, ' ').slice(0, 160);
|
|
231
|
+
}
|
package/lib/paths.js
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
// Path and glob helpers: workspace-relative resolution and target matching.
|
|
2
|
+
|
|
3
|
+
import { INVARIANTS_RELATIVE } from './invariants.js';
|
|
4
|
+
|
|
5
|
+
const UNGATED_EXTENSIONS = new Set([
|
|
6
|
+
'.md', '.txt', '.png', '.jpg', '.jpeg', '.svg', '.gif', '.webp', '.pdf',
|
|
7
|
+
'.log', '.lock', '.csv', '.tsv',
|
|
8
|
+
]);
|
|
9
|
+
|
|
10
|
+
export function normPath(value) {
|
|
11
|
+
return String(value ?? '').replace(/\\/g, '/');
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export function isAbsolutePath(value) {
|
|
15
|
+
return /^[a-z]:\//i.test(value) || value.startsWith('/');
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export function extensionOf(relative) {
|
|
19
|
+
const name = relative.slice(relative.lastIndexOf('/') + 1);
|
|
20
|
+
const dot = name.lastIndexOf('.');
|
|
21
|
+
return dot <= 0 ? '' : name.slice(dot).toLowerCase();
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function globToRegExp(pattern) {
|
|
25
|
+
const source = normPath(pattern).trim().replace(/\/+$/, '');
|
|
26
|
+
let out = '';
|
|
27
|
+
for (let i = 0; i < source.length; i += 1) {
|
|
28
|
+
const char = source[i];
|
|
29
|
+
if (char === '*') {
|
|
30
|
+
if (source[i + 1] === '*') {
|
|
31
|
+
i += 1;
|
|
32
|
+
if (source[i + 1] === '/') {
|
|
33
|
+
i += 1;
|
|
34
|
+
out += '(?:[^/]+/)*';
|
|
35
|
+
} else {
|
|
36
|
+
out += '.*';
|
|
37
|
+
}
|
|
38
|
+
} else {
|
|
39
|
+
out += '[^/]*';
|
|
40
|
+
}
|
|
41
|
+
} else if (char === '?') {
|
|
42
|
+
out += '[^/]';
|
|
43
|
+
} else if ('\\^$+.()|{}[]'.includes(char)) {
|
|
44
|
+
out += `\\${char}`;
|
|
45
|
+
} else {
|
|
46
|
+
out += char;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
return new RegExp(`^${out}$`, 'i');
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export function relativeToRoot(filePath, root) {
|
|
53
|
+
const path = normPath(filePath);
|
|
54
|
+
if (!root) return { relative: path, absolute: isAbsolutePath(path) };
|
|
55
|
+
const base = normPath(root).replace(/\/+$/, '');
|
|
56
|
+
const pathLower = path.toLowerCase();
|
|
57
|
+
const baseLower = base.toLowerCase();
|
|
58
|
+
if (pathLower === baseLower) return { relative: '', absolute: false };
|
|
59
|
+
if (pathLower.startsWith(`${baseLower}/`)) {
|
|
60
|
+
return { relative: path.slice(base.length + 1), absolute: false };
|
|
61
|
+
}
|
|
62
|
+
return { relative: path, absolute: isAbsolutePath(path) };
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export function matchesPattern(relative, absolute, pattern) {
|
|
66
|
+
const matcher = globToRegExp(pattern);
|
|
67
|
+
if (matcher.test(relative)) return true;
|
|
68
|
+
if (!absolute) return false;
|
|
69
|
+
// The workspace root is unknown, so try each trailing segment run.
|
|
70
|
+
const segments = relative.split('/');
|
|
71
|
+
for (let i = 1; i < segments.length; i += 1) {
|
|
72
|
+
if (matcher.test(segments.slice(i).join('/'))) return true;
|
|
73
|
+
}
|
|
74
|
+
return false;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export function matchesTargets(relative, absolute, targets) {
|
|
78
|
+
return (targets ?? []).some(pattern => matchesPattern(relative, absolute, pattern));
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export function isAlwaysWritable(relative) {
|
|
82
|
+
const value = relative.toLowerCase();
|
|
83
|
+
if (value === INVARIANTS_RELATIVE) return true;
|
|
84
|
+
if (value.endsWith(`/${INVARIANTS_RELATIVE}`)) return true;
|
|
85
|
+
if (value === '.dsh' || value.startsWith('.dsh/')) return true;
|
|
86
|
+
return value.includes('/.dsh/');
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export function isGatedPath(relative) {
|
|
90
|
+
if (isAlwaysWritable(relative)) return false;
|
|
91
|
+
return !UNGATED_EXTENSIONS.has(extensionOf(relative));
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// ---------------------------------------------------------------------------
|
|
95
|
+
// Structural fingerprint
|
|
96
|
+
//
|
|
97
|
+
// Deliberately lexical, not semantic. It separates "the public surface moved"
|
|
98
|
+
// from "another branch was added" without pretending to understand the file.
|
|
99
|
+
// Only exported names carry a signature: an internal rename is not a contract
|
|
100
|
+
// change, and counting it as one would drown the signal.
|
|
101
|
+
|
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
// Scope records: the per-session declaration, its durable file, and the
|
|
2
|
+
// argument validators the tool shares with it.
|
|
3
|
+
|
|
4
|
+
import { promises as fsp } from 'node:fs';
|
|
5
|
+
import { join } from 'node:path';
|
|
6
|
+
import { settings } from './config.js';
|
|
7
|
+
|
|
8
|
+
export const MODES = ['fix', 'rewrite', 'feature'];
|
|
9
|
+
export const DEPTHS = ['quick', 'deep'];
|
|
10
|
+
export const AUTHORIZATIONS = ['user', 'assumed'];
|
|
11
|
+
const STATE_VERSION = 1;
|
|
12
|
+
|
|
13
|
+
/** @type {Map<string, object>} */
|
|
14
|
+
export const scopes = new Map();
|
|
15
|
+
|
|
16
|
+
export function describeTargets(scope) {
|
|
17
|
+
return scope.targets.length > 0 ? scope.targets.join(', ') : '(none)';
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function emptyScope(agentId, cwd) {
|
|
21
|
+
return {
|
|
22
|
+
id: `scope-${Date.now().toString(36)}`,
|
|
23
|
+
agentId,
|
|
24
|
+
root: cwd,
|
|
25
|
+
mode: 'fix',
|
|
26
|
+
depth: 'deep',
|
|
27
|
+
necessity: '',
|
|
28
|
+
authorization: 'assumed',
|
|
29
|
+
targets: [],
|
|
30
|
+
contracts: [],
|
|
31
|
+
excluded: [],
|
|
32
|
+
revisions: [],
|
|
33
|
+
touched: [],
|
|
34
|
+
before: {},
|
|
35
|
+
observation: null,
|
|
36
|
+
cause: null,
|
|
37
|
+
discard: [],
|
|
38
|
+
refuted: [],
|
|
39
|
+
prior: null,
|
|
40
|
+
watch: null,
|
|
41
|
+
declaredAt: Date.now(),
|
|
42
|
+
updatedAt: Date.now(),
|
|
43
|
+
closed: null,
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function publicView(scope) {
|
|
48
|
+
return {
|
|
49
|
+
declarationId: scope.id,
|
|
50
|
+
mode: scope.mode,
|
|
51
|
+
depth: scope.depth,
|
|
52
|
+
authorization: scope.authorization,
|
|
53
|
+
necessity: scope.necessity,
|
|
54
|
+
targets: scope.targets,
|
|
55
|
+
contracts: scope.contracts,
|
|
56
|
+
excluded: scope.excluded,
|
|
57
|
+
revisions: scope.revisions.length,
|
|
58
|
+
touched: [...new Set(scope.touched)],
|
|
59
|
+
observation: scope.observation,
|
|
60
|
+
cause: scope.cause,
|
|
61
|
+
discard: scope.discard ?? [],
|
|
62
|
+
refuted: (scope.refuted ?? []).length,
|
|
63
|
+
prior: scope.prior ?? null,
|
|
64
|
+
updatedAt: scope.updatedAt ?? null,
|
|
65
|
+
root: scope.root ?? null,
|
|
66
|
+
closed: scope.closed !== null,
|
|
67
|
+
closure: scope.closed ?? null,
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export function requireString(args, field) {
|
|
72
|
+
const value = args[field];
|
|
73
|
+
if (typeof value !== 'string' || value.trim() === '') {
|
|
74
|
+
throw new Error(`change_scope: "${field}" is required and must be a non-empty string.`);
|
|
75
|
+
}
|
|
76
|
+
return value.trim();
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export function optionalStringArray(args, field) {
|
|
80
|
+
const value = args[field];
|
|
81
|
+
if (value === undefined || value === null) return undefined;
|
|
82
|
+
if (!Array.isArray(value) || value.some(item => typeof item !== 'string' || item.trim() === '')) {
|
|
83
|
+
throw new Error(`change_scope: "${field}" must be an array of non-empty strings.`);
|
|
84
|
+
}
|
|
85
|
+
return value.map(item => item.trim());
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export function requireEnum(value, allowed, field, fallback) {
|
|
89
|
+
if (value === undefined || value === null) {
|
|
90
|
+
if (fallback !== undefined) return fallback;
|
|
91
|
+
throw new Error(`change_scope: "${field}" is required. Allowed: ${allowed.join(', ')}.`);
|
|
92
|
+
}
|
|
93
|
+
if (!allowed.includes(value)) {
|
|
94
|
+
throw new Error(`change_scope: "${field}" must be one of ${allowed.join(', ')}.`);
|
|
95
|
+
}
|
|
96
|
+
return value;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export function sessionOf(ctx, agent) {
|
|
100
|
+
if (!agent) return undefined;
|
|
101
|
+
const direct = agent.session;
|
|
102
|
+
if (direct) return direct;
|
|
103
|
+
try {
|
|
104
|
+
return ctx.agents?.get?.(agent.id)?.session;
|
|
105
|
+
} catch {
|
|
106
|
+
return undefined;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
export function workingDirectoryOf(ctx, agent) {
|
|
111
|
+
const session = sessionOf(ctx, agent);
|
|
112
|
+
if (!session) return undefined;
|
|
113
|
+
try {
|
|
114
|
+
return ctx.workingDirectory.get(session);
|
|
115
|
+
} catch {
|
|
116
|
+
return undefined;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
// ---------------------------------------------------------------------------
|
|
121
|
+
// Durable scope records
|
|
122
|
+
//
|
|
123
|
+
// One JSON file per session under <workspace>/.dsh/change-scope/. The in-memory
|
|
124
|
+
// map is the hot copy; the file is what survives a plugin reload, a restart, or
|
|
125
|
+
// a resumed session. Persistence is best effort: a failed write never blocks an
|
|
126
|
+
// edit, and a malformed file is ignored rather than trusted.
|
|
127
|
+
|
|
128
|
+
function sanitizeId(value) {
|
|
129
|
+
const text = String(value ?? 'anonymous').replace(/[^A-Za-z0-9._-]/g, '_').slice(0, 120);
|
|
130
|
+
return text === '' ? 'anonymous' : text;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
function statePath(root, agentId) {
|
|
134
|
+
return join(root, settings().stateDir, `${sanitizeId(agentId)}.json`);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
export async function saveScope(scope) {
|
|
138
|
+
if (!scope?.root) return null;
|
|
139
|
+
try {
|
|
140
|
+
const target = statePath(scope.root, scope.agentId);
|
|
141
|
+
await fsp.mkdir(join(scope.root, settings().stateDir), { recursive: true });
|
|
142
|
+
scope.updatedAt = Date.now();
|
|
143
|
+
const payload = { version: STATE_VERSION, ...scope };
|
|
144
|
+
await fsp.writeFile(target, `${JSON.stringify(payload, null, 2)}\n`, 'utf8');
|
|
145
|
+
return target;
|
|
146
|
+
} catch {
|
|
147
|
+
return null;
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
function stringsOf(value) {
|
|
152
|
+
return Array.isArray(value) ? value.filter(item => typeof item === 'string') : [];
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
export async function loadScope(root, agentId) {
|
|
156
|
+
if (!root) return null;
|
|
157
|
+
try {
|
|
158
|
+
const text = await fsp.readFile(statePath(root, agentId), 'utf8');
|
|
159
|
+
const parsed = JSON.parse(text);
|
|
160
|
+
if (!parsed || parsed.version !== STATE_VERSION) return null;
|
|
161
|
+
if (typeof parsed.id !== 'string' || !Array.isArray(parsed.targets)) return null;
|
|
162
|
+
if (typeof parsed.before !== 'object' || parsed.before === null) return null;
|
|
163
|
+
return {
|
|
164
|
+
id: parsed.id,
|
|
165
|
+
agentId,
|
|
166
|
+
root: typeof parsed.root === 'string' ? parsed.root : root,
|
|
167
|
+
mode: MODES.includes(parsed.mode) ? parsed.mode : 'fix',
|
|
168
|
+
depth: DEPTHS.includes(parsed.depth) ? parsed.depth : 'deep',
|
|
169
|
+
necessity: typeof parsed.necessity === 'string' ? parsed.necessity : '',
|
|
170
|
+
authorization: AUTHORIZATIONS.includes(parsed.authorization) ? parsed.authorization : 'assumed',
|
|
171
|
+
targets: stringsOf(parsed.targets),
|
|
172
|
+
contracts: stringsOf(parsed.contracts),
|
|
173
|
+
excluded: stringsOf(parsed.excluded),
|
|
174
|
+
revisions: Array.isArray(parsed.revisions) ? parsed.revisions : [],
|
|
175
|
+
touched: stringsOf(parsed.touched),
|
|
176
|
+
before: parsed.before,
|
|
177
|
+
observation: parsed.observation ?? null,
|
|
178
|
+
cause: parsed.cause ?? null,
|
|
179
|
+
discard: stringsOf(parsed.discard),
|
|
180
|
+
refuted: Array.isArray(parsed.refuted) ? parsed.refuted : [],
|
|
181
|
+
prior: parsed.prior ?? null,
|
|
182
|
+
watch: parsed.watch ?? null,
|
|
183
|
+
declaredAt: typeof parsed.declaredAt === 'number' ? parsed.declaredAt : Date.now(),
|
|
184
|
+
updatedAt: typeof parsed.updatedAt === 'number' ? parsed.updatedAt : Date.now(),
|
|
185
|
+
closed: parsed.closed ?? null,
|
|
186
|
+
};
|
|
187
|
+
} catch {
|
|
188
|
+
return null;
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
export async function resolveScope(root, agentId) {
|
|
193
|
+
const cached = scopes.get(agentId);
|
|
194
|
+
if (cached) return cached;
|
|
195
|
+
const loaded = await loadScope(root, agentId);
|
|
196
|
+
if (loaded) {
|
|
197
|
+
scopes.set(agentId, loaded);
|
|
198
|
+
return loaded;
|
|
199
|
+
}
|
|
200
|
+
return undefined;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
// ---------------------------------------------------------------------------
|
|
204
|
+
// Invariant sedimentation
|
|
205
|
+
|
package/lib/session.js
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Session-log questions: did the agent actually ask the user, or does the
|
|
3
|
+
* transcript merely contain a plan to? These read committed events only.
|
|
4
|
+
*/
|
|
5
|
+
export function identicalCause(left, right) {
|
|
6
|
+
if (!left || !right) return false;
|
|
7
|
+
return left.contract === right.contract && left.class === right.class;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
function sessionEvents(session) {
|
|
11
|
+
try {
|
|
12
|
+
const events = session?.ownEvents?.();
|
|
13
|
+
return Array.isArray(events) ? events : null;
|
|
14
|
+
} catch {
|
|
15
|
+
return null;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function lastIndexMatching(events, predicate) {
|
|
20
|
+
for (let index = events.length - 1; index >= 0; index -= 1) {
|
|
21
|
+
if (predicate(events[index])) return index;
|
|
22
|
+
}
|
|
23
|
+
return -1;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function isAskCall(event) {
|
|
27
|
+
return event?.type === 'tool/call' && event.data?.name === 'ask_user_question';
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function askedAfter(events, boundary) {
|
|
31
|
+
for (let index = Math.max(boundary + 1, 0); index < events.length; index += 1) {
|
|
32
|
+
if (isAskCall(events[index])) return true;
|
|
33
|
+
}
|
|
34
|
+
return false;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function isDeclareCall(event) {
|
|
38
|
+
if (event?.type !== 'tool/call' || event.data?.name !== 'change_scope') return false;
|
|
39
|
+
try {
|
|
40
|
+
return JSON.parse(event.data.arguments ?? '{}').action === 'declare';
|
|
41
|
+
} catch {
|
|
42
|
+
return false;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// null means the session log was unavailable, so the check could not run.
|
|
47
|
+
export function askedBeforeDeclare(session) {
|
|
48
|
+
const events = sessionEvents(session);
|
|
49
|
+
if (!events) return null;
|
|
50
|
+
const lastUser = lastIndexMatching(events, event => event?.type === 'user/message');
|
|
51
|
+
const lastAsk = lastIndexMatching(events, isAskCall);
|
|
52
|
+
if (lastAsk < 0) return false;
|
|
53
|
+
// Asked after the latest human turn: the ordinary case.
|
|
54
|
+
if (lastAsk > lastUser) return true;
|
|
55
|
+
// A question's answer is itself recorded as a user message, so the boundary
|
|
56
|
+
// moves past the ask that prompted it. When the latest user message is that
|
|
57
|
+
// answer — no other user message sits between the ask and it — the ask still
|
|
58
|
+
// counts as having happened before this declaration.
|
|
59
|
+
const answeredDirectly = !events
|
|
60
|
+
.slice(lastAsk + 1, lastUser)
|
|
61
|
+
.some(event => event?.type === 'user/message');
|
|
62
|
+
return answeredDirectly;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export function askedBeforeClose(session) {
|
|
66
|
+
const events = sessionEvents(session);
|
|
67
|
+
if (!events) return null;
|
|
68
|
+
const boundary = lastIndexMatching(events, isDeclareCall);
|
|
69
|
+
return askedAfter(events, boundary);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function flatten(value) {
|
|
73
|
+
return String(value ?? '').replace(/\\/g, '');
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Was the verification actually run, and did it report what the agent says?
|
|
78
|
+
*
|
|
79
|
+
* Only committed events are read: a tool call that carried the command, and the
|
|
80
|
+
* result that came back for the same call id. null means the log was unavailable,
|
|
81
|
+
* so the question could not be asked at all.
|
|
82
|
+
*/
|
|
83
|
+
export function evidenceInLog(session, command, actual) {
|
|
84
|
+
const events = sessionEvents(session);
|
|
85
|
+
if (!events || !command) return null;
|
|
86
|
+
const declared = lastIndexMatching(events, isDeclareCall);
|
|
87
|
+
const from = declared < 0 ? 0 : declared;
|
|
88
|
+
const wanted = flatten(command).trim();
|
|
89
|
+
const reported = flatten(actual).trim();
|
|
90
|
+
let commandSeen = false;
|
|
91
|
+
let outputMatched = false;
|
|
92
|
+
for (let index = from; index < events.length; index += 1) {
|
|
93
|
+
const event = events[index];
|
|
94
|
+
if (event?.type !== 'tool/call') continue;
|
|
95
|
+
const name = event.data?.name;
|
|
96
|
+
if (!name || name === 'ask_user_question' || name === 'change_scope') continue;
|
|
97
|
+
if (!flatten(event.data?.arguments).includes(wanted)) continue;
|
|
98
|
+
commandSeen = true;
|
|
99
|
+
const callId = event.data?.callId;
|
|
100
|
+
if (!callId) continue;
|
|
101
|
+
for (let next = index + 1; next < events.length; next += 1) {
|
|
102
|
+
const result = events[next];
|
|
103
|
+
if (result?.type !== 'tool/result') continue;
|
|
104
|
+
if (result.data?.message?.toolCallId !== callId) continue;
|
|
105
|
+
if (reported === '' || flatten(JSON.stringify(result.data)).includes(reported)) {
|
|
106
|
+
outputMatched = true;
|
|
107
|
+
}
|
|
108
|
+
break;
|
|
109
|
+
}
|
|
110
|
+
if (outputMatched) break;
|
|
111
|
+
}
|
|
112
|
+
return { commandSeen, outputMatched };
|
|
113
|
+
}
|
|
114
|
+
|