@eyeauras/insight-cli 0.7.0 → 0.8.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.cli-package-build.json +1 -1
- package/SKILL.md +1 -1
- package/dist/src/activity-audit.d.ts +7 -0
- package/dist/src/activity-audit.js +14 -4
- package/dist/src/analysis-storage.d.ts +5 -1
- package/dist/src/analysis-storage.js +9 -2
- package/dist/src/audit-retention.d.ts +8 -2
- package/dist/src/audit-retention.js +68 -7
- package/dist/src/cli.js +21 -5
- package/dist/src/context-diagnostics.d.ts +1 -1
- package/dist/src/context-diagnostics.js +10 -2
- package/dist/src/contexts.d.ts +118 -10
- package/dist/src/contexts.js +851 -199
- package/dist/src/debugger.js +2 -1
- package/dist/src/diagnostic-error.js +1 -1
- package/dist/src/inline-script.js +3 -4
- package/dist/src/lifecycle.d.ts +11 -0
- package/dist/src/lifecycle.js +34 -6
- package/dist/src/native-inputs.d.ts +6 -0
- package/dist/src/native-inputs.js +30 -6
- package/dist/src/native-queries.js +1 -6
- package/dist/src/native-service.d.ts +40 -0
- package/dist/src/native-service.js +406 -0
- package/dist/src/research.d.ts +29 -1
- package/dist/src/research.js +106 -27
- package/dist/src/server.d.ts +38 -1
- package/dist/src/server.js +160 -12
- package/dist/src/storage-gc.js +1 -1
- package/dist/src/sync-policy.js +2 -1
- package/dist/src/timed-backend.js +8 -0
- package/dist/src/timing-report.d.ts +32 -0
- package/dist/src/timing-report.js +74 -0
- package/dist/src/tool-runtime/identity.js +86 -1
- package/dist/src/tool-runtime/supervisor.js +6 -5
- package/dist/src/transport.d.ts +35 -0
- package/dist/src/transport.js +77 -7
- package/dist/src/unresolved-guidance.d.ts +46 -0
- package/dist/src/unresolved-guidance.js +55 -0
- package/dist/src/windbg.d.ts +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/worker-lease.d.ts +17 -0
- package/dist/src/worker-lease.js +50 -0
- package/dist/src/workspace.d.ts +5 -9
- package/dist/src/workspace.js +20 -41
- package/package.json +1 -1
- package/references/native/InsightHeadlessMain.java +9 -2
- package/references/native/InsightNativeCheckout.java +113 -43
- package/references/native/InsightNativeFingerprint.java +28 -1
- package/references/native/InsightNativeRead.java +32 -9
- package/references/native/InsightNativeService.java +43 -0
- package/references/native/InsightNativeView.java +17 -6
- package/references/native/InsightOwnedScripts.java +170 -0
- package/references/native/InsightWorkerLease.java +132 -0
- package/references/recovery.md +68 -3
- package/references/research.md +38 -4
- package/references/setup.md +5 -1
- 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 +68 -3
- 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 +68 -3
- package/skill-bundle/insight-cli/references/setup.md +5 -1
- 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 +68 -3
- package/skill-bundle/insight-ghidra/references/research.md +38 -4
- package/skill-bundle/insight-ghidra/references/setup.md +5 -1
- 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 +68 -3
- 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 +68 -3
- 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 +68 -3
- package/skills/insight-ghidra/references/research.md +38 -4
- package/skills/insight-ghidra/references/setup.md +5 -1
- 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 +68 -3
- 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,434 @@
|
|
|
1
|
+
import { DatabaseSync } from 'node:sqlite';
|
|
2
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
3
|
+
import { constants } from 'node:fs';
|
|
4
|
+
import { open, lstat, mkdir, realpath, link, unlink, rmdir } from 'node:fs/promises';
|
|
5
|
+
import { resolve, dirname, basename, join, relative, isAbsolute, sep } from 'node:path';
|
|
6
|
+
import { Artifacts } from '../artifacts.js';
|
|
7
|
+
import { workSchema, workTableColumns } from './store.js';
|
|
8
|
+
import { archivedOutcomes, array, definition, digest, fail, identifier, integer, object, sha, stable, string } from './model.js';
|
|
9
|
+
const manifestLimit = 32 * 1024 * 1024, stateLimit = 2 * 1024 * 1024 * 1024, lineLimit = 16 * 1024 * 1024, artifactLimit = 100000;
|
|
10
|
+
const stages = ['discovered', 'partial', 'reconstructed', 'corpus_match', 'reviewed', 'mismatch'];
|
|
11
|
+
function artifact(value) {
|
|
12
|
+
const r = object(value), kind = r.kind ?? (typeof r.id === 'string' ? r.id.split(':')[0] : undefined), hash = sha(r.sha256);
|
|
13
|
+
if (kind !== 'input' && kind !== 'snapshot')
|
|
14
|
+
fail('backup', 'Unknown work artifact kind.');
|
|
15
|
+
if (r.id !== kind + ':' + hash)
|
|
16
|
+
fail('backup', 'Artifact identity/hash disagreement.');
|
|
17
|
+
return { id: String(r.id), kind, sha256: hash, size: integer(r.size, 1, 4 * 1024 * 1024 * 1024) };
|
|
18
|
+
}
|
|
19
|
+
function references(value, refs, depth = 0) {
|
|
20
|
+
if (depth > 128)
|
|
21
|
+
fail('limit', 'Backup metadata nesting exceeds 128.');
|
|
22
|
+
if (!value || typeof value !== 'object')
|
|
23
|
+
return;
|
|
24
|
+
if (Array.isArray(value)) {
|
|
25
|
+
for (const item of value)
|
|
26
|
+
references(item, refs, depth + 1);
|
|
27
|
+
return;
|
|
28
|
+
}
|
|
29
|
+
const r = value;
|
|
30
|
+
if (typeof r.id === 'string' && /^(input|snapshot):[0-9a-f]{64}$/.test(r.id)) {
|
|
31
|
+
const a = artifact(r), prior = refs.get(a.id);
|
|
32
|
+
if (prior && stable(prior) !== stable(a))
|
|
33
|
+
fail('backup', 'Conflicting artifact declarations.');
|
|
34
|
+
refs.set(a.id, a);
|
|
35
|
+
if (refs.size > artifactLimit)
|
|
36
|
+
fail('limit', 'M0 backup exceeds 100000 artifact references.');
|
|
37
|
+
}
|
|
38
|
+
if (r.record === 'row') {
|
|
39
|
+
const row = object(r.row);
|
|
40
|
+
for (const key of ['data', 'result'])
|
|
41
|
+
if (typeof row[key] === 'string')
|
|
42
|
+
references(JSON.parse(row[key]), refs, depth + 1);
|
|
43
|
+
}
|
|
44
|
+
for (const item of Object.values(r))
|
|
45
|
+
references(item, refs, depth + 1);
|
|
46
|
+
}
|
|
47
|
+
async function ordinary(path, limit) {
|
|
48
|
+
const info = await lstat(path);
|
|
49
|
+
if (!info.isFile() || info.isSymbolicLink() || info.size < 1 || info.size > limit)
|
|
50
|
+
fail('backup', 'Expected a bounded ordinary backup file.');
|
|
51
|
+
const handle = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
52
|
+
try {
|
|
53
|
+
const opened = await handle.stat();
|
|
54
|
+
if (!opened.isFile() || opened.size !== info.size)
|
|
55
|
+
fail('backup', 'Backup file changed while opening.');
|
|
56
|
+
return handle;
|
|
57
|
+
}
|
|
58
|
+
catch (error) {
|
|
59
|
+
await handle.close();
|
|
60
|
+
throw error;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
async function scanState(path, expected, visit) {
|
|
64
|
+
const handle = await ordinary(path, stateLimit), hash = createHash('sha256');
|
|
65
|
+
let size = 0, pending = '';
|
|
66
|
+
try {
|
|
67
|
+
for await (const chunk of handle.createReadStream({ encoding: 'utf8', autoClose: false })) {
|
|
68
|
+
const text = String(chunk);
|
|
69
|
+
hash.update(text);
|
|
70
|
+
size += Buffer.byteLength(text);
|
|
71
|
+
if (size > expected.size)
|
|
72
|
+
fail('backup', 'State grew while reading.');
|
|
73
|
+
pending += text;
|
|
74
|
+
let index;
|
|
75
|
+
while ((index = pending.indexOf('\n')) >= 0) {
|
|
76
|
+
const line = pending.slice(0, index);
|
|
77
|
+
pending = pending.slice(index + 1);
|
|
78
|
+
if (!line || Buffer.byteLength(line) > lineLimit)
|
|
79
|
+
fail('limit', 'State record exceeds the M0 budget.');
|
|
80
|
+
visit(object(JSON.parse(line)));
|
|
81
|
+
}
|
|
82
|
+
if (Buffer.byteLength(pending) > lineLimit)
|
|
83
|
+
fail('limit', 'State record exceeds the M0 budget.');
|
|
84
|
+
}
|
|
85
|
+
if (pending || size !== expected.size || hash.digest('hex') !== expected.sha256)
|
|
86
|
+
fail('backup', 'State is incomplete or its hash changed.');
|
|
87
|
+
}
|
|
88
|
+
finally {
|
|
89
|
+
await handle.close();
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
async function verifyPayload(storage, ref) {
|
|
93
|
+
const directory = join(storage.directory, 'artifacts'), info = await lstat(directory);
|
|
94
|
+
if (!info.isDirectory() || info.isSymbolicLink() || await realpath(directory) !== resolve(directory))
|
|
95
|
+
fail('backup', 'Artifact directory is not an ordinary owned directory.');
|
|
96
|
+
const path = storage.path(ref), handle = await ordinary(path, ref.size), hash = createHash('sha256');
|
|
97
|
+
let size = 0;
|
|
98
|
+
try {
|
|
99
|
+
for await (const chunk of handle.createReadStream({ autoClose: false })) {
|
|
100
|
+
size += chunk.length;
|
|
101
|
+
if (size > ref.size)
|
|
102
|
+
fail('backup', 'Payload grew during verification.');
|
|
103
|
+
hash.update(chunk);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
finally {
|
|
107
|
+
await handle.close();
|
|
108
|
+
}
|
|
109
|
+
if (size !== ref.size || hash.digest('hex') !== ref.sha256)
|
|
110
|
+
fail('backup', 'Backup payload hash/size mismatch.');
|
|
111
|
+
return path;
|
|
112
|
+
}
|
|
113
|
+
export async function loadManifest(directory) {
|
|
114
|
+
if ((await lstat(directory)).isSymbolicLink())
|
|
115
|
+
fail('backup', 'Backup root must not be a symbolic link.');
|
|
116
|
+
const root = await realpath(directory), path = join(root, 'manifest.json'), handle = await ordinary(path, manifestLimit);
|
|
117
|
+
const parts = [];
|
|
118
|
+
let length = 0;
|
|
119
|
+
try {
|
|
120
|
+
for await (const chunk of handle.createReadStream({ autoClose: false })) {
|
|
121
|
+
const bytes = Buffer.from(chunk);
|
|
122
|
+
length += bytes.length;
|
|
123
|
+
if (length > manifestLimit)
|
|
124
|
+
fail('limit', 'Manifest grew beyond its budget.');
|
|
125
|
+
parts.push(bytes);
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
finally {
|
|
129
|
+
await handle.close();
|
|
130
|
+
}
|
|
131
|
+
const bytes = Buffer.concat(parts);
|
|
132
|
+
const r = object(JSON.parse(bytes.toString('utf8')));
|
|
133
|
+
if (r.schema !== 1 || r.kind !== 'insight-work-backup')
|
|
134
|
+
fail('backup', 'Unsupported work backup format.');
|
|
135
|
+
identifier(r.id);
|
|
136
|
+
identifier(r.incarnation);
|
|
137
|
+
const state = object(r.state);
|
|
138
|
+
if (state.file !== 'state.jsonl')
|
|
139
|
+
fail('backup', 'State filename is fixed, never a caller path.');
|
|
140
|
+
const refs = array(r.artifacts, artifactLimit).map(artifact);
|
|
141
|
+
if (new Set(refs.map(x => x.id)).size !== refs.length)
|
|
142
|
+
fail('backup', 'Duplicate manifest artifacts.');
|
|
143
|
+
const manifest = { ...r, state: { file: 'state.jsonl', sha256: sha(state.sha256), size: integer(state.size, 1, stateLimit) }, artifacts: refs };
|
|
144
|
+
return { root, path, bytes, manifest, sha256: createHash('sha256').update(bytes).digest('hex') };
|
|
145
|
+
}
|
|
146
|
+
function inspector(manifest, visit) {
|
|
147
|
+
let records = 0, ended = false, header = false, requests = 0;
|
|
148
|
+
const refs = new Map(), counts = {}, targets = new Set();
|
|
149
|
+
return {
|
|
150
|
+
read(record) {
|
|
151
|
+
if (ended)
|
|
152
|
+
fail('backup', 'Records follow the end marker.');
|
|
153
|
+
if (!records && (record.record !== 'header' || record.format !== 'insight-work-backup-state' || record.schema !== 1 || record.workSchema !== 2 || record.incarnation !== manifest.incarnation))
|
|
154
|
+
fail('backup', 'State header identity/version mismatch.');
|
|
155
|
+
if (record.record === 'header') {
|
|
156
|
+
if (header)
|
|
157
|
+
fail('backup', 'Duplicate state header.');
|
|
158
|
+
header = true;
|
|
159
|
+
}
|
|
160
|
+
else if (record.record === 'row') {
|
|
161
|
+
const table = string(record.table), columns = workTableColumns[table];
|
|
162
|
+
if (!columns)
|
|
163
|
+
fail('backup', 'Unknown required work table.');
|
|
164
|
+
const row = object(record.row);
|
|
165
|
+
if (stable(Object.keys(row).sort()) !== stable([...columns].sort()))
|
|
166
|
+
fail('backup', 'Stored columns disagree with work schema.');
|
|
167
|
+
for (const value of Object.values(row))
|
|
168
|
+
if (value !== null && typeof value !== 'string' && !(typeof value === 'number' && Number.isSafeInteger(value)))
|
|
169
|
+
fail('backup', 'Unsupported stored scalar.');
|
|
170
|
+
counts[table] = (counts[table] ?? 0) + 1;
|
|
171
|
+
}
|
|
172
|
+
else if (record.record === 'target') {
|
|
173
|
+
const target = object(record.value), id = string(target.id);
|
|
174
|
+
if (targets.has(id))
|
|
175
|
+
fail('backup', 'Duplicate target metadata.');
|
|
176
|
+
targets.add(id);
|
|
177
|
+
const input = artifact(target.input);
|
|
178
|
+
if (input.kind !== 'input' || input.sha256 !== sha(target.binarySha256))
|
|
179
|
+
fail('backup', 'Target bytes/hash disagree.');
|
|
180
|
+
}
|
|
181
|
+
else if (record.record === 'administration') {
|
|
182
|
+
object(record.request);
|
|
183
|
+
requests++;
|
|
184
|
+
}
|
|
185
|
+
else if (record.record === 'end') {
|
|
186
|
+
if (record.complete !== true || record.accepted1to1 !== 0 || record.recordsBeforeEnd !== records || record.requestCount !== requests)
|
|
187
|
+
fail('backup', 'Invalid final state marker.');
|
|
188
|
+
const declared = object(record.counts);
|
|
189
|
+
for (const table of Object.keys(workTableColumns))
|
|
190
|
+
if (declared[table] !== (counts[table] ?? 0))
|
|
191
|
+
fail('backup', 'State counts disagree.');
|
|
192
|
+
ended = true;
|
|
193
|
+
}
|
|
194
|
+
else
|
|
195
|
+
fail('backup', 'Unknown required record kind.');
|
|
196
|
+
references(record, refs);
|
|
197
|
+
visit?.(record);
|
|
198
|
+
records++;
|
|
199
|
+
},
|
|
200
|
+
finish() {
|
|
201
|
+
if (!ended)
|
|
202
|
+
fail('backup', 'Missing final state marker.');
|
|
203
|
+
const declared = new Map(manifest.artifacts.map(x => [x.id, x]));
|
|
204
|
+
if (refs.size !== declared.size)
|
|
205
|
+
fail('backup', 'Artifact inventory does not close the state references.');
|
|
206
|
+
for (const [id, ref] of refs)
|
|
207
|
+
if (stable(declared.get(id)) !== stable(ref))
|
|
208
|
+
fail('backup', 'Missing or changed retained artifact declaration.');
|
|
209
|
+
return { records, counts, targets: targets.size, artifacts: refs.size };
|
|
210
|
+
},
|
|
211
|
+
};
|
|
212
|
+
}
|
|
213
|
+
export async function verifyWorkBackup(directory) {
|
|
214
|
+
const loaded = await loadManifest(resolve(directory)), inspect = inspector(loaded.manifest);
|
|
215
|
+
await scanState(join(loaded.root, 'state.jsonl'), loaded.manifest.state, r => inspect.read(r));
|
|
216
|
+
const summary = inspect.finish(), storage = new Artifacts(loaded.root);
|
|
217
|
+
for (const ref of loaded.manifest.artifacts)
|
|
218
|
+
await verifyPayload(storage, ref);
|
|
219
|
+
return { ...loaded, summary };
|
|
220
|
+
}
|
|
221
|
+
export async function backupWork(store, workspace, destination) {
|
|
222
|
+
const output = join(await realpath(dirname(resolve(destination))), basename(resolve(destination)));
|
|
223
|
+
const rel = relative(workspace.directory, output);
|
|
224
|
+
if (!rel || (!isAbsolute(rel) && rel !== '..' && !rel.startsWith('..' + sep)))
|
|
225
|
+
fail('backup', 'Backup must be outside the source workspace.');
|
|
226
|
+
await mkdir(output, { mode: 0o700 }); // Exclusive root; completion is the last, fixed manifest file.
|
|
227
|
+
const refs = new Map();
|
|
228
|
+
try {
|
|
229
|
+
const state = store.writeBackupState(join(output, 'state.jsonl'), r => references(r, refs));
|
|
230
|
+
const storage = new Artifacts(output);
|
|
231
|
+
for (const ref of [...refs.values()].sort((a, b) => a.id.localeCompare(b.id))) {
|
|
232
|
+
const copied = await storage.capture(await workspace.artifacts.verify(ref), ref.kind);
|
|
233
|
+
if (stable(copied) !== stable(ref))
|
|
234
|
+
fail('backup', 'Copied artifact differs from its declaration.');
|
|
235
|
+
}
|
|
236
|
+
const manifest = { schema: 1, kind: 'insight-work-backup', id: 'b_' + randomUUID(), incarnation: store.incarnation,
|
|
237
|
+
scope: 'All work projects, journal, history, receipts, target bytes and referenced payloads; no native sessions, profiles, credentials or tool installations.',
|
|
238
|
+
state: { file: 'state.jsonl', sha256: state.sha256, size: state.size }, artifacts: [...refs.values()].sort((a, b) => a.id.localeCompare(b.id)), createdAt: Date.now() };
|
|
239
|
+
const data = stable(manifest) + '\n';
|
|
240
|
+
if (Buffer.byteLength(data) > manifestLimit)
|
|
241
|
+
fail('limit', 'Backup manifest exceeds 32 MiB.');
|
|
242
|
+
const pending = join(output, 'pending-manifest-' + randomUUID()), handle = await open(pending, 'wx', 0o600);
|
|
243
|
+
try {
|
|
244
|
+
await handle.writeFile(data);
|
|
245
|
+
await handle.sync();
|
|
246
|
+
}
|
|
247
|
+
finally {
|
|
248
|
+
await handle.close();
|
|
249
|
+
}
|
|
250
|
+
await link(pending, join(output, 'manifest.json'));
|
|
251
|
+
await unlink(pending);
|
|
252
|
+
if (process.platform !== 'win32') {
|
|
253
|
+
const directory = await open(output, constants.O_RDONLY);
|
|
254
|
+
try {
|
|
255
|
+
await directory.sync();
|
|
256
|
+
}
|
|
257
|
+
finally {
|
|
258
|
+
await directory.close();
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
const verified = await verifyWorkBackup(output);
|
|
262
|
+
return { path: output, manifestSha256: verified.sha256, backupId: manifest.id, scope: manifest.scope, ...verified.summary, accepted1to1: 0 };
|
|
263
|
+
}
|
|
264
|
+
catch (error) {
|
|
265
|
+
fail('backup', 'Backup is incomplete or could not be verified; preserve this output and inspect it before using another destination.', { path: output, completionMarker: 'manifest.json', cause: error instanceof Error ? error.message : String(error) });
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
function validateStage(db, targets, incarnation) {
|
|
269
|
+
if (db.prepare('PRAGMA foreign_key_check').all().length)
|
|
270
|
+
fail('backup', 'Backup has broken work references.');
|
|
271
|
+
const projects = new Map();
|
|
272
|
+
for (const row of db.prepare('SELECT id,data FROM projects').iterate()) {
|
|
273
|
+
const p = object(JSON.parse(String(row.data)));
|
|
274
|
+
identifier(p.id);
|
|
275
|
+
sha(p.binarySha256);
|
|
276
|
+
if (p.id !== row.id || targets.get(p.target)?.binarySha256 !== p.binarySha256)
|
|
277
|
+
fail('backup', 'Project target binding disagrees.');
|
|
278
|
+
integer(p.revision, 1, Number.MAX_SAFE_INTEGER);
|
|
279
|
+
integer(p.planningRevision, 1, p.revision);
|
|
280
|
+
if (p.epoch !== incarnation || p.phase !== 'reverse-engineering' || p.inventory.complete !== false)
|
|
281
|
+
fail('backup', 'Unsupported project epoch/phase/completeness.');
|
|
282
|
+
projects.set(p.id, p);
|
|
283
|
+
}
|
|
284
|
+
const checkPackage = (value, project) => {
|
|
285
|
+
const fn = object(value), p = projects.get(project);
|
|
286
|
+
if (!p)
|
|
287
|
+
fail('backup', 'Function has no project.');
|
|
288
|
+
const declared = definition(fn.definition, p.binarySha256);
|
|
289
|
+
if (fn.id !== declared.id || fn.rva !== declared.rva || fn.name !== declared.name || fn.risk !== declared.risk || stable(fn.resources) !== stable(declared.resources)
|
|
290
|
+
|| !stages.includes(fn.stage) || fn.accepted1to1 !== false)
|
|
291
|
+
fail('backup', 'Invalid work function package.');
|
|
292
|
+
integer(fn.version, 1, Number.MAX_SAFE_INTEGER);
|
|
293
|
+
integer(fn.definitionRevision, 1, fn.version);
|
|
294
|
+
if (fn.definitionSha256 !== digest(fn.definition))
|
|
295
|
+
fail('backup', 'Definition hash mismatch.');
|
|
296
|
+
if (fn.source) {
|
|
297
|
+
artifact(fn.source);
|
|
298
|
+
artifact(fn.contract);
|
|
299
|
+
integer(fn.packageDefinitionRevision, 1, fn.definitionRevision);
|
|
300
|
+
}
|
|
301
|
+
return fn;
|
|
302
|
+
};
|
|
303
|
+
for (const row of db.prepare('SELECT * FROM functions').iterate()) {
|
|
304
|
+
const fn = checkPackage(JSON.parse(String(row.data)), String(row.project));
|
|
305
|
+
if (fn.id !== row.id || fn.rva !== row.rva || fn.stage !== row.stage)
|
|
306
|
+
fail('backup', 'Invalid work function identity/stage.');
|
|
307
|
+
const last = db.prepare('SELECT data FROM function_versions WHERE project=? AND id=? AND version=?').get(String(row.project), String(row.id), fn.version);
|
|
308
|
+
if (!last || last.data !== row.data)
|
|
309
|
+
fail('backup', 'Current function version is not retained.');
|
|
310
|
+
}
|
|
311
|
+
for (const row of db.prepare('SELECT * FROM function_versions').iterate()) {
|
|
312
|
+
const fn = checkPackage(JSON.parse(String(row.data)), String(row.project));
|
|
313
|
+
if (fn.id !== row.id || fn.version !== row.version)
|
|
314
|
+
fail('backup', 'Malformed function history.');
|
|
315
|
+
}
|
|
316
|
+
for (const row of db.prepare('SELECT * FROM tasks').iterate()) {
|
|
317
|
+
const task = object(JSON.parse(String(row.data)));
|
|
318
|
+
if (task.id !== row.id || task.project !== row.project || task.status !== row.status || !['queued', 'leased', 'submitted', 'cancelled'].includes(task.status))
|
|
319
|
+
fail('backup', 'Invalid task metadata.');
|
|
320
|
+
identifier(task.id);
|
|
321
|
+
integer(task.fence, 0, Number.MAX_SAFE_INTEGER);
|
|
322
|
+
integer(task.leaseUntil, 0, Number.MAX_SAFE_INTEGER);
|
|
323
|
+
if (!['reconstruct', 'review'].includes(task.kind) || task.epoch !== projects.get(task.project)?.epoch)
|
|
324
|
+
fail('backup', 'Invalid task kind/epoch.');
|
|
325
|
+
const ids = array(task.functions, 50).map(x => string(x, 256));
|
|
326
|
+
if (!ids.length || new Set(ids).size !== ids.length)
|
|
327
|
+
fail('backup', 'Invalid frozen scope.');
|
|
328
|
+
for (const id of ids)
|
|
329
|
+
if (!db.prepare('SELECT 1 FROM functions WHERE project=? AND id=?').get(task.project, id))
|
|
330
|
+
fail('backup', 'Task function is absent.');
|
|
331
|
+
if (stable(Object.keys(object(task.versions)).sort()) !== stable([...ids].sort()))
|
|
332
|
+
fail('backup', 'Task versions do not close its frozen scope.');
|
|
333
|
+
for (const version of Object.values(task.versions))
|
|
334
|
+
integer(version, 1, Number.MAX_SAFE_INTEGER);
|
|
335
|
+
}
|
|
336
|
+
for (const row of db.prepare('SELECT l.project,l.resource,l.task,t.project owner,t.status,t.data FROM locks l JOIN tasks t ON t.id=l.task').iterate()) {
|
|
337
|
+
const task = JSON.parse(String(row.data));
|
|
338
|
+
if (row.project !== row.owner || !['queued', 'leased'].includes(String(row.status)) || !task.resources.includes(String(row.resource)))
|
|
339
|
+
fail('backup', 'Reservation disagrees with its frozen task.');
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
export async function prepareWorkRestore(store, workspace, input) {
|
|
343
|
+
const verified = typeof input === "string" ? await loadManifest(resolve(input)) : input;
|
|
344
|
+
const manifestRef = { ...await workspace.artifacts.capture(verified.path, 'input'), name: 'manifest.json' };
|
|
345
|
+
if (manifestRef.sha256 !== verified.sha256)
|
|
346
|
+
fail('backup', 'Manifest changed during capture.');
|
|
347
|
+
const statePath = join(verified.root, 'state.jsonl');
|
|
348
|
+
await (await ordinary(statePath, stateLimit)).close();
|
|
349
|
+
const stateRef = { ...await workspace.artifacts.capture(statePath, 'input'), name: 'state.jsonl' };
|
|
350
|
+
if (stateRef.sha256 !== verified.manifest.state.sha256)
|
|
351
|
+
fail('backup', 'State changed during capture.');
|
|
352
|
+
const stageDirectory = join(workspace.directory, 'work-restore-' + randomUUID());
|
|
353
|
+
await mkdir(stageDirectory, { mode: 0o700 });
|
|
354
|
+
const stagePath = join(stageDirectory, 'stage.sqlite'), stage = new DatabaseSync(stagePath), targets = new Map();
|
|
355
|
+
const cleanup = async () => { stage.close(); await unlink(stagePath); await rmdir(stageDirectory); };
|
|
356
|
+
try {
|
|
357
|
+
stage.exec(workSchema);
|
|
358
|
+
stage.exec('CREATE TABLE backup_administration(id TEXT PRIMARY KEY)');
|
|
359
|
+
stage.exec('BEGIN IMMEDIATE');
|
|
360
|
+
const inspect = inspector(verified.manifest, r => {
|
|
361
|
+
if (r.record === 'row') {
|
|
362
|
+
const table = String(r.table);
|
|
363
|
+
if (table === 'archived_requests')
|
|
364
|
+
return; // Imported after current receipt collection.
|
|
365
|
+
const columns = workTableColumns[table], row = object(r.row);
|
|
366
|
+
stage.prepare('INSERT INTO ' + table + '(' + columns.join(',') + ') VALUES(' + columns.map(() => '?').join(',') + ')')
|
|
367
|
+
.run(...columns.map(c => row[c]));
|
|
368
|
+
}
|
|
369
|
+
else if (r.record === 'target') {
|
|
370
|
+
const target = object(r.value);
|
|
371
|
+
targets.set(String(target.id), target);
|
|
372
|
+
}
|
|
373
|
+
});
|
|
374
|
+
await scanState(workspace.artifacts.path({ ...stateRef, kind: 'input' }), verified.manifest.state, r => inspect.read(r));
|
|
375
|
+
inspect.finish();
|
|
376
|
+
// A second bounded pass retains request history, including failed/no-op intents and earlier restores.
|
|
377
|
+
const archive = (key, value) => {
|
|
378
|
+
identifier(key);
|
|
379
|
+
const previous = stage.prepare('SELECT data FROM archived_requests WHERE caller_id=?').get(key);
|
|
380
|
+
const histories = [...(previous ? archivedOutcomes(JSON.parse(String(previous.data))) : []), ...archivedOutcomes(value)];
|
|
381
|
+
const unique = [...new Map(histories.map(item => [stable(item), item])).values()];
|
|
382
|
+
const retained = unique.length === 1 ? unique[0] : { kind: 'request-history-set', histories: unique };
|
|
383
|
+
stage.prepare('INSERT INTO archived_requests VALUES(?,?) ON CONFLICT(caller_id) DO UPDATE SET data=excluded.data').run(key, stable(retained));
|
|
384
|
+
};
|
|
385
|
+
await scanState(workspace.artifacts.path({ ...stateRef, kind: 'input' }), verified.manifest.state, r => {
|
|
386
|
+
if (r.record === 'row' && r.table === 'archived_requests') {
|
|
387
|
+
const row = object(r.row);
|
|
388
|
+
archive(String(row.caller_id), JSON.parse(String(row.data)));
|
|
389
|
+
}
|
|
390
|
+
if (r.record === 'administration') {
|
|
391
|
+
const request = object(r.request), id = String(request.id), local = stage.prepare('SELECT result FROM receipts WHERE id=?').get(id);
|
|
392
|
+
if (typeof request.operation !== 'string' || !request.operation.startsWith('work.'))
|
|
393
|
+
fail('backup', 'Unexpected administration namespace.');
|
|
394
|
+
stage.prepare('INSERT INTO backup_administration VALUES(?)').run(id);
|
|
395
|
+
if (request.state === 'applied' && !local)
|
|
396
|
+
fail('backup', 'Applied request lacks the captured local receipt.');
|
|
397
|
+
if (stable(r.receipt) !== stable(local ? JSON.parse(String(local.result)) : null))
|
|
398
|
+
fail('backup', 'Request/local receipt mismatch.');
|
|
399
|
+
archive(String(request.callerId ?? id), { request, receipt: r.receipt, origin: { incarnation: verified.manifest.incarnation, backupId: verified.manifest.id } });
|
|
400
|
+
}
|
|
401
|
+
});
|
|
402
|
+
if (stage.prepare('SELECT 1 FROM receipts r WHERE NOT EXISTS(SELECT 1 FROM backup_administration a WHERE a.id=r.id)').get())
|
|
403
|
+
fail('backup', 'Work receipt has no administration intent.');
|
|
404
|
+
validateStage(stage, targets, verified.manifest.incarnation);
|
|
405
|
+
stage.exec('COMMIT');
|
|
406
|
+
const storage = new Artifacts(verified.root);
|
|
407
|
+
for (const ref of verified.manifest.artifacts) {
|
|
408
|
+
const captured = await workspace.artifacts.capture(await verifyPayload(storage, ref), ref.kind);
|
|
409
|
+
if (stable(captured) !== stable(ref))
|
|
410
|
+
fail('backup', 'Restored payload differs.');
|
|
411
|
+
}
|
|
412
|
+
const bindings = new Map();
|
|
413
|
+
for (const [oldId, target] of targets) {
|
|
414
|
+
const input = artifact(target.input);
|
|
415
|
+
const current = await workspace.importTarget(workspace.artifacts.path(input));
|
|
416
|
+
if (current.binarySha256 !== target.binarySha256)
|
|
417
|
+
fail('binding', 'Restored target changed.');
|
|
418
|
+
bindings.set(oldId, current.id);
|
|
419
|
+
}
|
|
420
|
+
return { stage, targets: bindings, origin: { incarnation: verified.manifest.incarnation, manifest: manifestRef, state: stateRef },
|
|
421
|
+
intent: { backupId: verified.manifest.id, manifestSha256: verified.sha256, stateSha256: stateRef.sha256 }, cleanup };
|
|
422
|
+
}
|
|
423
|
+
catch (error) {
|
|
424
|
+
try {
|
|
425
|
+
stage.exec('ROLLBACK');
|
|
426
|
+
}
|
|
427
|
+
catch { }
|
|
428
|
+
try {
|
|
429
|
+
await cleanup();
|
|
430
|
+
}
|
|
431
|
+
catch { }
|
|
432
|
+
throw error;
|
|
433
|
+
}
|
|
434
|
+
}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import { type CommandContext } from '@eyeauras/cli-factory';
|
|
2
|
+
import { type Workspace } from '../workspace.js';
|
|
3
|
+
type Access = <T>(c: CommandContext, action: (workspace: Workspace) => Promise<T>) => Promise<T>;
|
|
4
|
+
export declare function workCommands(access: Access): import("@eyeauras/cli-factory").CommandDefinition[];
|
|
5
|
+
export {};
|