@eyeauras/insight-cli 0.8.0 → 0.8.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/.cli-package-build.json +1 -1
- package/SKILL.md +1 -1
- package/dist/src/cli.js +2 -0
- package/dist/src/contexts.d.ts +2 -1
- package/dist/src/contexts.js +22 -9
- package/dist/src/research.d.ts +1 -0
- package/dist/src/research.js +1 -1
- package/dist/src/work/backup.d.ts +66 -0
- package/dist/src/work/backup.js +434 -0
- package/dist/src/work/commands.d.ts +5 -0
- package/dist/src/work/commands.js +277 -0
- package/dist/src/work/dashboard.d.ts +12 -0
- package/dist/src/work/dashboard.js +103 -0
- package/dist/src/work/model.d.ts +131 -0
- package/dist/src/work/model.js +124 -0
- package/dist/src/work/store.d.ts +368 -0
- package/dist/src/work/store.js +1050 -0
- package/dist/src/work/timing.d.ts +26 -0
- package/dist/src/work/timing.js +80 -0
- package/dist/src/workspace.d.ts +2 -0
- package/dist/src/workspace.js +13 -1
- package/package.json +1 -1
- package/references/recovery.md +6 -0
- package/references/work-tracking.md +203 -0
- package/runtime/toolbox.json +1 -0
- package/skill-bundle/insight-artifacts/SKILL.md +1 -1
- package/skill-bundle/insight-artifacts/references/recovery.md +6 -0
- package/skill-bundle/insight-binary/SKILL.md +1 -1
- package/skill-bundle/insight-capture/SKILL.md +1 -1
- package/skill-bundle/insight-cli/SKILL.md +1 -1
- package/skill-bundle/insight-cli/references/recovery.md +6 -0
- package/skill-bundle/insight-die/SKILL.md +1 -1
- package/skill-bundle/insight-dnspy/SKILL.md +1 -1
- package/skill-bundle/insight-dotnet-dump/SKILL.md +1 -1
- package/skill-bundle/insight-dotnet-stack/SKILL.md +1 -1
- package/skill-bundle/insight-dotnet-trace/SKILL.md +1 -1
- package/skill-bundle/insight-frida/SKILL.md +1 -1
- package/skill-bundle/insight-ghidra/SKILL.md +1 -1
- package/skill-bundle/insight-ghidra/references/recovery.md +6 -0
- package/skill-bundle/insight-ilspy/SKILL.md +1 -1
- package/skill-bundle/insight-interop/SKILL.md +1 -1
- package/skill-bundle/insight-lldb/SKILL.md +1 -1
- package/skill-bundle/insight-llvm/SKILL.md +1 -1
- package/skill-bundle/insight-managed-heap/SKILL.md +1 -1
- package/skill-bundle/insight-managed-metadata/SKILL.md +1 -1
- package/skill-bundle/insight-mitmproxy/SKILL.md +1 -1
- package/skill-bundle/insight-overview/SKILL.md +1 -1
- package/skill-bundle/insight-procmon/SKILL.md +1 -1
- package/skill-bundle/insight-re/SKILL.md +5 -1
- package/skill-bundle/insight-re/references/recovery.md +6 -0
- package/skill-bundle/insight-re/references/work-tracking.md +203 -0
- package/skill-bundle/insight-sevenzip/SKILL.md +1 -1
- package/skill-bundle/insight-strace/SKILL.md +1 -1
- package/skill-bundle/insight-tshark/SKILL.md +1 -1
- package/skill-bundle/insight-windbg/SKILL.md +1 -1
- package/skill-bundle/manifest.json +1 -1
- package/skills/insight-artifacts/SKILL.md +1 -1
- package/skills/insight-artifacts/references/recovery.md +6 -0
- package/skills/insight-binary/SKILL.md +1 -1
- package/skills/insight-capture/SKILL.md +1 -1
- package/skills/insight-die/SKILL.md +1 -1
- package/skills/insight-dnspy/SKILL.md +1 -1
- package/skills/insight-dotnet-dump/SKILL.md +1 -1
- package/skills/insight-dotnet-stack/SKILL.md +1 -1
- package/skills/insight-dotnet-trace/SKILL.md +1 -1
- package/skills/insight-frida/SKILL.md +1 -1
- package/skills/insight-ghidra/SKILL.md +1 -1
- package/skills/insight-ghidra/references/recovery.md +6 -0
- package/skills/insight-ilspy/SKILL.md +1 -1
- package/skills/insight-interop/SKILL.md +1 -1
- package/skills/insight-lldb/SKILL.md +1 -1
- package/skills/insight-llvm/SKILL.md +1 -1
- package/skills/insight-managed-heap/SKILL.md +1 -1
- package/skills/insight-managed-metadata/SKILL.md +1 -1
- package/skills/insight-mitmproxy/SKILL.md +1 -1
- package/skills/insight-overview/SKILL.md +1 -1
- package/skills/insight-procmon/SKILL.md +1 -1
- package/skills/insight-re/SKILL.md +5 -1
- package/skills/insight-re/references/recovery.md +6 -0
- package/skills/insight-re/references/work-tracking.md +203 -0
- package/skills/insight-sevenzip/SKILL.md +1 -1
- package/skills/insight-strace/SKILL.md +1 -1
- package/skills/insight-tshark/SKILL.md +1 -1
- package/skills/insight-windbg/SKILL.md +1 -1
|
@@ -0,0 +1,1050 @@
|
|
|
1
|
+
import { timingReport } from './timing.js';
|
|
2
|
+
import { DatabaseSync } from 'node:sqlite';
|
|
3
|
+
import { chmodSync, existsSync, lstatSync } from 'node:fs';
|
|
4
|
+
import { join } from 'node:path';
|
|
5
|
+
import { randomUUID } from 'node:crypto';
|
|
6
|
+
import { createHash } from 'node:crypto';
|
|
7
|
+
import { openSync, writeSync, fsyncSync, closeSync, unlinkSync } from 'node:fs';
|
|
8
|
+
import { archivedOutcomes, array, definition, digest, fail, leaseToken, identifier, integer, object, passport, sha, stable, string, reviewState } from './model.js';
|
|
9
|
+
export const workTableColumns = {
|
|
10
|
+
projects: ['id', 'data'], functions: ['project', 'id', 'rva', 'stage', 'data'], tasks: ['id', 'project', 'status', 'data'],
|
|
11
|
+
locks: ['project', 'resource', 'task'], events: ['seq', 'project', 'revision', 'kind', 'data'], receipts: ['id', 'result'],
|
|
12
|
+
graph_nodes: ['project', 'id', 'data'], graph_edges: ['project', 'id', 'data'],
|
|
13
|
+
function_versions: ['project', 'id', 'version', 'data', 'reason', 'at', 'request'], archived_requests: ['caller_id', 'data'],
|
|
14
|
+
function_resources: ['project', 'function_id', 'resource', 'evidence_edge'],
|
|
15
|
+
};
|
|
16
|
+
/** Edge kinds whose source exclusively reserves the target; everything else is a read dependency. */
|
|
17
|
+
export const exclusiveEdgeKinds = ['writes', 'initializes', 'owns', 'frees'];
|
|
18
|
+
const timingIndexes = `CREATE INDEX IF NOT EXISTS work_clock_by_task ON events(project,json_extract(data,'$.task'),seq)
|
|
19
|
+
WHERE kind IN ('task.claimed','reconstruction.submitted','review.submitted');
|
|
20
|
+
CREATE INDEX IF NOT EXISTS work_package_events ON events(project,json_extract(data,'$.request'))
|
|
21
|
+
WHERE kind IN ('reconstruction.submitted','review.submitted');`;
|
|
22
|
+
export const workSchema = `
|
|
23
|
+
PRAGMA busy_timeout=5000; PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL; PRAGMA foreign_keys=ON;
|
|
24
|
+
CREATE TABLE IF NOT EXISTS projects(id TEXT PRIMARY KEY,data TEXT NOT NULL);
|
|
25
|
+
CREATE TABLE IF NOT EXISTS functions(project TEXT NOT NULL REFERENCES projects(id),id TEXT NOT NULL,
|
|
26
|
+
rva INTEGER NOT NULL,stage TEXT NOT NULL,data TEXT NOT NULL,PRIMARY KEY(project,id));
|
|
27
|
+
CREATE INDEX IF NOT EXISTS function_frontier ON functions(project,stage,rva);
|
|
28
|
+
CREATE TABLE IF NOT EXISTS tasks(id TEXT PRIMARY KEY,project TEXT NOT NULL REFERENCES projects(id),
|
|
29
|
+
status TEXT NOT NULL,data TEXT NOT NULL);
|
|
30
|
+
CREATE INDEX IF NOT EXISTS task_project ON tasks(project,status);
|
|
31
|
+
CREATE TABLE IF NOT EXISTS locks(project TEXT NOT NULL,resource TEXT NOT NULL,task TEXT NOT NULL REFERENCES tasks(id),
|
|
32
|
+
PRIMARY KEY(project,resource));
|
|
33
|
+
CREATE TABLE IF NOT EXISTS events(seq INTEGER PRIMARY KEY AUTOINCREMENT,project TEXT NOT NULL,
|
|
34
|
+
revision INTEGER NOT NULL,kind TEXT NOT NULL,data TEXT NOT NULL);
|
|
35
|
+
${timingIndexes}
|
|
36
|
+
CREATE TABLE IF NOT EXISTS receipts(id TEXT PRIMARY KEY,result TEXT NOT NULL);
|
|
37
|
+
CREATE TABLE IF NOT EXISTS graph_nodes(project TEXT NOT NULL REFERENCES projects(id),id TEXT NOT NULL,data TEXT NOT NULL,PRIMARY KEY(project,id));
|
|
38
|
+
CREATE TABLE IF NOT EXISTS graph_edges(project TEXT NOT NULL REFERENCES projects(id),id TEXT NOT NULL,data TEXT NOT NULL,PRIMARY KEY(project,id));
|
|
39
|
+
CREATE TABLE IF NOT EXISTS work_metadata(key TEXT PRIMARY KEY,value TEXT NOT NULL);
|
|
40
|
+
CREATE TABLE IF NOT EXISTS function_versions(project TEXT NOT NULL,id TEXT NOT NULL,version INTEGER NOT NULL,
|
|
41
|
+
data TEXT NOT NULL,reason TEXT NOT NULL,at INTEGER NOT NULL,request TEXT,PRIMARY KEY(project,id,version),
|
|
42
|
+
FOREIGN KEY(project,id) REFERENCES functions(project,id));
|
|
43
|
+
CREATE TABLE IF NOT EXISTS archived_requests(caller_id TEXT PRIMARY KEY,data TEXT NOT NULL);
|
|
44
|
+
CREATE TABLE IF NOT EXISTS function_resources(project TEXT NOT NULL,function_id TEXT NOT NULL,resource TEXT NOT NULL,evidence_edge TEXT NOT NULL,
|
|
45
|
+
PRIMARY KEY(project,function_id,resource,evidence_edge),FOREIGN KEY(project,function_id) REFERENCES functions(project,id));
|
|
46
|
+
CREATE TRIGGER IF NOT EXISTS work_versions_no_update BEFORE UPDATE ON function_versions BEGIN SELECT RAISE(ABORT,'immutable work version'); END;
|
|
47
|
+
CREATE TRIGGER IF NOT EXISTS work_versions_no_delete BEFORE DELETE ON function_versions BEGIN SELECT RAISE(ABORT,'immutable work version'); END;
|
|
48
|
+
`;
|
|
49
|
+
/** Fast profile-owned workflow data. Native Ghidra publication remains in Research/Workspace. */
|
|
50
|
+
export class WorkStore {
|
|
51
|
+
workspace;
|
|
52
|
+
clock;
|
|
53
|
+
db;
|
|
54
|
+
incarnation;
|
|
55
|
+
currentRequest;
|
|
56
|
+
constructor(workspace, clock = Date.now, readOnly = false) {
|
|
57
|
+
this.workspace = workspace;
|
|
58
|
+
this.clock = clock;
|
|
59
|
+
const path = join(workspace.directory, 'work.sqlite');
|
|
60
|
+
if (existsSync(path) && (!lstatSync(path).isFile() || lstatSync(path).isSymbolicLink()))
|
|
61
|
+
fail('storage', 'Work database must be an ordinary profile-owned file.');
|
|
62
|
+
const present = existsSync(path);
|
|
63
|
+
this.db = new DatabaseSync(readOnly && !present ? ':memory:' : path, { readOnly: readOnly && present });
|
|
64
|
+
if (!readOnly && !present)
|
|
65
|
+
chmodSync(path, 0o600);
|
|
66
|
+
try {
|
|
67
|
+
const version = Number(this.db.prepare('PRAGMA user_version').get()?.user_version);
|
|
68
|
+
if (version > 2)
|
|
69
|
+
fail('storage', 'Work schema is newer; preserve it and use its matching build.');
|
|
70
|
+
if (version === 2) {
|
|
71
|
+
const epoch = this.db.prepare("SELECT value FROM work_metadata WHERE key='incarnation'").get()?.value;
|
|
72
|
+
if (!epoch)
|
|
73
|
+
fail('storage', 'Work incarnation is missing; preserve and recover the database.');
|
|
74
|
+
this.incarnation = String(epoch);
|
|
75
|
+
this.db.exec('PRAGMA busy_timeout=5000; PRAGMA foreign_keys=ON;');
|
|
76
|
+
if (!readOnly)
|
|
77
|
+
this.reconcileWriterScopes();
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
if (readOnly && present)
|
|
81
|
+
fail('migrationRequired', 'Run work migrate with Update permission before reading this older ledger.');
|
|
82
|
+
this.db.exec(workSchema);
|
|
83
|
+
this.tx(() => {
|
|
84
|
+
this.db.prepare('INSERT OR IGNORE INTO work_metadata VALUES(?,?)').run('incarnation', randomUUID());
|
|
85
|
+
const epoch = String(this.db.prepare("SELECT value FROM work_metadata WHERE key='incarnation'").get().value);
|
|
86
|
+
if (version < 2) {
|
|
87
|
+
for (const row of this.db.prepare('SELECT id,data FROM projects ORDER BY id').iterate()) {
|
|
88
|
+
const p = JSON.parse(String(row.data));
|
|
89
|
+
p.planningRevision ??= p.revision;
|
|
90
|
+
p.epoch ??= epoch;
|
|
91
|
+
this.putProject(p);
|
|
92
|
+
}
|
|
93
|
+
for (const row of this.db.prepare('SELECT project,data FROM functions ORDER BY project,id').iterate()) {
|
|
94
|
+
const fn = JSON.parse(String(row.data));
|
|
95
|
+
fn.definitionRevision ??= 1;
|
|
96
|
+
fn.definitionSha256 ??= digest(fn.definition);
|
|
97
|
+
if (fn.source)
|
|
98
|
+
fn.packageDefinitionRevision ??= fn.definitionRevision;
|
|
99
|
+
this.db.prepare('UPDATE functions SET data=? WHERE project=? AND id=?').run(stable(fn), String(row.project), fn.id);
|
|
100
|
+
this.recordVersion(String(row.project), fn, 'migration-current-only');
|
|
101
|
+
}
|
|
102
|
+
for (const row of this.db.prepare('SELECT data FROM tasks ORDER BY id').iterate()) {
|
|
103
|
+
const task = JSON.parse(String(row.data));
|
|
104
|
+
task.epoch ??= epoch;
|
|
105
|
+
this.putTask(task);
|
|
106
|
+
}
|
|
107
|
+
const affected = new Set();
|
|
108
|
+
for (const row of this.db.prepare('SELECT project,data FROM graph_edges ORDER BY project,id').iterate()) {
|
|
109
|
+
const project = String(row.project);
|
|
110
|
+
if (this.retainGraphResources(project, JSON.parse(String(row.data))))
|
|
111
|
+
affected.add(project);
|
|
112
|
+
}
|
|
113
|
+
for (const id of affected) {
|
|
114
|
+
const project = this.project(id), reason = 'M0 migrated direct graph reservations; legacy scopes require replanning.';
|
|
115
|
+
const cancelledTasks = this.invalidateTasks(project, reason).length;
|
|
116
|
+
this.invalidatePackages(project, reason);
|
|
117
|
+
this.event(project, 'resources.migrated', { reason, cancelledTasks });
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
this.db.prepare("INSERT OR REPLACE INTO work_metadata VALUES('writer_scope_check', '1')").run();
|
|
121
|
+
this.db.exec('PRAGMA user_version=2');
|
|
122
|
+
}, true);
|
|
123
|
+
this.incarnation = String(this.db.prepare("SELECT value FROM work_metadata WHERE key='incarnation'").get().value);
|
|
124
|
+
}
|
|
125
|
+
catch (error) {
|
|
126
|
+
this.db.close();
|
|
127
|
+
throw error;
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
// Development schema 2 could keep a source-less assignment after its writer
|
|
131
|
+
// footprint expanded. Reconcile only live scopes once at the next writable open.
|
|
132
|
+
reconcileWriterScopes() {
|
|
133
|
+
const marker = "SELECT 1 FROM work_metadata WHERE key='writer_scope_check'";
|
|
134
|
+
if (this.db.prepare(marker).get())
|
|
135
|
+
return;
|
|
136
|
+
this.tx(() => {
|
|
137
|
+
if (this.db.prepare(marker).get())
|
|
138
|
+
return;
|
|
139
|
+
this.db.exec(timingIndexes);
|
|
140
|
+
const active = this.db.prepare("SELECT data FROM tasks WHERE status IN ('queued','leased')").all();
|
|
141
|
+
for (const row of active) {
|
|
142
|
+
const task = JSON.parse(String(row.data));
|
|
143
|
+
const held = new Set(task.resources);
|
|
144
|
+
const missing = task.functions.filter(fn => this.derivedResources(task.project, fn, 10001).some(key => !held.has(key)));
|
|
145
|
+
if (missing.length)
|
|
146
|
+
this.invalidateTasks(this.project(task.project), 'New writer evidence expanded the reserved scope', new Set(missing));
|
|
147
|
+
}
|
|
148
|
+
this.db.prepare("INSERT INTO work_metadata VALUES('writer_scope_check','1')").run();
|
|
149
|
+
}, true);
|
|
150
|
+
}
|
|
151
|
+
close() { this.db.close(); }
|
|
152
|
+
tx(action, write = false) {
|
|
153
|
+
this.db.exec(write ? 'BEGIN IMMEDIATE' : 'BEGIN');
|
|
154
|
+
try {
|
|
155
|
+
const result = action();
|
|
156
|
+
this.db.exec('COMMIT');
|
|
157
|
+
return result;
|
|
158
|
+
}
|
|
159
|
+
catch (error) {
|
|
160
|
+
this.db.exec('ROLLBACK');
|
|
161
|
+
throw error;
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
project(id) {
|
|
165
|
+
identifier(id);
|
|
166
|
+
const row = this.db.prepare('SELECT data FROM projects WHERE id=?').get(id);
|
|
167
|
+
if (!row)
|
|
168
|
+
fail('notFound', 'Project is not present in this profile.');
|
|
169
|
+
const result = JSON.parse(String(row.data));
|
|
170
|
+
if (this.workspace.target(result.target).binarySha256 !== result.binarySha256)
|
|
171
|
+
fail('binding', 'Project target identity changed.');
|
|
172
|
+
return result;
|
|
173
|
+
}
|
|
174
|
+
putProject(project) { this.db.prepare('UPDATE projects SET data=? WHERE id=?').run(stable(project), project.id); }
|
|
175
|
+
function(project, id) {
|
|
176
|
+
const row = this.db.prepare('SELECT data FROM functions WHERE project=? AND id=?').get(project, string(id, 256));
|
|
177
|
+
if (!row)
|
|
178
|
+
fail('notFound', 'Function is not present in this project.');
|
|
179
|
+
return JSON.parse(String(row.data));
|
|
180
|
+
}
|
|
181
|
+
recordVersion(project, fn, reason) {
|
|
182
|
+
const prior = this.db.prepare('SELECT data FROM function_versions WHERE project=? AND id=? AND version=?').get(project, fn.id, fn.version);
|
|
183
|
+
if (prior) {
|
|
184
|
+
if (prior.data !== stable(fn))
|
|
185
|
+
fail('storage', 'Function version was already retained with other bytes.');
|
|
186
|
+
return;
|
|
187
|
+
}
|
|
188
|
+
this.db.prepare('INSERT INTO function_versions VALUES(?,?,?,?,?,?,?)')
|
|
189
|
+
.run(project, fn.id, fn.version, stable(fn), reason, this.clock(), this.currentRequest ?? null);
|
|
190
|
+
}
|
|
191
|
+
putFunction(project, fn, reason = 'package.changed') {
|
|
192
|
+
this.db.prepare('UPDATE functions SET stage=?,data=? WHERE project=? AND id=?').run(fn.stage, stable(fn), project, fn.id);
|
|
193
|
+
this.recordVersion(project, fn, reason);
|
|
194
|
+
}
|
|
195
|
+
task(id) {
|
|
196
|
+
const row = this.db.prepare('SELECT data FROM tasks WHERE id=?').get(identifier(id));
|
|
197
|
+
if (!row)
|
|
198
|
+
fail('notFound', 'Task was not found.');
|
|
199
|
+
return JSON.parse(String(row.data));
|
|
200
|
+
}
|
|
201
|
+
putTask(task) { this.db.prepare('UPDATE tasks SET status=?,data=? WHERE id=?').run(task.status, stable(task), task.id); }
|
|
202
|
+
event(project, kind, data, planning = true) {
|
|
203
|
+
project.revision++;
|
|
204
|
+
if (planning)
|
|
205
|
+
project.planningRevision = project.revision;
|
|
206
|
+
this.putProject(project);
|
|
207
|
+
this.db.prepare('INSERT INTO events(project,revision,kind,data) VALUES(?,?,?,?)')
|
|
208
|
+
.run(project.id, project.revision, kind, stable({ at: this.clock(), request: this.currentRequest, ...object(data) }));
|
|
209
|
+
}
|
|
210
|
+
/** An explicit epoch must match; omission is allowed. Restore already cancels every old assignment. */
|
|
211
|
+
checkEpoch(project, epoch) {
|
|
212
|
+
if (epoch !== undefined && identifier(epoch) !== project.epoch)
|
|
213
|
+
fail('staleEpoch', 'This epoch belongs to another work incarnation; read a fresh brief.');
|
|
214
|
+
}
|
|
215
|
+
cancelled(task) {
|
|
216
|
+
fail('taskCancelled', 'Task was cancelled and cannot be resumed; request new work with work next.', { task: task.id, reason: task.result, functions: task.functions, retry: `work next --kind ${task.kind} --functions ${task.functions.join(',')}` });
|
|
217
|
+
}
|
|
218
|
+
planning(project, expected, epoch) {
|
|
219
|
+
this.checkEpoch(project, epoch);
|
|
220
|
+
const value = integer(expected, 1, Number.MAX_SAFE_INTEGER);
|
|
221
|
+
if (value < (project.planningRevision ?? project.revision) || value > project.revision)
|
|
222
|
+
fail('staleRevision', 'Refresh the shared brief before planning.', { currentRevision: project.revision, planningRevision: project.planningRevision, epoch: project.epoch });
|
|
223
|
+
}
|
|
224
|
+
lease(taskId, worker, fence, epoch) {
|
|
225
|
+
const task = this.task(taskId);
|
|
226
|
+
const project = this.project(task.project);
|
|
227
|
+
this.checkEpoch(project, epoch);
|
|
228
|
+
if (task.status === 'cancelled')
|
|
229
|
+
this.cancelled(task);
|
|
230
|
+
if (task.epoch !== project.epoch)
|
|
231
|
+
fail('staleEpoch', 'Assignment belongs to another work incarnation.');
|
|
232
|
+
if (task.status !== 'leased' || task.worker !== identifier(worker) || task.fence !== integer(fence, 1, Number.MAX_SAFE_INTEGER)
|
|
233
|
+
|| task.leaseUntil <= this.clock())
|
|
234
|
+
fail('staleLease', 'Lease is expired, reclaimed or belongs to another worker.');
|
|
235
|
+
for (const id of task.functions)
|
|
236
|
+
if (this.function(task.project, id).version !== task.versions[id])
|
|
237
|
+
fail('staleFunction', 'Assigned function changed since planning; preserve work and re-plan.');
|
|
238
|
+
return task;
|
|
239
|
+
}
|
|
240
|
+
invalidateTasks(project, reason, functionIds) {
|
|
241
|
+
const ids = [];
|
|
242
|
+
for (const row of this.db.prepare("SELECT data FROM tasks WHERE project=? AND status IN ('queued','leased') ORDER BY id").all(project.id)) {
|
|
243
|
+
const task = JSON.parse(String(row.data));
|
|
244
|
+
if (functionIds && !task.functions.some(id => functionIds.has(id)))
|
|
245
|
+
continue;
|
|
246
|
+
const previous = { ...task };
|
|
247
|
+
task.status = 'cancelled';
|
|
248
|
+
task.fence = integer(task.fence + 1, 1, Number.MAX_SAFE_INTEGER);
|
|
249
|
+
task.leaseUntil = 0;
|
|
250
|
+
task.result = { reason, replanRequired: true };
|
|
251
|
+
this.putTask(task);
|
|
252
|
+
this.db.prepare('DELETE FROM locks WHERE task=?').run(task.id);
|
|
253
|
+
this.event(project, 'task.invalidated', { reason, previous, task: task.id });
|
|
254
|
+
ids.push(task.id);
|
|
255
|
+
}
|
|
256
|
+
return ids;
|
|
257
|
+
}
|
|
258
|
+
/**
|
|
259
|
+
* Only a writer edge reserves its target exclusively. Calls/reads are read dependencies: they are
|
|
260
|
+
* visible in handoff and invalidate packages of their endpoints when new, but never lock.
|
|
261
|
+
*/
|
|
262
|
+
retainGraphResources(project, edge) {
|
|
263
|
+
const fn = String(edge.source), resource = String(edge.target);
|
|
264
|
+
if (edge.confidence === 'rejected' || !exclusiveEdgeKinds.includes(String(edge.kind)) || fn === resource
|
|
265
|
+
|| !this.db.prepare('SELECT 1 FROM functions WHERE project=? AND id=?').get(project, fn))
|
|
266
|
+
return 0;
|
|
267
|
+
return Number(this.db.prepare('INSERT OR IGNORE INTO function_resources VALUES(?,?,?,?)').run(project, fn, resource, String(edge.id)).changes);
|
|
268
|
+
}
|
|
269
|
+
/** Exclusive keys from retained writer edges; older rows derived from other edge kinds are ignored. */
|
|
270
|
+
derivedResources(project, fn, limit) {
|
|
271
|
+
return this.db.prepare(`SELECT DISTINCT r.resource FROM function_resources r JOIN graph_edges e ON e.project=r.project AND e.id=r.evidence_edge
|
|
272
|
+
WHERE r.project=? AND r.function_id=? AND json_extract(e.data,'$.source')=r.function_id AND json_extract(e.data,'$.confidence')<>'rejected'
|
|
273
|
+
AND json_extract(e.data,'$.kind') IN (${exclusiveEdgeKinds.map(() => '?').join(',')}) LIMIT ?`)
|
|
274
|
+
.all(project, fn, ...exclusiveEdgeKinds, limit).map(row => String(row.resource));
|
|
275
|
+
}
|
|
276
|
+
/** Retained packages (with source) of the given functions become invalid; packages without source are untouched. */
|
|
277
|
+
invalidatePackages(project, reason, functionIds) {
|
|
278
|
+
const changed = new Set();
|
|
279
|
+
const lookup = this.db.prepare('SELECT data FROM functions WHERE project=? AND id=?');
|
|
280
|
+
const rows = functionIds ? Array.from(functionIds, id => lookup.get(project.id, id)) :
|
|
281
|
+
this.db.prepare('SELECT data FROM functions WHERE project=? ORDER BY id').iterate(project.id);
|
|
282
|
+
for (const row of rows) {
|
|
283
|
+
const fn = JSON.parse(String(row.data));
|
|
284
|
+
if (functionIds && !fn.source)
|
|
285
|
+
continue;
|
|
286
|
+
fn.version++;
|
|
287
|
+
fn.invalidated = { reason, at: this.clock(), request: this.currentRequest };
|
|
288
|
+
if (fn.source)
|
|
289
|
+
fn.stage = 'partial';
|
|
290
|
+
this.putFunction(project.id, fn, 'dependencies.changed');
|
|
291
|
+
changed.add(fn.id);
|
|
292
|
+
}
|
|
293
|
+
return changed;
|
|
294
|
+
}
|
|
295
|
+
reviseDefinition(projectId, functionId, expectedVersion, input, artifact, epoch) {
|
|
296
|
+
const project = this.project(projectId);
|
|
297
|
+
this.checkEpoch(project, epoch);
|
|
298
|
+
const current = this.function(project.id, functionId), manifest = object(input);
|
|
299
|
+
if (current.version !== integer(expectedVersion, 1, Number.MAX_SAFE_INTEGER))
|
|
300
|
+
fail('staleFunction', 'Definition/package changed; inspect it before revising.');
|
|
301
|
+
if (manifest.schema !== 1 || manifest.kind !== 'function-definition-revision' || manifest.binarySha256 !== project.binarySha256)
|
|
302
|
+
fail('binding', 'Revision requires the exact target hash and function-definition-revision kind.');
|
|
303
|
+
const next = definition(manifest.definition, project.binarySha256), reason = string(manifest.reason, 2000);
|
|
304
|
+
if (next.id !== current.id)
|
|
305
|
+
fail('binding', 'An entry change creates another anchor; it cannot revise this function.');
|
|
306
|
+
if (stable(next.definition) === stable(current.definition)) {
|
|
307
|
+
this.event(project, 'definition.confirmed', { function: current.id, artifact, reason }, false);
|
|
308
|
+
return { function: current.id, version: current.version, definitionRevision: current.definitionRevision, changed: false, revision: project.revision };
|
|
309
|
+
}
|
|
310
|
+
const cancelledTasks = this.invalidateTasks(project, reason, new Set([current.id])).length;
|
|
311
|
+
current.definition = next.definition;
|
|
312
|
+
current.resources = next.resources;
|
|
313
|
+
current.name = next.name;
|
|
314
|
+
current.risk = next.risk;
|
|
315
|
+
current.definitionRevision = (current.definitionRevision ?? 1) + 1;
|
|
316
|
+
current.definitionSha256 = digest(current.definition);
|
|
317
|
+
current.invalidated = { reason, at: this.clock(), request: this.currentRequest };
|
|
318
|
+
current.version++;
|
|
319
|
+
if (current.source)
|
|
320
|
+
current.stage = 'partial';
|
|
321
|
+
this.putFunction(project.id, current, 'definition.revised');
|
|
322
|
+
this.event(project, 'definition.revised', { function: current.id, definitionRevision: current.definitionRevision, artifact, reason, cancelledTasks });
|
|
323
|
+
return { function: current.id, version: current.version, definitionRevision: current.definitionRevision, definitionSha256: current.definitionSha256, changed: true, cancelledTasks, revision: project.revision, accepted1to1: false };
|
|
324
|
+
}
|
|
325
|
+
history(projectId, functionId, after, limit) {
|
|
326
|
+
return this.tx(() => {
|
|
327
|
+
const project = this.project(projectId);
|
|
328
|
+
this.function(project.id, functionId);
|
|
329
|
+
const rows = this.db.prepare('SELECT version,data,reason,at,request FROM function_versions WHERE project=? AND id=? AND version>? ORDER BY version LIMIT ?')
|
|
330
|
+
.all(project.id, functionId, integer(after, 0, Number.MAX_SAFE_INTEGER), integer(limit, 1, 1000) + 1);
|
|
331
|
+
return { project: project.id, function: functionId, items: rows.slice(0, limit).map(row => ({ version: Number(row.version), data: JSON.parse(String(row.data)),
|
|
332
|
+
reason: String(row.reason), at: Number(row.at), request: row.request === null ? null : String(row.request) })),
|
|
333
|
+
nextAfterVersion: rows.length > limit ? Number(rows[limit - 1].version) : null, historyScope: 'Retained M0 versions; earlier package history is available only where legacy events captured it.' };
|
|
334
|
+
});
|
|
335
|
+
}
|
|
336
|
+
/** Explicitly withdraw a current approval without inventing a definition/source change. */
|
|
337
|
+
reopenReview(projectId, functionId, sourceSha256, expectedVersion, reason, epoch) {
|
|
338
|
+
const project = this.project(projectId);
|
|
339
|
+
this.checkEpoch(project, epoch);
|
|
340
|
+
const fn = this.function(project.id, functionId);
|
|
341
|
+
if (fn.version !== integer(expectedVersion, 1, Number.MAX_SAFE_INTEGER))
|
|
342
|
+
fail('staleFunction', 'Package changed; inspect it before reopening review.');
|
|
343
|
+
if (!fn.source || fn.source.sha256 !== sha(sourceSha256) || !fn.contract)
|
|
344
|
+
fail('binding', 'Reopening review must name the current source hash and retained package.');
|
|
345
|
+
if (fn.invalidated || reviewState(fn) !== 'approved' || !['reviewed', 'partial'].includes(fn.stage))
|
|
346
|
+
fail('conflict', 'Only a current approved, non-invalidated package can be reopened.');
|
|
347
|
+
if (this.db.prepare('SELECT 1 FROM locks WHERE project=? AND resource=?').get(project.id, fn.id))
|
|
348
|
+
fail('reservedFunction', 'Complete or cancel the outstanding assignment before reopening review.');
|
|
349
|
+
const why = string(reason, 2000);
|
|
350
|
+
fn.reviewRequired = { reason: why, at: this.clock(), sourceSha256: fn.source.sha256, contractSha256: fn.contract.sha256, request: this.currentRequest };
|
|
351
|
+
fn.stage = 'partial';
|
|
352
|
+
fn.version++;
|
|
353
|
+
this.putFunction(project.id, fn, 'review.reopened');
|
|
354
|
+
this.event(project, 'review.reopened', { function: fn.id, sourceSha256: fn.source.sha256, contractSha256: fn.contract.sha256,
|
|
355
|
+
previousReview: fn.review, reason: why, version: fn.version });
|
|
356
|
+
return { function: fn.id, sourceSha256: fn.source.sha256, contractSha256: fn.contract.sha256, version: fn.version,
|
|
357
|
+
reviewState: reviewState(fn), revision: project.revision, accepted1to1: false };
|
|
358
|
+
}
|
|
359
|
+
/** One local transaction is replayed only from its durable receipt, never from an external effect. */
|
|
360
|
+
assertCurrentRequestId(requestId) {
|
|
361
|
+
if (this.db.prepare('SELECT 1 FROM archived_requests WHERE caller_id=?').get(identifier(requestId)))
|
|
362
|
+
fail('historicalRequest', 'This ID belongs to restored history; inspect work request and use a new intent.');
|
|
363
|
+
}
|
|
364
|
+
mutate(operation, input, requestId, action) {
|
|
365
|
+
this.assertCurrentRequestId(requestId);
|
|
366
|
+
const reservation = this.workspace.reserveAdministration('work.' + operation, input, identifier(requestId));
|
|
367
|
+
const key = reservation.request.id;
|
|
368
|
+
if (reservation.request.state === 'failed')
|
|
369
|
+
fail('previousFailure', 'Request has a retained failure; use a new intent.', reservation.request.result);
|
|
370
|
+
try {
|
|
371
|
+
const result = this.tx(() => {
|
|
372
|
+
const previous = this.db.prepare('SELECT result FROM receipts WHERE id=?').get(key);
|
|
373
|
+
if (previous)
|
|
374
|
+
return JSON.parse(String(previous.result));
|
|
375
|
+
if (reservation.request.state === 'applied')
|
|
376
|
+
fail('storage', 'Applied work receipt is missing; preserve storage and recover it.');
|
|
377
|
+
this.currentRequest = key;
|
|
378
|
+
let next;
|
|
379
|
+
try {
|
|
380
|
+
next = action();
|
|
381
|
+
}
|
|
382
|
+
finally {
|
|
383
|
+
this.currentRequest = undefined;
|
|
384
|
+
}
|
|
385
|
+
this.db.prepare('INSERT INTO receipts VALUES(?,?)').run(key, stable(next));
|
|
386
|
+
return next;
|
|
387
|
+
}, true);
|
|
388
|
+
this.workspace.administrationState(key, 'applied', result);
|
|
389
|
+
return result;
|
|
390
|
+
}
|
|
391
|
+
catch (error) {
|
|
392
|
+
// If COMMIT succeeded but the Workspace acknowledgment failed, the local receipt is authoritative.
|
|
393
|
+
if (reservation.request.state !== 'applied' && !this.db.prepare('SELECT 1 FROM receipts WHERE id=?').get(key))
|
|
394
|
+
this.workspace.administrationState(key, 'failed', { code: error.code ?? 'work.failed', message: error instanceof Error ? error.message : 'Work transaction failed' });
|
|
395
|
+
throw error;
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
create(projectId, targetId, name) {
|
|
399
|
+
const id = identifier(projectId), target = this.workspace.target(targetId);
|
|
400
|
+
if (this.db.prepare('SELECT 1 FROM projects WHERE id=?').get(id))
|
|
401
|
+
fail('conflict', 'Project ID already exists.');
|
|
402
|
+
const project = { id, target: target.id, binarySha256: target.binarySha256, name: string(name), revision: 1, planningRevision: 1, epoch: this.incarnation,
|
|
403
|
+
phase: 'reverse-engineering', inventory: { complete: false, reportedTotal: null, sources: [] }, createdAt: this.clock() };
|
|
404
|
+
this.db.prepare('INSERT INTO projects VALUES(?,?)').run(id, stable(project));
|
|
405
|
+
this.db.prepare('INSERT INTO events(project,revision,kind,data) VALUES(?,?,?,?)')
|
|
406
|
+
.run(id, 1, 'project.created', stable({ at: this.clock(), request: this.currentRequest, target: target.id }));
|
|
407
|
+
return { project, strict1to1: 'No function is accepted without a replayable exhaustive/formal verifier.' };
|
|
408
|
+
}
|
|
409
|
+
importInventory(projectId, input, artifact, epoch) {
|
|
410
|
+
const project = this.project(projectId), manifest = object(input);
|
|
411
|
+
this.checkEpoch(project, epoch);
|
|
412
|
+
if (manifest.schema !== 1 || manifest.binarySha256 !== project.binarySha256)
|
|
413
|
+
fail('binding', 'Inventory schema/target SHA does not match this project.');
|
|
414
|
+
if (manifest.kind !== 'function-definitions')
|
|
415
|
+
fail('invalid', 'Only function definitions are admitted; unwind regions are not functions.');
|
|
416
|
+
const functions = array(manifest.functions, 5000).map(x => definition(x, project.binarySha256));
|
|
417
|
+
if (!functions.length || new Set(functions.map(f => f.id)).size !== functions.length)
|
|
418
|
+
fail('invalid', 'Inventory needs unique function entries.');
|
|
419
|
+
let added = 0;
|
|
420
|
+
for (const fn of functions) {
|
|
421
|
+
const previous = this.db.prepare('SELECT data FROM functions WHERE project=? AND id=?').get(project.id, fn.id);
|
|
422
|
+
if (previous) {
|
|
423
|
+
const prior = JSON.parse(String(previous.data));
|
|
424
|
+
if (stable(prior.definition) !== stable(fn.definition))
|
|
425
|
+
fail('conflict', 'Imported definition changed; do not overwrite retained reconstruction.');
|
|
426
|
+
}
|
|
427
|
+
else {
|
|
428
|
+
fn.definitionRevision = 1;
|
|
429
|
+
fn.definitionSha256 = digest(fn.definition);
|
|
430
|
+
this.db.prepare('INSERT INTO functions VALUES(?,?,?,?,?)').run(project.id, fn.id, fn.rva, fn.stage, stable(fn));
|
|
431
|
+
added++;
|
|
432
|
+
this.recordVersion(project.id, fn, 'inventory.imported');
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
if (manifest.reportedTotal !== undefined)
|
|
436
|
+
project.inventory.reportedTotal = integer(manifest.reportedTotal, Number(this.db.prepare('SELECT count(*) n FROM functions WHERE project=?').get(project.id).n), 100_000_000);
|
|
437
|
+
project.inventory.sources.push(artifact);
|
|
438
|
+
this.event(project, 'inventory.imported', { artifact, added, source: manifest.source ?? null, completeness: 'not-established' }, added > 0);
|
|
439
|
+
return { project: project.id, revision: project.revision, added, inventoryComplete: false };
|
|
440
|
+
}
|
|
441
|
+
/**
|
|
442
|
+
* "Has unknowns" is not "needs rework". A partial package returns to the reconstruct lane only when
|
|
443
|
+
* it has no source, was invalidated by new evidence/definition, or a reviewer rejected it. Partial
|
|
444
|
+
* packages with current source go to review; an approval records the review but keeps them partial.
|
|
445
|
+
*/
|
|
446
|
+
static needsRework(fn) {
|
|
447
|
+
return fn.stage === 'discovered' || fn.stage === 'mismatch' || fn.stage === 'partial' && (!fn.source || !!fn.invalidated || fn.review?.approved === false);
|
|
448
|
+
}
|
|
449
|
+
static reviewable(fn) {
|
|
450
|
+
if (fn.stage === 'reconstructed' || fn.stage === 'corpus_match')
|
|
451
|
+
return true;
|
|
452
|
+
return fn.stage === 'partial' && !!fn.source && !fn.invalidated && (!!fn.reviewRequired || fn.review?.sourceSha256 !== fn.source.sha256);
|
|
453
|
+
}
|
|
454
|
+
static reworkSql = `(stage IN ('discovered','mismatch') OR stage='partial' AND (json_extract(data,'$.source') IS NULL
|
|
455
|
+
OR json_extract(data,'$.invalidated') IS NOT NULL OR json_extract(data,'$.review.approved')=0))`;
|
|
456
|
+
plan(projectId, expectedRevision, count, kind, selected, afterRva = -1, epoch, excludeAuthor) {
|
|
457
|
+
const project = this.project(projectId);
|
|
458
|
+
this.planning(project, expectedRevision, epoch);
|
|
459
|
+
count = integer(count, 1, 50);
|
|
460
|
+
if (!['reconstruct', 'review'].includes(kind))
|
|
461
|
+
fail('invalid', 'Task kind is reconstruct or review.');
|
|
462
|
+
if (selected && (!selected.length || selected.length > count || new Set(selected).size !== selected.length))
|
|
463
|
+
fail('scope', 'Explicit function selection must contain 1..count unique IDs.');
|
|
464
|
+
// Explicit reconstruct selection may rework any package that is not reviewed/reconstructed;
|
|
465
|
+
// automatic selection serves new functions first, then packages that need rework.
|
|
466
|
+
const eligible = (fn) => kind === 'review' ? WorkStore.reviewable(fn)
|
|
467
|
+
: selected ? ['discovered', 'partial', 'mismatch'].includes(fn.stage) : WorkStore.needsRework(fn);
|
|
468
|
+
const lanes = kind === 'review' ? ["stage IN ('reconstructed','corpus_match','partial')"]
|
|
469
|
+
: ["stage='discovered'", `stage<>'discovered' AND ${WorkStore.reworkSql}`];
|
|
470
|
+
const start = integer(afterRva, -1, 0xffffffff);
|
|
471
|
+
const accepted = [], resources = new Set(), holders = new Set();
|
|
472
|
+
let scanned = 0, skippedHubs = 0, reserved = 0, ownWork = 0, lane = 0, cursor = start;
|
|
473
|
+
const page = () => selected ? selected.map(id => this.function(project.id, id)) :
|
|
474
|
+
this.db.prepare(`SELECT data FROM functions WHERE project=? AND rva>? AND ${lanes[lane]} ORDER BY rva LIMIT 5000`)
|
|
475
|
+
.all(project.id, cursor).map(row => JSON.parse(String(row.data)));
|
|
476
|
+
// Automatic selection walks bounded pages lane by lane until the slice is full; explicit selection is exact.
|
|
477
|
+
for (let pages = 0; accepted.length < count && pages < (selected ? 1 : 20); pages++) {
|
|
478
|
+
const candidates = page();
|
|
479
|
+
if (!candidates.length) {
|
|
480
|
+
if (selected || ++lane >= lanes.length)
|
|
481
|
+
break;
|
|
482
|
+
cursor = start;
|
|
483
|
+
continue;
|
|
484
|
+
}
|
|
485
|
+
scanned += candidates.length;
|
|
486
|
+
for (const fn of candidates) {
|
|
487
|
+
if (accepted.length >= count)
|
|
488
|
+
break;
|
|
489
|
+
cursor = fn.rva;
|
|
490
|
+
if (!eligible(fn) || kind === 'review' && excludeAuthor !== undefined && fn.author === excludeAuthor) {
|
|
491
|
+
if (eligible(fn))
|
|
492
|
+
ownWork++;
|
|
493
|
+
if (selected)
|
|
494
|
+
fail('conflict', 'Function is not eligible for the requested work kind.');
|
|
495
|
+
continue;
|
|
496
|
+
}
|
|
497
|
+
const derived = this.derivedResources(project.id, fn.id, 10001);
|
|
498
|
+
if (derived.length > 10000) {
|
|
499
|
+
if (selected)
|
|
500
|
+
fail('limit', 'Exclusive resource frontier exceeds 10000; use a smaller investigated scope.');
|
|
501
|
+
skippedHubs++;
|
|
502
|
+
continue;
|
|
503
|
+
}
|
|
504
|
+
const keys = [...new Set([fn.id, ...fn.resources, ...derived])];
|
|
505
|
+
if (new Set([...resources, ...keys]).size > 10000) {
|
|
506
|
+
if (selected || !accepted.length)
|
|
507
|
+
fail('limit', 'Assignment resource set exceeds 10000; reduce the function count.');
|
|
508
|
+
break;
|
|
509
|
+
}
|
|
510
|
+
const holder = keys.map(key => this.db.prepare('SELECT task FROM locks WHERE project=? AND resource=?').get(project.id, key)).find(Boolean);
|
|
511
|
+
if (holder) {
|
|
512
|
+
if (selected)
|
|
513
|
+
fail('conflict', 'Explicitly selected function/resource is already reserved.');
|
|
514
|
+
reserved++;
|
|
515
|
+
holders.add(String(holder.task));
|
|
516
|
+
continue;
|
|
517
|
+
}
|
|
518
|
+
accepted.push(fn);
|
|
519
|
+
keys.forEach(key => resources.add(key));
|
|
520
|
+
}
|
|
521
|
+
if (selected)
|
|
522
|
+
break;
|
|
523
|
+
}
|
|
524
|
+
if (!accepted.length) {
|
|
525
|
+
const waiting = Number(this.db.prepare(`SELECT count(*) n FROM functions WHERE project=? AND ${WorkStore.reworkSql}`).get(project.id).n);
|
|
526
|
+
const waitingIds = this.db.prepare(`SELECT id FROM functions WHERE project=? AND ${WorkStore.reworkSql} ORDER BY rva LIMIT 20`).all(project.id).map(row => String(row.id));
|
|
527
|
+
// Name who holds the reservations: a released lease keeps its scope until claimed again or cancelled.
|
|
528
|
+
const reservedBy = [...holders].slice(0, 20).map(id => {
|
|
529
|
+
const t = this.task(id);
|
|
530
|
+
return { task: t.id, status: t.status, worker: t.worker ?? null, leaseUntil: t.leaseUntil || null, functions: t.functions.length };
|
|
531
|
+
});
|
|
532
|
+
const hint = reserved ? 'Eligible functions are reserved by outstanding tasks (reservedBy); a queued (released) task keeps its scope until '
|
|
533
|
+
+ 'claimed with work claim --task ID or cancelled with work cancel. Retry after they are submitted or cancelled.'
|
|
534
|
+
: ownWork ? 'Remaining review candidates are your own reconstructions; another worker must review them.'
|
|
535
|
+
: kind === 'review' && waiting ? `${waiting} functions need (re)construction before review; take --kind reconstruct work.`
|
|
536
|
+
: 'No eligible function remains for this work kind.';
|
|
537
|
+
fail('noWork', 'No unreserved eligible function was found. ' + hint, { scanned, reserved, ownWork, skippedHubs, awaitingReconstruction: waiting, awaitingReconstructionIds: waitingIds, reservedBy, scanBound: 100000 });
|
|
538
|
+
}
|
|
539
|
+
if (Buffer.byteLength(stable([...resources])) > 512 * 1024)
|
|
540
|
+
fail('limit', 'Assignment resource bytes exceed 512 KiB; reduce the function count.');
|
|
541
|
+
const task = { id: 'w_' + randomUUID(), project: project.id, kind, status: 'queued',
|
|
542
|
+
functions: accepted.map(f => f.id), versions: Object.fromEntries(accepted.map(f => [f.id, f.version])),
|
|
543
|
+
resources: [...resources].sort(), fence: 0, leaseUntil: 0, createdAt: this.clock(), epoch: project.epoch };
|
|
544
|
+
this.db.prepare('INSERT INTO tasks VALUES(?,?,?,?)').run(task.id, project.id, task.status, stable(task));
|
|
545
|
+
for (const resource of resources)
|
|
546
|
+
this.db.prepare('INSERT INTO locks VALUES(?,?,?)').run(project.id, resource, task.id);
|
|
547
|
+
this.event(project, 'task.planned', { task });
|
|
548
|
+
return { task, revision: project.revision };
|
|
549
|
+
}
|
|
550
|
+
claim(taskId, worker, ttl) {
|
|
551
|
+
const task = this.task(taskId), project = this.project(task.project);
|
|
552
|
+
worker = identifier(worker);
|
|
553
|
+
ttl = integer(ttl, 30, 3600);
|
|
554
|
+
if (task.status === 'cancelled')
|
|
555
|
+
this.cancelled(task);
|
|
556
|
+
if (!['queued', 'leased'].includes(task.status) || task.status === 'leased' && task.leaseUntil > this.clock())
|
|
557
|
+
fail('alreadyClaimed', 'Task is submitted or has an active lease.');
|
|
558
|
+
if (task.kind === 'review' && task.functions.some(id => this.function(task.project, id).author === worker))
|
|
559
|
+
fail('selfReview', 'Reviewer must differ from every reconstruction author in this slice.');
|
|
560
|
+
for (const id of task.functions)
|
|
561
|
+
if (this.function(task.project, id).version !== task.versions[id])
|
|
562
|
+
fail('staleFunction', 'Task inputs changed. Cancel this reservation and plan a fresh task.');
|
|
563
|
+
task.status = 'leased';
|
|
564
|
+
task.worker = worker;
|
|
565
|
+
task.fence = integer(task.fence + 1, 1, Number.MAX_SAFE_INTEGER);
|
|
566
|
+
task.leaseUntil = this.clock() + ttl * 1000;
|
|
567
|
+
this.putTask(task);
|
|
568
|
+
this.event(project, 'task.claimed', { task: task.id, worker, fence: task.fence, leaseUntil: task.leaseUntil }, false);
|
|
569
|
+
return { task, revision: project.revision, lease: leaseToken(task) };
|
|
570
|
+
}
|
|
571
|
+
/** Plan and claim one slice atomically at the current state; no observed revision is needed. */
|
|
572
|
+
next(projectId, worker, count, kind, ttl, epoch, selected) {
|
|
573
|
+
const project = this.project(projectId);
|
|
574
|
+
worker = identifier(worker);
|
|
575
|
+
if (selected)
|
|
576
|
+
count = Math.max(count, selected.length);
|
|
577
|
+
// A worker retry may only take packages that still need rework; plan --functions remains the orchestrator override.
|
|
578
|
+
if (selected && kind === 'reconstruct')
|
|
579
|
+
for (const id of selected)
|
|
580
|
+
if (!WorkStore.needsRework(this.function(project.id, id)))
|
|
581
|
+
fail('conflict', 'Function no longer needs rework (already resubmitted or awaiting review); take plain work next.', { function: id });
|
|
582
|
+
const planned = this.plan(project.id, project.revision, count, kind, selected, -1, epoch, worker);
|
|
583
|
+
return this.claim(planned.task.id, worker, ttl);
|
|
584
|
+
}
|
|
585
|
+
heartbeat(taskId, worker, fence, ttl, epoch) {
|
|
586
|
+
const task = this.lease(taskId, worker, fence, epoch), project = this.project(task.project);
|
|
587
|
+
task.leaseUntil = this.clock() + integer(ttl, 30, 3600) * 1000;
|
|
588
|
+
this.putTask(task);
|
|
589
|
+
this.event(project, 'task.renewed', { task: task.id, worker, fence }, false);
|
|
590
|
+
return { task, revision: project.revision };
|
|
591
|
+
}
|
|
592
|
+
release(taskId, worker, fence, epoch) {
|
|
593
|
+
const task = this.lease(taskId, worker, fence, epoch), project = this.project(task.project);
|
|
594
|
+
task.status = 'queued';
|
|
595
|
+
delete task.worker;
|
|
596
|
+
task.leaseUntil = 0;
|
|
597
|
+
this.putTask(task);
|
|
598
|
+
this.event(project, 'task.released', { task: task.id, fence }, false);
|
|
599
|
+
return { task, revision: project.revision };
|
|
600
|
+
}
|
|
601
|
+
cancel(taskId, expectedRevision, reason, epoch) {
|
|
602
|
+
const task = this.task(taskId), project = this.project(task.project);
|
|
603
|
+
this.planning(project, expectedRevision, epoch);
|
|
604
|
+
if (!['queued', 'leased'].includes(task.status))
|
|
605
|
+
fail('conflict', 'Only an outstanding task can be cancelled.');
|
|
606
|
+
task.status = 'cancelled';
|
|
607
|
+
task.fence = integer(task.fence + 1, 1, Number.MAX_SAFE_INTEGER);
|
|
608
|
+
task.leaseUntil = 0;
|
|
609
|
+
task.result = { reason: string(reason, 2000) };
|
|
610
|
+
this.putTask(task);
|
|
611
|
+
this.db.prepare('DELETE FROM locks WHERE task=?').run(task.id);
|
|
612
|
+
this.event(project, 'task.cancelled', { task: task.id, reason });
|
|
613
|
+
return { task, revision: project.revision };
|
|
614
|
+
}
|
|
615
|
+
submit(taskId, worker, fence, entries, epoch) {
|
|
616
|
+
const task = this.lease(taskId, worker, fence, epoch), project = this.project(task.project);
|
|
617
|
+
if (task.kind !== 'reconstruct')
|
|
618
|
+
fail('invalid', 'Use review for a review assignment.');
|
|
619
|
+
if (entries.length !== task.functions.length || new Set(entries.map(e => e.id)).size !== entries.length
|
|
620
|
+
|| entries.some(e => !task.functions.includes(e.id)))
|
|
621
|
+
fail('scope', 'Submission must cover exactly the assigned slice.');
|
|
622
|
+
for (const entry of entries) {
|
|
623
|
+
const fn = this.function(project.id, entry.id), contract = passport(entry.passport);
|
|
624
|
+
fn.source = entry.source;
|
|
625
|
+
fn.contract = entry.contract;
|
|
626
|
+
fn.passport = contract;
|
|
627
|
+
fn.author = worker;
|
|
628
|
+
fn.packageDefinitionRevision = fn.definitionRevision;
|
|
629
|
+
delete fn.invalidated;
|
|
630
|
+
fn.stage = contract.unknowns.length ? 'partial' : 'reconstructed';
|
|
631
|
+
fn.version++;
|
|
632
|
+
delete fn.review;
|
|
633
|
+
delete fn.reviewRequired;
|
|
634
|
+
delete fn.comparison;
|
|
635
|
+
this.putFunction(project.id, fn);
|
|
636
|
+
}
|
|
637
|
+
task.status = 'submitted';
|
|
638
|
+
task.leaseUntil = 0;
|
|
639
|
+
task.result = { functions: entries.map(e => e.id), accepted1to1: false };
|
|
640
|
+
this.putTask(task);
|
|
641
|
+
this.db.prepare('DELETE FROM locks WHERE task=?').run(task.id);
|
|
642
|
+
this.event(project, 'reconstruction.submitted', { task: task.id, worker, functions: entries.map(e => e.id) });
|
|
643
|
+
return { task, revision: project.revision, accepted1to1: false };
|
|
644
|
+
}
|
|
645
|
+
review(taskId, worker, fence, decisions, epoch) {
|
|
646
|
+
const task = this.lease(taskId, worker, fence, epoch), project = this.project(task.project);
|
|
647
|
+
if (task.kind !== 'review')
|
|
648
|
+
fail('invalid', 'This is not a review assignment.');
|
|
649
|
+
if (decisions.length !== task.functions.length || new Set(decisions.map(e => e.id)).size !== decisions.length
|
|
650
|
+
|| decisions.some(e => !task.functions.includes(e.id)))
|
|
651
|
+
fail('scope', 'Review must cover exactly the assigned slice.');
|
|
652
|
+
for (const decision of decisions) {
|
|
653
|
+
if (typeof decision.approved !== 'boolean')
|
|
654
|
+
fail('invalid', 'Review approved must be a JSON boolean.');
|
|
655
|
+
const fn = this.function(project.id, decision.id);
|
|
656
|
+
if (fn.invalidated)
|
|
657
|
+
fail('staleFunction', 'Reconstruct against the current definition/dependencies before review.');
|
|
658
|
+
if (fn.author === worker)
|
|
659
|
+
fail('selfReview', 'A reconstruction author cannot approve their own work.');
|
|
660
|
+
if (fn.source?.sha256 !== decision.sourceSha256)
|
|
661
|
+
fail('staleFunction', 'Review does not name the current source hash.');
|
|
662
|
+
fn.review = { worker, sourceSha256: decision.sourceSha256, contractSha256: fn.contract?.sha256, note: decision.note, approved: decision.approved };
|
|
663
|
+
delete fn.reviewRequired;
|
|
664
|
+
// Approval never erases unknowns: a package with open unknowns stays partial with its review recorded.
|
|
665
|
+
const open = (fn.passport?.unknowns ?? []).length > 0;
|
|
666
|
+
fn.stage = decision.approved && !open ? 'reviewed' : 'partial';
|
|
667
|
+
fn.version++;
|
|
668
|
+
this.putFunction(project.id, fn);
|
|
669
|
+
}
|
|
670
|
+
task.status = 'submitted';
|
|
671
|
+
task.leaseUntil = 0;
|
|
672
|
+
task.result = { decisions, accepted1to1: false };
|
|
673
|
+
this.putTask(task);
|
|
674
|
+
this.db.prepare('DELETE FROM locks WHERE task=?').run(task.id);
|
|
675
|
+
this.event(project, 'review.submitted', { task: task.id, worker });
|
|
676
|
+
return { task, revision: project.revision, accepted1to1: false };
|
|
677
|
+
}
|
|
678
|
+
compare(projectId, functionId, sourceSha, original, reconstruction, artifacts, layout, epoch) {
|
|
679
|
+
const project = this.project(projectId), fn = this.function(project.id, functionId);
|
|
680
|
+
this.checkEpoch(project, epoch);
|
|
681
|
+
if (fn.invalidated)
|
|
682
|
+
fail('staleFunction', 'Reconstruct against the current definition/dependencies before comparison.');
|
|
683
|
+
if (this.db.prepare('SELECT 1 FROM locks WHERE project=? AND resource=?').get(project.id, fn.id))
|
|
684
|
+
fail('reservedFunction', 'Comparison cannot change a reserved package. Complete or cancel its outstanding assignment first.');
|
|
685
|
+
if (!fn.source || fn.source.sha256 !== sourceSha)
|
|
686
|
+
fail('binding', 'Comparison must name the current reconstructed source.');
|
|
687
|
+
const a = object(original), b = object(reconstruction);
|
|
688
|
+
for (const value of [a, b])
|
|
689
|
+
if (value.schema !== 1 || value.binarySha256 !== project.binarySha256 || value.function !== fn.id)
|
|
690
|
+
fail('binding', 'Observation corpus belongs to another target or function.');
|
|
691
|
+
if (b.sourceSha256 !== sourceSha)
|
|
692
|
+
fail('binding', 'Reconstruction observations name another source.');
|
|
693
|
+
const cases = (value) => array(value, 10000).map(row => {
|
|
694
|
+
const c = object(row), outcome = object(c.outcome);
|
|
695
|
+
string(c.input, 65536);
|
|
696
|
+
if (outcome.encoding !== 'hex-bytes-v1' || typeof outcome.bytes !== 'string' || outcome.bytes.length > 131072 || !/^(?:[0-9a-f]{2})*$/.test(outcome.bytes))
|
|
697
|
+
fail('invalid', 'Outcomes need lossless lowercase hex-bytes-v1 bytes, not JSON numeric approximations.');
|
|
698
|
+
if (sha(outcome.layoutSha256) !== layout.sha256)
|
|
699
|
+
fail('binding', 'Outcome layout hash must match the retained layout artifact.');
|
|
700
|
+
return c;
|
|
701
|
+
});
|
|
702
|
+
const left = cases(a.cases), right = cases(b.cases);
|
|
703
|
+
if (!left.length || left.length !== right.length)
|
|
704
|
+
fail('invalid', 'Both corpora need the same nonempty input set.');
|
|
705
|
+
const indexed = new Map(right.map(c => [stable(c.input), c]));
|
|
706
|
+
if (indexed.size !== right.length || new Set(left.map(c => stable(c.input))).size !== left.length)
|
|
707
|
+
fail('invalid', 'Duplicate corpus inputs are not coverage.');
|
|
708
|
+
let mismatches = 0;
|
|
709
|
+
const firstMismatchInputs = [];
|
|
710
|
+
for (const c of left) {
|
|
711
|
+
const other = indexed.get(stable(c.input));
|
|
712
|
+
if (!other)
|
|
713
|
+
fail('invalid', 'Corpus input sets differ.');
|
|
714
|
+
if (stable(c.outcome) !== stable(other.outcome)) {
|
|
715
|
+
mismatches++;
|
|
716
|
+
if (firstMismatchInputs.length < 5)
|
|
717
|
+
firstMismatchInputs.push(c.input);
|
|
718
|
+
}
|
|
719
|
+
}
|
|
720
|
+
const result = { cases: left.length, mismatches, firstMismatchInputs, artifacts, layout, sourceSha256: sourceSha,
|
|
721
|
+
level: 'supplied-corpus-comparison', origin: 'Input observations are reported, not native-execution attestation', accepted1to1: false };
|
|
722
|
+
const unknowns = Array.isArray(fn.passport?.unknowns) ? fn.passport.unknowns : [];
|
|
723
|
+
const rejected = fn.review?.approved === false;
|
|
724
|
+
fn.comparison = result;
|
|
725
|
+
fn.stage = mismatches ? 'mismatch' : unknowns.length || rejected || fn.reviewRequired ? 'partial' : fn.stage === 'reviewed' ? 'reviewed' : 'corpus_match';
|
|
726
|
+
fn.version++;
|
|
727
|
+
if (mismatches && !rejected)
|
|
728
|
+
delete fn.review;
|
|
729
|
+
this.putFunction(project.id, fn);
|
|
730
|
+
this.event(project, 'corpus.compared', { function: fn.id, ...result });
|
|
731
|
+
return { project: project.id, revision: project.revision, ...result };
|
|
732
|
+
}
|
|
733
|
+
certify() { fail('proofVerifierUnavailable', 'Strict 1:1 acceptance requires a supported replayable exhaustive/formal verifier. Corpus matches, reviews and uploaded passed flags cannot authorize it.'); }
|
|
734
|
+
importGraph(projectId, input, artifact, epoch) {
|
|
735
|
+
const project = this.project(projectId), manifest = object(input);
|
|
736
|
+
this.checkEpoch(project, epoch);
|
|
737
|
+
let changed = 0;
|
|
738
|
+
if (manifest.schema !== 1 || manifest.binarySha256 !== project.binarySha256 || manifest.kind !== 'dependency-graph')
|
|
739
|
+
fail('binding', 'Graph schema, kind and full target hash are required.');
|
|
740
|
+
const nodes = array(manifest.nodes, 5000).map(object), edges = array(manifest.edges, 10000).map(object);
|
|
741
|
+
const kinds = ['global', 'type', 'vtable', 'dispatch-site', 'packet', 'asset-package', 'subsystem', 'source-declaration'];
|
|
742
|
+
const affected = new Set();
|
|
743
|
+
const expanded = new Set();
|
|
744
|
+
const put = (table, row) => {
|
|
745
|
+
const id = string(row.id, 256), data = stable(row), prior = this.db.prepare(`SELECT data FROM ${table} WHERE project=? AND id=?`).get(project.id, id);
|
|
746
|
+
if (prior && prior.data !== data)
|
|
747
|
+
fail('conflict', 'Graph evidence is additive. Correct with a new record ID.');
|
|
748
|
+
if (!prior) {
|
|
749
|
+
this.db.prepare(`INSERT INTO ${table} VALUES(?,?,?)`).run(project.id, id, data);
|
|
750
|
+
changed++;
|
|
751
|
+
}
|
|
752
|
+
return !prior;
|
|
753
|
+
};
|
|
754
|
+
for (const node of nodes) {
|
|
755
|
+
const kind = string(node.kind);
|
|
756
|
+
string(node.label);
|
|
757
|
+
string(node.evidence, 4000);
|
|
758
|
+
if (!kinds.includes(kind) || !string(node.id, 256).startsWith(`${kind}:${project.binarySha256}:`))
|
|
759
|
+
fail('binding', 'Graph node ID must include its kind and full target hash. Function definitions use inventory import.');
|
|
760
|
+
if (!['observed', 'reported', 'hypothesis', 'rejected'].includes(String(node.confidence)))
|
|
761
|
+
fail('invalid', 'Node confidence is explicit.');
|
|
762
|
+
put('graph_nodes', node);
|
|
763
|
+
}
|
|
764
|
+
const endpoint = (value) => {
|
|
765
|
+
const id = string(value, 256);
|
|
766
|
+
if (!this.db.prepare('SELECT 1 FROM functions WHERE project=? AND id=?').get(project.id, id)
|
|
767
|
+
&& !this.db.prepare('SELECT 1 FROM graph_nodes WHERE project=? AND id=?').get(project.id, id))
|
|
768
|
+
fail('notFound', 'Graph endpoint has no explicit inventory node.');
|
|
769
|
+
return id;
|
|
770
|
+
};
|
|
771
|
+
for (const edge of edges) {
|
|
772
|
+
endpoint(edge.source);
|
|
773
|
+
endpoint(edge.target);
|
|
774
|
+
string(edge.kind, 128);
|
|
775
|
+
string(edge.evidence, 4000);
|
|
776
|
+
if (!['observed', 'reported', 'hypothesis', 'rejected'].includes(String(edge.confidence)))
|
|
777
|
+
fail('invalid', 'Edge confidence is explicit.');
|
|
778
|
+
if (put('graph_edges', edge) && edge.confidence !== 'rejected')
|
|
779
|
+
for (const end of [edge.source, edge.target])
|
|
780
|
+
if (this.db.prepare('SELECT 1 FROM functions WHERE project=? AND id=?').get(project.id, String(end)))
|
|
781
|
+
affected.add(String(end));
|
|
782
|
+
if (this.retainGraphResources(project.id, edge)) {
|
|
783
|
+
const owner = this.db.prepare('SELECT task FROM locks WHERE project=? AND resource=?').get(project.id, String(edge.source));
|
|
784
|
+
if (owner && !this.db.prepare('SELECT 1 FROM locks WHERE project=? AND task=? AND resource=?').get(project.id, String(owner.task), String(edge.target)))
|
|
785
|
+
expanded.add(String(edge.source));
|
|
786
|
+
}
|
|
787
|
+
}
|
|
788
|
+
// Only endpoints of new non-rejected edges are affected: their retained packages become invalid and
|
|
789
|
+
// assignments that froze those packages are cancelled. Nodes and rejected edges invalidate nothing.
|
|
790
|
+
const invalidated = affected.size ? this.invalidatePackages(project, 'Dependency graph changed at this function', affected) : new Set();
|
|
791
|
+
const replan = new Set([...invalidated, ...expanded]);
|
|
792
|
+
const cancelled = replan.size ? this.invalidateTasks(project, 'Dependency evidence changed the package or its exclusive reservations', replan) : [];
|
|
793
|
+
// Counts are exact; ID lists are bounded to the first 100 and say so.
|
|
794
|
+
const ids = (values) => { const all = [...values].sort(); return { ids: all.slice(0, 100), truncated: all.length > 100 }; };
|
|
795
|
+
const impact = { affectedFunctionIds: ids(affected), invalidatedPackageIds: ids(invalidated), cancelledTaskIds: ids(cancelled) };
|
|
796
|
+
project.inventory.sources.push(artifact);
|
|
797
|
+
this.event(project, 'graph.imported', { artifact, nodes: nodes.length, edges: edges.length, changed,
|
|
798
|
+
affectedFunctions: affected.size, invalidatedPackages: invalidated.size, cancelledTasks: cancelled.length, ...impact, complete: false }, changed > 0);
|
|
799
|
+
return { project: project.id, revision: project.revision, nodes: nodes.length, edges: edges.length, changed, affectedFunctions: affected.size,
|
|
800
|
+
invalidatedPackages: invalidated.size, cancelledTasks: cancelled.length, ...impact, graphComplete: false,
|
|
801
|
+
impact: 'Endpoint-scoped invalidation; only writer edges reserve resources. This is not proved dependency closure.' };
|
|
802
|
+
}
|
|
803
|
+
timing(projectId, selected) {
|
|
804
|
+
return this.tx(() => ({ project: this.context(projectId), ...timingReport(this.db, projectId, selected) }));
|
|
805
|
+
}
|
|
806
|
+
context(projectId) {
|
|
807
|
+
const { id, target, binarySha256, epoch, revision } = this.project(projectId);
|
|
808
|
+
return { id, target, binarySha256, epoch, revision };
|
|
809
|
+
}
|
|
810
|
+
projects() { return this.tx(() => this.db.prepare('SELECT data FROM projects ORDER BY id').all().map(r => JSON.parse(String(r.data)))); }
|
|
811
|
+
request(callerId) {
|
|
812
|
+
const archived = this.db.prepare('SELECT data FROM archived_requests WHERE caller_id=?').get(identifier(callerId));
|
|
813
|
+
if (archived) {
|
|
814
|
+
const histories = archivedOutcomes(JSON.parse(String(archived.data))), current = this.workspace.administrationByCaller(callerId);
|
|
815
|
+
if (current?.operation.startsWith('work.') && !histories.some(row => object(row.request).id === current.id)) {
|
|
816
|
+
const local = this.db.prepare('SELECT result FROM receipts WHERE id=?').get(current.id);
|
|
817
|
+
histories.push({ request: current, receipt: local ? JSON.parse(String(local.result)) : null, origin: { incarnation: this.incarnation, scope: 'current-work-administration' } });
|
|
818
|
+
}
|
|
819
|
+
return histories.length === 1 ? { ...histories[0], historical: true, leaseAuthorization: 'not-current' } :
|
|
820
|
+
{ historical: true, leaseAuthorization: 'not-current', ambiguous: true, histories };
|
|
821
|
+
}
|
|
822
|
+
const request = this.workspace.administrationByCaller(identifier(callerId));
|
|
823
|
+
if (!request || !request.operation.startsWith('work.'))
|
|
824
|
+
fail('notFound', 'No work intent with that request ID in this profile.');
|
|
825
|
+
const receipt = this.db.prepare('SELECT result FROM receipts WHERE id=?').get(request.id);
|
|
826
|
+
return { request, receipt: receipt ? JSON.parse(String(receipt.result)) : null };
|
|
827
|
+
}
|
|
828
|
+
events(projectId, after, limit) {
|
|
829
|
+
return this.tx(() => {
|
|
830
|
+
const project = this.project(projectId), rows = this.db.prepare('SELECT seq,revision,kind,data FROM events WHERE project=? AND seq>? ORDER BY seq LIMIT ?')
|
|
831
|
+
.all(project.id, integer(after, 0, Number.MAX_SAFE_INTEGER), integer(limit, 1, 1000) + 1);
|
|
832
|
+
return { project: project.id, revision: project.revision, items: rows.slice(0, limit).map(r => ({ ...r, data: JSON.parse(String(r.data)) })),
|
|
833
|
+
nextAfter: rows.length > limit ? Number(rows[limit - 1].seq) : null };
|
|
834
|
+
});
|
|
835
|
+
}
|
|
836
|
+
/** Synchronous streamed projection holds one consistent read snapshot without buffering the inventory. */
|
|
837
|
+
export(projectId, path) {
|
|
838
|
+
const fd = openSync(path, 'wx', 0o600), hash = createHash('sha256');
|
|
839
|
+
let records = 0;
|
|
840
|
+
const line = (value) => {
|
|
841
|
+
const bytes = Buffer.from(stable(value) + '\n');
|
|
842
|
+
let offset = 0;
|
|
843
|
+
while (offset < bytes.length)
|
|
844
|
+
offset += writeSync(fd, bytes, offset);
|
|
845
|
+
hash.update(bytes);
|
|
846
|
+
records++;
|
|
847
|
+
};
|
|
848
|
+
try {
|
|
849
|
+
return this.tx(() => {
|
|
850
|
+
const project = this.project(projectId), requests = new Set();
|
|
851
|
+
line({ record: 'project', schema: 1, project, target: this.workspace.target(project.target), generatedAt: this.clock(), accepted1to1: 0 });
|
|
852
|
+
for (const [table, record] of [['functions', 'function'], ['graph_nodes', 'node'], ['graph_edges', 'edge'], ['tasks', 'task']])
|
|
853
|
+
for (const row of this.db.prepare(`SELECT data FROM ${table} WHERE project=? ORDER BY id`).iterate(project.id))
|
|
854
|
+
line({ record, value: JSON.parse(String(row.data)) });
|
|
855
|
+
for (const row of this.db.prepare('SELECT seq,revision,kind,data FROM events WHERE project=? ORDER BY seq').iterate(project.id)) {
|
|
856
|
+
const data = JSON.parse(String(row.data));
|
|
857
|
+
if (data.request)
|
|
858
|
+
requests.add(data.request);
|
|
859
|
+
line({ record: 'event', ...row, data });
|
|
860
|
+
}
|
|
861
|
+
// Restores key archived rows by caller label. Events reference internal
|
|
862
|
+
// request IDs, including individual outcomes within a retained history set.
|
|
863
|
+
const histories = new Map();
|
|
864
|
+
for (const row of this.db.prepare('SELECT data FROM archived_requests').iterate()) {
|
|
865
|
+
const record = JSON.parse(String(row.data));
|
|
866
|
+
for (const outcome of archivedOutcomes(record)) {
|
|
867
|
+
const id = String(object(outcome.request).id);
|
|
868
|
+
if (requests.has(id) && (record.kind !== 'request-history-set' || !histories.has(id)))
|
|
869
|
+
histories.set(id, outcome);
|
|
870
|
+
}
|
|
871
|
+
}
|
|
872
|
+
const receiptById = this.db.prepare('SELECT result FROM receipts WHERE id=?');
|
|
873
|
+
for (const id of requests) {
|
|
874
|
+
const history = histories.get(id);
|
|
875
|
+
const request = history?.request ?? this.workspace.administration(id), receipt = receiptById.get(id);
|
|
876
|
+
// The work receipt is authoritative during the small post-COMMIT/pre-ACK window.
|
|
877
|
+
line({ record: 'request', value: request, workReceipt: history?.receipt ?? (receipt ? JSON.parse(String(receipt.result)) : null),
|
|
878
|
+
...(history ? { historical: true, leaseAuthorization: 'not-current' } : {}) });
|
|
879
|
+
}
|
|
880
|
+
line({ record: 'end', revision: project.revision, recordsBeforeEnd: records, complete: true, scope: 'This project workflow snapshot only; discovery/graph/1:1 remain incomplete. Artifacts are references, not payload copies.' });
|
|
881
|
+
fsyncSync(fd);
|
|
882
|
+
return { path, project: project.id, revision: project.revision, records, sha256: hash.digest('hex'), artifacts: 'Preserve the profile artifact directory separately.' };
|
|
883
|
+
});
|
|
884
|
+
}
|
|
885
|
+
catch (error) {
|
|
886
|
+
closeSync(fd);
|
|
887
|
+
unlinkSync(path);
|
|
888
|
+
throw error;
|
|
889
|
+
}
|
|
890
|
+
finally {
|
|
891
|
+
try {
|
|
892
|
+
closeSync(fd);
|
|
893
|
+
}
|
|
894
|
+
catch { }
|
|
895
|
+
}
|
|
896
|
+
}
|
|
897
|
+
graph(projectId, after, limit, kind) {
|
|
898
|
+
return this.tx(() => {
|
|
899
|
+
const project = this.project(projectId), table = kind === 'nodes' ? 'graph_nodes' : 'graph_edges';
|
|
900
|
+
const rows = this.db.prepare(`SELECT id,data FROM ${table} WHERE project=? AND id>? ORDER BY id LIMIT ?`)
|
|
901
|
+
.all(project.id, after, integer(limit, 1, 1000) + 1);
|
|
902
|
+
return { project: project.id, revision: project.revision, items: rows.slice(0, limit).map(r => JSON.parse(String(r.data))),
|
|
903
|
+
nextAfter: rows.length > limit ? String(rows[limit - 1].id) : null, complete: false };
|
|
904
|
+
});
|
|
905
|
+
}
|
|
906
|
+
handoff(taskId) {
|
|
907
|
+
return this.tx(() => {
|
|
908
|
+
const task = this.task(taskId), project = this.project(task.project);
|
|
909
|
+
return { project, task, functions: task.functions.map(id => this.function(project.id, id)),
|
|
910
|
+
instructions: ['Reconstruct only this assigned slice. Do not implement game/subsystems.',
|
|
911
|
+
'Preserve ABI, exact effects, errors, ordering, unknowns and source evidence.',
|
|
912
|
+
'Renew the lease. Submit with worker and current fence. A stale lease cannot write.',
|
|
913
|
+
'Reconstruction, corpus equality and review are not universal 1:1 proof.'] };
|
|
914
|
+
});
|
|
915
|
+
}
|
|
916
|
+
snapshot(projectId, limit = 200) {
|
|
917
|
+
return this.tx(() => {
|
|
918
|
+
const project = this.project(projectId), counts = { discovered: 0, partial: 0, reconstructed: 0, corpus_match: 0, reviewed: 0, mismatch: 0 };
|
|
919
|
+
for (const row of this.db.prepare('SELECT stage,count(*) n FROM functions WHERE project=? GROUP BY stage').all(project.id))
|
|
920
|
+
counts[row.stage] = Number(row.n);
|
|
921
|
+
return { project, counts, trackedFunctions: Object.values(counts).reduce((a, b) => a + b, 0), accepted1to1: 0,
|
|
922
|
+
functions: this.db.prepare('SELECT data FROM functions WHERE project=? ORDER BY rva LIMIT ?').all(project.id, integer(limit, 1, 1000)).map(row => { const fn = JSON.parse(String(row.data)); return { ...fn, reviewState: reviewState(fn) }; }),
|
|
923
|
+
tasks: this.db.prepare('SELECT data FROM tasks WHERE project=? ORDER BY rowid DESC LIMIT 100').all(project.id).map(row => JSON.parse(String(row.data))),
|
|
924
|
+
events: this.db.prepare('SELECT seq,revision,kind,data FROM events WHERE project=? ORDER BY seq DESC LIMIT 50').all(project.id).map(row => ({ ...row, data: JSON.parse(String(row.data)) })),
|
|
925
|
+
graph: { nodes: this.db.prepare('SELECT data FROM graph_nodes WHERE project=? ORDER BY id LIMIT 200').all(project.id).map(r => JSON.parse(String(r.data))),
|
|
926
|
+
edges: this.db.prepare('SELECT data FROM graph_edges WHERE project=? ORDER BY id LIMIT 200').all(project.id).map(r => JSON.parse(String(r.data))),
|
|
927
|
+
nodeCount: Number(this.db.prepare('SELECT count(*) n FROM graph_nodes WHERE project=?').get(project.id).n),
|
|
928
|
+
edgeCount: Number(this.db.prepare('SELECT count(*) n FROM graph_edges WHERE project=?').get(project.id).n), complete: false },
|
|
929
|
+
generatedAt: this.clock(), functionLimit: limit, limits: ['Inventory completeness is not established.', 'Universal 1:1 certification is unavailable; no function is accepted.', 'Displayed function/task/event slices are bounded.'] };
|
|
930
|
+
});
|
|
931
|
+
}
|
|
932
|
+
/** Full work metadata only: native contexts/configuration are deliberately outside this snapshot. */
|
|
933
|
+
writeBackupState(path, observe) {
|
|
934
|
+
const fd = openSync(path, 'wx', 0o600), hash = createHash('sha256');
|
|
935
|
+
let records = 0, bytes = 0;
|
|
936
|
+
const line = (value) => {
|
|
937
|
+
const data = Buffer.from(stable(value) + '\n');
|
|
938
|
+
if (data.length > 16 * 1024 * 1024 || bytes + data.length > 2 * 1024 * 1024 * 1024)
|
|
939
|
+
fail('limit', 'Work backup metadata exceeds the M0 record/total budget.');
|
|
940
|
+
let offset = 0;
|
|
941
|
+
while (offset < data.length)
|
|
942
|
+
offset += writeSync(fd, data, offset);
|
|
943
|
+
hash.update(data);
|
|
944
|
+
bytes += data.length;
|
|
945
|
+
records++;
|
|
946
|
+
observe(value);
|
|
947
|
+
};
|
|
948
|
+
try {
|
|
949
|
+
const result = this.workspace.withAdministrationSnapshot('work.', requests => this.tx(() => {
|
|
950
|
+
line({ record: 'header', format: 'insight-work-backup-state', schema: 1, workSchema: 2, incarnation: this.incarnation, profile: this.workspace.profile, createdAt: this.clock() });
|
|
951
|
+
const targets = new Set();
|
|
952
|
+
for (const row of this.db.prepare('SELECT data FROM projects ORDER BY id').iterate()) {
|
|
953
|
+
const project = JSON.parse(String(row.data));
|
|
954
|
+
if (!targets.has(project.target)) {
|
|
955
|
+
line({ record: 'target', value: this.workspace.target(project.target) });
|
|
956
|
+
targets.add(project.target);
|
|
957
|
+
}
|
|
958
|
+
}
|
|
959
|
+
const counts = {};
|
|
960
|
+
for (const [table] of Object.entries(workTableColumns)) {
|
|
961
|
+
let count = 0;
|
|
962
|
+
for (const row of this.db.prepare(`SELECT * FROM ${table} ORDER BY rowid`).iterate()) {
|
|
963
|
+
line({ record: 'row', table, row });
|
|
964
|
+
count++;
|
|
965
|
+
}
|
|
966
|
+
counts[table] = count;
|
|
967
|
+
}
|
|
968
|
+
let requestCount = 0;
|
|
969
|
+
for (const request of requests) {
|
|
970
|
+
const receipt = this.db.prepare('SELECT result FROM receipts WHERE id=?').get(request.id);
|
|
971
|
+
if (request.state === 'applied' && !receipt)
|
|
972
|
+
fail('storage', 'Applied work administration lacks a local receipt.');
|
|
973
|
+
line({ record: 'administration', request, receipt: receipt ? JSON.parse(String(receipt.result)) : null });
|
|
974
|
+
requestCount++;
|
|
975
|
+
}
|
|
976
|
+
line({ record: 'end', recordsBeforeEnd: records, counts, requestCount, complete: true, accepted1to1: 0 });
|
|
977
|
+
fsyncSync(fd);
|
|
978
|
+
return { counts, requestCount, incarnation: this.incarnation };
|
|
979
|
+
}, true));
|
|
980
|
+
return { ...result, sha256: hash.digest('hex'), size: bytes, records };
|
|
981
|
+
}
|
|
982
|
+
finally {
|
|
983
|
+
closeSync(fd);
|
|
984
|
+
}
|
|
985
|
+
}
|
|
986
|
+
restoreState(stage, targets, origin) {
|
|
987
|
+
for (const table of Object.keys(workTableColumns))
|
|
988
|
+
if (Number(this.db.prepare(`SELECT count(*) n FROM ${table}`).get().n))
|
|
989
|
+
fail('conflict', 'Restore requires empty work storage; never replace current work.');
|
|
990
|
+
const current = this.currentRequest ? this.workspace.administration(this.currentRequest) : undefined;
|
|
991
|
+
if (current?.callerId && stage.prepare('SELECT 1 FROM archived_requests WHERE caller_id=?').get(current.callerId))
|
|
992
|
+
fail('conflict', 'Restore request ID collides with historical history; use a fresh ID.');
|
|
993
|
+
for (const [table, columns] of Object.entries(workTableColumns)) {
|
|
994
|
+
if (table === 'locks' || table === 'receipts')
|
|
995
|
+
continue;
|
|
996
|
+
const insert = this.db.prepare(`INSERT INTO ${table}(${columns.join(',')}) VALUES(${columns.map(() => '?').join(',')})`);
|
|
997
|
+
for (const source of stage.prepare(`SELECT * FROM ${table} ORDER BY rowid`).iterate()) {
|
|
998
|
+
const row = { ...source };
|
|
999
|
+
if (table === 'projects') {
|
|
1000
|
+
const project = JSON.parse(String(row.data));
|
|
1001
|
+
const target = targets.get(project.target);
|
|
1002
|
+
if (!target)
|
|
1003
|
+
fail('binding', 'Backup target mapping is incomplete.');
|
|
1004
|
+
project.target = target;
|
|
1005
|
+
project.epoch = this.incarnation;
|
|
1006
|
+
delete project.epochRequired;
|
|
1007
|
+
row.data = stable(project);
|
|
1008
|
+
}
|
|
1009
|
+
insert.run(...columns.map(column => row[column] ?? null));
|
|
1010
|
+
}
|
|
1011
|
+
}
|
|
1012
|
+
let cancelledTasks = 0;
|
|
1013
|
+
for (const row of this.db.prepare('SELECT data FROM tasks ORDER BY id').iterate()) {
|
|
1014
|
+
const task = JSON.parse(String(row.data)), previous = { ...task };
|
|
1015
|
+
task.epoch = this.incarnation;
|
|
1016
|
+
if (task.status === 'queued' || task.status === 'leased') {
|
|
1017
|
+
task.status = 'cancelled';
|
|
1018
|
+
task.fence = integer(task.fence + 1, 1, Number.MAX_SAFE_INTEGER);
|
|
1019
|
+
task.leaseUntil = 0;
|
|
1020
|
+
delete task.worker;
|
|
1021
|
+
task.result = { reason: 'Restore requires a fresh assignment in the new epoch', replanRequired: true };
|
|
1022
|
+
cancelledTasks++;
|
|
1023
|
+
this.putTask(task);
|
|
1024
|
+
this.event(this.project(task.project), 'task.restore-cancelled', { previous, task: task.id, origin });
|
|
1025
|
+
}
|
|
1026
|
+
else
|
|
1027
|
+
this.putTask(task);
|
|
1028
|
+
}
|
|
1029
|
+
const projects = [];
|
|
1030
|
+
let restoredProjects = 0;
|
|
1031
|
+
for (const row of this.db.prepare('SELECT id FROM projects ORDER BY id').iterate()) {
|
|
1032
|
+
const project = this.project(String(row.id));
|
|
1033
|
+
this.event(project, 'project.restored', { origin, epoch: this.incarnation });
|
|
1034
|
+
restoredProjects++;
|
|
1035
|
+
if (projects.length < 100)
|
|
1036
|
+
projects.push({ id: project.id, target: project.target, revision: project.revision, planningRevision: project.planningRevision, epoch: project.epoch });
|
|
1037
|
+
}
|
|
1038
|
+
return { projects, restoredProjects, projectsComplete: restoredProjects <= 100, projectSummaryLimit: 100,
|
|
1039
|
+
cancelledTasks, origin, epoch: this.incarnation, accepted1to1: 0, scope: 'Work metadata and retained artifacts; no native contexts or configuration restored.' };
|
|
1040
|
+
}
|
|
1041
|
+
functions(projectId, after, limit) {
|
|
1042
|
+
return this.tx(() => {
|
|
1043
|
+
const project = this.project(projectId), rows = this.db.prepare('SELECT data FROM functions WHERE project=? AND rva>? ORDER BY rva LIMIT ?')
|
|
1044
|
+
.all(project.id, integer(after, -1, 0xffffffff), integer(limit, 1, 1000) + 1).map(row => JSON.parse(String(row.data)));
|
|
1045
|
+
const more = rows.length > limit, items = rows.slice(0, limit).map(fn => ({ ...fn, reviewState: reviewState(fn) }));
|
|
1046
|
+
return { project: project.id, revision: project.revision, items,
|
|
1047
|
+
nextAfterRva: more ? items.at(-1)?.rva : null, consistency: 'This page only; revision is explicit. This is not a frozen whole-project export.' };
|
|
1048
|
+
});
|
|
1049
|
+
}
|
|
1050
|
+
}
|