@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.
Files changed (84) hide show
  1. package/.cli-package-build.json +1 -1
  2. package/SKILL.md +1 -1
  3. package/dist/src/cli.js +2 -0
  4. package/dist/src/contexts.d.ts +2 -1
  5. package/dist/src/contexts.js +22 -9
  6. package/dist/src/research.d.ts +1 -0
  7. package/dist/src/research.js +1 -1
  8. package/dist/src/work/backup.d.ts +66 -0
  9. package/dist/src/work/backup.js +434 -0
  10. package/dist/src/work/commands.d.ts +5 -0
  11. package/dist/src/work/commands.js +277 -0
  12. package/dist/src/work/dashboard.d.ts +12 -0
  13. package/dist/src/work/dashboard.js +103 -0
  14. package/dist/src/work/model.d.ts +131 -0
  15. package/dist/src/work/model.js +124 -0
  16. package/dist/src/work/store.d.ts +368 -0
  17. package/dist/src/work/store.js +1050 -0
  18. package/dist/src/work/timing.d.ts +26 -0
  19. package/dist/src/work/timing.js +80 -0
  20. package/dist/src/workspace.d.ts +2 -0
  21. package/dist/src/workspace.js +13 -1
  22. package/package.json +1 -1
  23. package/references/recovery.md +6 -0
  24. package/references/work-tracking.md +203 -0
  25. package/runtime/toolbox.json +1 -0
  26. package/skill-bundle/insight-artifacts/SKILL.md +1 -1
  27. package/skill-bundle/insight-artifacts/references/recovery.md +6 -0
  28. package/skill-bundle/insight-binary/SKILL.md +1 -1
  29. package/skill-bundle/insight-capture/SKILL.md +1 -1
  30. package/skill-bundle/insight-cli/SKILL.md +1 -1
  31. package/skill-bundle/insight-cli/references/recovery.md +6 -0
  32. package/skill-bundle/insight-die/SKILL.md +1 -1
  33. package/skill-bundle/insight-dnspy/SKILL.md +1 -1
  34. package/skill-bundle/insight-dotnet-dump/SKILL.md +1 -1
  35. package/skill-bundle/insight-dotnet-stack/SKILL.md +1 -1
  36. package/skill-bundle/insight-dotnet-trace/SKILL.md +1 -1
  37. package/skill-bundle/insight-frida/SKILL.md +1 -1
  38. package/skill-bundle/insight-ghidra/SKILL.md +1 -1
  39. package/skill-bundle/insight-ghidra/references/recovery.md +6 -0
  40. package/skill-bundle/insight-ilspy/SKILL.md +1 -1
  41. package/skill-bundle/insight-interop/SKILL.md +1 -1
  42. package/skill-bundle/insight-lldb/SKILL.md +1 -1
  43. package/skill-bundle/insight-llvm/SKILL.md +1 -1
  44. package/skill-bundle/insight-managed-heap/SKILL.md +1 -1
  45. package/skill-bundle/insight-managed-metadata/SKILL.md +1 -1
  46. package/skill-bundle/insight-mitmproxy/SKILL.md +1 -1
  47. package/skill-bundle/insight-overview/SKILL.md +1 -1
  48. package/skill-bundle/insight-procmon/SKILL.md +1 -1
  49. package/skill-bundle/insight-re/SKILL.md +5 -1
  50. package/skill-bundle/insight-re/references/recovery.md +6 -0
  51. package/skill-bundle/insight-re/references/work-tracking.md +203 -0
  52. package/skill-bundle/insight-sevenzip/SKILL.md +1 -1
  53. package/skill-bundle/insight-strace/SKILL.md +1 -1
  54. package/skill-bundle/insight-tshark/SKILL.md +1 -1
  55. package/skill-bundle/insight-windbg/SKILL.md +1 -1
  56. package/skill-bundle/manifest.json +1 -1
  57. package/skills/insight-artifacts/SKILL.md +1 -1
  58. package/skills/insight-artifacts/references/recovery.md +6 -0
  59. package/skills/insight-binary/SKILL.md +1 -1
  60. package/skills/insight-capture/SKILL.md +1 -1
  61. package/skills/insight-die/SKILL.md +1 -1
  62. package/skills/insight-dnspy/SKILL.md +1 -1
  63. package/skills/insight-dotnet-dump/SKILL.md +1 -1
  64. package/skills/insight-dotnet-stack/SKILL.md +1 -1
  65. package/skills/insight-dotnet-trace/SKILL.md +1 -1
  66. package/skills/insight-frida/SKILL.md +1 -1
  67. package/skills/insight-ghidra/SKILL.md +1 -1
  68. package/skills/insight-ghidra/references/recovery.md +6 -0
  69. package/skills/insight-ilspy/SKILL.md +1 -1
  70. package/skills/insight-interop/SKILL.md +1 -1
  71. package/skills/insight-lldb/SKILL.md +1 -1
  72. package/skills/insight-llvm/SKILL.md +1 -1
  73. package/skills/insight-managed-heap/SKILL.md +1 -1
  74. package/skills/insight-managed-metadata/SKILL.md +1 -1
  75. package/skills/insight-mitmproxy/SKILL.md +1 -1
  76. package/skills/insight-overview/SKILL.md +1 -1
  77. package/skills/insight-procmon/SKILL.md +1 -1
  78. package/skills/insight-re/SKILL.md +5 -1
  79. package/skills/insight-re/references/recovery.md +6 -0
  80. package/skills/insight-re/references/work-tracking.md +203 -0
  81. package/skills/insight-sevenzip/SKILL.md +1 -1
  82. package/skills/insight-strace/SKILL.md +1 -1
  83. package/skills/insight-tshark/SKILL.md +1 -1
  84. package/skills/insight-windbg/SKILL.md +1 -1
