jg-agent-hq 2.0.0 → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (155) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/README.md +14 -14
  3. package/api/README.md +97 -65
  4. package/dist/actions/actions.js +15 -0
  5. package/dist/cli/cli.js +28 -5
  6. package/dist/cli/utilities.d.ts +3 -0
  7. package/dist/cli/utilities.js +13 -0
  8. package/dist/collaboration/dispatch/types.d.ts +2 -2
  9. package/dist/contracts/actions/types.d.ts +4 -4
  10. package/dist/contracts/browser/index.d.ts +1 -3
  11. package/dist/contracts/browser/index.js +1 -3
  12. package/dist/contracts/browser/types.d.ts +15 -1447
  13. package/dist/contracts/browser/types.js +3 -112
  14. package/dist/contracts/index.d.ts +9 -11
  15. package/dist/contracts/index.js +6 -8
  16. package/dist/contracts/plans/index.d.ts +4 -6
  17. package/dist/contracts/plans/index.js +2 -4
  18. package/dist/contracts/plans/types.d.ts +38 -905
  19. package/dist/contracts/plans/types.js +13 -139
  20. package/dist/contracts/sessions/index.d.ts +2 -0
  21. package/dist/contracts/sessions/index.js +2 -0
  22. package/dist/contracts/sessions/types.d.ts +101 -0
  23. package/dist/contracts/sessions/types.js +43 -0
  24. package/dist/contracts/types.d.ts +551 -1035
  25. package/dist/contracts/types.js +32 -0
  26. package/dist/index.d.ts +2 -2
  27. package/dist/index.js +1 -1
  28. package/dist/plans/admission.d.ts +6 -6
  29. package/dist/plans/admission.js +1 -1
  30. package/dist/plans/authority.d.ts +2 -0
  31. package/dist/plans/authority.js +23 -13
  32. package/dist/plans/documents.d.ts +20 -17
  33. package/dist/plans/documents.js +29 -63
  34. package/dist/plans/files.d.ts +2 -2
  35. package/dist/plans/files.js +5 -5
  36. package/dist/plans/finalization.d.ts +6 -8
  37. package/dist/plans/finalization.js +25 -26
  38. package/dist/plans/index.d.ts +2 -3
  39. package/dist/plans/index.js +1 -2
  40. package/dist/plans/plans.d.ts +8 -8
  41. package/dist/plans/plans.js +36 -83
  42. package/dist/plans/projections.d.ts +2 -2
  43. package/dist/plans/projections.js +44 -82
  44. package/dist/plans/revisions.d.ts +4 -5
  45. package/dist/plans/revisions.js +5 -44
  46. package/dist/plans/types.d.ts +5 -281
  47. package/dist/plans/types.js +2 -30
  48. package/dist/plans/utilities.js +2 -11
  49. package/dist/providers/claude/agents/agents.d.ts +16 -0
  50. package/dist/providers/claude/agents/agents.js +80 -0
  51. package/dist/providers/claude/agents/constants.d.ts +3 -0
  52. package/dist/providers/claude/agents/constants.js +4 -0
  53. package/dist/providers/claude/agents/index.d.ts +1 -0
  54. package/dist/providers/claude/agents/index.js +2 -0
  55. package/dist/providers/claude/agents/types.d.ts +14 -0
  56. package/dist/providers/claude/agents/types.js +9 -0
  57. package/dist/providers/claude/claude.js +2 -0
  58. package/dist/providers/claude/history/history.model.js +2 -0
  59. package/dist/providers/claude/history/types.d.ts +115 -368
  60. package/dist/providers/claude/index.d.ts +1 -0
  61. package/dist/providers/claude/index.js +2 -0
  62. package/dist/providers/claude/transformers.js +14 -1
  63. package/dist/providers/codex/adapter.d.ts +1 -1
  64. package/dist/providers/codex/adapter.js +26 -3
  65. package/dist/providers/codex/codex.js +51 -18
  66. package/dist/providers/codex/events.d.ts +2 -1
  67. package/dist/providers/codex/events.js +8 -3
  68. package/dist/providers/codex/index.d.ts +1 -1
  69. package/dist/providers/codex/index.js +1 -1
  70. package/dist/providers/codex/rpc.d.ts +9 -4
  71. package/dist/providers/codex/rpc.js +109 -47
  72. package/dist/providers/codex/skill-roots/constants.d.ts +4 -0
  73. package/dist/providers/codex/skill-roots/constants.js +7 -0
  74. package/dist/providers/codex/skill-roots/index.d.ts +2 -0
  75. package/dist/providers/codex/skill-roots/index.js +4 -0
  76. package/dist/providers/codex/skill-roots/skill-roots.d.ts +35 -0
  77. package/dist/providers/codex/skill-roots/skill-roots.js +93 -0
  78. package/dist/providers/codex/transformers.d.ts +3 -1
  79. package/dist/providers/codex/transformers.js +41 -3
  80. package/dist/providers/codex/types.d.ts +38 -1
  81. package/dist/providers/codex/types.js +15 -3
  82. package/dist/providers/codex/websocket/constants.d.ts +11 -0
  83. package/dist/providers/codex/websocket/constants.js +18 -0
  84. package/dist/providers/codex/websocket/index.d.ts +1 -0
  85. package/dist/providers/codex/websocket/index.js +2 -0
  86. package/dist/providers/codex/websocket/websocket.d.ts +7 -0
  87. package/dist/providers/codex/websocket/websocket.js +219 -0
  88. package/dist/providers/index.d.ts +2 -2
  89. package/dist/providers/index.js +1 -1
  90. package/dist/providers/process.d.ts +2 -2
  91. package/dist/providers/process.js +37 -4
  92. package/dist/providers/registry/registry.js +2 -1
  93. package/dist/providers/types.d.ts +25 -2
  94. package/dist/runtime/runtime.js +11 -3
  95. package/dist/runtime/state/index.d.ts +1 -1
  96. package/dist/runtime/state/index.js +1 -1
  97. package/dist/runtime/state/state.d.ts +15 -0
  98. package/dist/runtime/state/state.js +92 -1
  99. package/dist/runtime/types.d.ts +0 -2
  100. package/dist/runtime/types.js +0 -3
  101. package/dist/sessions/sessions.js +2 -0
  102. package/dist/snapshots/archive/archive.d.ts +29 -0
  103. package/dist/snapshots/archive/archive.js +342 -0
  104. package/dist/snapshots/archive/constants.d.ts +5 -0
  105. package/dist/snapshots/archive/constants.js +8 -0
  106. package/dist/snapshots/archive/index.d.ts +1 -0
  107. package/dist/snapshots/archive/index.js +2 -0
  108. package/dist/snapshots/artifacts.d.ts +10 -1
  109. package/dist/snapshots/artifacts.js +38 -13
  110. package/dist/snapshots/capture.d.ts +15 -0
  111. package/dist/snapshots/capture.js +158 -0
  112. package/dist/snapshots/database.d.ts +2 -0
  113. package/dist/snapshots/database.js +35 -55
  114. package/dist/snapshots/fences.d.ts +10 -0
  115. package/dist/snapshots/fences.js +51 -0
  116. package/dist/snapshots/index.d.ts +1 -0
  117. package/dist/snapshots/index.js +2 -0
  118. package/dist/snapshots/snapshots.d.ts +7 -3
  119. package/dist/snapshots/snapshots.js +31 -117
  120. package/dist/snapshots/snapshots.worker.js +5 -1
  121. package/dist/snapshots/types.d.ts +35 -3
  122. package/dist/snapshots/types.js +19 -4
  123. package/dist/storage/index.d.ts +2 -1
  124. package/dist/storage/index.js +2 -1
  125. package/dist/storage/schema/constants.d.ts +2 -0
  126. package/dist/storage/schema/constants.js +9 -0
  127. package/dist/storage/schema/index.d.ts +3 -0
  128. package/dist/storage/schema/index.js +6 -0
  129. package/dist/storage/schema/schema.d.ts +18 -0
  130. package/dist/storage/schema/schema.js +59 -0
  131. package/dist/storage/schema/types.d.ts +7 -0
  132. package/dist/storage/schema/types.js +8 -0
  133. package/dist/storage/storage.d.ts +1 -1
  134. package/dist/storage/storage.js +2 -2
  135. package/dist/storage/types.d.ts +0 -5
  136. package/dist/storage/types.js +0 -6
  137. package/dist/store/collaboration/collaboration.model.d.ts +2 -2
  138. package/dist/store/control/types.d.ts +16 -16
  139. package/dist/store/plans/plans.model.d.ts +3 -105
  140. package/dist/store/plans/plans.model.js +6 -46
  141. package/dist/store/schema.js +7 -35
  142. package/dist/store/schema.sql +91 -16
  143. package/dist/store/sessions/index.d.ts +1 -0
  144. package/dist/store/sessions/index.js +2 -0
  145. package/dist/store/sessions/sessions.model.d.ts +28 -0
  146. package/dist/store/sessions/sessions.model.js +105 -0
  147. package/dist/store/store.js +13 -7
  148. package/dist/store/store.worker.js +16 -11
  149. package/dist/store/types.d.ts +134 -513
  150. package/dist/store/types.js +21 -7
  151. package/docs/recovery.md +8 -4
  152. package/errors/README.md +3 -3
  153. package/package.json +2 -2
  154. package/dist/plans/reconciliation.d.ts +0 -34
  155. package/dist/plans/reconciliation.js +0 -246
