buildproof 0.0.0-stage → 3.7.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE.txt +2 -0
- package/README.md +23 -2
- package/bin/buildproof.js +253 -0
- package/core/ai.js +193 -0
- package/core/av-scan.js +66 -0
- package/core/bug-hunter/engine.js +4 -0
- package/core/certs.js +194 -0
- package/core/claims.js +53 -0
- package/core/config.js +57 -0
- package/core/deps-guard.js +49 -0
- package/core/edits.js +97 -0
- package/core/fixlib.js +93 -0
- package/core/flow.js +852 -0
- package/core/gate.js +193 -0
- package/core/hooks.js +120 -0
- package/core/integrity.js +321 -0
- package/core/keep-corrupt.js +17 -0
- package/core/license.js +165 -0
- package/core/machine-proof.js +27 -0
- package/core/project-lock.js +31 -0
- package/core/projects.js +180 -0
- package/core/proof-score.js +11 -0
- package/core/runner.js +46 -0
- package/core/scope.js +153 -0
- package/core/security-scan.js +68 -0
- package/core/server.js +322 -0
- package/core/service.js +89 -0
- package/core/snapshot.js +90 -0
- package/core/store.js +45 -0
- package/core/vault.js +77 -0
- package/license/.keep +0 -0
- package/license/vendor.pub.pem +3 -0
- package/package.json +39 -4
- package/scripts/guard.js +311 -0
- package/web/apple-touch-icon.png +0 -0
- package/web/favicon-32.png +0 -0
- package/web/html2canvas.min.js +20 -0
- package/web/icon-192.png +0 -0
- package/web/icon-512.png +0 -0
- package/web/index.html +834 -0
- package/web/manifest.webmanifest +12 -0
package/core/certs.js
ADDED
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
/**
|
|
3
|
+
* Signed proof certificates (ed25519, key generated and kept on this computer).
|
|
4
|
+
* A certificate is a canonical JSON payload + signature + public key.
|
|
5
|
+
* The exported HTML file verifies itself in the browser (WebCrypto Ed25519), no server needed.
|
|
6
|
+
*/
|
|
7
|
+
const fs = require('fs');
|
|
8
|
+
const os = require('os');
|
|
9
|
+
const path = require('path');
|
|
10
|
+
const crypto = require('crypto');
|
|
11
|
+
const store = require('./store');
|
|
12
|
+
const { DATA_DIR } = require('./config');
|
|
13
|
+
|
|
14
|
+
const KEY_DIR = path.join(DATA_DIR, 'keys');
|
|
15
|
+
const PRIV = path.join(KEY_DIR, 'signing-ed25519.pem');
|
|
16
|
+
const PUB = path.join(KEY_DIR, 'signing-ed25519.pub.pem');
|
|
17
|
+
|
|
18
|
+
function keys() {
|
|
19
|
+
if (!fs.existsSync(PRIV)) {
|
|
20
|
+
fs.mkdirSync(KEY_DIR, { recursive: true });
|
|
21
|
+
const { privateKey, publicKey } = crypto.generateKeyPairSync('ed25519');
|
|
22
|
+
fs.writeFileSync(PRIV, privateKey.export({ type: 'pkcs8', format: 'pem' }), { mode: 0o600 });
|
|
23
|
+
fs.writeFileSync(PUB, publicKey.export({ type: 'spki', format: 'pem' }));
|
|
24
|
+
}
|
|
25
|
+
const privateKey = crypto.createPrivateKey(fs.readFileSync(PRIV));
|
|
26
|
+
const publicKey = crypto.createPublicKey(fs.readFileSync(PUB));
|
|
27
|
+
const spki = publicKey.export({ type: 'spki', format: 'der' });
|
|
28
|
+
return { privateKey, publicKey, spkiB64: spki.toString('base64'), fingerprint: fingerprintOf(spki) };
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function fingerprintOf(spkiDer) {
|
|
32
|
+
return crypto.createHash('sha256').update(spkiDer).digest('hex').slice(0, 32).toUpperCase().match(/.{4}/g).join(' ');
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Stable JSON: sorted keys, no whitespace. Same bytes in Node and in the browser. */
|
|
36
|
+
function canonical(v) {
|
|
37
|
+
if (Array.isArray(v)) return '[' + v.map(canonical).join(',') + ']';
|
|
38
|
+
if (v && typeof v === 'object') return '{' + Object.keys(v).sort().filter((k) => v[k] !== undefined).map((k) => JSON.stringify(k) + ':' + canonical(v[k])).join(',') + '}';
|
|
39
|
+
return JSON.stringify(v === undefined ? null : v);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function sha256File(abs) { try { return crypto.createHash('sha256').update(fs.readFileSync(abs)).digest('hex'); } catch { return null; } }
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Build + sign a certificate from a finished task (supervised or guard).
|
|
46
|
+
* Only issued when the work is proven and integrity is clean, or when a human explicitly accepted warnings.
|
|
47
|
+
*/
|
|
48
|
+
/**
|
|
49
|
+
* Fingerprint of the WHOLE certified code: sha256 of every file (sorted "path sha256" lines).
|
|
50
|
+
* The client recomputes it on the code they received - any difference shows up.
|
|
51
|
+
*/
|
|
52
|
+
function treeOf(root, opts = {}) {
|
|
53
|
+
const { walk } = require('./snapshot');
|
|
54
|
+
const { DEFAULTS } = require('./config');
|
|
55
|
+
const files = walk(root, DEFAULTS.ignoreDirs, opts.legacy ? 20000 : DEFAULTS.maxProjectFiles, { legacy: !!opts.legacy }).sort();
|
|
56
|
+
const list = files.map((f) => ({ file: f, sha256: sha256File(path.join(root, f)) }));
|
|
57
|
+
const treeHash = crypto.createHash('sha256').update(list.map((x) => `${x.file} ${x.sha256}`).join('\n')).digest('hex');
|
|
58
|
+
return { treeHash, count: list.length, files: list.length <= 3000 ? list : null };
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function gitInfo(root) {
|
|
62
|
+
try {
|
|
63
|
+
const { spawnSync } = require('child_process');
|
|
64
|
+
const head = spawnSync('git', ['rev-parse', 'HEAD'], { cwd: root, encoding: 'utf8', windowsHide: true, timeout: 5000 });
|
|
65
|
+
if (head.status !== 0) return null;
|
|
66
|
+
const st = spawnSync('git', ['status', '--porcelain'], { cwd: root, encoding: 'utf8', windowsHide: true, timeout: 5000 });
|
|
67
|
+
return { commit: head.stdout.trim(), dirty: !!st.stdout.trim() };
|
|
68
|
+
} catch { return null; }
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function issue(task, project, { acceptedWarnings = false } = {}) {
|
|
72
|
+
const k = keys();
|
|
73
|
+
const tree = treeOf(project.root);
|
|
74
|
+
const checks = Object.entries(task.after || {}).map(([step, r]) => ({
|
|
75
|
+
step,
|
|
76
|
+
before: task.baseline && task.baseline[step] ? (task.baseline[step].pass ? 'pass' : 'fail') : 'n/a',
|
|
77
|
+
after: r.pass ? 'pass' : r.ran === false ? 'did_not_run' : 'fail',
|
|
78
|
+
ms: r.ms || 0,
|
|
79
|
+
tests: r.tests || null,
|
|
80
|
+
}));
|
|
81
|
+
const changed = (task.changedFiles || []).map((c) => ({ file: c.file, kind: c.kind, sha256: c.kind === 'deleted' ? null : sha256File(path.join(project.root, c.file)) }));
|
|
82
|
+
const integ = task.integrity || { clean: true, findings: [], rulesChecked: [] };
|
|
83
|
+
const payload = {
|
|
84
|
+
format: 'buildproof-certificate/1',
|
|
85
|
+
id: 'c_' + crypto.randomBytes(6).toString('hex'),
|
|
86
|
+
issuedAt: new Date().toISOString(),
|
|
87
|
+
machine: os.hostname(),
|
|
88
|
+
project: project.name,
|
|
89
|
+
task: { id: task.id, kind: task.kind || 'supervised', text: task.text, source: task.source || 'web' },
|
|
90
|
+
result: acceptedWarnings ? 'ACCEPTED_WITH_WARNINGS' : 'PROVEN',
|
|
91
|
+
checks,
|
|
92
|
+
integrity: { clean: !!integ.clean, rulesChecked: integ.rulesChecked || [], findings: (integ.findings || []).map((f) => ({ rule: f.rule, file: f.file, text: f.text })) },
|
|
93
|
+
scope: { approved: task.approvedScope || null, outsideReverted: (task.scopeGuard && task.scopeGuard.reverted) || [] },
|
|
94
|
+
changes: changed,
|
|
95
|
+
ai: { calls: task.aiCalls || 0, model: task.aiModel || null, local: task.aiLocal !== false },
|
|
96
|
+
revertCheck: task.revertCheck ? { verdict: task.revertCheck.verdict, text: task.revertCheck.text } : null,
|
|
97
|
+
claims: (task.claims || []).map((c) => ({ claim: c.text, true: c.truth, why: c.why })),
|
|
98
|
+
rerun: { walk: 2, projectType: project.type, steps: Object.keys(task.after || {}), treeHash: tree.treeHash, fileCount: tree.count, files: tree.files, git: gitInfo(project.root) },
|
|
99
|
+
};
|
|
100
|
+
const body = canonical(payload);
|
|
101
|
+
const signature = crypto.sign(null, Buffer.from(body, 'utf8'), k.privateKey).toString('base64');
|
|
102
|
+
const cert = { id: payload.id, taskId: task.id, project: project.name, result: payload.result, issuedAt: payload.issuedAt, payload, signature, publicKey: k.spkiB64, fingerprint: k.fingerprint };
|
|
103
|
+
store.insert('certs', cert);
|
|
104
|
+
return cert;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Level 2 trust: the BuildProof license server countersigns the certificate and writes it to a public log,
|
|
109
|
+
* so a client can see WHO issued it (a registered, licensed developer) and WHEN. Best effort - offline is fine.
|
|
110
|
+
*/
|
|
111
|
+
async function countersign(cert, cfg) {
|
|
112
|
+
if (!cfg || !cfg.licenseServer) return null;
|
|
113
|
+
const key = require('./license').currentKey();
|
|
114
|
+
if (!key) return null;
|
|
115
|
+
const certHash = crypto.createHash('sha256').update(canonical(cert.payload)).digest('hex');
|
|
116
|
+
const ask = () => require('./ai').request(`${cfg.licenseServer.replace(/\/$/, '')}/api/countersign`, { certHash, fingerprint: cert.fingerprint, licenseKey: key, proof: require('./machine-proof').make('countersign', certHash) }, 5000);
|
|
117
|
+
let r = await ask();
|
|
118
|
+
// not registered yet (offline at activation, or a renewed key) -> register this signing key, try once more
|
|
119
|
+
if (r.json && r.json.error === 'fingerprint_not_registered' && await registerFingerprint(cfg)) r = await ask();
|
|
120
|
+
if (!r.ok || !r.json || !r.json.ok) return null;
|
|
121
|
+
const cs = { server: cfg.licenseServer, entry: r.json.entry, sig: r.json.sig };
|
|
122
|
+
store.update('certs', cert.id, { countersign: cs });
|
|
123
|
+
return cs;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
async function registerFingerprint(cfg) {
|
|
127
|
+
if (!cfg || !cfg.licenseServer) return null;
|
|
128
|
+
const key = require('./license').currentKey();
|
|
129
|
+
if (!key) return null;
|
|
130
|
+
const k = require('./license').parseKey(key);
|
|
131
|
+
const id = k.ok ? k.payload.id : '';
|
|
132
|
+
const r = await require('./ai').request(`${cfg.licenseServer.replace(/\/$/, '')}/api/register`, { licenseKey: key, fingerprint: keys().fingerprint, proof: require('./machine-proof').make('register', id) }, 5000);
|
|
133
|
+
return r.ok;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
function verify(cert) {
|
|
137
|
+
try {
|
|
138
|
+
// the fingerprint sits outside the signed payload: it must be the one of the key that signed, or it could name anybody
|
|
139
|
+
if (cert.fingerprint != null && cert.fingerprint !== require('./machine-proof').fingerprintOfSpki(cert.publicKey)) return false;
|
|
140
|
+
const pub = crypto.createPublicKey({ key: Buffer.from(cert.publicKey, 'base64'), format: 'der', type: 'spki' });
|
|
141
|
+
return crypto.verify(null, Buffer.from(canonical(cert.payload), 'utf8'), pub, Buffer.from(cert.signature, 'base64'));
|
|
142
|
+
} catch { return false; }
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
function esc(s) { return String(s == null ? '' : s).replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c])); }
|
|
146
|
+
|
|
147
|
+
/** Self-contained, self-verifying certificate page. */
|
|
148
|
+
function html(cert) {
|
|
149
|
+
const p = cert.payload;
|
|
150
|
+
const good = p.result === 'PROVEN';
|
|
151
|
+
const row = (c) => `<tr><td>${esc(c.step)}${c.tests ? ` <span class="dim">· ${c.tests.passed}/${c.tests.total} tests</span>` : ''}</td><td class="${c.before === 'pass' ? 'g' : 'r'}">${esc(c.before)}</td><td class="${c.after === 'pass' ? 'g' : 'r'}">${esc(c.after)}</td><td class="mono dim">${(c.ms / 1000).toFixed(1)}s</td></tr>`;
|
|
152
|
+
const integ = p.integrity.clean
|
|
153
|
+
? `<li class="g">No tests deleted, skipped or weakened</li><li class="g">No new mocks, sleeps or silent catches</li><li class="g">No checks silenced, no test scripts changed</li>`
|
|
154
|
+
: p.integrity.findings.map((f) => `<li class="r">${esc(f.text)} <span class="mono dim">${esc(f.file)}</span></li>`).join('');
|
|
155
|
+
const files = p.changes.map((c) => `<li><span class="mono">${esc(c.file)}</span> <span class="dim">${esc(c.kind)}</span>${c.sha256 ? `<br><span class="mono dim small">sha256 ${esc(c.sha256)}</span>` : ''}</li>`).join('') || '<li class="dim">No files changed</li>';
|
|
156
|
+
return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
|
157
|
+
<title>BuildProof certificate ${esc(p.id)}</title>
|
|
158
|
+
<style>*{box-sizing:border-box}body{margin:0;background:#F4F5F7;font:500 18px/1.5 Inter,"Segoe UI",system-ui,sans-serif;color:#0A0A0A}
|
|
159
|
+
.wrap{max-width:760px;margin:0 auto;padding:24px 16px 48px}.card{background:#fff;border:1px solid #E6E6E6;border-radius:16px;padding:22px;margin-bottom:14px}
|
|
160
|
+
h1{font-size:15px;letter-spacing:1.5px;text-transform:uppercase;color:#5F6368;margin:0 0 14px}.big{font:800 34px/1.1 Inter,system-ui,sans-serif;color:${good ? '#12803F' : '#B26A00'};letter-spacing:.5px}
|
|
161
|
+
.task{font-size:22px;font-weight:650;margin:12px 0 4px}.dim{color:#5F6368}.small{font-size:13px}.mono{font-family:ui-monospace,Consolas,"DejaVu Sans Mono",monospace;font-size:14px;word-break:break-all}
|
|
162
|
+
table{width:100%;border-collapse:collapse}td{padding:9px 6px;border-top:1px solid #EEE}td:nth-child(2),td:nth-child(3){font-weight:700;width:90px}.g{color:#12803F}.r{color:#C5221F}
|
|
163
|
+
ul{margin:0;padding-left:20px}li{margin:6px 0}h2{font-size:15px;color:#5F6368;margin:0 0 8px}
|
|
164
|
+
#sig{font-weight:700;padding:12px 14px;border-radius:12px;background:#F1F2F4}#sig.ok{background:#ECF7F0;color:#12803F}#sig.bad{background:#FDF1F0;color:#C5221F}</style></head>
|
|
165
|
+
<body><div class="wrap">
|
|
166
|
+
<div class="card"><h1>BuildProof certificate</h1><div class="big">${good ? 'PROVEN' : 'ACCEPTED WITH WARNINGS'}</div>
|
|
167
|
+
<div class="task">${esc(p.task.text)}</div><div class="dim">${esc(p.project)} · ${esc(new Date(p.issuedAt).toUTCString())} · ${esc(p.machine)}</div></div>
|
|
168
|
+
<div class="card"><h2>Checks · before → after</h2><table>${p.checks.map(row).join('')}</table></div>
|
|
169
|
+
<div class="card"><h2>Test integrity · ${p.integrity.rulesChecked.length} rules checked</h2><ul>${integ}</ul></div>
|
|
170
|
+
${p.revertCheck ? `<div class="card"><h2>Revert check</h2><div class="${p.revertCheck.verdict === 'covered' ? 'g' : p.revertCheck.verdict === 'skipped' ? 'dim' : 'r'}">${esc(p.revertCheck.text)}</div></div>` : ''}
|
|
171
|
+
${(p.claims || []).length ? `<div class="card"><h2>What the AI claimed</h2><ul>${p.claims.map((c) => `<li class="${c.true === false ? 'r' : c.true ? 'g' : 'dim'}">${c.true === false ? 'NOT TRUE: ' : c.true ? 'True: ' : 'Unknown: '}${esc(c.claim)} <span class="dim">(${esc(c.why)})</span></li>`).join('')}</ul></div>` : ''}
|
|
172
|
+
<div class="card"><h2>Changed files</h2><ul>${files}</ul></div>
|
|
173
|
+
<div class="card"><h2>AI</h2><div>${p.ai.calls} call(s)${p.ai.model ? ' · ' + esc(p.ai.model) : ''} · ${p.ai.local ? 'ran locally, code never left the computer' : 'remote model'}</div></div>
|
|
174
|
+
${cert.countersign ? `<div class="card"><h2>Countersigned</h2><div class="g">Registered with BuildProof at ${esc(new Date(cert.countersign.entry.time).toUTCString())} - public log: ${esc(cert.countersign.server)}/verify</div></div>` : ''}
|
|
175
|
+
<div class="card"><h2>Check it yourself</h2><div>Run the same checks on the code you received:</div><p class="mono" style="background:#F4F5F7;padding:10px 12px;border-radius:10px">npx buildproof verify certificate.html --rerun <your-project-folder></p><div class="dim small">It confirms the code is exactly the certified version (${p.rerun ? p.rerun.fileCount : '?'} files${p.rerun && p.rerun.git ? ', git ' + esc(p.rerun.git.commit.slice(0, 10)) : ''}) and runs ${p.rerun ? esc(p.rerun.steps.join(', ')) : 'the checks'} again on your computer.</div></div>
|
|
176
|
+
<div class="card"><h2>Signature</h2><div id="sig">Checking signature…</div>
|
|
177
|
+
<p class="mono dim small">ed25519 · key fingerprint <span id="fp">${esc(cert.fingerprint)}</span><br>certificate ${esc(p.id)}</p>
|
|
178
|
+
<p class="dim small">The signature proves this report was not changed after it was issued on the developer's computer. Ask the developer to confirm the key fingerprint.</p></div>
|
|
179
|
+
</div>
|
|
180
|
+
<script id="cert" type="application/json">${JSON.stringify({ payload: p, signature: cert.signature, publicKey: cert.publicKey, fingerprint: cert.fingerprint, countersign: cert.countersign || null }).replace(/</g, '\\u003c')}</script>
|
|
181
|
+
<script>
|
|
182
|
+
function canonical(v){if(Array.isArray(v))return'['+v.map(canonical).join(',')+']';if(v&&typeof v==='object')return'{'+Object.keys(v).sort().filter(function(k){return v[k]!==undefined}).map(function(k){return JSON.stringify(k)+':'+canonical(v[k])}).join(',')+'}';return JSON.stringify(v===undefined?null:v)}
|
|
183
|
+
function b64(s){var b=atob(s),u=new Uint8Array(b.length);for(var i=0;i<b.length;i++)u[i]=b.charCodeAt(i);return u}
|
|
184
|
+
(async function(){var el=document.getElementById('sig');try{var c=JSON.parse(document.getElementById('cert').textContent);
|
|
185
|
+
var key=await crypto.subtle.importKey('spki',b64(c.publicKey),{name:'Ed25519'},false,['verify']);
|
|
186
|
+
var ok=await crypto.subtle.verify({name:'Ed25519'},key,b64(c.signature),new TextEncoder().encode(canonical(c.payload)));
|
|
187
|
+
var h=Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256',b64(c.publicKey)))).map(function(b){return b.toString(16).padStart(2,'0')}).join('').slice(0,32).toUpperCase().match(/.{4}/g).join(' ');
|
|
188
|
+
if(c.fingerprint!==h)ok=false;var fe=document.getElementById('fp');if(fe)fe.textContent=h;
|
|
189
|
+
el.className=ok?'ok':'bad';el.textContent=ok?'✓ Signature valid. This report was not modified.':'✗ Signature INVALID. This report was modified.';}
|
|
190
|
+
catch(e){el.textContent='This browser cannot check ed25519 signatures. Open the file in a current Chrome, Edge, Safari or Firefox.';}})();
|
|
191
|
+
</script></body></html>`;
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
module.exports = { issue, verify, html, canonical, keys, treeOf, countersign, registerFingerprint };
|
package/core/claims.js
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
/**
|
|
3
|
+
* Claim vs reality: what the AI SAID it did, compared with what really happened.
|
|
4
|
+
* Deterministic patterns, no AI. A false claim never blocks proof by itself - it is reported loudly.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
const CLAIMS = [
|
|
8
|
+
{ id: 'tests_pass', re: /\b(all (the )?tests? (now )?(pass|passed|are passing|green)|tests? (are |now )*(passing|pass(es)?|green)|test suite (now )?pass(es)?)\b/i, text: 'All tests pass' },
|
|
9
|
+
{ id: 'build_ok', re: /\b(build (now )?(succeeds|succeeded|passes|passed|is green|works)|compiles (successfully|cleanly|without errors))\b/i, text: 'The build works' },
|
|
10
|
+
{ id: 'tests_added', re: /\b(added|wrote|created|new) (\d+ )?(new )?(unit |integration |e2e )?tests?\b/i, text: 'Tests were added' },
|
|
11
|
+
{ id: 'tests_untouched', re: /\b(did ?n[o']t|did not|without) (change|modify|touch|edit)(ing)? (any )?(of the )?(existing )?tests?\b/i, text: 'Tests were not changed' },
|
|
12
|
+
{ id: 'fixed', re: /\b(fixed|resolved|the (bug|issue|error) is (now )?(gone|fixed|resolved))\b/i, text: 'The problem is fixed' },
|
|
13
|
+
];
|
|
14
|
+
|
|
15
|
+
function extract(text) {
|
|
16
|
+
const s = String(text || '').slice(-20000);
|
|
17
|
+
if (!s.trim()) return [];
|
|
18
|
+
const out = [];
|
|
19
|
+
for (const c of CLAIMS) {
|
|
20
|
+
const m = s.match(c.re);
|
|
21
|
+
if (m) out.push({ id: c.id, text: c.text, quote: quoteAround(s, m.index, m[0].length) });
|
|
22
|
+
}
|
|
23
|
+
return out;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function quoteAround(s, i, len) {
|
|
27
|
+
const start = Math.max(0, s.lastIndexOf('\n', i) + 1, i - 80);
|
|
28
|
+
let end = s.indexOf('\n', i + len); if (end < 0 || end - i > 120) end = Math.min(s.length, i + len + 80);
|
|
29
|
+
return s.slice(start, end).trim().slice(0, 200);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* @param {string} text the AI's own words (final message)
|
|
34
|
+
* @param {object} r { after, changes, integrity, testFilesChanged, testCasesBefore, testCasesAfter, verdict }
|
|
35
|
+
*/
|
|
36
|
+
function compare(text, r) {
|
|
37
|
+
const claims = extract(text);
|
|
38
|
+
const after = r.after || {};
|
|
39
|
+
const testSteps = Object.keys(after).filter((s) => /test/.test(s));
|
|
40
|
+
const buildSteps = Object.keys(after).filter((s) => !/test/.test(s));
|
|
41
|
+
const testChanges = (r.changes || []).filter((c) => r.isTest(c.file));
|
|
42
|
+
return claims.map((c) => {
|
|
43
|
+
let truth = null; let why = '';
|
|
44
|
+
if (c.id === 'tests_pass') { truth = testSteps.length ? testSteps.every((s) => after[s].pass) : null; why = testSteps.length ? testSteps.map((s) => `${s} ${after[s].pass ? 'passed' : 'failed'}`).join(', ') : 'no test step to check'; }
|
|
45
|
+
if (c.id === 'build_ok') { truth = buildSteps.length ? buildSteps.every((s) => after[s].pass) : null; why = buildSteps.length ? buildSteps.map((s) => `${s} ${after[s].pass ? 'passed' : 'failed'}`).join(', ') : 'no build step to check'; }
|
|
46
|
+
if (c.id === 'tests_added') { truth = (r.testCasesAfter || 0) > (r.testCasesBefore || 0); why = `test cases ${r.testCasesBefore || 0} -> ${r.testCasesAfter || 0}`; }
|
|
47
|
+
if (c.id === 'tests_untouched') { truth = testChanges.length === 0; why = testChanges.length ? `changed: ${testChanges.map((x) => x.file).join(', ')}` : 'no test file changed'; }
|
|
48
|
+
if (c.id === 'fixed') { truth = !!(r.verdict && r.verdict.ok); why = r.verdict ? (r.verdict.ok ? 'all checks pass' : `still failing: ${(r.verdict.stillFailing || []).concat(r.verdict.regressions || []).join(', ') || 'not proven'}`) : 'not checked'; }
|
|
49
|
+
return { ...c, truth, why };
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
module.exports = { extract, compare, CLAIMS };
|
package/core/config.js
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
/** Config: defaults <- data/config.json <- env. Zero dependencies. */
|
|
3
|
+
const fs = require('fs');
|
|
4
|
+
const path = require('path');
|
|
5
|
+
const crypto = require('crypto');
|
|
6
|
+
|
|
7
|
+
const ROOT = path.resolve(__dirname, '..');
|
|
8
|
+
// Installed with npm (inside node_modules): data lives in the user's home, so updates never touch it.
|
|
9
|
+
const NPM_MODE = /[\\/]node_modules[\\/]/.test(ROOT);
|
|
10
|
+
const HOME_DIR = path.join(require('os').homedir(), '.buildproof');
|
|
11
|
+
const DATA_DIR = process.env.MGR_DATA_DIR || (NPM_MODE ? path.join(HOME_DIR, 'data') : path.join(ROOT, 'data'));
|
|
12
|
+
const LOG_DIR = process.env.MGR_LOG_DIR || (NPM_MODE ? path.join(HOME_DIR, 'logs') : path.join(ROOT, 'logs'));
|
|
13
|
+
const CONFIG_FILE = path.join(DATA_DIR, 'config.json');
|
|
14
|
+
|
|
15
|
+
const DEFAULTS = {
|
|
16
|
+
port: 38700,
|
|
17
|
+
host: '0.0.0.0',
|
|
18
|
+
allowedHosts: [], // extra host names this server answers to (IPs, localhost and *.ts.net always work)
|
|
19
|
+
token: '', // generated on first run
|
|
20
|
+
ollama: { endpoint: 'http://127.0.0.1:11434', model: 'qwen2.5-coder:14b', timeoutMs: 180000 },
|
|
21
|
+
budget: { maxAiCallsPerTask: 3, maxTaskSeconds: 900 },
|
|
22
|
+
commandTimeoutMs: 300000,
|
|
23
|
+
maxScopeFiles: 8,
|
|
24
|
+
licenseServer: '', // e.g. https://buildproof.dev - countersigned, publicly logged certificates
|
|
25
|
+
maxFileBytes: 60000,
|
|
26
|
+
maxProjectFiles: 100000, // more files than this: the guard refuses (it never guards half a project)
|
|
27
|
+
bugHunter: 'warn', // hidden-bug hunt on proven changes: 'warn' (shown, not blocking), 'block', 'off'
|
|
28
|
+
bugHunterSeconds: 120,
|
|
29
|
+
ignoreDirs: ['node_modules', '.git', '.next', 'dist', 'build', 'out', 'coverage', '.expo', '.turbo', '.cache', 'Library', 'Temp', 'obj', 'bin', '__pycache__', '.pytest_cache', '.mypy_cache', '.ruff_cache', '.venv', 'venv', '.tox', 'target', 'vendor', '.gradle', '.phpunit.cache', '.phpunit.result.cache', '.rspec_status', '.bundle'],
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
function deepMerge(a, b) {
|
|
33
|
+
const out = { ...a };
|
|
34
|
+
for (const [k, v] of Object.entries(b || {})) {
|
|
35
|
+
out[k] = v && typeof v === 'object' && !Array.isArray(v) ? deepMerge(a[k] || {}, v) : v;
|
|
36
|
+
}
|
|
37
|
+
return out;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function load() {
|
|
41
|
+
fs.mkdirSync(DATA_DIR, { recursive: true });
|
|
42
|
+
// first run, or a damaged file (kept aside as config.json.corrupt-<time>, never silently overwritten)
|
|
43
|
+
const file = require('./keep-corrupt').readJsonSafe(CONFIG_FILE) || {};
|
|
44
|
+
let cfg = deepMerge(DEFAULTS, file);
|
|
45
|
+
if (!cfg.token) {
|
|
46
|
+
cfg.token = crypto.randomBytes(18).toString('base64url');
|
|
47
|
+
fs.writeFileSync(CONFIG_FILE, JSON.stringify({ ...file, token: cfg.token }, null, 2), 'utf8');
|
|
48
|
+
}
|
|
49
|
+
if (process.env.MGR_PORT) cfg.port = Number(process.env.MGR_PORT);
|
|
50
|
+
if (process.env.MGR_TOKEN) cfg.token = process.env.MGR_TOKEN;
|
|
51
|
+
if (process.env.MGR_OLLAMA_ENDPOINT) cfg.ollama.endpoint = process.env.MGR_OLLAMA_ENDPOINT;
|
|
52
|
+
if (process.env.MGR_OLLAMA_MODEL) cfg.ollama.model = process.env.MGR_OLLAMA_MODEL;
|
|
53
|
+
if (process.env.MGR_LICENSE_SERVER) cfg.licenseServer = process.env.MGR_LICENSE_SERVER;
|
|
54
|
+
return cfg;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
module.exports = { load, ROOT, DATA_DIR, LOG_DIR, NPM_MODE, HOME_DIR, CONFIG_FILE, DEFAULTS };
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
/**
|
|
3
|
+
* Installed packages are not part of the snapshot (too big), so an AI could "fix" a failing test by editing
|
|
4
|
+
* node_modules/<the test runner or a dependency> instead of the code. Installs keep the package files' own dates
|
|
5
|
+
* (npm writes 1985), so a code file inside node_modules / the virtualenv that was written after the guard started,
|
|
6
|
+
* while no package / lock file changed, is an edit, not an install.
|
|
7
|
+
*
|
|
8
|
+
* Files written while BuildProof itself ran the project's scripts (baseline, checks: a build may write into
|
|
9
|
+
* node_modules/.prisma, caches ...) are the project's own doing: `windows` lists those [start, end] times.
|
|
10
|
+
*
|
|
11
|
+
* tampered(root, sinceMs, changes, windows) -> { file, total } | { skipped: reason } | null
|
|
12
|
+
*/
|
|
13
|
+
const fs = require('fs');
|
|
14
|
+
const path = require('path');
|
|
15
|
+
|
|
16
|
+
const DEP_DIRS = ['node_modules', '.venv', 'venv', 'vendor'];
|
|
17
|
+
const MANIFEST = /(^|\/)(package\.json|package-lock\.json|npm-shrinkwrap\.json|yarn\.lock|pnpm-lock\.yaml|bun\.lockb|requirements[^/]*\.txt|pyproject\.toml|poetry\.lock|Pipfile(\.lock)?|uv\.lock|setup\.(py|cfg)|go\.(mod|sum)|Cargo\.(toml|lock)|composer\.(json|lock)|Gemfile(\.lock)?|pom\.xml|build\.gradle(\.kts)?|packages\.lock\.json|[^/]+\.csproj)$/i;
|
|
18
|
+
const CODE = /\.([cm]?js|[cm]?ts|jsx|tsx|node|py|pth|json|php|rb|go)$/i;
|
|
19
|
+
const SKIP = new Set(['__pycache__']); // and every folder whose name starts with a dot (.cache, .prisma, .vite, .bin ...)
|
|
20
|
+
const MAX_ENTRIES = 400000;
|
|
21
|
+
const MAX_MS = 8000;
|
|
22
|
+
|
|
23
|
+
function tampered(root, sinceMs, changes, windows) {
|
|
24
|
+
// a file written by the project's own scripts is written AFTER the run started (no slack before it, or an AI edit made just before a check would be missed)
|
|
25
|
+
const ours = (t) => (windows || []).some(([a, b]) => t >= a - 50 && t <= (b || Date.now()) + 2000);
|
|
26
|
+
if (!Number.isFinite(sinceMs)) return null;
|
|
27
|
+
if ((changes || []).some((c) => MANIFEST.test(c.file))) return { skipped: 'packages were installed or changed' };
|
|
28
|
+
const t0 = Date.now();
|
|
29
|
+
let seen = 0; let first = null; let total = 0;
|
|
30
|
+
const rec = (dir, rel) => {
|
|
31
|
+
let entries; try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return; }
|
|
32
|
+
for (const e of entries) {
|
|
33
|
+
if (++seen > MAX_ENTRIES || Date.now() - t0 > MAX_MS) throw new Error('budget');
|
|
34
|
+
if (SKIP.has(e.name) || e.name.startsWith('.') || e.isSymbolicLink()) continue;
|
|
35
|
+
const abs = path.join(dir, e.name); const r = rel + '/' + e.name;
|
|
36
|
+
if (e.isDirectory()) { rec(abs, r); continue; }
|
|
37
|
+
if (!e.isFile() || !CODE.test(e.name)) continue;
|
|
38
|
+
let st; try { st = fs.statSync(abs); } catch { continue; }
|
|
39
|
+
// ctime too: an edit can set the modified date back, not the change time
|
|
40
|
+
const t = Math.max(st.mtimeMs, st.ctimeMs);
|
|
41
|
+
if (t > sinceMs + 1000 && !ours(t)) { total++; if (!first) first = r.slice(1); }
|
|
42
|
+
}
|
|
43
|
+
};
|
|
44
|
+
try { for (const d of DEP_DIRS) if (fs.existsSync(path.join(root, d))) rec(path.join(root, d), '/' + d); }
|
|
45
|
+
catch (e) { if (e.message === 'budget') return first ? { file: first, total, partial: true } : { skipped: 'too many package files to scan in time' }; throw e; }
|
|
46
|
+
return first ? { file: first, total } : null;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
module.exports = { tampered, MANIFEST };
|
package/core/edits.js
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
/**
|
|
3
|
+
* Safe edits: every write is backed up OUTSIDE the project (data/backups/<taskId>/...),
|
|
4
|
+
* so rollback is always possible and backups never pollute the project.
|
|
5
|
+
*/
|
|
6
|
+
const fs = require('fs');
|
|
7
|
+
const path = require('path');
|
|
8
|
+
const { DATA_DIR } = require('./config');
|
|
9
|
+
|
|
10
|
+
function isInside(root, abs) {
|
|
11
|
+
const rel = path.relative(path.resolve(root), path.resolve(abs));
|
|
12
|
+
return !!rel && !rel.startsWith('..') && !path.isAbsolute(rel);
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
function backupDir(taskId) { return path.join(DATA_DIR, 'backups', taskId); }
|
|
16
|
+
|
|
17
|
+
/** Back up a project file once per task (first version wins = pre-task state). */
|
|
18
|
+
function backupFile(root, taskId, rel) {
|
|
19
|
+
const abs = path.join(root, rel);
|
|
20
|
+
const dst = path.join(backupDir(taskId), 'files', rel);
|
|
21
|
+
const manifestPath = path.join(backupDir(taskId), 'manifest.json');
|
|
22
|
+
let manifest = {};
|
|
23
|
+
try { manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8')); } catch { manifest = {}; }
|
|
24
|
+
if (manifest[rel]) return manifest[rel];
|
|
25
|
+
fs.mkdirSync(path.dirname(dst), { recursive: true });
|
|
26
|
+
const existed = fs.existsSync(abs);
|
|
27
|
+
if (existed) fs.copyFileSync(abs, dst);
|
|
28
|
+
manifest[rel] = { existed };
|
|
29
|
+
fs.mkdirSync(backupDir(taskId), { recursive: true });
|
|
30
|
+
fs.writeFileSync(manifestPath, JSON.stringify(manifest, null, 2));
|
|
31
|
+
return manifest[rel];
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Write new full content for files. Rejects anything outside root or outside allowed list. */
|
|
35
|
+
function applyEdits(root, taskId, edits, allowed) {
|
|
36
|
+
const allowedSet = new Set((allowed || []).map((f) => f.replace(/\\/g, '/')));
|
|
37
|
+
const applied = [];
|
|
38
|
+
const rejected = [];
|
|
39
|
+
for (const e of edits || []) {
|
|
40
|
+
const rel = String(e.path || '').replace(/\\/g, '/').replace(/^\.\//, '');
|
|
41
|
+
const abs = path.resolve(root, rel);
|
|
42
|
+
if (!rel || !isInside(root, abs)) { rejected.push({ file: rel, reason: 'outside_project' }); continue; }
|
|
43
|
+
if (allowed && !allowedSet.has(rel)) { rejected.push({ file: rel, reason: 'outside_approved_scope' }); continue; }
|
|
44
|
+
const before = fs.existsSync(abs) ? fs.readFileSync(abs, 'utf8') : null;
|
|
45
|
+
backupFile(root, taskId, rel);
|
|
46
|
+
fs.mkdirSync(path.dirname(abs), { recursive: true });
|
|
47
|
+
fs.writeFileSync(abs, String(e.content == null ? '' : e.content), 'utf8');
|
|
48
|
+
applied.push({ file: rel, diff: unifiedDiff(before || '', String(e.content || ''), rel) });
|
|
49
|
+
}
|
|
50
|
+
return { applied, rejected };
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Restore given files (or all backed-up files) to pre-task state. */
|
|
54
|
+
function restore(root, taskId, files) {
|
|
55
|
+
const manifestPath = path.join(backupDir(taskId), 'manifest.json');
|
|
56
|
+
let manifest = {};
|
|
57
|
+
try { manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8')); } catch { return { restored: [], failed: [] }; }
|
|
58
|
+
const targets = files || Object.keys(manifest);
|
|
59
|
+
const restored = [];
|
|
60
|
+
const failed = [];
|
|
61
|
+
for (const rel of targets) {
|
|
62
|
+
const m = manifest[rel];
|
|
63
|
+
if (!m) { failed.push({ file: rel, reason: 'no_backup' }); continue; }
|
|
64
|
+
const abs = path.join(root, rel);
|
|
65
|
+
try {
|
|
66
|
+
if (m.existed) {
|
|
67
|
+
fs.mkdirSync(path.dirname(abs), { recursive: true });
|
|
68
|
+
fs.copyFileSync(path.join(backupDir(taskId), 'files', rel), abs);
|
|
69
|
+
const now = new Date(); try { fs.utimesSync(abs, now, now); } catch { /* keep going */ } // Windows keeps the old date: build tools would reuse a stale build
|
|
70
|
+
} else if (fs.existsSync(abs)) fs.unlinkSync(abs);
|
|
71
|
+
restored.push(rel);
|
|
72
|
+
} catch (e) { failed.push({ file: rel, reason: e.message }); }
|
|
73
|
+
}
|
|
74
|
+
return { restored, failed };
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** Compact line diff for reports (LCS-based, fine for files up to a few thousand lines). */
|
|
78
|
+
function unifiedDiff(a, b, name) {
|
|
79
|
+
const A = a.split(/\r?\n/);
|
|
80
|
+
const B = b.split(/\r?\n/);
|
|
81
|
+
if (A.length * B.length > 4e6) return `--- a/${name}\n+++ b/${name}\n(diff too large: ${A.length} -> ${B.length} lines)`;
|
|
82
|
+
const n = A.length; const m = B.length;
|
|
83
|
+
const dp = Array.from({ length: n + 1 }, () => new Uint32Array(m + 1));
|
|
84
|
+
for (let i = n - 1; i >= 0; i--) for (let j = m - 1; j >= 0; j--) {
|
|
85
|
+
dp[i][j] = A[i] === B[j] ? dp[i + 1][j + 1] + 1 : Math.max(dp[i + 1][j], dp[i][j + 1]);
|
|
86
|
+
}
|
|
87
|
+
const lines = [`--- a/${name}`, `+++ b/${name}`];
|
|
88
|
+
let i = 0; let j = 0;
|
|
89
|
+
while (i < n || j < m) {
|
|
90
|
+
if (i < n && j < m && A[i] === B[j]) { i++; j++; continue; }
|
|
91
|
+
if (j < m && (i >= n || dp[i][j + 1] >= dp[i + 1][j])) { lines.push(`+${B[j]} (line ${j + 1})`); j++; }
|
|
92
|
+
else { lines.push(`-${A[i]} (line ${i + 1})`); i++; }
|
|
93
|
+
}
|
|
94
|
+
return lines.join('\n');
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
module.exports = { applyEdits, restore, backupFile, unifiedDiff, isInside, backupDir };
|
package/core/fixlib.js
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
/**
|
|
3
|
+
* Fix library (no AI):
|
|
4
|
+
* - seed rules: error pattern -> deterministic action
|
|
5
|
+
* - learned fixes: exact error signature + exact file state -> recorded verified edit
|
|
6
|
+
*/
|
|
7
|
+
const crypto = require('crypto');
|
|
8
|
+
const fs = require('fs');
|
|
9
|
+
const path = require('path');
|
|
10
|
+
const store = require('./store');
|
|
11
|
+
const { hashFile } = require('./snapshot');
|
|
12
|
+
|
|
13
|
+
const SEED_RULES = [
|
|
14
|
+
{
|
|
15
|
+
id: 'deps_missing',
|
|
16
|
+
match: (err, project) => project.needsInstall || /cannot find module|module not found|err_module_not_found|can't resolve/i.test(err),
|
|
17
|
+
when: (err, project) => project.needsInstall || (project.type !== 'python' && /cannot find module ['"](?![a-zA-Z]:)[^.'"/\\][^'"]*['"]/i.test(err)),
|
|
18
|
+
action: 'npm_install',
|
|
19
|
+
title: 'Dependencies are missing - install them',
|
|
20
|
+
explain: 'The project cannot find its packages. Fix: npm install (installs the dependencies listed in package.json).',
|
|
21
|
+
},
|
|
22
|
+
{
|
|
23
|
+
id: 'native_rebuild',
|
|
24
|
+
match: (err) => /was compiled against a different node\.js version|node_module_version|npm rebuild/i.test(err),
|
|
25
|
+
when: () => true,
|
|
26
|
+
action: 'npm_rebuild',
|
|
27
|
+
title: 'A native module was built for another Node version - rebuild',
|
|
28
|
+
explain: 'A package was compiled for a different Node version. Fix: npm rebuild.',
|
|
29
|
+
},
|
|
30
|
+
];
|
|
31
|
+
|
|
32
|
+
function matchSeed(errText, project) {
|
|
33
|
+
for (const r of SEED_RULES) {
|
|
34
|
+
if (r.match(errText || '', project) && r.when(errText || '', project)) return r;
|
|
35
|
+
}
|
|
36
|
+
return null;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Stable signature of an error: strip paths, numbers, quotes noise. */
|
|
40
|
+
function signature(errText) {
|
|
41
|
+
const lines = String(errText || '')
|
|
42
|
+
.split(/\r?\n/)
|
|
43
|
+
.filter((l) => /error|fail|cannot|expected|undefined|not a function|is not defined|assert/i.test(l))
|
|
44
|
+
.slice(0, 6)
|
|
45
|
+
.map((l) => l.replace(/[A-Za-z]:\\[^\s:)]+|\/[^\s:)]+\/[^\s:)]+/g, '<path>')
|
|
46
|
+
.replace(/\b\d+(\.\d+)?(ms|s)?\b/g, '<n>')
|
|
47
|
+
.replace(/\s+/g, ' ')
|
|
48
|
+
.trim());
|
|
49
|
+
if (!lines.length) return null;
|
|
50
|
+
return crypto.createHash('sha256').update(lines.join('\n')).digest('hex').slice(0, 20);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* A learned fix is replayed only when the files are byte-identical to before AND
|
|
55
|
+
* it fixed the very tests this task is about (or, for old entries, the exact same failure).
|
|
56
|
+
*/
|
|
57
|
+
function findLearned(errText, project, targetNames) {
|
|
58
|
+
const sig = signature(errText);
|
|
59
|
+
if (!sig) return null;
|
|
60
|
+
const targets = targetNames || [];
|
|
61
|
+
const entries = store.list('fixes', (f) => f.projectType === project.type && (
|
|
62
|
+
targets.length ? Array.isArray(f.fixedTests) && f.fixedTests.length > 0 && targets.every((n) => f.fixedTests.includes(n)) : f.signature === sig));
|
|
63
|
+
for (const entry of entries.reverse()) {
|
|
64
|
+
const ok = entry.edits.every((e) => hashFile(path.join(project.root, e.path)) === e.beforeHash);
|
|
65
|
+
if (ok) return entry;
|
|
66
|
+
}
|
|
67
|
+
return null;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function learn({ errText, project, edits, beforeHashes, taskId, instruction, fixedTests }) {
|
|
71
|
+
const sig = signature(errText);
|
|
72
|
+
if (!sig || !edits.length) return null;
|
|
73
|
+
const entry = {
|
|
74
|
+
id: 'fx_' + crypto.randomBytes(5).toString('hex'),
|
|
75
|
+
signature: sig,
|
|
76
|
+
projectType: project.type,
|
|
77
|
+
projectId: project.id,
|
|
78
|
+
instruction: instruction || '',
|
|
79
|
+
sourceTaskId: taskId,
|
|
80
|
+
fixedTests: fixedTests || [],
|
|
81
|
+
edits: edits.map((e) => ({ path: e.path, beforeHash: beforeHashes[e.path] || null, content: e.content })),
|
|
82
|
+
uses: 0,
|
|
83
|
+
createdAt: new Date().toISOString(),
|
|
84
|
+
};
|
|
85
|
+
store.insert('fixes', entry);
|
|
86
|
+
return entry;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function readContent(root, rel) {
|
|
90
|
+
try { return fs.readFileSync(path.join(root, rel), 'utf8'); } catch { return null; }
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
module.exports = { SEED_RULES, matchSeed, signature, findLearned, learn, readContent };
|