@@ -1 +1 @@
1
- {"version":1,"artifact":"3c5d4ee1cf073825a74ba09b3f8b851cccefea0688d1cae155be30f698c4713f"}
1
+ {"version":1,"artifact":"a124e451fc65f74607c50ec8b19effb9d565f80001b485af4001b07cfb82a3e3"}
package/SKILL.md CHANGED
@@ -3,7 +3,7 @@ name: insight-cli
3
3
  description: Choose and prepare reverse-engineering capabilities from the insight-cli toolbox for binary, managed-code and runtime investigations. Use to discover the appropriate tool or its packaged skill before installing native runtimes.
4
4
  ---
5
5
 
6
- # insight-cli 0.8.0
6
+ # insight-cli 0.8.2
7
7
 
8
8
  If local help/status reports AppData or IPC access denied, retry that **read-only probe**
9
9
  with the agent host's normal permission escalation, then use that route for later authorized
package/dist/src/cli.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { workCommands } from './work/commands.js';
1
2
  import { ghidraBudget } from './budgets.js';
2
3
  import { captureCommands } from './capture.js';
3
4
  import { binaryCommands } from './binary.js';
@@ -416,6 +417,7 @@ export function createDefinition(options = {}) {
416
417
  },
417
418
  builtins: [skillCommand()],