@@ -0,0 +1,342 @@
1
+ import { createCipheriv, createDecipheriv, randomBytes } from 'node:crypto';
2
+ import { createReadStream, createWriteStream } from 'node:fs';
3
+ import { lstat, mkdir, mkdtemp, open, realpath, rm } from 'node:fs/promises';
4
+ import { dirname, isAbsolute, join, resolve } from 'node:path';
5
+ import { pipeline } from 'node:stream/promises';
6
+ import { Exception, extractMessage, hasErrorCode, isException } from 'jg-exception';
7
+ import { SNAPSHOT_COMPANIONS, SNAPSHOT_COMPLETE, SNAPSHOT_COPY_BYTES, SNAPSHOT_MANIFEST, } from '../constants.js';
8
+ import { invalidSnapshot, openSnapshotFile, readSnapshotRecords, reserveSnapshotDirectory, syncSnapshotDirectory, } from '../files.js';
9
+ import { inspectHqSnapshot } from '../snapshots.js';
10
+ import { ARCHIVE_FORMAT, ARCHIVE_IV_BYTES, ARCHIVE_KEY_BYTES, ARCHIVE_PATH_BYTES, ARCHIVE_TAG_BYTES, } from './constants.js';
11
+ /**
12
+ * Requires a 32-byte key and an absolute, normalized path beneath an existing canonical parent.
13
+ * @throws
14
+ * - JG_AGENT_HQ_SNAPSHOT_INVALID: The HQ snapshot is invalid
15
+ */
16
+ const checkInputs = async (path, key) => {
17
+ if (!Buffer.isBuffer(key) || key.length !== ARCHIVE_KEY_BYTES)
18
+ invalidSnapshot();
19
+ if (typeof path !== 'string' || !isAbsolute(path) || resolve(path) !== path)
20
+ invalidSnapshot();
21
+ if ((await realpath(dirname(path))) !== dirname(path))
22
+ invalidSnapshot();
23
+ };
24
+ /**
25
+ * Keeps snapshot classifications and reports any other failure, including a failed cleanup,
26
+ * as an operational one.
27
+ * @returns The original or translated error for the caller to throw.
28
+ */
29
+ const classify = (cause) => isException(cause) &&
30
+ ['JG_AGENT_HQ_SNAPSHOT_INVALID', 'JG_AGENT_HQ_STORAGE_INVALID'].includes(cause.code)
31
+ ? cause
32
+ : new Exception(`The HQ snapshot operation failed: ${extractMessage(cause)}`, {
33
+ code: 'JG_AGENT_HQ_SNAPSHOT_FAILED',
34
+ data: { kind: 'operation-failed' },
35
+ cause,
36
+ });
37
+ /** Encodes one entry header: the path length, the UTF-8 path and the content length. */
38
+ const encodeHeader = (path, bytes) => {
39
+ const name = Buffer.from(path, 'utf8');
40
+ const header = Buffer.alloc(2 + name.length + 8);
41
+ header.writeUInt16BE(name.length, 0);
42
+ name.copy(header, 2);
43
+ header.writeBigUInt64BE(BigInt(bytes), 2 + name.length);
44
+ return header;
45
+ };
46
+ /**
47
+ * Streams each snapshot file in manifest order behind its header, reading exactly its size.
48
+ * @returns Plaintext chunks for the cipher.
49
+ * @throws
50
+ * - JG_AGENT_HQ_SNAPSHOT_INVALID: The HQ snapshot is invalid
51
+ */
52
+ const readEntries = async function* (directory) {
53
+ const entry = async function* (path, maximumBytes) {
54
+ const file = await openSnapshotFile(join(directory, path), maximumBytes);
55
+ if (!file)
56
+ invalidSnapshot();
57
+ try {
58
+ const { size } = await file.stat();
59
+ yield encodeHeader(path, size);
60
+ let remaining = size;
61
+ while (remaining) {
62
+ const chunk = Buffer.alloc(Math.min(SNAPSHOT_COPY_BYTES, remaining));
63
+ const { bytesRead } = await file.read(chunk, 0, chunk.length, null);
64
+ if (!bytesRead)
65
+ invalidSnapshot();
66
+ remaining -= bytesRead;
67
+ yield chunk.subarray(0, bytesRead);
68
+ }
69
+ }
70
+ finally {
71
+ await file.close();
72
+ }
73
+ };
74
+ yield* entry(SNAPSHOT_MANIFEST, Number.MAX_SAFE_INTEGER);
75
+ yield* entry(SNAPSHOT_COMPLETE, 4096);
76
+ for await (const { record } of readSnapshotRecords(directory)) {
77
+ if (record.kind === 'database')
78
+ yield* entry('hq.sqlite', record.file.bytes);
79
+ else if (record.kind === 'action-key')
80
+ yield* entry('action.key', ARCHIVE_KEY_BYTES);
81
+ else if (record.kind === 'plan')
82
+ for (const [field, filename, maximumBytes] of SNAPSHOT_COMPANIONS)
83
+ if (record[field])
84
+ yield* entry(`plans/${record.key}/${filename}`, maximumBytes);
85
+ }
86
+ };
87
+ /**
88
+ * Encrypts a verified snapshot into one new private file with AES-256-GCM: a format identifier,
89
+ * a fresh 12-byte IV, the ciphertext of every snapshot file in manifest order with its path and
90
+ * length, and the authentication tag. The caller keeps the 32-byte key.
91
+ * @param snapshotDirectory A snapshot from createHqSnapshot.
92
+ * @param archivePath An absent absolute path beneath an existing canonical parent.
93
+ * @param key The 32-byte encryption key.
94
+ * @returns The inspection of the snapshot that was packed.
95
+ * @throws
96
+ * - JG_AGENT_HQ_SNAPSHOT_INVALID: The HQ snapshot is invalid
97
+ * - JG_AGENT_HQ_SNAPSHOT_FAILED: The HQ snapshot operation failed
98
+ * - JG_AGENT_HQ_STORAGE_INVALID: The HQ storage is invalid
99
+ */
100
+ export const packHqSnapshot = async (snapshotDirectory, archivePath, key) => {
101
+ let isCreated = false;
102
+ try {
103
+ await checkInputs(archivePath, key);
104
+ const inspection = await inspectHqSnapshot(snapshotDirectory);
105
+ let archive;
106
+ try {
107
+ archive = await open(archivePath, 'wx', 0o600);
108
+ }
109
+ catch (cause) {
110
+ if (hasErrorCode(cause, 'EEXIST'))
111
+ invalidSnapshot();
112
+ throw cause;
113
+ }
114
+ isCreated = true;
115
+ const iv = randomBytes(ARCHIVE_IV_BYTES);
116
+ const prefix = Buffer.concat([ARCHIVE_FORMAT, iv]);
117
+ try {
118
+ await archive.write(prefix, 0, prefix.length, 0);
119
+ }
120
+ finally {
121
+ await archive.close();
122
+ }
123
+ const cipher = createCipheriv('aes-256-gcm', key, iv);
124
+ await pipeline(readEntries(snapshotDirectory), cipher, createWriteStream(archivePath, { flags: 'r+', start: prefix.length }));
125
+ const tag = cipher.getAuthTag();
126
+ const completed = await open(archivePath, 'r+');
127
+ try {
128
+ await completed.write(tag, 0, tag.length, (await completed.stat()).size);
129
+ await completed.sync();
130
+ }
131
+ finally {
132
+ await completed.close();
133
+ }
134
+ await syncSnapshotDirectory(dirname(archivePath));
135
+ return inspection;
136
+ }
137
+ catch (cause) {
138
+ let failure = cause;
139
+ if (isCreated)
140
+ try {
141
+ await rm(archivePath, { force: true });
142
+ }
143
+ catch (cleanup) {
144
+ failure = new AggregateError([cause, cleanup], 'Snapshot cleanup failed');
145
+ }
146
+ throw classify(failure);
147
+ }
148
+ };
149
+ /**
150
+ * Decrypts the whole archive into a private plaintext file and verifies its tag before any of
151
+ * its bytes are trusted.
152
+ * @throws
153
+ * - JG_AGENT_HQ_SNAPSHOT_INVALID: The HQ snapshot is invalid
154
+ */
155
+ const decryptArchive = async (archivePath, output, key) => {
156
+ const archive = await openSnapshotFile(archivePath, Number.MAX_SAFE_INTEGER, false);
157
+ if (!archive)
158
+ invalidSnapshot();
159
+ const prefixBytes = ARCHIVE_FORMAT.length + ARCHIVE_IV_BYTES;
160
+ const prefix = Buffer.alloc(prefixBytes);
161
+ const tag = Buffer.alloc(ARCHIVE_TAG_BYTES);
162
+ let size;
163
+ try {
164
+ size = (await archive.stat()).size;
165
+ if (size < prefixBytes + ARCHIVE_TAG_BYTES)
166
+ invalidSnapshot();
167
+ await archive.read(prefix, 0, prefixBytes, 0);
168
+ await archive.read(tag, 0, ARCHIVE_TAG_BYTES, size - ARCHIVE_TAG_BYTES);
169
+ }
170
+ finally {
171
+ await archive.close();
172
+ }
173
+ if (!prefix.subarray(0, ARCHIVE_FORMAT.length).equals(ARCHIVE_FORMAT))
174
+ invalidSnapshot();
175
+ const decipher = createDecipheriv('aes-256-gcm', key, prefix.subarray(ARCHIVE_FORMAT.length)).setAuthTag(tag);
176
+ try {
177
+ await pipeline(createReadStream(archivePath, { start: prefixBytes, end: size - ARCHIVE_TAG_BYTES - 1 }), decipher, createWriteStream(output, { flags: 'wx', mode: 0o600 }));
178
+ }
179
+ catch (cause) {
180
+ // filesystem failures stay operational; a wrong key, a modified byte or a truncation fail the tag
181
+ if (cause instanceof Error && 'syscall' in cause)
182
+ throw cause;
183
+ throw new Exception('The HQ snapshot is invalid', {
184
+ code: 'JG_AGENT_HQ_SNAPSHOT_INVALID',
185
+ data: { kind: 'invalid-request' },
186
+ cause,
187
+ });
188
+ }
189
+ const plaintext = await open(output, 'r');
190
+ try {
191
+ await plaintext.sync();
192
+ }
193
+ finally {
194
+ await plaintext.close();
195
+ }
196
+ };
197
+ /**
198
+ * Writes the verified plaintext's entries into the new snapshot directory, accepting only
199
+ * the manifest's listed paths at exactly their listed sizes.
200
+ * @throws
201
+ * - JG_AGENT_HQ_SNAPSHOT_INVALID: The HQ snapshot is invalid
202
+ */
203
+ const writeEntries = async (plaintextPath, directory) => {
204
+ const input = await open(plaintextPath, 'r');
205
+ try {
206
+ const { size } = await input.stat();
207
+ let position = 0;
208
+ const readExact = async (length) => {
209
+ if (position + length > size)
210
+ invalidSnapshot();
211
+ const buffer = Buffer.alloc(length);
212
+ let offset = 0;
213
+ while (offset < length) {
214
+ const { bytesRead } = await input.read(buffer, offset, length - offset, position + offset);
215
+ if (!bytesRead)
216
+ invalidSnapshot();
217
+ offset += bytesRead;
218
+ }
219
+ position += length;
220
+ return buffer;
221
+ };
222
+ const readHeader = async () => {
223
+ const length = (await readExact(2)).readUInt16BE(0);
224
+ if (!length || length > ARCHIVE_PATH_BYTES)
225
+ invalidSnapshot();
226
+ let path;
227
+ try {
228
+ path = new TextDecoder('utf-8', { fatal: true }).decode(await readExact(length));
229
+ }
230
+ catch {
231
+ invalidSnapshot();
232
+ }
233
+ const bytes = (await readExact(8)).readBigUInt64BE(0);
234
+ if (bytes > BigInt(size - position))
235
+ invalidSnapshot();
236
+ return { path, bytes: Number(bytes) };
237
+ };
238
+ const copy = async (path, bytes) => {
239
+ const output = await open(join(directory, path), 'wx', 0o600);
240
+ try {
241
+ let remaining = bytes;
242
+ while (remaining) {
243
+ const chunk = await readExact(Math.min(SNAPSHOT_COPY_BYTES, remaining));
244
+ await output.write(chunk, 0, chunk.length, null);
245
+ remaining -= chunk.length;
246
+ }
247
+ await output.sync();
248
+ }
249
+ finally {
250
+ await output.close();
251
+ }
252
+ };
253
+ const manifest = await readHeader();
254
+ if (manifest.path !== SNAPSHOT_MANIFEST)
255
+ invalidSnapshot();
256
+ await copy(SNAPSHOT_MANIFEST, manifest.bytes);
257
+ const completion = await readHeader();
258
+ if (completion.path !== SNAPSHOT_COMPLETE || completion.bytes > 4096)
259
+ invalidSnapshot();
260
+ await copy(SNAPSHOT_COMPLETE, completion.bytes);
261
+ const listed = new Map();
262
+ for await (const { record } of readSnapshotRecords(directory)) {
263
+ if (record.kind === 'database')
264
+ listed.set('hq.sqlite', record.file.bytes);
265
+ else if (record.kind === 'action-key')
266
+ listed.set('action.key', record.file.bytes);
267
+ else if (record.kind === 'plan')
268
+ for (const [field, filename] of SNAPSHOT_COMPANIONS) {
269
+ const file = record[field];
270
+ if (file)
271
+ listed.set(`plans/${record.key}/${filename}`, file.bytes);
272
+ }
273
+ }
274
+ const plans = join(directory, 'plans');
275
+ await mkdir(plans, { mode: 0o700 });
276
+ const created = new Set();
277
+ while (position < size) {
278
+ const entry = await readHeader();
279
+ if (listed.get(entry.path) !== entry.bytes)
280
+ invalidSnapshot();
281
+ listed.delete(entry.path);
282
+ const parts = entry.path.split('/');
283
+ if (parts.length === 3 && !created.has(parts[1])) {
284
+ await mkdir(join(plans, parts[1]), { mode: 0o700 });
285
+ created.add(parts[1]);
286
+ }
287
+ await copy(entry.path, entry.bytes);
288
+ }
289
+ if (listed.size)
290
+ invalidSnapshot();
291
+ for (const key of created)
292
+ await syncSnapshotDirectory(join(plans, key));
293
+ await syncSnapshotDirectory(plans);
294
+ await syncSnapshotDirectory(directory);
295
+ }
296
+ finally {
297
+ await input.close();
298
+ }
299
+ };
300
+ /**
301
+ * Restores an archive from packHqSnapshot into a new snapshot directory. The archive is decrypted
302
+ * into a private temporary file and its tag verified before the destination is created; then
303
+ * only manifest-listed paths are written, at their listed sizes, and the result is inspected.
304
+ * @param archivePath The archive to unpack.
305
+ * @param destination An absent absolute directory beneath an existing canonical parent.
306
+ * @param key The 32-byte key the archive was packed with.
307
+ * @returns The inspection of the unpacked snapshot, ready for restoreHqSnapshot.
308
+ * @throws
309
+ * - JG_AGENT_HQ_SNAPSHOT_INVALID: The HQ snapshot is invalid
310
+ * - JG_AGENT_HQ_SNAPSHOT_FAILED: The HQ snapshot operation failed
311
+ * - JG_AGENT_HQ_STORAGE_INVALID: The HQ storage is invalid
312
+ */
313
+ export const unpackHqSnapshot = async (archivePath, destination, key) => {
314
+ let scratch;
315
+ let owned;
316
+ try {
317
+ await checkInputs(destination, key);
318
+ try {
319
+ await lstat(destination);
320
+ invalidSnapshot();
321
+ }
322
+ catch (cause) {
323
+ if (!hasErrorCode(cause, 'ENOENT'))
324
+ throw cause;
325
+ }
326
+ scratch = await mkdtemp(join(dirname(destination), '.hq-unpack-'));
327
+ await decryptArchive(archivePath, join(scratch, 'plaintext'), key);
328
+ owned = await reserveSnapshotDirectory(destination);
329
+ await writeEntries(join(scratch, 'plaintext'), owned);
330
+ const inspection = await inspectHqSnapshot(owned);
331
+ await rm(scratch, { recursive: true });
332
+ return inspection;
333
+ }
334
+ catch (cause) {
335
+ // attempt both removals so a stuck scratch directory never keeps the destination
336
+ const cleanups = await Promise.allSettled([owned, scratch]
337
+ .filter((path) => path !== undefined)
338
+ .map((path) => rm(path, { recursive: true, force: true })));
339
+ const failures = cleanups.flatMap((result) => result.status === 'rejected' ? [result.reason] : []);
340
+ throw classify(failures.length ? new AggregateError([cause, ...failures], 'Snapshot cleanup failed') : cause);
341
+ }
342
+ };
@@ -0,0 +1,5 @@
1
+ export declare const ARCHIVE_FORMAT: Buffer<ArrayBuffer>;
2
+ export declare const ARCHIVE_KEY_BYTES = 32;
3
+ export declare const ARCHIVE_IV_BYTES = 12;
4
+ export declare const ARCHIVE_TAG_BYTES = 16;
5
+ export declare const ARCHIVE_PATH_BYTES = 4096;
@@ -0,0 +1,8 @@
1
+ // leading bytes that identify the archive layout below
2
+ export const ARCHIVE_FORMAT = Buffer.from('JGHQSNA1', 'latin1');
3
+ // AES-256-GCM parameters: a 32-byte operator key, a fresh 12-byte IV and a 16-byte tag
4
+ export const ARCHIVE_KEY_BYTES = 32;
5
+ export const ARCHIVE_IV_BYTES = 12;
6
+ export const ARCHIVE_TAG_BYTES = 16;
7
+ // each entry is a 2-byte path length, the UTF-8 path and an 8-byte content length
8
+ export const ARCHIVE_PATH_BYTES = 4096;
@@ -0,0 +1 @@
1
+ export { packHqSnapshot, unpackHqSnapshot } from './archive.js';
@@ -0,0 +1,2 @@
1
+ // encrypted archives
2
+ export { packHqSnapshot, unpackHqSnapshot } from './archive.js';
@@ -1,7 +1,16 @@
1
+ import type { DatabaseSync } from 'node:sqlite';
2
+ import { type IPlanRevision } from '../contracts/index.js';
1
3
  import type { ISnapshotPlan } from './types.js';
