buildproof 0.0.0-stage → 3.8.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/core/flow.js ADDED
@@ -0,0 +1,852 @@
1
+ 'use strict';
2
+ /**
3
+ * Two ways to work, same guarantees:
4
+ *
5
+ * A) Supervised task (BuildProof does the work):
6
+ * diagnosing -> awaiting_approval -> executing -> verifying -> done | unproven | rolled_back | failed
7
+ *
8
+ * B) Guard (the developer works with ANY AI tool - Cursor, Claude Code, Copilot...):
9
+ * baselining -> watching -> (check ...) -> done (certificate) | rolled_back
10
+ *
11
+ * Guarantees:
12
+ * - Nothing is written before the developer approves the scope (A).
13
+ * - Every file in the project is copied first -> full rollback is always possible.
14
+ * - Any change outside the approved scope is reverted automatically (A).
15
+ * - Test-integrity guard: deleting / skipping / weakening tests, mocks, sleeps, silent catches -> rejected.
16
+ * - Fail-closed gate: a check that did not really run = not proven. Never "done" by default.
17
+ * - Proven work gets a signed certificate.
18
+ * - A verified AI fix is stored in the fix library and replayed next time without AI.
19
+ */
20
+ const fs = require('fs');
21
+ const path = require('path');
22
+ const crypto = require('crypto');
23
+ const store = require('./store');
24
+ const projects = require('./projects');
25
+ const snapshot = require('./snapshot');
26
+ const scope = require('./scope');
27
+ const fixlib = require('./fixlib');
28
+ const edits = require('./edits');
29
+ const ai = require('./ai');
30
+ const gate = require('./gate');
31
+ const integrity = require('./integrity');
32
+ const certs = require('./certs');
33
+ const claims = require('./claims');
34
+ const license = require('./license');
35
+ const { run } = require('./runner');
36
+ const { DATA_DIR } = require('./config');
37
+
38
+ const FIX_INTENT = /\bfix|\bbug|\berror|broken|failing|fails?\b|crash|exception|doesn'?t work|not working|repair|תקן|באג|שגיאה|נשבר|לא עובד|נכשל/i;
39
+ const GUARD_ACTIVE = ['baselining', 'watching', 'checking'];
40
+ const running = new Map(); // taskId -> { stop: boolean }
41
+ const busyProjects = new Set();
42
+ let listeners = [];
43
+
44
+ function now() { return new Date().toISOString(); }
45
+ function newId(prefix) { return prefix + crypto.randomBytes(6).toString('hex'); }
46
+ function onChange(fn) { listeners.push(fn); return () => { listeners = listeners.filter((l) => l !== fn); }; }
47
+ function emit(task) { for (const l of listeners) { try { l(task); } catch { /* ignore */ } } }
48
+
49
+ function log(taskId, line) {
50
+ const t = store.get('tasks', taskId);
51
+ if (!t) return;
52
+ t.log = t.log || [];
53
+ t.log.push({ at: now(), line: String(line).slice(0, 2000) });
54
+ if (t.log.length > 400) t.log.splice(0, t.log.length - 400);
55
+ store.update('tasks', taskId, { log: t.log });
56
+ emit(store.get('tasks', taskId));
57
+ }
58
+
59
+ function setState(taskId, state, patch = {}) {
60
+ const t = store.update('tasks', taskId, { state, ...patch });
61
+ emit(t);
62
+ return t;
63
+ }
64
+
65
+ function tail(s, n = 4000) { s = String(s || ''); return s.length > n ? '...\n' + s.slice(-n) : s; }
66
+ function isLocalEndpoint(u) { try { return /^(localhost|127\.\d+\.\d+\.\d+|\[?::1\]?)$/i.test(new URL(u).hostname); } catch { return false; } }
67
+
68
+ /* ---------------- verification (fail-closed) ---------------- */
69
+
70
+ async function verify(project, cfg, taskId, label) {
71
+ const results = {};
72
+ for (const step of project.verify) {
73
+ if (running.get(taskId)?.stop) break;
74
+ const { cmd, args } = projects.commandFor(project, step);
75
+ log(taskId, `${label}: ${cmd === 'npm' ? 'npm run ' + step : step + ' (' + [require('path').basename(cmd), ...args].join(' ') + ')'}`);
76
+ const t0 = Date.now();
77
+ const r = await run(cmd, args, { cwd: project.root, timeoutMs: cfg.commandTimeoutMs, env: { PYTHONDONTWRITEBYTECODE: '1' } });
78
+ if (/test/.test(step) && project.junitXml) r.output = String(r.output || '') + junitSummary(path.join(project.root, project.junitXml), t0);
79
+ const g = gate.evaluate(step, r, { strictCounts: STRICT_TYPES.has(project.type) });
80
+ // file paths are taken from the FULL output (the stored output is cut to its tail)
81
+ const paths = [...new Set((String(r.output || '').match(/[\w@./\\:-]+\.(?:[cm]?[jt]sx?|py)\b/g) || []).filter((x) => !/node_modules|node:internal/.test(x)))].slice(0, 300);
82
+ results[step] = { ...g, output: tail(r.output, 6000), paths, failBlocks: g.pass ? undefined : enrichBlocks(project.root, gate.failureBlocks(r.output)) };
83
+ const extra = g.tests ? ` ${g.tests.passed}/${g.tests.total} tests` : '';
84
+ log(taskId, `${label}: ${step} -> ${g.pass ? 'PASS' : g.ran ? 'FAIL' : 'DID NOT RUN (' + g.reason + ')'}${extra} (${Math.round(r.ms / 1000)}s)`);
85
+ }
86
+ return results;
87
+ }
88
+
89
+ const STRICT_TYPES = new Set(['go', 'rust', 'java-maven', 'java-gradle', 'dotnet', 'ruby', 'php']);
90
+ /** Gradle prints no totals: read the JUnit XML it wrote in THIS run (older files are ignored) and add a Maven-style summary. */
91
+ function junitSummary(dir, sinceMs) {
92
+ let tests = 0, failures = 0, errors = 0, skipped = 0; const failed = [];
93
+ (function rec(d) {
94
+ let es = []; try { es = fs.readdirSync(d, { withFileTypes: true }); } catch { return; }
95
+ for (const e of es) {
96
+ const f = path.join(d, e.name);
97
+ if (e.isDirectory()) { rec(f); continue; }
98
+ if (!/\.xml$/i.test(e.name)) continue;
99
+ try { if (fs.statSync(f).mtimeMs < sinceMs - 1000) continue; } catch { continue; }
100
+ const x = fs.readFileSync(f, 'utf8');
101
+ const suite = x.match(/<testsuite\b[^>]*>/); if (!suite) continue;
102
+ const at = (k) => +((suite[0].match(new RegExp(`\\b${k}="(\\d+)"`)) || [0, 0])[1]);
103
+ tests += at('tests'); failures += at('failures'); errors += at('errors'); skipped += at('skipped');
104
+ const re = /<testcase\b[^>]*name="([^"]+)"[^>]*classname="([^"]+)"[^>]*>(?:(?!<\/testcase>)[\s\S])*?<(failure|error)\b/g; let m;
105
+ while ((m = re.exec(x))) failed.push(`${m[2]}.${m[1].replace(/\(\)$/, '')}`);
106
+ }
107
+ })(dir);
108
+ if (!tests) return '';
109
+ return `\n${failed.map((n) => `[ERROR] ${n} failed`).join('\n')}\nTests run: ${tests}, Failures: ${failures}, Errors: ${errors}, Skipped: ${skipped}\n`;
110
+ }
111
+
112
+ /** Add the exact failing line of the test ("assert.strictEqual(fee(1000), 5)") to each failure block. */
113
+ function enrichBlocks(root, blocks) {
114
+ const out = {};
115
+ for (const [name, text] of Object.entries(blocks).slice(0, 40)) {
116
+ let extra = '';
117
+ const re = /([\w@./\\:-]+\.(?:[cm]?[jt]sx?|py))(?::|", line )(\d+)/g;
118
+ let m;
119
+ while ((m = re.exec(text))) {
120
+ const abs = path.isAbsolute(m[1]) ? m[1] : path.join(root, m[1]);
121
+ if (!abs.toLowerCase().startsWith(path.resolve(root).toLowerCase()) || !integrity.isTestFile(path.relative(root, abs).split(path.sep).join('/'))) continue;
122
+ const src = fixlib.readContent(root, path.relative(root, abs)) || '';
123
+ const line = src.split(/\r?\n/)[Number(m[2]) - 1];
124
+ if (line && !/^\s*(test|it|describe|def )\b/.test(line)) { extra = `\nFAILING LINE ${path.relative(root, abs).split(path.sep).join('/')}:${m[2]}: ${line.trim()}`; break; }
125
+ }
126
+ out[name] = (text.length > 1200 ? text.slice(0, 1200) + '\n...' : text) + extra;
127
+ }
128
+ return out;
129
+ }
130
+
131
+ /** Only the failures of THIS task's tests, with the failing line - small and to the point. */
132
+ function focusedFailure(results, names) {
133
+ const parts = [];
134
+ for (const r of Object.values(results || {})) for (const n of names) if (r.failBlocks && r.failBlocks[n]) parts.push(r.failBlocks[n]);
135
+ return parts.join('\n\n');
136
+ }
137
+
138
+ function failureText(results) {
139
+ return Object.entries(results || {}).filter(([, r]) => !r.pass).map(([s, r]) => `### ${s} (exit ${r.code}${r.reason ? ', ' + r.reason : ''})\n${r.output}`).join('\n\n');
140
+ }
141
+
142
+ /** Kept for compatibility: judge(baseline, after, isFix) -> gate.judge with the baseline steps. */
143
+ function judge(baseline, after, isFix) { return gate.judge(baseline, after, Object.keys(baseline), isFix); }
144
+
145
+ /* ---------------- full-project safety copy ---------------- */
146
+
147
+ function fullCopyDir(taskId) { return path.join(DATA_DIR, 'backups', taskId, 'full'); }
148
+
149
+ /**
150
+ * Put a file back into the project. Windows keeps the OLD modified date when it copies a file, and build tools that
151
+ * decide by date (MSBuild / dotnet, cargo, make, tsc --incremental) would then reuse a stale build of the other version.
152
+ * So a file put back always gets "now" as its date.
153
+ */
154
+ function putBack(src, abs) {
155
+ fs.mkdirSync(path.dirname(abs), { recursive: true });
156
+ fs.copyFileSync(src, abs);
157
+ const now = new Date(); try { fs.utimesSync(abs, now, now); } catch { /* read-only: the copy itself is done */ }
158
+ }
159
+ function linksFile(taskId) { return path.join(DATA_DIR, 'backups', taskId, 'links.json'); }
160
+ function takeSafetyCopy(project, cfg, taskId) {
161
+ const files = snapshot.walk(project.root, cfg.ignoreDirs, cfg.maxProjectFiles);
162
+ if (files.truncated) throw new Error(`the project has more than ${cfg.maxProjectFiles || snapshot.MAX_FILES} files - too big to guard completely. Add build / data folders to "ignoreDirs" or raise "maxProjectFiles" in the settings`);
163
+ const dst = fullCopyDir(taskId);
164
+ const links = {};
165
+ for (const rel of files) {
166
+ const from = path.join(project.root, rel);
167
+ if (snapshot.isLink(from)) { links[rel] = fs.readlinkSync(from); continue; } // a link is kept as a link, never followed
168
+ const to = path.join(dst, rel);
169
+ fs.mkdirSync(path.dirname(to), { recursive: true });
170
+ fs.copyFileSync(from, to);
171
+ }
172
+ fs.mkdirSync(path.dirname(linksFile(taskId)), { recursive: true });
173
+ fs.writeFileSync(linksFile(taskId), JSON.stringify(links));
174
+ const snap = snapshot.take(project.root, cfg.ignoreDirs, cfg.maxProjectFiles);
175
+ fs.writeFileSync(path.join(DATA_DIR, 'backups', taskId, 'snapshot.json'), JSON.stringify(snap));
176
+ return snap;
177
+ }
178
+
179
+ function loadSnapshot(taskId) {
180
+ try { return JSON.parse(fs.readFileSync(path.join(DATA_DIR, 'backups', taskId, 'snapshot.json'), 'utf8')); } catch { return null; }
181
+ }
182
+
183
+ function restoreFiles(project, taskId, changes) {
184
+ const restored = [];
185
+ let links = {}; try { links = JSON.parse(fs.readFileSync(linksFile(taskId), 'utf8')); } catch { /* older backup: no links */ }
186
+ for (const c of changes) {
187
+ const abs = path.join(project.root, c.file);
188
+ const src = path.join(fullCopyDir(taskId), c.file);
189
+ try {
190
+ // a link put there by the AI is removed first: writing "through" it would change a file outside the project
191
+ if (snapshot.isLink(abs)) fs.unlinkSync(abs);
192
+ if (c.kind === 'added') { if (fs.existsSync(abs)) fs.unlinkSync(abs); }
193
+ else if (Object.prototype.hasOwnProperty.call(links, c.file)) { fs.mkdirSync(path.dirname(abs), { recursive: true }); if (fs.existsSync(abs)) fs.unlinkSync(abs); fs.symlinkSync(links[c.file], abs); }
194
+ else putBack(src, abs);
195
+ restored.push(c.file);
196
+ } catch { /* reported by caller via re-snapshot */ }
197
+ }
198
+ return restored;
199
+ }
200
+
201
+ function rollbackAll(project, cfg, taskId, before) {
202
+ const changes = snapshot.diff(before, snapshot.take(project.root, cfg.ignoreDirs, cfg.maxProjectFiles));
203
+ return restoreFiles(project, taskId, changes);
204
+ }
205
+
206
+ /** Revert anything changed outside the approved scope (lockfiles allowed only for install actions). */
207
+ function enforceScope(project, cfg, taskId, before, allowed, allowLockfiles) {
208
+ const allowedSet = new Set(allowed);
209
+ const changes = snapshot.diff(before, snapshot.take(project.root, cfg.ignoreDirs, cfg.maxProjectFiles));
210
+ const outside = changes.filter((c) => !allowedSet.has(c.file) && !(allowLockfiles && /package-lock\.json$|yarn\.lock$|pnpm-lock\.yaml$/.test(c.file)));
211
+ const reverted = outside.length ? restoreFiles(project, taskId, outside) : [];
212
+ return { changes, outside, reverted };
213
+ }
214
+
215
+ function checkIntegrity(project, cfg, taskId, changes, extra) {
216
+ const testFiles = snapshot.walk(project.root, cfg.ignoreDirs, cfg.maxProjectFiles).filter((f) => integrity.isTestFile(f));
217
+ // a changed entry that is now a link to somewhere outside the project
218
+ const marked = changes.map((c) => { const out = c.kind === 'deleted' ? null : snapshot.linkOutside(project.root, c.file); return out ? { ...c, link: out } : c; });
219
+ const res = integrity.analyze({ root: project.root, beforeDir: fullCopyDir(taskId), changes: marked, testFiles });
220
+ for (const f of (extra && extra.findings) || []) res.findings.push(f);
221
+ res.clean = res.findings.length === 0;
222
+ return res;
223
+ }
224
+
225
+ /** Guard-only checks outside the snapshot: hooks that were connected, installed packages. */
226
+ function guardExtras(task, project, changes) {
227
+ const findings = [];
228
+ const add = (rule, file, detail) => findings.push({ rule, file, detail: String(detail || '').slice(0, 200), text: integrity.RULE_TEXT[rule] });
229
+ const nowHooks = require('./hooks').status(project.root);
230
+ for (const [tool, st] of Object.entries(task.hooksAtStart || {})) if (st && st.connected && !(nowHooks[tool] && nowHooks[tool].connected)) add('guard_disabled', tool === 'git' ? '.git/hooks/pre-commit' : tool, `${tool} hook removed`);
231
+ let dep = null;
232
+ try { dep = require('./deps-guard').tampered(project.root, Date.parse(task.createdAt), changes, task.runWindows || []); } catch (e) { dep = { skipped: e.message }; }
233
+ if (dep && dep.file) { add('dependency_tampered', dep.file, `${dep.total} file(s) in the installed packages edited after the guard started`); store.update('tasks', task.id, { packagesEdited: Math.max(task.packagesEdited || 0, dep.total) }); }
234
+ return { findings, deps: dep };
235
+ }
236
+
237
+ /** Tests the AI may READ (never edit): the failing ones, else tests that import the files in scope. */
238
+ function readOnlyContext(project, cfg, plan, allowed) {
239
+ let tests = (plan.protectedTests || []).slice();
240
+ if (!tests.length) {
241
+ const all = snapshot.walk(project.root, cfg.ignoreDirs, cfg.maxProjectFiles).filter((f) => integrity.isTestFile(f));
242
+ tests = all.filter((f) => scope.localImports(project.root, f, all.concat(allowed)).some((x) => allowed.includes(x)));
243
+ }
244
+ const out = []; let budget = 24000;
245
+ for (const f of tests.slice(0, 4)) {
246
+ const c = fixlib.readContent(project.root, f);
247
+ if (c == null || c.length > budget) continue;
248
+ budget -= c.length; out.push({ path: f, content: c });
249
+ }
250
+ return out;
251
+ }
252
+
253
+ function sc0(plan) { return plan.protectedTests || []; }
254
+
255
+ /** Names of the failing tests that belong to this task (from its target test files). */
256
+ function targetTestNames(project, baseline, testFiles) {
257
+ const names = new Set();
258
+ const srcs = testFiles.map((f) => ({ f, c: fixlib.readContent(project.root, f) || '' }));
259
+ for (const [, r] of Object.entries(baseline || {})) {
260
+ for (const n of r.failedTests || []) {
261
+ const short = String(n).split('::').pop().split('.').pop();
262
+ if (srcs.some((x) => n.startsWith(x.f) || (short.length > 3 && x.c.includes(short)) || x.c.includes(n))) names.add(n);
263
+ }
264
+ }
265
+ return [...names].slice(0, 20);
266
+ }
267
+
268
+ function countCasesIn(root, files) { return files.reduce((n, f) => n + integrity.countCases(fixlib.readContent(root, f) || ''), 0); }
269
+
270
+ /**
271
+ * Revert check: put the ORIGINAL source files back for a moment and run the tests again.
272
+ * Proof that the tests really depend on this change (not flaky, not unrelated).
273
+ * covered tests fail without the change -> strong proof
274
+ * not_covered tests pass without the change (new work) -> warning
275
+ * flaky a failing test now passes even without the fix -> NOT proven
276
+ */
277
+ async function revertCheck(project, cfg, taskId, changes, baseline, after) {
278
+ const src = changes.filter((c) => c.kind !== 'deleted' && !integrity.isTestFile(c.file) && /\.([cm]?[jt]sx?|py|vue|svelte|go|rs|java|kt|cs|fs|rb|php)$/i.test(c.file));
279
+ const steps = (project.verify || []).filter((s) => /test/.test(s));
280
+ if (cfg.revertCheck === false) return { ran: false, verdict: 'skipped', text: 'Revert check is turned off' };
281
+ if (!license.has('revertCheck')) return { ran: false, verdict: 'skipped', text: 'Revert check is a Pro feature' };
282
+ if (!src.length || !steps.length) return { ran: false, verdict: 'skipped', text: !steps.length ? 'No test step to run' : 'No source file changed' };
283
+ const keep = path.join(DATA_DIR, 'backups', taskId, 'revert');
284
+ fs.rmSync(keep, { recursive: true, force: true });
285
+ const placed = {};
286
+ try {
287
+ for (const c of src) {
288
+ const abs = path.join(project.root, c.file);
289
+ const k = path.join(keep, c.file);
290
+ fs.mkdirSync(path.dirname(k), { recursive: true });
291
+ fs.copyFileSync(abs, k);
292
+ if (c.kind === 'added') fs.unlinkSync(abs);
293
+ else putBack(path.join(fullCopyDir(taskId), c.file), abs);
294
+ placed[c.file] = c.kind === 'added' ? null : snapshot.hashFile(abs);
295
+ }
296
+ log(taskId, `revert check: original version of ${src.length} file(s) put back for a moment`);
297
+ const results = await verify({ ...project, verify: steps }, cfg, taskId, 'revert-check');
298
+ let unknown = false;
299
+ const failsWithout = steps.some((s) => {
300
+ const r = results[s]; const a = after && after[s];
301
+ if (!r || !r.ran) return false;
302
+ if (!a || a.pass) return !r.pass;
303
+ // old failures exist: compare test by test - something that passes now must fail without the change
304
+ if (Array.isArray(r.failedTests) && Array.isArray(a.failedTests)) { const now = new Set(a.failedTests); return r.failedTests.some((x) => !now.has(x)); }
305
+ unknown = true; return false;
306
+ });
307
+ const wasFailing = steps.some((s) => baseline && baseline[s] && !baseline[s].pass);
308
+ if (!failsWithout && unknown) return { ran: true, verdict: 'skipped', text: 'Could not compare test by test (old failures in the project)', files: src.map((c) => c.file) };
309
+ const verdict = failsWithout ? 'covered' : wasFailing ? 'flaky' : 'not_covered';
310
+ const text = verdict === 'covered' ? 'The tests fail without this change, so they really check it'
311
+ : verdict === 'flaky' ? 'The tests pass even WITHOUT the change - the failure was flaky or unrelated'
312
+ : 'The tests pass with or without this change - no test covers it';
313
+ return { ran: true, verdict, failsWithout, text, files: src.map((c) => c.file) };
314
+ } finally {
315
+ const conflicts = [];
316
+ for (const c of src) {
317
+ const abs = path.join(project.root, c.file);
318
+ const cur = fs.existsSync(abs) ? snapshot.hashFile(abs) : null;
319
+ if (c.file in placed && cur !== placed[c.file]) { conflicts.push(c.file); continue; }
320
+ fs.mkdirSync(path.dirname(abs), { recursive: true });
321
+ putBack(path.join(keep, c.file), abs);
322
+ }
323
+ if (conflicts.length) log(taskId, `revert check: ${conflicts.join(', ')} changed during the check - left as is, saved copy in ${keep}`);
324
+ else { log(taskId, 'revert check: changed files restored'); fs.rmSync(keep, { recursive: true, force: true }); }
325
+ }
326
+ }
327
+
328
+ /** Text diffs of changed files, for reports (bounded). */
329
+ function diffsFor(project, taskId, changes) {
330
+ const out = [];
331
+ for (const c of changes.slice(0, 25)) {
332
+ const a = c.kind === 'added' ? '' : fixlib.readContent(fullCopyDir(taskId), c.file);
333
+ const b = c.kind === 'deleted' ? '' : fixlib.readContent(project.root, c.file);
334
+ if (a == null || b == null || a.length + b.length > 200000 || /\u0000/.test(a + b)) { out.push({ file: c.file, diff: `(${c.kind}, binary or large file)` }); continue; }
335
+ out.push({ file: c.file, diff: edits.unifiedDiff(a, b, c.file) });
336
+ }
337
+ return out;
338
+ }
339
+
340
+ function lineStats(diffs) {
341
+ let plus = 0; let minus = 0;
342
+ for (const d of diffs || []) for (const l of String(d.diff).split('\n')) { if (/^\+(?!\+\+)/.test(l)) plus++; else if (/^-(?!--)/.test(l)) minus++; }
343
+ return { plus, minus };
344
+ }
345
+
346
+ /** A marker per guarded folder, readable WITHOUT the service: a hook must not wave a commit through just because the service is down. */
347
+ function markerFile(root) { return path.join(DATA_DIR, 'active-guards', crypto.createHash('sha256').update(path.resolve(root).toLowerCase()).digest('hex').slice(0, 24) + '.json'); }
348
+ function markActive(root, taskId) {
349
+ try {
350
+ const f = markerFile(root);
351
+ if (taskId) { fs.mkdirSync(path.dirname(f), { recursive: true }); fs.writeFileSync(f, JSON.stringify({ root: path.resolve(root), taskId, since: now() })); }
352
+ else fs.rmSync(f, { force: true });
353
+ } catch { /* best effort: the service itself still decides */ }
354
+ }
355
+
356
+ function activeGuard(projectId) {
357
+ return store.list('tasks', (t) => t.kind === 'guard' && t.projectId === projectId && GUARD_ACTIVE.includes(t.state))[0] || null;
358
+ }
359
+
360
+ /* ---------------- A) supervised task: create + diagnose ---------------- */
361
+
362
+ function create({ projectId, text, source }) {
363
+ const project = store.get('projects', projectId);
364
+ if (!project) return { ok: false, error: 'project_not_found' };
365
+ if (!String(text || '').trim()) return { ok: false, error: 'empty_task' };
366
+ if (activeGuard(projectId)) return { ok: false, error: 'project_is_guarded' };
367
+ const task = {
368
+ id: newId('t_'),
369
+ kind: 'supervised',
370
+ projectId,
371
+ projectName: project.name,
372
+ text: String(text).trim().slice(0, 4000),
373
+ source: source || 'web',
374
+ isFix: FIX_INTENT.test(text),
375
+ state: 'diagnosing',
376
+ createdAt: now(),
377
+ log: [],
378
+ aiCalls: 0,
379
+ cheatsBlocked: 0,
380
+ };
381
+ store.insert('tasks', task);
382
+ emit(task);
383
+ return { ok: true, task };
384
+ }
385
+
386
+ async function diagnose(taskId, cfg) {
387
+ const t = store.get('tasks', taskId);
388
+ const project = projects.refresh(t.projectId);
389
+ log(taskId, `project: ${project.name} (${project.type}) at ${project.root}`);
390
+ for (const n of project.notes || []) log(taskId, `note: ${n}`);
391
+ if (project.type === 'unknown' || project.type === 'unity') {
392
+ return setState(taskId, 'failed', { resultText: `Project type "${project.type}" is not supported yet. This version supports Node / Web and Python projects.`, finishedAt: now() });
393
+ }
394
+
395
+ let baseline = {};
396
+ if (!project.needsInstall) baseline = await verify(project, cfg, taskId, 'baseline');
397
+ const errText = failureText(baseline);
398
+ const isFix = t.isFix || Object.values(baseline).some((r) => !r.pass);
399
+ const files = snapshot.walk(project.root, cfg.ignoreDirs, cfg.maxProjectFiles);
400
+
401
+ let plan;
402
+ // scope + the task's own failing tests first: the library may only replay a fix for THESE tests
403
+ const allPaths = Object.values(baseline).filter((r) => !r.pass).flatMap((r) => r.paths || []);
404
+ const sc = scope.propose({ root: project.root, text: t.text, errText: errText + '\n' + allPaths.join('\n'), files, max: cfg.maxScopeFiles, maxBytes: cfg.maxFileBytes });
405
+ const preTargets = targetTestNames(project, baseline, (sc.targetTests && sc.targetTests.length ? sc.targetTests : sc.protectedTests).slice());
406
+ const seed = fixlib.matchSeed(errText, project);
407
+ const learned = errText ? fixlib.findLearned(errText, project, preTargets) : null;
408
+ if (seed) {
409
+ plan = { kind: 'library', rule: seed.id, action: seed.action, title: seed.title, explain: seed.explain, scope: ['package-lock.json'], reasons: { 'package-lock.json': 'install may update the lockfile' } };
410
+ } else if (learned) {
411
+ plan = { kind: 'learned', fixId: learned.id, title: 'Known fix from the library (no AI)', explain: `This exact failure was fixed and verified before (task ${learned.sourceTaskId}). The same fix will be replayed.`, scope: learned.edits.map((e) => e.path), reasons: Object.fromEntries(learned.edits.map((e) => [e.path, 'verified fix from the library'])), protectedTests: sc.protectedTests, targetTests: sc.targetTests };
412
+ } else {
413
+ const h = await ai.health(cfg);
414
+ if (!sc.files.length) {
415
+ plan = { kind: 'unknown', title: 'No matching files found', explain: 'Could not tell which files this task needs. Name the file in the task (for example src/app.js).', scope: [], reasons: {}, protectedTests: sc.protectedTests };
416
+ } else if (!h.ok) {
417
+ plan = { kind: 'unknown', title: 'Not in the library, and the AI is unavailable', explain: `Diagnosis: ${isFix ? 'failing steps: ' + Object.keys(baseline).filter((s) => !baseline[s].pass).join(', ') : 'change requested'}. Relevant files: ${sc.files.join(', ')}. The AI (${ai.describe(cfg).label}) is unavailable: ${h.reason}.`, scope: sc.files, reasons: sc.reasons, protectedTests: sc.protectedTests };
418
+ } else {
419
+ plan = { kind: 'ai', title: ai.describe(cfg).local ? 'Local AI, supervised' : 'AI, supervised', explain: `No known fix in the library. ${ai.describe(cfg).label} may change only the approved files. Every change is checked for test cheating, verified, and rolled back if it breaks anything.`, scope: sc.files, reasons: sc.reasons, protectedTests: sc.protectedTests, targetTests: sc.targetTests };
420
+ }
421
+ }
422
+ log(taskId, `plan: ${plan.kind} - ${plan.title}`);
423
+ const targetNames = targetTestNames(project, baseline, (plan.targetTests || sc0(plan)).slice());
424
+ if (targetNames.length) log(taskId, `task tests: ${targetNames.join('; ')}`);
425
+ return setState(taskId, 'awaiting_approval', {
426
+ isFix,
427
+ baseline,
428
+ targetNames,
429
+ verifySteps: project.verify,
430
+ errorSignature: fixlib.signature(errText),
431
+ plan,
432
+ proposedScope: plan.scope,
433
+ });
434
+ }
435
+
436
+ /* ---------------- A) execute after approval ---------------- */
437
+
438
+ async function execute(taskId, cfg, approvedScope) {
439
+ const t = store.get('tasks', taskId);
440
+ const project = projects.refresh(t.projectId);
441
+ const startedAt = Date.now();
442
+ const allowed = (approvedScope || t.proposedScope || []).map((f) => String(f).replace(/\\/g, '/'));
443
+ const aiLocal = ai.describe(cfg).local;
444
+ setState(taskId, 'executing', { approvedScope: allowed, approvedAt: now(), aiModel: ai.describe(cfg).label, aiLocal });
445
+ log(taskId, `approved scope: ${allowed.join(', ') || '(none)'}`);
446
+ const before = takeSafetyCopy(project, cfg, taskId);
447
+ log(taskId, `safety copy: ${Object.keys(before).length} files`);
448
+ const beforeHashes = Object.fromEntries(allowed.map((f) => [f, before[f] || null]));
449
+ const plan = t.plan;
450
+ const ctl = running.get(taskId);
451
+ const overBudget = () => (Date.now() - startedAt) / 1000 > cfg.budget.maxTaskSeconds;
452
+
453
+ let after = {};
454
+ let verdict = null;
455
+ let integ = null;
456
+ let aiSummary = '';
457
+ let appliedEdits = [];
458
+ let scopeReport = { outside: [], reverted: [] };
459
+ let steps = [];
460
+
461
+ const finishCheck = async (label) => {
462
+ scopeReport = enforceScope(project, cfg, taskId, before, allowed, plan.kind === 'library');
463
+ if (scopeReport.reverted.length) log(taskId, `scope guard: reverted ${scopeReport.reverted.length} change(s) outside the approved scope: ${scopeReport.reverted.join(', ')}`);
464
+ const changes = snapshot.diff(before, snapshot.take(project.root, cfg.ignoreDirs, cfg.maxProjectFiles));
465
+ integ = checkIntegrity(project, cfg, taskId, changes);
466
+ if (!integ.clean) {
467
+ const cur = store.get('tasks', taskId);
468
+ store.update('tasks', taskId, { cheatsBlocked: (cur.cheatsBlocked || 0) + 1 });
469
+ for (const f of integ.findings) log(taskId, `integrity guard: ${f.text} - ${f.file}: ${f.detail}`);
470
+ verdict = { ok: false, proven: false, regressions: [], stillFailing: [], fixedNow: [], missing: [], notRun: [], fewerTests: [], steps: [] };
471
+ return verdict;
472
+ }
473
+ setState(taskId, 'verifying');
474
+ const refreshed = projects.refresh(project.id);
475
+ steps = refreshed.verify;
476
+ after = await verify(refreshed, cfg, taskId, label);
477
+ verdict = gate.judge(t.baseline || {}, after, steps, t.isFix);
478
+ // a fix must fix THIS task's tests, not just any other failing test
479
+ const tn = t.targetNames || [];
480
+ if (verdict.ok && t.isFix && tn.length) {
481
+ const still = Object.values(after).flatMap((r) => (Array.isArray(r.failedTests) ? r.failedTests.filter((n) => tn.includes(n)) : []));
482
+ if (still.length) { verdict.ok = false; verdict.targetStill = still; verdict.stillFailing = verdict.stillFailing.length ? verdict.stillFailing : ['test']; }
483
+ }
484
+ return verdict;
485
+ };
486
+
487
+ try {
488
+ if (plan.kind === 'library') {
489
+ const cmd = plan.action === 'npm_rebuild' ? ['rebuild'] : ['install', '--no-audit', '--no-fund'];
490
+ log(taskId, `library action: npm ${cmd.join(' ')}`);
491
+ const r = await run('npm', cmd, { cwd: project.root, timeoutMs: cfg.commandTimeoutMs });
492
+ log(taskId, `npm ${cmd[0]} -> ${r.ok ? 'OK' : 'FAIL'}`);
493
+ if (!r.ok) log(taskId, tail(r.output, 1500));
494
+ const p2 = projects.refresh(project.id);
495
+ if (!Object.keys(t.baseline || {}).length && p2.verify.length) {
496
+ t.baseline = Object.fromEntries(p2.verify.map((s) => [s, { pass: false, ran: false, reason: 'not_installed' }]));
497
+ store.update('tasks', taskId, { baseline: t.baseline });
498
+ }
499
+ await finishCheck('after');
500
+ } else if (plan.kind === 'learned') {
501
+ const entry = store.get('fixes', plan.fixId);
502
+ const res = edits.applyEdits(project.root, taskId, entry.edits.map((e) => ({ path: e.path, content: e.content })), allowed);
503
+ appliedEdits = res.applied;
504
+ log(taskId, `replayed learned fix ${entry.id} (${res.applied.length} file(s))`);
505
+ await finishCheck('after');
506
+ if (verdict.ok) store.update('fixes', entry.id, { uses: (entry.uses || 0) + 1, lastUsedAt: now() });
507
+ } else if (plan.kind === 'ai') {
508
+ const focus = (t.targetNames || []).length ? `Failing tests for THIS task: ${t.targetNames.join('; ')}\n` : '';
509
+ const failFor = (res) => { const f = focusedFailure(res, t.targetNames || []); return f ? focus + f : focus + failureText(res); };
510
+ let failure = t.isFix ? failFor(t.baseline || {}) : '';
511
+ for (let attempt = 1; attempt <= cfg.budget.maxAiCallsPerTask; attempt++) {
512
+ if (ctl?.stop) throw new Error('stopped_by_user');
513
+ if (overBudget()) { log(taskId, 'budget: time limit reached'); break; }
514
+ if (attempt > 1) { const r = rollbackAll(project, cfg, taskId, before); log(taskId, `attempt ${attempt}: reset ${r.length} file(s) to original`); }
515
+ const filesForAi = allowed.map((f) => ({ path: f, content: fixlib.readContent(project.root, f) }));
516
+ const contextFiles = readOnlyContext(project, cfg, plan, allowed);
517
+ log(taskId, `AI attempt ${attempt}/${cfg.budget.maxAiCallsPerTask}: asking ${ai.describe(cfg).label}`);
518
+ const prop = await ai.proposeEdits(cfg, { instruction: t.text, files: filesForAi, context: contextFiles, failure, attempt });
519
+ const cur = store.get('tasks', taskId);
520
+ const sent = aiLocal ? 0 : filesForAi.reduce((n, f) => n + Buffer.byteLength(f.content || ''), 0) + Buffer.byteLength(t.text + failure);
521
+ store.update('tasks', taskId, { aiCalls: (cur.aiCalls || 0) + 1, bytesSentOff: (cur.bytesSentOff || 0) + sent });
522
+ if (!prop.ok) { log(taskId, `AI error: ${prop.error}`); break; }
523
+ aiSummary = prop.summary;
524
+ log(taskId, `AI: ${prop.summary || '(no summary)'} - ${prop.edits.length} edit(s), ${prop.tokens.prompt + prop.tokens.output} tokens`);
525
+ if (!prop.edits.length) { log(taskId, 'AI proposed no edits'); failure = 'You returned NO edits. The code IS wrong - the test below fails. Return the corrected COMPLETE content of the file.\n' + (t.isFix ? failFor(t.baseline || {}) : ''); continue; }
526
+ const res = edits.applyEdits(project.root, taskId, prop.edits, allowed);
527
+ for (const rj of res.rejected) log(taskId, `scope guard: AI tried to edit ${rj.file} (${rj.reason}) - blocked`);
528
+ appliedEdits = res.applied.map((a) => ({ ...a, content: (prop.edits.find((e) => e.path.replace(/\\/g, '/').replace(/^\.\//, '') === a.file) || {}).content }));
529
+ if (!res.applied.length) { failure = 'Your previous answer edited only files outside the allowed list. Edit ONLY the listed files.'; continue; }
530
+ await finishCheck(`verify#${attempt}`);
531
+ if (verdict.ok) break;
532
+ if (integ && !integ.clean) { failure = integrity.feedback(integ.findings) + '\n' + (t.isFix ? failFor(t.baseline || {}) : ''); log(taskId, `attempt ${attempt} not accepted: test cheating detected`); continue; }
533
+ if (!verdict.steps.length) break; // nothing can prove it - stop spending AI calls
534
+ failure = failFor(after) || gate.whyNot(verdict);
535
+ log(taskId, `attempt ${attempt} not accepted: ${gate.whyNot(verdict)}`);
536
+ }
537
+ } else {
538
+ return setState(taskId, 'failed', { resultText: plan.explain, finishedAt: now() });
539
+ }
540
+ } catch (e) {
541
+ const restored = rollbackAll(project, cfg, taskId, before);
542
+ log(taskId, `${e.message === 'stopped_by_user' ? 'stopped by user' : 'error: ' + e.message} - rolled back ${restored.length} file(s)`);
543
+ return setState(taskId, e.message === 'stopped_by_user' ? 'stopped' : 'failed', { resultText: 'Stopped. Everything was restored to the original state.', finishedAt: now() });
544
+ }
545
+
546
+ const changedFiles = snapshot.diff(before, snapshot.take(project.root, cfg.ignoreDirs, cfg.maxProjectFiles));
547
+ const diffs = diffsFor(project, taskId, changedFiles);
548
+ const common = { after, verdict, aiSummary, integrity: integ, diffs, lineStats: lineStats(diffs), scopeGuard: { outside: scopeReport.outside.map((c) => c.file), reverted: scopeReport.reverted } };
549
+
550
+ // No build/test script at all: applied, clean, but honestly NOT proven. No certificate.
551
+ if (verdict && !verdict.ok && verdict.steps.length === 0 && integ && integ.clean && changedFiles.length) {
552
+ log(taskId, 'applied, but the project has no build/test script - NOT proven');
553
+ return setState(taskId, 'unproven', { ...common, changedFiles, resultText: 'Applied, but NOT proven: the project has no build or test script. Add a "test" script to get proof. You can undo this change.', finishedAt: now() });
554
+ }
555
+
556
+ if (!verdict || !verdict.ok) {
557
+ const restored = rollbackAll(project, cfg, taskId, before);
558
+ log(taskId, `not proven -> rolled back ${restored.length} file(s); project is exactly as before`);
559
+ return setState(taskId, 'rolled_back', { ...common, resultText: `Not accepted: ${gate.whyNot(verdict, integ)}. Everything was restored to the original state.`, finishedAt: now() });
560
+ }
561
+
562
+ if (plan.kind !== 'library') {
563
+ common.revertCheck = await revertCheck(project, cfg, taskId, changedFiles, t.baseline, after);
564
+ log(taskId, `revert check: ${common.revertCheck.verdict} - ${common.revertCheck.text}`);
565
+ if (common.revertCheck.verdict === 'flaky') {
566
+ const restored = rollbackAll(project, cfg, taskId, before);
567
+ log(taskId, `not proven (flaky) -> rolled back ${restored.length} file(s)`);
568
+ return setState(taskId, 'rolled_back', { ...common, resultText: `Not accepted: ${common.revertCheck.text}. Everything was restored to the original state.`, finishedAt: now() });
569
+ }
570
+ }
571
+
572
+ let learnedId = null;
573
+ if (plan.kind === 'ai' && t.isFix && t.errorSignature && appliedEdits.length) {
574
+ const fixedTests = Object.values(verdict.testLevel || {}).flatMap((x) => x.fixed || []);
575
+ const entry = fixlib.learn({ errText: failureText(t.baseline || {}), project, edits: appliedEdits.map((a) => ({ path: a.file, content: a.content })), beforeHashes, taskId, instruction: t.text, fixedTests: fixedTests.length ? fixedTests : (t.targetNames || []) });
576
+ learnedId = entry && entry.id;
577
+ if (learnedId) log(taskId, `learned: verified fix saved to library (${learnedId}) - next time no AI needed`);
578
+ }
579
+ const proofText = `Proof: ${Object.keys(after).map((s) => `${s} ${after[s].pass ? 'passed' : 'failed'}`).join(', ')}${verdict.fixedNow.length ? '. Fixed: ' + verdict.fixedNow.join(', ') : ''}. Test integrity clean.`;
580
+ const done = setState(taskId, 'done', {
581
+ ...common, learnedId, changedFiles,
582
+ resultText: `${plan.kind === 'ai' ? (ai.describe(cfg).local ? 'Done by local AI, supervised.' : 'Done by AI, supervised.') : 'Done from the library, no AI.'} ${proofText}`,
583
+ finishedAt: now(),
584
+ });
585
+ if (!license.has('certificates')) { log(taskId, 'certificate: not included in this plan'); return done; }
586
+ try {
587
+ const cert = certs.issue(done, project);
588
+ log(taskId, `certificate signed: ${cert.id}`);
589
+ certs.countersign(cert, cfg).then((cs) => { if (cs) log(taskId, `certificate countersigned by ${cs.server}`); }).catch(() => {});
590
+ return setState(taskId, 'done', { certId: cert.id });
591
+ } catch (e) { log(taskId, `certificate error: ${e.message}`); return done; }
592
+ }
593
+
594
+ /* ---------------- B) guard over any AI tool ---------------- */
595
+
596
+ function guardStart({ projectId, source }, cfg) {
597
+ const project = store.get('projects', projectId);
598
+ if (!project) return { ok: false, error: 'project_not_found' };
599
+ if (activeGuard(projectId)) return { ok: true, task: activeGuard(projectId), already: true };
600
+ if (busyProjects.has(projectId)) return { ok: false, error: 'project_busy' };
601
+ const task = {
602
+ id: newId('g_'), kind: 'guard', projectId, projectName: project.name,
603
+ text: `Guard ${project.name} while you work with any AI tool`, source: source || 'web',
604
+ state: 'baselining', createdAt: now(), log: [], aiCalls: 0, cheatsBlocked: 0, checks: 0,
605
+ };
606
+ store.insert('tasks', task);
607
+ busyProjects.add(projectId);
608
+ markActive(project.root, task.id);
609
+ let p;
610
+ try {
611
+ p = projects.refresh(projectId);
612
+ const snap = takeSafetyCopy(p, cfg, task.id);
613
+ store.update('tasks', task.id, { testCasesBefore: countCasesIn(p.root, Object.keys(snap).filter((f) => integrity.isTestFile(f))), hooksAtStart: require('./hooks').status(p.root) });
614
+ log(task.id, `safety copy: ${Object.keys(snap).length} files`);
615
+ } catch (e) {
616
+ busyProjects.delete(projectId);
617
+ markActive(project.root, null);
618
+ setState(task.id, 'failed', { resultText: `Guard could not start: ${e.message}`, finishedAt: now() });
619
+ return { ok: false, error: e.message };
620
+ }
621
+ (async () => {
622
+ try {
623
+ const b0 = Date.now();
624
+ const baseline = p.needsInstall ? {} : await verify(p, cfg, task.id, 'baseline');
625
+ setState(task.id, 'watching', { baseline, verifySteps: p.verify, watchingSince: now(), runWindows: [[b0, Date.now()]], resultText: 'Watching. Work with your AI tool, then press Check.' });
626
+ } catch (e) {
627
+ markActive(project.root, null);
628
+ setState(task.id, 'failed', { resultText: `Guard could not start: ${e.message}`, finishedAt: now() });
629
+ } finally { busyProjects.delete(projectId); }
630
+ })();
631
+ return { ok: true, task };
632
+ }
633
+
634
+ async function guardCheck(id, cfg, { claim = '' } = {}) {
635
+ const t = store.get('tasks', id);
636
+ if (!t || t.kind !== 'guard') return { ok: false, error: 'not_found' };
637
+ if (t.state !== 'watching') return { ok: false, error: `not_watching (${t.state})` };
638
+ if (busyProjects.has(t.projectId)) return { ok: false, error: 'project_busy' };
639
+ busyProjects.add(t.projectId);
640
+ running.set(id, { stop: false });
641
+ try {
642
+ const p = projects.refresh(t.projectId);
643
+ const before = loadSnapshot(id);
644
+ if (!before) return { ok: false, error: 'snapshot_missing' };
645
+ setState(id, 'checking', { lastCheck: null });
646
+ const examined = snapshot.take(p.root, cfg.ignoreDirs, cfg.maxProjectFiles); // exactly the files this check looks at
647
+ if (examined.truncated) { setState(id, 'watching', { lastCheck: null, resultText: `Not proven: the project now has more than ${cfg.maxProjectFiles || snapshot.MAX_FILES} files - too big to check completely.` }); return { ok: false, error: 'project_too_big' }; }
648
+ const changes = snapshot.diff(before, examined);
649
+ // secrets written by the AI: only the files changed since guard start are scanned
650
+ const threats = require('./security-scan').scan(p.root, changes.filter((c) => c.kind !== 'deleted').map((c) => c.file));
651
+ if (threats.length) {
652
+ for (const th of threats) log(id, `security: ${th.type} in ${th.file}:${th.line}`);
653
+ setState(id, 'watching', { lastCheck: null, securityFindings: threats, resultText: `Security risk: ${threats.length} secret(s) written into the project (${threats.map((x) => x.file).join(', ')}). Approval blocked - remove them and check again.` });
654
+ return { ok: false, error: 'security_risk', count: threats.length };
655
+ }
656
+ // viruses in the files the AI changed (ClamAV). Missing ClamAV does not block; a virus does.
657
+ const av = require('./av-scan').scan(p.root, changes.filter((c) => c.kind !== 'deleted').map((c) => c.file));
658
+ log(id, `antivirus: ${av.status}${av.engine ? '' : ' (ClamAV not installed)'}${av.scanned ? `, ${av.scanned} file(s)` : ''}${av.detail ? ' - ' + av.detail : ''}`);
659
+ if (av.status === 'infected') {
660
+ for (const h of av.hits) log(id, `antivirus: ${h.sig} in ${h.file}`);
661
+ setState(id, 'watching', { lastCheck: null, malwareFindings: av.hits, antivirus: av.status, resultText: `Malware: ${av.hits.length} infected file(s) written into the project (${av.hits.map((x) => x.file + ' = ' + x.sig).join(', ')}). Approval blocked - remove them and check again.` });
662
+ return { ok: false, error: 'malware', count: av.hits.length };
663
+ }
664
+ log(id, `check: ${changes.length} file(s) changed since guard start`);
665
+ const ex = guardExtras(t, p, changes);
666
+ if (ex.deps && ex.deps.skipped) log(id, `installed packages: not checked - ${ex.deps.skipped}`);
667
+ const integ = checkIntegrity(p, cfg, id, changes, ex);
668
+ for (const f of integ.findings) log(id, `integrity guard: ${f.text} - ${f.file}: ${f.detail}`);
669
+ const runStart = Date.now();
670
+ const after = await verify(p, cfg, id, 'check');
671
+ const verdict = gate.judge(t.baseline || {}, after, p.verify, false);
672
+ let ok = verdict.ok && integ.clean && changes.length > 0;
673
+ let rc = null;
674
+ if (ok) {
675
+ rc = await revertCheck(p, cfg, id, changes, t.baseline, after);
676
+ log(id, `revert check: ${rc.verdict} - ${rc.text}`);
677
+ if (rc.verdict === 'flaky') ok = false;
678
+ }
679
+ // hidden bugs the passing tests miss (changed JS files only, isolated copy, time limit)
680
+ let hb = null;
681
+ if (ok && cfg.bugHunter !== 'off') {
682
+ const codeFiles = changes.filter((c) => c.kind !== 'deleted' && /\.c?js$/i.test(c.file) && !integrity.isTestFile(c.file)).map((c) => c.file);
683
+ if (codeFiles.length) {
684
+ const budget = Math.max(10, Number(cfg.bugHunterSeconds) || 120) * 1000;
685
+ const run = require('./bug-hunter/engine').hunt({ root: p.root, files: codeFiles, oldRoot: fullCopyDir(id), oldModulesFrom: p.root, outDir: path.join(DATA_DIR, 'backups', id, 'evidence') });
686
+ const res = await Promise.race([run.then((r) => r, (e) => ({ error: e.message })), new Promise((r) => setTimeout(() => r({ error: 'time limit' }), budget).unref())]);
687
+ hb = res.error ? { error: res.error, findings: [], regressions: [] } : { findings: res.findings.map(({ input, ctor, prior, ...f }) => f), regressions: res.regressions.map(({ input, ctor, ...f }) => f), stats: res.stats };
688
+ log(id, `hidden bug hunt: ${hb.error ? 'not finished - ' + hb.error : `${hb.findings.length} possible bug(s), ${hb.regressions.length} behaviour change(s), ${hb.stats.calls} calls`}`);
689
+ for (const f of hb.findings) log(id, `hidden bug: ${f.oracle} in ${f.file} ${f.export}(${f.inputPreview}) -> ${f.outcome}`);
690
+ if (hb.findings.length && cfg.bugHunter === 'block') ok = false;
691
+ }
692
+ }
693
+ const testFilesNow = snapshot.walk(p.root, cfg.ignoreDirs, cfg.maxProjectFiles).filter((f) => integrity.isTestFile(f));
694
+ const testCasesAfter = countCasesIn(p.root, testFilesNow);
695
+ const claimList = claim && changes.length && license.has('claims') ? claims.compare(claim, { after, changes, verdict: { ...verdict, ok }, isTest: integrity.isTestFile, testCasesBefore: t.testCasesBefore || 0, testCasesAfter }) : [];
696
+ for (const c of claimList.filter((x) => x.truth === false)) log(id, `claim check: AI said "${c.text}" - NOT TRUE (${c.why})`);
697
+ const diffs = diffsFor(p, id, changes);
698
+ // files that changed WHILE the check ran were never examined: not proven, and approval needs a new check
699
+ const during = snapshot.diff(examined, snapshot.take(p.root, cfg.ignoreDirs, cfg.maxProjectFiles));
700
+ if (during.length) { ok = false; log(id, `check: ${during.length} file(s) changed while the check was running: ${during.slice(0, 5).map((c) => c.file).join(', ')}`); }
701
+ const checkedHashes = examined;
702
+ fs.writeFileSync(path.join(DATA_DIR, 'backups', id, 'checked.json'), JSON.stringify(checkedHashes));
703
+ const hbText = hb && hb.findings.length ? ` Warning: ${hb.findings.length} possible hidden bug(s) the tests miss (${hb.findings.slice(0, 3).map((f) => f.oracle + ' ' + f.export).join(', ')}).` : '';
704
+ const why = during.length ? `Not proven: ${during.length} file(s) changed while the check was running (${during.slice(0, 3).map((c) => c.file).join(', ')}). Wait until the AI tool has finished, then check again.` : changes.length === 0 ? 'No changes yet' : hb && hb.findings.length && cfg.bugHunter === 'block' && !ok ? `Not proven: ${hb.findings.length} hidden bug(s) found (${hb.findings.slice(0, 3).map((f) => f.oracle + ' ' + f.export + '(' + f.inputPreview + ')').join(', ')}).` : ok ? `Proven: ${Object.keys(after).map((s) => `${s} ${after[s].pass ? 'passed' : 'failed'}`).join(', ')}. Test integrity clean.${rc && rc.verdict === 'covered' ? ' The tests fail without this change.' : rc && rc.verdict === 'not_covered' ? ' Warning: no test covers this change.' : ''}${hbText}` : rc && rc.verdict === 'flaky' ? `Not proven: ${rc.text}` : gate.whyNot(verdict, integ);
705
+ const cur = store.get('tasks', id);
706
+ // the same cheating change checked again is ONE blocked cheat, not one per click
707
+ const cheatSig = integ.clean ? null : crypto.createHash('sha256').update(JSON.stringify(changes.map((c) => [c.file, checkedHashes[c.file] || null]))).digest('hex');
708
+ const out = setState(id, 'watching', {
709
+ after, verdict, integrity: integ, changedFiles: changes, diffs, lineStats: lineStats(diffs), revertCheck: rc, claims: claimList, claimText: claim ? String(claim).slice(-4000) : null, testCasesAfter,
710
+ lastCheck: { at: now(), ok, files: changes.length, integrityOnly: !ok && !during.length && verdict.ok && !integ.clean && changes.length > 0 && !(rc && rc.verdict === 'flaky') },
711
+ runWindows: [...(cur.runWindows || []), [runStart, Date.now()]].slice(-200),
712
+ antivirus: av.status, hiddenBugs: hb,
713
+ proofScore: require('./proof-score').score({lastCheck:{ok},integrity:integ,revertCheck:rc}), checks: (cur.checks || 0) + 1,
714
+ cheatsBlocked: (cur.cheatsBlocked || 0) + (cheatSig && cheatSig !== cur.lastCheatSig ? 1 : 0), lastCheatSig: cheatSig || cur.lastCheatSig || null,
715
+ resultText: why,
716
+ });
717
+ log(id, `check result: ${ok ? 'PROVEN' : 'NOT PROVEN'} - ${why}`);
718
+ return { ok: true, proven: ok, task: out };
719
+ } catch (e) {
720
+ setState(id, 'watching', { resultText: `Check error: ${e.message}` });
721
+ return { ok: false, error: e.message };
722
+ } finally { busyProjects.delete(t.projectId); running.delete(id); }
723
+ }
724
+
725
+ function guardAccept(id, cfg, { force = false } = {}) {
726
+ const t = store.get('tasks', id);
727
+ if (!t || t.kind !== 'guard') return { ok: false, error: 'not_found' };
728
+ if (t.state !== 'watching') return { ok: false, error: `not_watching (${t.state})` };
729
+ if (!t.lastCheck) return { ok: false, error: 'check_first' };
730
+ const p = store.get('projects', t.projectId);
731
+ let checked = null;
732
+ try { checked = JSON.parse(fs.readFileSync(path.join(DATA_DIR, 'backups', id, 'checked.json'), 'utf8')); } catch { /* none */ }
733
+ const nowSnap = snapshot.take(p.root, cfg.ignoreDirs, cfg.maxProjectFiles);
734
+ if (!checked || snapshot.diff(checked, nowSnap).length) return { ok: false, error: 'changed_since_check' };
735
+ // force may accept ONLY an intentional test change (build and tests passed, an integrity rule flagged a test edit).
736
+ // A failing build or failing tests can never be accepted, force or not.
737
+ if (!t.lastCheck.ok && !(force && t.lastCheck.integrityOnly)) return { ok: false, error: 'not_proven' };
738
+ if (!t.lastCheck.files) return { ok: false, error: 'no_changes' };
739
+ markActive(p.root, null);
740
+ const done = setState(id, 'done', { acceptedAt: now(), acceptedWithWarnings: !t.lastCheck.ok, finishedAt: now(), resultText: t.lastCheck.ok ? t.resultText : `Accepted by you with warnings: ${t.resultText}` });
741
+ if (!license.has('certificates')) { log(id, 'accepted - certificates are not included in this plan'); return { ok: true, task: done, cert: null }; }
742
+ const cert = certs.issue(done, p, { acceptedWarnings: !t.lastCheck.ok });
743
+ certs.countersign(cert, cfg).then((cs) => { if (cs) log(id, `certificate countersigned by ${cs.server}`); }).catch(() => {});
744
+ log(id, `certificate signed: ${cert.id}${!t.lastCheck.ok ? ' (with warnings)' : ''}`);
745
+ return { ok: true, task: setState(id, 'done', { certId: cert.id }), cert: { id: cert.id } };
746
+ }
747
+
748
+ function guardRollback(id, cfg) {
749
+ const t = store.get('tasks', id);
750
+ if (!t || t.kind !== 'guard') return { ok: false, error: 'not_found' };
751
+ if (!['watching', 'failed'].includes(t.state)) return { ok: false, error: `cannot_rollback (${t.state})` };
752
+ const p = store.get('projects', t.projectId);
753
+ const before = loadSnapshot(id);
754
+ if (!before) return { ok: false, error: 'snapshot_missing' };
755
+ const restored = rollbackAll(p, cfg, id, before);
756
+ const left = snapshot.diff(before, snapshot.take(p.root, cfg.ignoreDirs, cfg.maxProjectFiles)).length;
757
+ if (left === 0) markActive(p.root, null);
758
+ // installed packages are not copied (too big): an edit there cannot be undone here - say so, never hide it
759
+ let dep = null; try { dep = require('./deps-guard').tampered(p.root, Date.parse(t.createdAt), [], t.runWindows || []); } catch { dep = null; }
760
+ const pk = Math.max(dep && dep.file ? dep.total : 0, t.packagesEdited || 0); // what any check saw, or what is seen now
761
+ log(id, `rollback: restored ${restored.length} file(s); ${left ? left + ' still differ' : 'project is exactly as at guard start'}${pk ? `; ${pk} file(s) inside the installed packages were edited - reinstall them (npm ci)` : ''}`);
762
+ return { ok: left === 0, restored, packagesEdited: pk, task: setState(id, 'rolled_back', { finishedAt: now(), resultText: `Rolled back. ${restored.length} file(s) restored to the state at guard start.${pk ? ` ${pk} file(s) inside the installed packages were edited and cannot be restored from here - reinstall them (npm ci).` : ''}` }) };
763
+ }
764
+
765
+ /* ---------------- public API ---------------- */
766
+
767
+ async function start(taskId, cfg) {
768
+ const t = store.get('tasks', taskId);
769
+ if (busyProjects.has(t.projectId)) {
770
+ log(taskId, 'project busy with another task - waiting');
771
+ while (busyProjects.has(t.projectId)) await new Promise((r) => setTimeout(r, 1000));
772
+ }
773
+ let unlock;
774
+ try { unlock = require('./project-lock').acquire(projects.refresh(t.projectId).root); } catch(e) { return setState(taskId,'failed',{resultText:e.message,finishedAt:now()}); }
775
+ busyProjects.add(t.projectId);
776
+ running.set(taskId, { stop: false });
777
+ try { await diagnose(taskId, cfg); } catch (e) { setState(taskId, 'failed', { resultText: `Diagnosis error: ${e.message}`, finishedAt: now() }); }
778
+ finally { busyProjects.delete(t.projectId); running.delete(taskId); unlock(); }
779
+ }
780
+
781
+ async function approve(taskId, cfg, approvedScope) {
782
+ const t = store.get('tasks', taskId);
783
+ if (!t || t.state !== 'awaiting_approval') return { ok: false, error: 'not_awaiting_approval' };
784
+ if (busyProjects.has(t.projectId)) return { ok: false, error: 'project_busy' };
785
+ busyProjects.add(t.projectId);
786
+ running.set(taskId, { stop: false });
787
+ execute(taskId, cfg, approvedScope)
788
+ .catch((e) => setState(taskId, 'failed', { resultText: `Error: ${e.message}`, finishedAt: now() }))
789
+ .finally(() => { busyProjects.delete(t.projectId); running.delete(taskId); });
790
+ return { ok: true };
791
+ }
792
+
793
+ function reject(taskId) {
794
+ const t = store.get('tasks', taskId);
795
+ if (!t || t.state !== 'awaiting_approval') return { ok: false, error: 'not_awaiting_approval' };
796
+ setState(taskId, 'rejected', { resultText: 'Rejected. Nothing was changed.', finishedAt: now() });
797
+ return { ok: true };
798
+ }
799
+
800
+ function stop(taskId) {
801
+ const ctl = running.get(taskId);
802
+ if (!ctl) return { ok: false, error: 'not_running' };
803
+ ctl.stop = true;
804
+ log(taskId, 'stop requested');
805
+ return { ok: true };
806
+ }
807
+
808
+ /** Manual undo of a finished task (restores pre-task copy of every changed file). */
809
+ function undo(taskId) {
810
+ const t = store.get('tasks', taskId);
811
+ if (!t || !['done', 'unproven'].includes(t.state)) return { ok: false, error: 'only_finished_tasks' };
812
+ const project = store.get('projects', t.projectId);
813
+ const restored = restoreFiles(project, taskId, t.changedFiles || []);
814
+ setState(taskId, 'undone', { resultText: `Undone. ${restored.length} file(s) restored.`, finishedAt: now() });
815
+ return { ok: true, restored };
816
+ }
817
+
818
+ /** After a restart: nothing may stay "running" forever; guards keep watching (their copy is on disk). */
819
+ /**
820
+ * After a crash / restart nothing may stay half-done:
821
+ * - a supervised task that was changing files -> the project is restored from its full copy
822
+ * - a revert check that was interrupted -> the developer's own version of the files is put back
823
+ */
824
+ function recoverAfterRestart(cfg) {
825
+ const ignore = (cfg && cfg.ignoreDirs) || require('./config').DEFAULTS.ignoreDirs;
826
+ for (const t of store.list('tasks', (x) => ['diagnosing', 'executing', 'verifying', 'baselining'].includes(x.state))) {
827
+ let note = 'The service restarted during this task. Check the project and send the task again.';
828
+ const project = store.get('projects', t.projectId);
829
+ const before = loadSnapshot(t.id);
830
+ if (project && before && ['executing', 'verifying'].includes(t.state)) {
831
+ try {
832
+ const restored = restoreFiles(project, t.id, snapshot.diff(before, snapshot.take(project.root, ignore)));
833
+ note = `The service restarted during this task. Everything was restored to the original state (${restored.length} file(s)).`;
834
+ } catch (e) { note += ` Restore problem: ${e.message}`; }
835
+ }
836
+ store.update('tasks', t.id, { state: t.state === 'executing' || t.state === 'verifying' ? 'rolled_back' : 'failed', finishedAt: now(), resultText: note });
837
+ }
838
+ for (const t of store.list('tasks', (x) => x.kind === 'guard' && ['checking', 'watching'].includes(x.state))) {
839
+ const keep = path.join(DATA_DIR, 'backups', t.id, 'revert');
840
+ const project = store.get('projects', t.projectId);
841
+ let note = t.state === 'checking' ? 'The service restarted during a check. Press Check again.' : null;
842
+ if (project && fs.existsSync(keep)) {
843
+ const files = snapshot.walk(keep, []);
844
+ for (const rel of files) putBack(path.join(keep, rel), path.join(project.root, rel));
845
+ fs.rmSync(keep, { recursive: true, force: true });
846
+ note = `The service restarted during a check. Your ${files.length} changed file(s) were put back. Press Check again.`;
847
+ }
848
+ if (note) store.update('tasks', t.id, { state: 'watching', resultText: note });
849
+ }
850
+ }
851
+
852
+ module.exports = { markerFile, enrichBlocks, focusedFailure, create, start, approve, reject, stop, undo, guardStart, guardCheck, guardAccept, guardRollback, recoverAfterRestart, activeGuard, onChange, judge, FIX_INTENT };