418
419
  commands: [
420
+ ...workCommands((c, action) => owner.openCommand(c, ({ workspace }) => action(workspace))),
419
421
  ...artifactsCommands(),
420
422
  ...diagnosticsCommands(c => owner.selected(c).workspace),
421
423
  ...llvmCommands(c => owner.selected(c).workspace),
@@ -320,10 +320,11 @@ export declare class GhidraContexts {
320
320
  revision: number;
321
321
  snapshot: Artifact;
322
322
  conflict: string;
323
+ reason?: 'not_published';
323
324
  } | {
324
325
  state: 'unknown';
325
326
  }>;
326
- /** Only the completed head-race branch before checkin() has this journal shape. */
327
+ /** A request that published nothing: the completed head-race branch before checkin(), or a check-in that was sent and created no version. */
327
328
  private recoverNativeRefusal;
328
329
  recoverModel(targetId: string): Promise<boolean>;
329
330
  dispose(): Promise<void>;
@@ -2279,7 +2279,7 @@ public class ${name} extends GhidraScript {
2279
2279
  const shared = await this.serverView(publication.target, revisionNumber, checkout.fileId);
2280
2280
  return { state: 'verified', revision: revisionNumber, snapshot: shared.snapshot };
2281
2281
  }
2282
- /** Only the completed head-race branch before checkin() has this journal shape. */
2282
+ /** A request that published nothing: the completed head-race branch before checkin(), or a check-in that was sent and created no version. */
2283
2283
  async recoverNativeRefusal(publication, checkout, saved) {
2284
2284
  const unknown = { state: 'unknown' }, context = this.workspace.context(publication);
2285
2285
  if (context.generation !== publication.generation || context.workingSnapshot?.id !== publication.snapshot.id ||
@@ -2301,19 +2301,31 @@ public class ${name} extends GhidraScript {
2301
2301
  return unknown;
2302
2302
  throw error;
2303
2303
  }
2304
- const result = object(journal.result ?? {}), before = object(journal.before ?? {});
2305
- if (stable(journal.request) !== stable(q) || journal.marker !== undefined || journal.checkoutId !== checkout.checkoutId || journal.baseVersion !== checkout.baseVersion ||
2306
- !Number.isSafeInteger(journal.headVersion) || Number(journal.headVersion) <= publication.expectedRevision || result.state !== 'conflict' ||
2304
+ const result = object(journal.result ?? {}), before = object(journal.before ?? {}), marker = 'insight native ' + publication.id;
2305
+ // A check-in that was sent and whose helper ended without a result. Ghidra's check-in either creates the version
2306
+ // with this marker and moves the checkout to it, or leaves both as they were: the checkout still at its base,
2307
+ // still modified, no check-in active and no version carrying the marker establish that nothing was published.
2308
+ const issued = journal.marker === marker && journal.result === undefined;
2309
+ if (stable(journal.request) !== stable(q) || journal.checkoutId !== checkout.checkoutId || journal.baseVersion !== checkout.baseVersion ||
2310
+ !Number.isSafeInteger(journal.headVersion) || before.fileId !== checkout.fileId || before.version !== checkout.baseVersion)
2311
+ return unknown;
2312
+ if (issued) {
2313
+ if (journal.headVersion !== publication.expectedRevision)
2314
+ return unknown;
2315
+ }
2316
+ else if (journal.marker !== undefined || Number(journal.headVersion) <= publication.expectedRevision || result.state !== 'conflict' ||
2307
2317
  result.conflict !== 'Shared head changed before native check-in' || result.nativeMergeInvocations !== 0 || !Array.isArray(result.nativePhases) || result.nativePhases.length !== 0 ||
2308
2318
  result.checkoutId !== checkout.checkoutId || result.baseVersion !== checkout.baseVersion || typeof result.modified !== 'boolean' ||
2309
- before.fingerprint !== saved.fingerprint || before.fileId !== checkout.fileId || before.version !== checkout.baseVersion || stable(result.saved) !== stable(before))
2319
+ before.fingerprint !== saved.fingerprint || stable(result.saved) !== stable(before))
2310
2320
  return unknown;
2311
- const observed = await this.nativeOperation(checkout, 'status');
2321
+ // The status call needs the project: a helper still running this check-in would hold it.
2322
+ const observed = await this.nativeOperation(checkout, 'status'), local = object(observed.saved ?? {});
2312
2323
  if (observed.state !== 'ready' || observed.checkedOut !== true || observed.recoverable !== false || observed.checkinActive !== false ||
2313
2324
  observed.fileId !== checkout.fileId || observed.checkoutId !== checkout.checkoutId || observed.baseVersion !== checkout.baseVersion ||
2314
- observed.modified !== result.modified || stable(observed.saved) !== stable(before))
2325
+ (issued ? observed.modified !== true || local.fileId !== checkout.fileId || local.version !== checkout.baseVersion :
2326
+ observed.modified !== result.modified || stable(observed.saved) !== stable(before)))
2315
2327
  return unknown;
2316
- const server = this.server(), marker = 'insight native ' + publication.id;
2328
+ const server = this.server();
2317
2329
  const history = (value) => {
2318
2330
  if (value.repository !== checkout.repository || value.path !== checkout.path || value.checkinActive !== false || !Number.isSafeInteger(value.version) ||
2319
2331
  Number(value.version) < Number(journal.headVersion) || !Array.isArray(value.versions) || !value.versions.length ||
@@ -2336,7 +2348,8 @@ public class ${name} extends GhidraScript {
2336
2348
  !await this.neverStartedOrClosed(context) || stable((await this.nativeOperation(checkout, 'status'))) !== stable(observed) ||
2337
2349
  stable(JSON.parse(await readFile(path, 'utf8'))) !== stable(journal))
2338
2350
  return unknown;
2339
- return { state: 'refused', revision: shared.revision, snapshot: shared.snapshot, conflict: String(result.conflict) };
2351
+ return { state: 'refused', revision: shared.revision, snapshot: shared.snapshot,
2352
+ ...(issued ? { reason: 'not_published', conflict: 'The native check-in was sent and created no version; the private work is retained. Merge again with a new request ID.' } : { conflict: String(result.conflict) }) };
2340
2353
  }
2341
2354
  async recoverModel(targetId) {
2342
2355
  if (this.workspace.activePublication(targetId))
@@ -126,6 +126,7 @@ export interface ResearchBackend {
126
126
  revision: number;
127
127
  snapshot: Artifact;
128
128
  conflict: string;
129
+ reason?: 'not_published';
129
130
  } | {
130
131
  state: 'unknown';
131
132
  }>;
@@ -560,7 +560,7 @@ export class Research {
560
560
  if (observed.state === 'verified' && backend.dropNative)
561
561
  await backend.dropNative(active);
562
562
  if (observed.state === 'refused')
563
- this.workspace.finishRefusedPublication(active.id, observed.revision, observed.snapshot, { session: active.session, target: active.target, state: 'conflict', reason: 'shared_changed', applied: 0,
563
+ this.workspace.finishRefusedPublication(active.id, observed.revision, observed.snapshot, { session: active.session, target: active.target, state: 'conflict', reason: observed.reason ?? 'shared_changed', applied: 0,
564
564
  pendingChanges: active.scalars.length + (active.complexChanges?.length ?? Number(active.complex)),
565
565
  conflicts: [{ engine: 'ghidra', message: observed.conflict }], reconciled: true });
566
566
  }
@@ -0,0 +1,66 @@
1
+ import { DatabaseSync } from 'node:sqlite';
2
+ import { type Artifact } from '../artifacts.js';
3
+ import { type Workspace } from '../workspace.js';
4
+ import { WorkStore } from './store.js';
5
+ import { type Attachment } from './model.js';
6
+ type Manifest = {
7
+ schema: 1;
8
+ kind: 'insight-work-backup';
9
+ id: string;
10
+ incarnation: string;
11
+ scope: string;
12
+ state: {
13
+ file: 'state.jsonl';
14
+ sha256: string;
15
+ size: number;
16
+ };
17
+ artifacts: Artifact[];
18
+ createdAt: number;
19
+ };
20
+ export declare function loadManifest(directory: string): Promise<{
21
+ root: string;
22
+ path: string;
23
+ bytes: Buffer<ArrayBuffer>;
24
+ manifest: Manifest;
25
+ sha256: string;
26
+ }>;
27
+ export declare function verifyWorkBackup(directory: string): Promise<{
28
+ summary: {
29
+ records: number;
30
+ counts: Record<string, number>;
31
+ targets: number;
32
+ artifacts: number;
33
+ };
34
+ root: string;
35
+ path: string;
36
+ bytes: Buffer<ArrayBuffer>;
37
+ manifest: Manifest;
38
+ sha256: string;
39
+ }>;
40
+ export declare function backupWork(store: WorkStore, workspace: Workspace, destination: string): Promise<{
41
+ accepted1to1: number;
42
+ records: number;
43
+ counts: Record<string, number>;
44
+ targets: number;
45
+ artifacts: number;
46
+ path: string;
47
+ manifestSha256: string;
48
+ backupId: string;
49
+ scope: string;
50
+ }>;
51
+ export declare function prepareWorkRestore(store: WorkStore, workspace: Workspace, input: string | Awaited<ReturnType<typeof loadManifest>>): Promise<{
52
+ stage: DatabaseSync;
53
+ targets: Map<string, string>;
54
+ origin: {
55
+ incarnation: string;
56
+ manifest: Attachment;
57
+ state: Attachment;
58
+ };
59
+ intent: {
60
+ backupId: string;
61
+ manifestSha256: string;
62
+ stateSha256: string;
63
+ };
64
+ cleanup: () => Promise<void>;
65
+ }>;
66
+ export {};
@@ -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 {};