4
+ /**
5
+ * Reads the distinct plan revisions the database's thread bindings record for one plan.
6
+ * @returns At most 32 revisions in a deterministic order.
7
+ */
8
+ export declare const readRecordedRevisions: (database: DatabaseSync, directory: string) => IPlanRevision[];
2
9
  /**
3
10
  * Observes identities and diagnostics in one captured artifact set without repairing source state.
11
+ * A plan whose copied revision differs from one its captured database records changed during
12
+ * capture or since those bindings were made, so restore treats its execution authority as stale.
4
13
  * Parser observations never become an approval or a conformance requirement for capture.
5
14
  * @returns Bounded identity and diagnostic fields for the inventory record.
6
15
  */
7
- export declare const observeSnapshotPlan: (directory: string, files: Pick<ISnapshotPlan, "plan" | "coordination">) => Promise<Pick<ISnapshotPlan, "planId" | "revision" | "diagnostics">>;
16
+ export declare const observeSnapshotPlan: (directory: string, files: Pick<ISnapshotPlan, "plan" | "milestones" | "coordination">, recordedRevisions: IPlanRevision[]) => Promise<Pick<ISnapshotPlan, "planId" | "revision" | "recordedRevisions" | "diagnostics">>;
@@ -1,36 +1,58 @@
1
1
  import { join } from 'node:path';
2
2
  import { readPrivateFile } from 'jg-fs';
3
3
  import { parsePlan } from 'jg-plans';
4
- import { PlanCoordinationSchema } from '../contracts/index.js';
4
+ import { PlanCoordinationSchema, PlanRevisionSchema, } from '../contracts/index.js';
5
+ import { computePlanRevision, isSamePlanRevision, observePlanContract } from '../plans/index.js';
6
+ /**
7
+ * Reads the distinct plan revisions the database's thread bindings record for one plan.
8
+ * @returns At most 32 revisions in a deterministic order.
9
+ */
10
+ export const readRecordedRevisions = (database, directory) => database
11
+ .prepare("SELECT DISTINCT json_extract(context, '$.observedRevision.planDigest') AS plan_digest, json_extract(context, '$.observedRevision.breakdownDigest') AS breakdown_digest FROM hq_thread_plan WHERE directory = ? ORDER BY plan_digest, breakdown_digest LIMIT 32")
12
+ .all(directory)
13
+ .map((row) => PlanRevisionSchema.parse({
14
+ planDigest: row.plan_digest,
15
+ breakdownDigest: row.breakdown_digest,
16
+ }));
5
17
  /**
6
18
  * Observes identities and diagnostics in one captured artifact set without repairing source state.
19
+ * A plan whose copied revision differs from one its captured database records changed during
20
+ * capture or since those bindings were made, so restore treats its execution authority as stale.
7
21
  * Parser observations never become an approval or a conformance requirement for capture.
8
22
  * @returns Bounded identity and diagnostic fields for the inventory record.
9
23
  */
10
- export const observeSnapshotPlan = async (directory, files) => {
24
+ export const observeSnapshotPlan = async (directory, files, recordedRevisions) => {
11
25
  const result = {
12
26
  planId: null,
13
27
  revision: null,
28
+ recordedRevisions,
14
29
  diagnostics: [],
15
30
  };
16
31
  if (!files.plan)
17
32
  result.diagnostics.push('plan-missing');
18
33
  else {
19
- const bytes = await readPrivateFile(join(directory, 'plan.md'), {
20
- maxBytes: 1_048_576,
21
- rootPath: directory,
22
- });
34
+ const decoder = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true });
23
35
  try {
24
- const plan = parsePlan(new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes));
25
- if (typeof plan.metadata.id === 'string')
26
- result.planId = plan.metadata.id;
27
- if (typeof plan.metadata.revision === 'number')
28
- result.revision = plan.metadata.revision;
29
- if (plan.diagnostics.some((entry) => entry.severity === 'error'))
36
+ const plan = decoder.decode(await readPrivateFile(join(directory, 'plan.md'), {
37
+ maxBytes: 1_048_576,
38
+ rootPath: directory,
39
+ }));
40
+ const milestones = files.milestones
41
+ ? decoder.decode(await readPrivateFile(join(directory, 'milestones.md'), {
42
+ maxBytes: 1_048_576,
43
+ rootPath: directory,
44
+ }))
45
+ : null;
46
+ const document = parsePlan(plan);
47
+ if (typeof document.metadata.id === 'string')
48
+ result.planId = document.metadata.id;
49
+ if (document.diagnostics.some((entry) => entry.severity === 'error'))
30
50
  result.diagnostics.push('plan-diagnostics');
51
+ result.revision = computePlanRevision({ ...observePlanContract(plan), milestones });
31
52
  }
32
53
  catch {
33
- result.diagnostics.push('plan-diagnostics');
54
+ if (!result.diagnostics.includes('plan-diagnostics'))
55
+ result.diagnostics.push('plan-diagnostics');
34
56
  }
35
57
  }
36
58
  if (files.coordination) {
@@ -46,5 +68,8 @@ export const observeSnapshotPlan = async (directory, files) => {
46
68
  result.diagnostics.push('coordination-invalid');
47
69
  }
48
70
  }
71
+ const revision = result.revision;
72
+ if (recordedRevisions.some((recorded) => !revision || !isSamePlanRevision(recorded, revision)))
73
+ result.diagnostics.push('plan-changed');
49
74
  return result;
50
75
  };
@@ -0,0 +1,15 @@
1
+ import { type ISnapshotSource, type IHqSnapshotInspection } from './types.js';
2
+ /**
3
+ * Streams the shared format-1 capture and verifies it before transferring destination ownership.
4
+ * The caller holds the coordination metadata lock; native work continues during the database
5
+ * backup, and each plan is copied under its own document locks. No full inventory is retained.
6
+ * @returns The fully verified snapshot, retained by the caller after this resolves.
7
+ * @throws
8
+ * - JG_AGENT_HQ_STORE_FAILED: The HQ store failed
9
+ * - JG_PLANS_LOCK_BUSY: The plan document is locked
10
+ * - JG_PLANS_LOCK_FAILED: The plan document lock operation failed
11
+ * - JG_AGENT_HQ_SNAPSHOT_INVALID: The HQ snapshot is invalid
12
+ * - JG_AGENT_HQ_SNAPSHOT_FAILED: The HQ snapshot operation failed
13
+ * - JG_AGENT_HQ_STORAGE_INVALID: The HQ storage is invalid
14
+ */
15
+ export declare const captureSnapshot: (context: ISnapshotSource, destination: string) => Promise<IHqSnapshotInspection>;
@@ -0,0 +1,158 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { lstat, mkdir, open, realpath, rm } from 'node:fs/promises';
3
+ import { dirname, join } from 'node:path';
4
+ import { DatabaseSync } from 'node:sqlite';
5
+ import { hashValue } from 'jg-crypto';
6
+ import { hasErrorCode } from 'jg-exception';
7
+ import { writePrivateFile } from 'jg-fs';
8
+ import { withPlanDocumentLocks } from 'jg-plans';
9
+ import { z } from 'zod';
10
+ import { isWithinWorkspace } from '../runtime/state/index.js';
11
+ import { PACKAGE_VERSION } from '../storage/schema/index.js';
12
+ import { observeSnapshotPlan, readRecordedRevisions } from './artifacts.js';
13
+ import { SNAPSHOT_COMPLETE, SNAPSHOT_COMPANIONS, SNAPSHOT_LINE_BYTES, SNAPSHOT_MANIFEST, } from './constants.js';
14
+ import { copySnapshotFile, invalidSnapshot, reserveSnapshotDirectory, syncSnapshotDirectory, } from './files.js';
15
+ import { SnapshotHeaderSchema, SnapshotRecordSchema, } from './types.js';
16
+ /**
17
+ * Copies one plan under its shared document locks; corrupt or missing source evidence stays explicit.
18
+ * @returns One fixed-size inventory record, with no repaired or invented authority.
19
+ * @throws
20
+ * - JG_PLANS_LOCK_BUSY: The plan document is locked
21
+ * - JG_PLANS_LOCK_FAILED: The plan document lock operation failed
22
+ * - JG_AGENT_HQ_SNAPSHOT_INVALID: The HQ snapshot is invalid
23
+ * - JG_AGENT_HQ_SNAPSHOT_FAILED: The HQ snapshot operation failed
24
+ */
25
+ const capturePlan = async (context, directory, snapshot, database) => {
26
+ const record = {
27
+ kind: 'plan',
28
+ key: hashValue(directory),
29
+ sourceDirectory: directory,
30
+ planId: null,
31
+ revision: null,
32
+ recordedRevisions: [],
33
+ plan: null,
34
+ milestones: null,
35
+ coordination: null,
36
+ diagnostics: [],
37
+ };
38
+ if (!context.allowedRoots.some((root) => isWithinWorkspace(root, directory))) {
39
+ record.diagnostics.push('plan-unavailable');
40
+ return record;
41
+ }
42
+ let exists = true;
43
+ try {
44
+ if ((await realpath(directory)) !== directory || !(await lstat(directory)).isDirectory())
45
+ invalidSnapshot();
46
+ }
47
+ catch (cause) {
48
+ if (hasErrorCode(cause, 'ENOENT'))
49
+ exists = false;
50
+ else
51
+ throw cause;
52
+ }
53
+ const output = join(snapshot, 'plans', record.key);
54
+ await mkdir(output, { mode: 0o700 });
55
+ if (exists)
56
+ await withPlanDocumentLocks(directory, ['plan', 'milestones'], async () => {
57
+ for (const [field, filename, maximumBytes] of SNAPSHOT_COMPANIONS)
58
+ record[field] = await copySnapshotFile(join(directory, filename), join(output, filename), maximumBytes, false, true);
59
+ });
60
+ Object.assign(record, await observeSnapshotPlan(output, record, readRecordedRevisions(database, directory)));
61
+ await syncSnapshotDirectory(output);
62
+ return record;
63
+ };
64
+ /**
65
+ * Streams the shared format-1 capture and verifies it before transferring destination ownership.
66
+ * The caller holds the coordination metadata lock; native work continues during the database
67
+ * backup, and each plan is copied under its own document locks. No full inventory is retained.
68
+ * @returns The fully verified snapshot, retained by the caller after this resolves.
69
+ * @throws
70
+ * - JG_AGENT_HQ_STORE_FAILED: The HQ store failed
71
+ * - JG_PLANS_LOCK_BUSY: The plan document is locked
72
+ * - JG_PLANS_LOCK_FAILED: The plan document lock operation failed
73
+ * - JG_AGENT_HQ_SNAPSHOT_INVALID: The HQ snapshot is invalid
74
+ * - JG_AGENT_HQ_SNAPSHOT_FAILED: The HQ snapshot operation failed
75
+ * - JG_AGENT_HQ_STORAGE_INVALID: The HQ storage is invalid
76
+ */
77
+ export const captureSnapshot = async (context, destination) => {
78
+ let owned;
79
+ try {
80
+ owned = await reserveSnapshotDirectory(destination);
81
+ await mkdir(join(owned, 'plans'), { mode: 0o700 });
82
+ const manifest = await open(join(owned, SNAPSHOT_MANIFEST), 'wx', 0o600);
83
+ const hash = createHash('sha256');
84
+ let records = 0;
85
+ const append = async (record) => {
86
+ const bytes = Buffer.from(JSON.stringify(SnapshotRecordSchema.parse(record)) + '\n');
87
+ if (bytes.length > SNAPSHOT_LINE_BYTES)
88
+ invalidSnapshot();
89
+ await manifest.writeFile(bytes);
90
+ hash.update(bytes);
91
+ records++;
92
+ };
93
+ try {
94
+ await append(SnapshotHeaderSchema.parse({
95
+ kind: 'header',
96
+ format: 1,
97
+ createdAt: new Date().toISOString(),
98
+ schemaHash: context.schemaHash,
99
+ packageVersion: PACKAGE_VERSION,
100
+ sourceStateRoot: context.stateRoot,
101
+ sourceCoordinationRoot: context.coordinationRoot,
102
+ sourceAllowedRoots: context.allowedRoots,
103
+ }));
104
+ const database = await open(join(owned, 'hq.sqlite'), 'wx', 0o600);
105
+ await database.close();
106
+ await context.backupDatabase(join(owned, 'hq.sqlite'));
107
+ const capturedDatabase = await copySnapshotFile(join(owned, 'hq.sqlite'), null);
108
+ if (!capturedDatabase)
109
+ invalidSnapshot();
110
+ await append({ kind: 'database', file: capturedDatabase });
111
+ const key = await copySnapshotFile(join(context.stateRoot, 'action.key'), join(owned, 'action.key'), 32);
112
+ if (key?.bytes !== 32 || key.sha256 !== context.actionKeyHash)
113
+ invalidSnapshot();
114
+ await append({ kind: 'action-key', file: key });
115
+ // plans registered after the backup belong to the next capture, so page the captured copy
116
+ const captured = new DatabaseSync(join(owned, 'hq.sqlite'), { readOnly: true });
117
+ try {
118
+ let after = '';
119
+ for (;;) {
120
+ const page = captured
121
+ .prepare('SELECT directory FROM hq_plan_registration WHERE directory > ? ORDER BY directory LIMIT 128')
122
+ .all(after)
123
+ .map((row) => z.string().parse(row.directory));
124
+ for (const directory of page) {
125
+ await append(await capturePlan(context, directory, owned, captured));
126
+ after = directory;
127
+ }
128
+ if (page.length < 128)
129
+ break;
130
+ }
131
+ }
132
+ finally {
133
+ captured.close();
134
+ }
135
+ await manifest.sync();
136
+ await syncSnapshotDirectory(join(owned, 'plans'));
137
+ await writePrivateFile(join(owned, SNAPSHOT_COMPLETE), JSON.stringify({ manifestSha256: hash.digest('hex'), records }) + '\n', { rootPath: owned, isExclusive: true });
138
+ await syncSnapshotDirectory(owned);
139
+ await syncSnapshotDirectory(dirname(owned));
140
+ }
141
+ finally {
142
+ await manifest.close();
143
+ }
144
+ return await context.verify(owned);
145
+ }
146
+ catch (cause) {
147
+ if (owned) {
148
+ try {
149
+ await rm(owned, { recursive: true });
150
+ await syncSnapshotDirectory(dirname(owned));
151
+ }
152
+ catch (cleanup) {
153
+ throw new AggregateError([cause, cleanup], 'Snapshot cleanup failed');
154
+ }
155
+ }
156
+ throw cause;
157
+ }
158
+ };
@@ -4,6 +4,7 @@ import { type IHqSnapshotInspection } from './types.js';
4
4
  * Memory stays bounded by one manifest line, one plan page and one report payload.
5
5
  * @returns Validated metadata without loading the growing inventory into the caller.
6
6
  * @throws
7
+ * - JG_AGENT_HQ_STORAGE_INVALID: The HQ storage is invalid
7
8
  * - JG_AGENT_HQ_SNAPSHOT_INVALID: The HQ snapshot is invalid
8
9
  */
9
10
  export declare const verifySnapshot: (directory: string) => Promise<IHqSnapshotInspection>;
@@ -12,6 +13,7 @@ export declare const verifySnapshot: (directory: string) => Promise<IHqSnapshotI
12
13
  * Only this operation's exclusively created destination is removed on a caught failure.
13
14
  * @returns The source inspection; the caller derives the fixed state/plans output paths.
14
15
  * @throws
16
+ * - JG_AGENT_HQ_STORAGE_INVALID: The HQ storage is invalid
15
17
  * - JG_AGENT_HQ_SNAPSHOT_INVALID: The HQ snapshot is invalid
16
18
  * - JG_AGENT_HQ_SNAPSHOT_FAILED: The HQ snapshot operation failed
17
19
  */