session-peer 0.3.6 → 0.5.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 (52) hide show
  1. package/CONTRIBUTING.md +6 -4
  2. package/PARITY.md +431 -6
  3. package/README.ja.md +14 -8
  4. package/README.ko.md +14 -8
  5. package/README.md +14 -8
  6. package/README.zh-CN.md +14 -8
  7. package/RELEASING.md +109 -0
  8. package/VALIDATION.md +806 -1
  9. package/dist/app-server.d.ts +207 -0
  10. package/dist/app-server.js +1044 -0
  11. package/dist/cli.js +229 -39
  12. package/dist/handoff-ledger.d.ts +103 -0
  13. package/dist/handoff-ledger.js +791 -0
  14. package/dist/handoff-observer-probe.d.ts +1 -0
  15. package/dist/handoff-observer-probe.js +170 -0
  16. package/dist/handoff-operations.d.ts +29 -0
  17. package/dist/handoff-operations.js +496 -0
  18. package/dist/handoff-writer-probe.d.ts +1 -0
  19. package/dist/handoff-writer-probe.js +146 -0
  20. package/dist/handoff.d.ts +112 -0
  21. package/dist/handoff.js +261 -0
  22. package/dist/help.js +18 -0
  23. package/dist/linux-native-probe.d.ts +1 -0
  24. package/dist/linux-native-probe.js +51 -0
  25. package/dist/linux-proc.d.ts +55 -0
  26. package/dist/linux-proc.js +150 -0
  27. package/dist/metadata-observation.d.ts +49 -0
  28. package/dist/metadata-observation.js +250 -0
  29. package/dist/native-profiles.d.ts +25 -0
  30. package/dist/native-profiles.js +62 -0
  31. package/dist/output.js +7 -1
  32. package/dist/process.d.ts +28 -0
  33. package/dist/process.js +284 -2
  34. package/dist/protocol.d.ts +2 -2
  35. package/dist/protocol.js +1 -1
  36. package/dist/send.d.ts +18 -1
  37. package/dist/send.js +91 -6
  38. package/dist/skill-metadata.js +7 -4
  39. package/dist/ssh-response.d.ts +11 -0
  40. package/dist/ssh-response.js +78 -2
  41. package/dist/ssh.d.ts +2 -1
  42. package/dist/ssh.js +37 -2
  43. package/dist/windows.d.ts +28 -0
  44. package/dist/windows.js +149 -1
  45. package/docs/api.md +255 -4
  46. package/docs/design/typescript-skill-compatibility.md +55 -2
  47. package/docs/guide.ja.md +36 -16
  48. package/docs/guide.ko.md +39 -19
  49. package/docs/guide.md +46 -20
  50. package/docs/guide.zh-CN.md +36 -16
  51. package/docs/shorthand.md +1 -1
  52. package/package.json +2 -2
@@ -0,0 +1,791 @@
1
+ // Private POSIX ledger. No native submission or transcript access occurs here.
2
+ // Fencing assumes intact retained history: unmarked clones/rollbacks cannot be
3
+ // detected by a local-only ledger. Windows ACL/bootstrap support is not claimed:
4
+ // src/windows.ts has a candidate owner-SID/protected-DACL/reparse guard, not
5
+ // connected here and not sufficient on its own; LockFileEx fencing, replace-over-open, durability and
6
+ // crash recovery have no native evidence, so every Windows ledger operation
7
+ // still fails closed (handoff_storage_unsupported) before touching storage.
8
+ import { randomBytes, randomUUID, createHash, timingSafeEqual, createCipheriv, createDecipheriv } from 'node:crypto';
9
+ import { closeSync, constants, fstatSync, fsyncSync, lstatSync, mkdirSync, openSync, readSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
10
+ import { isAbsolute, join, resolve } from 'node:path';
11
+ import { createRequire } from 'node:module';
12
+ import { canonicalId, closed, fail, HANDOFF_LIMITS, HandoffBudget, parseStrictJson, safeId, safeInteger, systemClock, validateConfirmation, validateHandoff, validateReceipt } from './handoff.js';
13
+ const reserveBytes = 65536;
14
+ export const payloadDigest = (payload) => createHash('sha256').update(payload).digest('hex');
15
+ function checkBinding(value) {
16
+ const row = closed(value, ['agent', 'destination', 'target', 'generation', 'payloadDigest'], ['home', 'writerIdentity']);
17
+ if (!['claude', 'codex'].includes(row.agent) || !safeId(row.destination, 512) || !safeId(row.target, 256) ||
18
+ (row.generation !== null && !safeId(row.generation, 256)) || typeof row.payloadDigest !== 'string' || !/^[a-f0-9]{64}$/.test(row.payloadDigest) ||
19
+ (row.home !== undefined && (!safeId(row.home, 4096) || !isAbsolute(row.home))) ||
20
+ (row.writerIdentity !== undefined && !safeId(row.writerIdentity, 256)))
21
+ fail('invalid_handoff_binding', 2);
22
+ return structuredClone(value);
23
+ }
24
+ function sameBinding(a, b) {
25
+ return ['agent', 'destination', 'target', 'home', 'writerIdentity', 'generation', 'payloadDigest'].every(key => a[key] === b[key]);
26
+ }
27
+ function checkQualification(value) {
28
+ const row = closed(value, ['version', 'commit', 'platform']);
29
+ if (!safeId(row.version, 64) || !safeId(row.platform, 64) || typeof row.commit !== 'string' || !/^[0-9a-f]{40}$/.test(row.commit))
30
+ fail('invalid_observation_qualification', 2);
31
+ return structuredClone(value);
32
+ }
33
+ function privateStat(path, directory) {
34
+ const uid = process.getuid?.();
35
+ if (uid === undefined || process.platform === 'win32')
36
+ fail('handoff_storage_unsupported');
37
+ const stat = lstatSync(path);
38
+ if (stat.isSymbolicLink() || (directory ? !stat.isDirectory() : !stat.isFile()) || stat.uid !== uid ||
39
+ (stat.mode & 0o777) !== (directory ? 0o700 : 0o600) || (!directory && stat.nlink !== 1))
40
+ fail('handoff_storage_untrusted');
41
+ return stat;
42
+ }
43
+ export class HandoffLedger {
44
+ path;
45
+ clock;
46
+ clockId = randomUUID();
47
+ constructor(path, options = {}) {
48
+ if (!isAbsolute(path))
49
+ fail('invalid_handoff_ledger', 2);
50
+ this.path = resolve(path);
51
+ this.clock = options.clock ?? systemClock;
52
+ }
53
+ filename() { return join(this.path, 'ledger.json'); }
54
+ // The separate private key is created only by fresh explicit init. A missing,
55
+ // changed or untrusted key cannot authorize migration or new submission.
56
+ key() {
57
+ const path = join(this.path, 'ledger.key'), before = privateStat(path, false);
58
+ if (before.size !== 32)
59
+ fail('handoff_ledger_corrupt');
60
+ const fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
61
+ try {
62
+ const opened = fstatSync(fd), bytes = Buffer.alloc(33);
63
+ if (opened.dev !== before.dev || opened.ino !== before.ino || opened.size !== 32 || opened.nlink !== 1 || opened.uid !== before.uid || (opened.mode & 0o777) !== 0o600)
64
+ fail('handoff_storage_untrusted');
65
+ let length = 0;
66
+ while (length < bytes.length) {
67
+ const count = readSync(fd, bytes, length, bytes.length - length, length);
68
+ if (!count)
69
+ break;
70
+ length += count;
71
+ }
72
+ const after = fstatSync(fd), current = privateStat(path, false);
73
+ if (length !== 32 || after.size !== 32 || after.mtimeMs !== opened.mtimeMs || after.ctimeMs !== opened.ctimeMs ||
74
+ after.nlink !== 1 || after.uid !== opened.uid || after.mode !== opened.mode || current.dev !== opened.dev || current.ino !== opened.ino ||
75
+ current.size !== after.size || current.mtimeMs !== after.mtimeMs || current.ctimeMs !== after.ctimeMs)
76
+ fail('handoff_storage_untrusted');
77
+ return Buffer.from(bytes.subarray(0, 32));
78
+ }
79
+ finally {
80
+ closeSync(fd);
81
+ }
82
+ }
83
+ protectDigest(digest, key, epoch, id) {
84
+ const nonce = randomBytes(12), cipher = createCipheriv('aes-256-gcm', key, nonce);
85
+ cipher.setAAD(Buffer.from(JSON.stringify(['handoff-binding-v1', epoch, id])));
86
+ const ciphertext = Buffer.concat([cipher.update(Buffer.from(digest, 'hex')), cipher.final()]);
87
+ return `sealed-v1:${nonce.toString('hex')}:${ciphertext.toString('hex')}:${cipher.getAuthTag().toString('hex')}`;
88
+ }
89
+ revealDigest(value, key, epoch, id) {
90
+ if (typeof value !== 'string' || !/^sealed-v1:[a-f0-9]{24}:[a-f0-9]{64}:[a-f0-9]{32}$/.test(value))
91
+ fail('handoff_ledger_corrupt');
92
+ const [, nonce, ciphertext, tag] = value.split(':');
93
+ const cipher = createDecipheriv('aes-256-gcm', key, Buffer.from(nonce, 'hex'));
94
+ cipher.setAAD(Buffer.from(JSON.stringify(['handoff-binding-v1', epoch, id])));
95
+ cipher.setAuthTag(Buffer.from(tag, 'hex'));
96
+ return Buffer.concat([cipher.update(Buffer.from(ciphertext, 'hex')), cipher.final()]).toString('hex');
97
+ }
98
+ lock(operation, create = false) {
99
+ try {
100
+ privateStat(this.path, true);
101
+ }
102
+ catch (error) {
103
+ if (error.code === 'ENOENT')
104
+ fail('handoff_history_unavailable');
105
+ throw error;
106
+ }
107
+ const path = join(this.path, 'ledger.lock');
108
+ if (create) {
109
+ try {
110
+ const created = openSync(path, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY, 0o600);
111
+ fsyncSync(created);
112
+ closeSync(created);
113
+ }
114
+ catch (error) {
115
+ if (error.code !== 'EEXIST')
116
+ throw error;
117
+ }
118
+ }
119
+ const before = privateStat(path, false);
120
+ const fd = openSync(path, constants.O_RDWR | constants.O_NOFOLLOW | constants.O_NONBLOCK);
121
+ try {
122
+ const opened = fstatSync(fd);
123
+ if (opened.dev !== before.dev || opened.ino !== before.ino)
124
+ fail('handoff_storage_untrusted');
125
+ const locks = createRequire(import.meta.url)('fs-ext-extra-prebuilt');
126
+ try {
127
+ locks.flockSync(fd, 'exnb');
128
+ }
129
+ catch {
130
+ fail('handoff_ledger_busy');
131
+ }
132
+ try {
133
+ return operation();
134
+ }
135
+ finally {
136
+ locks.flockSync(fd, 'un');
137
+ }
138
+ }
139
+ finally {
140
+ closeSync(fd);
141
+ }
142
+ }
143
+ read() {
144
+ privateStat(this.path, true);
145
+ const path = this.filename(), stat = privateStat(path, false);
146
+ if (stat.size > HANDOFF_LIMITS.journal)
147
+ fail('handoff_ledger_corrupt');
148
+ const fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
149
+ let bytes;
150
+ try {
151
+ const opened = fstatSync(fd);
152
+ if (opened.dev !== stat.dev || opened.ino !== stat.ino || opened.size > HANDOFF_LIMITS.journal)
153
+ fail('handoff_storage_untrusted');
154
+ const buffer = Buffer.alloc(Math.min(opened.size + 1, HANDOFF_LIMITS.journal + 1));
155
+ let length = 0;
156
+ while (length < buffer.length) {
157
+ const count = readSync(fd, buffer, length, buffer.length - length, length);
158
+ if (!count)
159
+ break;
160
+ length += count;
161
+ }
162
+ if (length > opened.size || length > HANDOFF_LIMITS.journal)
163
+ fail('handoff_ledger_corrupt');
164
+ bytes = buffer.subarray(0, length);
165
+ }
166
+ finally {
167
+ closeSync(fd);
168
+ }
169
+ try {
170
+ const wrapper = closed(parseStrictJson(bytes, { scope: 'outer', maxBytes: HANDOFF_LIMITS.journal }), ['digest', 'data']);
171
+ if (typeof wrapper.digest !== 'string' || wrapper.digest !== payloadDigest(JSON.stringify(wrapper.data)))
172
+ fail();
173
+ const data = closed(wrapper.data, ['version', 'epoch', 'keyId', 'quarantined', 'records']);
174
+ if (data.version !== 1 || !canonicalId(data.epoch) || typeof data.quarantined !== 'boolean' || !data.records || typeof data.records !== 'object' || Array.isArray(data.records))
175
+ fail();
176
+ const key = this.key();
177
+ if (data.keyId !== payloadDigest(key))
178
+ fail();
179
+ const records = data.records;
180
+ if (Object.keys(records).length > HANDOFF_LIMITS.intents)
181
+ fail();
182
+ for (const [id, item] of Object.entries(records)) {
183
+ closed(item, ['binding', 'preparedUtc', 'clockId', 'preparedMono', 'phase', 'handoff', 'waits', 'reserve'], ['capabilityHash', 'capabilityClockId', 'receiptId', 'revoked', 'expired', 'deliverySupported', 'clientUserMessageId', 'observationQualification']);
184
+ if (!canonicalId(id))
185
+ fail();
186
+ item.binding = { ...item.binding, payloadDigest: this.revealDigest(item.binding?.payloadDigest, key, data.epoch, id) };
187
+ checkBinding(item.binding);
188
+ if (item.observationQualification !== undefined)
189
+ checkQualification(item.observationQualification);
190
+ if (!canonicalId(id) || !canonicalId(item.clockId) || !safeInteger(item.preparedUtc) || typeof item.preparedMono !== 'number' || item.preparedMono < 0 ||
191
+ !['prepared', 'attempted', 'finished', 'refused'].includes(item.phase) || !Array.isArray(item.waits) || item.waits.length > HANDOFF_LIMITS.waits ||
192
+ !safeInteger(item.reserve) || item.reserve > reserveBytes || (item.capabilityHash !== undefined && !/^[a-f0-9]{64}$/.test(item.capabilityHash)) ||
193
+ (item.capabilityClockId !== undefined && !canonicalId(item.capabilityClockId)) ||
194
+ (item.receiptId !== undefined && !canonicalId(item.receiptId)) ||
195
+ (item.deliverySupported !== undefined && typeof item.deliverySupported !== 'boolean') ||
196
+ (item.clientUserMessageId !== undefined && !safeId(item.clientUserMessageId)) ||
197
+ (item.deliverySupported && (!safeId(item.clientUserMessageId) || item.binding.generation === null)))
198
+ fail();
199
+ const h = validateHandoff(item.handoff);
200
+ if (h.correlationId !== id || h.ledgerEpoch !== data.epoch || h.targetGeneration !== item.binding.generation)
201
+ fail();
202
+ for (const wait of item.waits) {
203
+ closed(wait, ['public', 'clockId', 'cutoff']);
204
+ if (!canonicalId(wait.clockId) || typeof wait.cutoff !== 'number' || !Number.isFinite(wait.cutoff))
205
+ fail();
206
+ // Current actions belong to the latest operation, not archived waits.
207
+ validateHandoff({ ...h, wait: wait.public, nextActions: ['reconcile'] });
208
+ }
209
+ }
210
+ return data;
211
+ }
212
+ catch {
213
+ fail('handoff_ledger_corrupt');
214
+ }
215
+ }
216
+ write(data) {
217
+ for (const item of Object.values(data.records))
218
+ validateHandoff(item.handoff);
219
+ const key = this.key();
220
+ if (data.keyId !== payloadDigest(key))
221
+ fail('handoff_ledger_corrupt');
222
+ const stored = structuredClone(data);
223
+ for (const [id, item] of Object.entries(stored.records)) {
224
+ checkBinding(item.binding);
225
+ item.binding = { ...item.binding, payloadDigest: this.protectDigest(item.binding.payloadDigest, key, data.epoch, id) };
226
+ }
227
+ // Both quota accounting and the corruption checksum use only ciphertext.
228
+ // A checksum over transient plaintext would itself permit payload guessing.
229
+ const text = JSON.stringify({ digest: payloadDigest(JSON.stringify(stored)), data: stored });
230
+ const reserves = Object.values(stored.records).reduce((sum, item) => sum + Math.max(0, item.reserve - Buffer.byteLength(JSON.stringify(item))), 0);
231
+ if (Buffer.byteLength(text) + reserves > HANDOFF_LIMITS.journal)
232
+ fail('handoff_ledger_full');
233
+ const temporary = join(this.path, `.ledger-${randomUUID()}.tmp`);
234
+ const fd = openSync(temporary, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600);
235
+ try {
236
+ writeFileSync(fd, text, 'utf8');
237
+ fsyncSync(fd);
238
+ }
239
+ catch (error) {
240
+ try {
241
+ unlinkSync(temporary);
242
+ }
243
+ catch { }
244
+ throw error;
245
+ }
246
+ finally {
247
+ closeSync(fd);
248
+ }
249
+ try {
250
+ renameSync(temporary, this.filename());
251
+ const directory = openSync(this.path, constants.O_RDONLY);
252
+ try {
253
+ fsyncSync(directory);
254
+ }
255
+ finally {
256
+ closeSync(directory);
257
+ }
258
+ }
259
+ catch (error) {
260
+ try {
261
+ unlinkSync(temporary);
262
+ }
263
+ catch { }
264
+ throw error;
265
+ }
266
+ }
267
+ init() {
268
+ if (process.platform === 'win32' || process.getuid?.() === undefined)
269
+ fail('handoff_storage_unsupported');
270
+ try {
271
+ mkdirSync(this.path, { mode: 0o700 });
272
+ }
273
+ catch (error) {
274
+ if (error.code !== 'EEXIST')
275
+ throw error;
276
+ }
277
+ return this.lock(() => {
278
+ try {
279
+ lstatSync(this.filename());
280
+ fail('handoff_ledger_exists');
281
+ }
282
+ catch (error) {
283
+ if (error.code !== 'ENOENT')
284
+ throw error;
285
+ }
286
+ const key = randomBytes(32), keyPath = join(this.path, 'ledger.key');
287
+ const keyFd = openSync(keyPath, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600);
288
+ try {
289
+ writeFileSync(keyFd, key);
290
+ fsyncSync(keyFd);
291
+ }
292
+ finally {
293
+ closeSync(keyFd);
294
+ }
295
+ const directory = openSync(this.path, constants.O_RDONLY);
296
+ try {
297
+ fsyncSync(directory);
298
+ }
299
+ finally {
300
+ closeSync(directory);
301
+ }
302
+ const epoch = randomUUID();
303
+ this.write({ version: 1, epoch, keyId: payloadDigest(key), quarantined: false, records: {} });
304
+ return { ledgerEpoch: epoch, storage: 'private_posix', cloneRollbackProtection: 'intact_retained_history_only' };
305
+ }, true);
306
+ }
307
+ usable(data, id) {
308
+ if (!canonicalId(id))
309
+ fail('invalid_correlation_id', 2);
310
+ const item = data.records[id];
311
+ if (!item)
312
+ fail('handoff_id_unknown');
313
+ if (data.quarantined)
314
+ fail('handoff_ledger_quarantined');
315
+ if (item.expired || this.clock.utc() - item.preparedUtc >= HANDOFF_LIMITS.detailMs)
316
+ fail('handoff_history_unavailable');
317
+ return item;
318
+ }
319
+ snapshot(item, quarantine = false, currentWait = item.waits.at(-1)) {
320
+ const h = structuredClone(item.handoff);
321
+ if (quarantine || item.expired || this.clock.utc() - item.preparedUtc >= HANDOFF_LIMITS.detailMs) {
322
+ h.state = 'unknown';
323
+ h.submission = { status: 'unknown' };
324
+ h.observation = { status: 'not_requested', injectionObserved: false };
325
+ h.ack = { status: 'unsupported' };
326
+ h.wait = { for: 'none', status: 'not_requested' };
327
+ h.nextActions = ['reconcile'];
328
+ }
329
+ else if (item.phase === 'attempted') {
330
+ h.state = 'unknown';
331
+ h.submission = { status: 'unknown' };
332
+ h.nextActions = ['reconcile'];
333
+ }
334
+ if ((item.capabilityClockId !== this.clockId || item.revoked || this.clock.monotonic() - item.preparedMono >= HANDOFF_LIMITS.capabilityMs) && h.ack.status === 'pending') {
335
+ h.ack = { status: 'unsupported' };
336
+ h.nextActions = ['reconcile'];
337
+ }
338
+ const resumed = item.observationQualification !== undefined && currentWait?.clockId === this.clockId && currentWait.public.for === 'delivered' && currentWait.public.status === 'pending';
339
+ if (item.clockId !== this.clockId && h.observation.status === 'pending' && !resumed) {
340
+ h.observation = { status: 'unsupported', injectionObserved: false };
341
+ h.nextActions = ['reconcile'];
342
+ }
343
+ return validateHandoff(h);
344
+ }
345
+ status(id) {
346
+ if (!canonicalId(id))
347
+ fail('invalid_correlation_id', 2);
348
+ let context = 'ledger_corrupt';
349
+ try {
350
+ const data = this.read(), item = data.records[id];
351
+ if (item)
352
+ return { handoff: this.snapshot(item, data.quarantined) };
353
+ context = 'id_unknown';
354
+ }
355
+ catch (error) {
356
+ if (error.code === 'ENOENT')
357
+ context = 'ledger_missing';
358
+ }
359
+ return { reason: 'handoff_history_unavailable', handoffQuery: { schemaVersion: 1, correlationId: id, status: 'unknown', context, retry: { allowed: false, reason: 'history_unavailable' } } };
360
+ }
361
+ selectWait(item, operationId) {
362
+ if (operationId !== undefined && !canonicalId(operationId))
363
+ fail('invalid_wait_operation_id', 2);
364
+ const wait = operationId === undefined ? item.waits.at(-1) : item.waits.find(value => value.public.operationId === operationId);
365
+ if (!wait)
366
+ fail('handoff_wait_unknown');
367
+ return wait;
368
+ }
369
+ operationSnapshot(item, wait) {
370
+ const h = this.snapshot(item, false, wait);
371
+ h.wait = structuredClone(wait.public);
372
+ // Actions from the latest wait cannot be projected onto a different operation.
373
+ h.nextActions = ['reconcile'];
374
+ return validateHandoff(h);
375
+ }
376
+ operationStatus(id, operationId) {
377
+ const data = this.read(), item = this.usable(data, id);
378
+ return this.operationSnapshot(item, this.selectWait(item, operationId));
379
+ }
380
+ // Private projection only. Do not return this binding/digest or qualification
381
+ // in ordinary JSON. Missing historical provenance cannot be reconstructed
382
+ // from today's native executable or a matching database schema.
383
+ observationContext(id) {
384
+ const data = this.read(), item = this.usable(data, id);
385
+ if (item.phase !== 'finished' || item.handoff.submission.status !== 'submitted' || !item.deliverySupported ||
386
+ !item.observationQualification || item.binding.agent !== 'codex' || !item.binding.home ||
387
+ !item.binding.generation || item.binding.writerIdentity !== item.binding.generation || !item.clientUserMessageId)
388
+ return undefined;
389
+ return structuredClone({ binding: item.binding, clientUserMessageId: item.clientUserMessageId, qualification: item.observationQualification });
390
+ }
391
+ prepare(binding, options = {}) {
392
+ binding = checkBinding(binding);
393
+ if (options.dryRun && (options.requestAck || options.observeDelivery || (options.waitFor && options.waitFor !== 'none')))
394
+ fail('incompatible_handoff_dry_run', 2);
395
+ if (options.correlationId && !canonicalId(options.correlationId))
396
+ fail('invalid_correlation_id', 2);
397
+ return this.lock(() => {
398
+ const data = this.read();
399
+ if (data.quarantined)
400
+ fail('handoff_ledger_quarantined');
401
+ let id = options.correlationId;
402
+ if (id) {
403
+ const item = this.usable(data, id);
404
+ if (!sameBinding(item.binding, binding))
405
+ fail('handoff_binding_conflict');
406
+ if (item.phase !== 'prepared')
407
+ fail('handoff_already_attempted');
408
+ if (!options.dryRun) {
409
+ this.configure(item, options);
410
+ this.write(data);
411
+ }
412
+ return this.snapshot(item);
413
+ }
414
+ if (options.dryRun)
415
+ fail('prepared_correlation_required', 2);
416
+ if (Object.keys(data.records).length >= HANDOFF_LIMITS.intents)
417
+ fail('handoff_ledger_full');
418
+ id = randomUUID();
419
+ const goal = options.waitFor ?? 'none';
420
+ if (!['none', 'delivered', 'acknowledged'].includes(goal))
421
+ fail('invalid_wait_for', 2);
422
+ // Runtime channels remain unsupported until a compatible private bootstrap
423
+ // and producer are proven by the integration, not merely by generation.
424
+ const h = { schemaVersion: 1, correlationId: id, ledgerEpoch: data.epoch, state: 'validated', submission: { status: 'not_attempted' },
425
+ observation: { status: options.observeDelivery ? 'unsupported' : 'not_requested', injectionObserved: false },
426
+ ack: { status: options.requestAck ? 'unsupported' : 'not_requested' }, wait: { for: 'none', status: 'not_requested' },
427
+ targetGeneration: binding.generation, decisionOwner: 'sender_operator', retry: { allowed: false, reason: 'receiver_dedup_unavailable' }, nextActions: [] };
428
+ const item = { binding, preparedUtc: Math.floor(this.clock.utc()), clockId: this.clockId, preparedMono: this.clock.monotonic(), phase: 'prepared', handoff: h, waits: [], reserve: reserveBytes };
429
+ data.records[id] = item;
430
+ this.configure(item, options);
431
+ this.write(data);
432
+ return this.snapshot(item);
433
+ });
434
+ }
435
+ configure(item, options) {
436
+ const h = item.handoff, goal = options.waitFor ?? 'none';
437
+ if (!['none', 'delivered', 'acknowledged'].includes(goal))
438
+ fail('invalid_wait_for', 2);
439
+ if (options.clientUserMessageId !== undefined && !safeId(options.clientUserMessageId))
440
+ fail('invalid_client_user_message_id', 2);
441
+ const clientId = options.clientUserMessageId ?? h.correlationId;
442
+ if (item.clientUserMessageId !== undefined && item.clientUserMessageId !== clientId)
443
+ fail('handoff_binding_conflict');
444
+ if (options.requestAck)
445
+ h.ack.status = 'unsupported';
446
+ const delivery = (options.observationSupported === true || options.channels?.delivery === true) && item.binding.generation !== null;
447
+ if (options.observeDelivery || goal === 'delivered') {
448
+ item.deliverySupported = delivery;
449
+ item.clientUserMessageId = clientId;
450
+ h.observation.status = delivery ? 'pending' : 'unsupported';
451
+ if (delivery && options.observationQualification !== undefined) {
452
+ const qualification = checkQualification(options.observationQualification);
453
+ if (item.observationQualification && JSON.stringify(item.observationQualification) !== JSON.stringify(qualification))
454
+ fail('handoff_binding_conflict');
455
+ item.observationQualification = qualification;
456
+ }
457
+ else
458
+ delete item.observationQualification;
459
+ }
460
+ else {
461
+ // A prepared reservation may be reused by a non-observing submission.
462
+ // Its old native qualification must not describe that different path.
463
+ item.deliverySupported = false;
464
+ delete item.observationQualification;
465
+ h.observation = { status: 'not_requested', injectionObserved: false };
466
+ }
467
+ if (goal !== 'none') {
468
+ const budget = options.budget ?? new HandoffBudget(30, this.clock);
469
+ this.addWait(item, goal, budget);
470
+ if (goal === 'delivered' && delivery)
471
+ h.wait.status = 'pending';
472
+ else {
473
+ h.wait.status = 'unsupported';
474
+ h.wait.reason = 'evidence_unsupported';
475
+ }
476
+ try {
477
+ budget.beforeEffect();
478
+ }
479
+ catch (error) {
480
+ h.wait.status = 'failed';
481
+ h.wait.reason = error.code;
482
+ }
483
+ if (goal === 'acknowledged')
484
+ h.ack.status = 'unsupported';
485
+ if (h.wait.status !== 'pending') {
486
+ h.state = 'refused';
487
+ h.submission.status = 'refused';
488
+ item.phase = 'refused';
489
+ }
490
+ item.waits.at(-1).public = structuredClone(h.wait);
491
+ }
492
+ }
493
+ // Durable intent is synced before returning authorization to the caller.
494
+ // A crash after this point, even before native effect, can never authorize retry.
495
+ commitEffect(id, binding, budget) {
496
+ binding = checkBinding(binding);
497
+ return this.lock(() => {
498
+ const data = this.read(), item = this.usable(data, id);
499
+ if (!sameBinding(item.binding, binding))
500
+ fail('handoff_binding_conflict');
501
+ if (item.phase !== 'prepared')
502
+ fail('handoff_already_attempted');
503
+ try {
504
+ budget?.beforeEffect();
505
+ }
506
+ catch (error) {
507
+ this.refuse(item, error.code);
508
+ this.write(data);
509
+ throw error;
510
+ }
511
+ item.phase = 'attempted';
512
+ item.clockId = this.clockId;
513
+ item.handoff.state = 'unknown';
514
+ item.handoff.submission.status = 'unknown';
515
+ item.handoff.nextActions = ['reconcile'];
516
+ this.write(data);
517
+ return this.snapshot(item);
518
+ });
519
+ }
520
+ refuse(item, reason) {
521
+ item.phase = 'refused';
522
+ item.handoff.state = 'refused';
523
+ item.handoff.submission.status = 'refused';
524
+ item.handoff.nextActions = [];
525
+ if (item.handoff.observation.status === 'pending')
526
+ item.handoff.observation = { status: 'failed', injectionObserved: false };
527
+ if (item.handoff.ack.status === 'pending') {
528
+ item.handoff.ack = { status: 'unsupported' };
529
+ item.revoked = true;
530
+ }
531
+ const wait = item.waits.at(-1);
532
+ if (wait?.public.status === 'pending') {
533
+ item.handoff.wait.status = 'failed';
534
+ item.handoff.wait.reason = reason ?? 'evidence_failed';
535
+ wait.public = structuredClone(item.handoff.wait);
536
+ }
537
+ }
538
+ refusePrepared(id, binding, reason) {
539
+ binding = checkBinding(binding);
540
+ return this.lock(() => {
541
+ const data = this.read(), item = this.usable(data, id);
542
+ if (!sameBinding(item.binding, binding))
543
+ fail('handoff_binding_conflict');
544
+ if (item.phase !== 'prepared')
545
+ fail('handoff_already_attempted');
546
+ this.refuse(item, reason);
547
+ this.write(data);
548
+ return this.snapshot(item);
549
+ });
550
+ }
551
+ recordSubmission(id, status) {
552
+ return this.lock(() => {
553
+ const data = this.read(), item = this.usable(data, id);
554
+ if (item.phase !== 'attempted' || item.clockId !== this.clockId)
555
+ fail('handoff_outcome_not_authorized');
556
+ item.phase = 'finished';
557
+ item.handoff.submission.status = status;
558
+ item.handoff.state = status;
559
+ item.handoff.nextActions = ['reconcile'];
560
+ if (status === 'refused')
561
+ this.refuse(item, 'evidence_failed');
562
+ this.write(data);
563
+ return this.snapshot(item);
564
+ });
565
+ }
566
+ recordObservation(id, observation, originalBinding) {
567
+ originalBinding = checkBinding(originalBinding);
568
+ closed(observation, ['clientUserMessageId', 'injectionObserved'], ['turn']);
569
+ if (!safeId(observation.clientUserMessageId) || typeof observation.injectionObserved !== 'boolean' ||
570
+ (!observation.injectionObserved && observation.turn !== undefined))
571
+ fail('invalid_handoff_observation');
572
+ return this.lock(() => {
573
+ const data = this.read(), item = this.usable(data, id), h = item.handoff;
574
+ if (!sameBinding(item.binding, originalBinding))
575
+ fail('handoff_binding_conflict');
576
+ if (!item.deliverySupported || item.binding.generation === null || item.clientUserMessageId !== observation.clientUserMessageId ||
577
+ item.phase !== 'finished' || h.submission.status !== 'submitted')
578
+ fail('handoff_observation_unverified');
579
+ if (!observation.injectionObserved)
580
+ return this.snapshot(item);
581
+ if (observation.turn !== undefined) {
582
+ closed(observation.turn, ['id', 'status']);
583
+ if (!safeId(observation.turn.id) || !['running', 'completed', 'failed', 'interrupted', 'unknown'].includes(observation.turn.status))
584
+ fail('invalid_handoff_observation');
585
+ const prior = h.observation.turn;
586
+ if (prior && (prior.id !== observation.turn.id || (['completed', 'failed', 'interrupted'].includes(prior.status) && prior.status !== observation.turn.status)))
587
+ fail('handoff_turn_conflict');
588
+ }
589
+ h.observation = { status: 'observed', injectionObserved: true, clientUserMessageId: observation.clientUserMessageId,
590
+ ...(observation.turn ? { turn: structuredClone(observation.turn) } : h.observation.turn ? { turn: h.observation.turn } : {}) };
591
+ if (h.ack.status !== 'acknowledged')
592
+ h.state = 'delivered';
593
+ // All delivery operations share this evidence instant, but keep their own
594
+ // cutoff and terminal result. A newer ACK wait cannot hide older waits.
595
+ const observedAt = this.clock.monotonic();
596
+ for (const wait of item.waits) {
597
+ // A resumed or concurrent observer owns its own monotonic cutoff. Keep
598
+ // foreign operations unclassified so their live owner can resolve them.
599
+ if (wait.public.status !== 'pending' || wait.public.for !== 'delivered' || wait.clockId !== this.clockId)
600
+ continue;
601
+ wait.public.status = observedAt < wait.cutoff ? 'satisfied' : 'timed_out_unknown';
602
+ }
603
+ if (item.waits.length)
604
+ h.wait = structuredClone(item.waits.at(-1).public);
605
+ h.nextActions = ['reconcile'];
606
+ this.write(data);
607
+ return this.snapshot(item);
608
+ });
609
+ }
610
+ recordObservationFailure(id, originalBinding, status, operationId) {
611
+ originalBinding = checkBinding(originalBinding);
612
+ if (!['unsupported', 'failed'].includes(status))
613
+ fail('invalid_handoff_observation');
614
+ return this.lock(() => {
615
+ const data = this.read(), item = this.usable(data, id), h = item.handoff;
616
+ if (!sameBinding(item.binding, originalBinding) || !item.deliverySupported || h.submission.status !== 'submitted')
617
+ fail('handoff_observation_unqualified');
618
+ const wait = operationId !== undefined ? this.selectWait(item, operationId) : item.waits.at(-1);
619
+ if (!h.observation.injectionObserved)
620
+ h.observation = { status, injectionObserved: false };
621
+ if (wait?.public.status === 'pending') {
622
+ wait.public.status = status;
623
+ wait.public.reason = status === 'unsupported' ? 'evidence_unsupported' : 'evidence_failed';
624
+ }
625
+ if (item.waits.length)
626
+ h.wait = structuredClone(item.waits.at(-1).public);
627
+ h.nextActions = ['reconcile'];
628
+ this.write(data);
629
+ return operationId !== undefined ? this.operationSnapshot(item, wait) : this.snapshot(item);
630
+ });
631
+ }
632
+ addWait(item, goal, budget) {
633
+ if (item.waits.length >= HANDOFF_LIMITS.waits)
634
+ fail('handoff_wait_quota');
635
+ item.handoff.wait = { for: goal, status: 'pending', operationId: randomUUID(), deadlineAtUtcMs: budget.deadlineAtUtcMs };
636
+ item.waits.push({ public: structuredClone(item.handoff.wait), clockId: this.clockId, cutoff: budget.cutoff });
637
+ }
638
+ beginWait(id, goal, budget = new HandoffBudget(30, this.clock), options = {}) {
639
+ if (!['delivered', 'acknowledged'].includes(goal))
640
+ fail('invalid_wait_for', 2);
641
+ return this.lock(() => {
642
+ const data = this.read(), item = this.usable(data, id);
643
+ this.addWait(item, goal, budget);
644
+ const h = item.handoff;
645
+ h.nextActions = ['reconcile'];
646
+ if ((goal === 'acknowledged' && h.ack.status === 'acknowledged') || (goal === 'delivered' && h.observation.injectionObserved))
647
+ h.wait.status = 'satisfied';
648
+ else if (budget.seconds <= 5) {
649
+ h.wait.status = 'failed';
650
+ h.wait.reason = 'insufficient_budget';
651
+ }
652
+ else if (goal === 'delivered' && item.deliverySupported && item.binding.generation !== null && h.submission.status === 'submitted' &&
653
+ (options.observationSupported === true ? item.observationQualification !== undefined : options.observationSupported === undefined && item.clockId === this.clockId)) {
654
+ h.observation = { status: 'pending', injectionObserved: false };
655
+ h.nextActions = ['keep_waiting', 'reconcile', 'stop_waiting'];
656
+ }
657
+ else if (goal === 'acknowledged' && item.capabilityHash && !item.revoked && item.capabilityClockId === this.clockId &&
658
+ this.clock.monotonic() - item.preparedMono < HANDOFF_LIMITS.capabilityMs && item.binding.generation !== null && h.submission.status === 'submitted') {
659
+ h.ack.status = 'pending';
660
+ h.nextActions = ['keep_waiting', 'reconcile', 'stop_waiting'];
661
+ }
662
+ else {
663
+ h.wait.status = 'unsupported';
664
+ h.wait.reason = 'evidence_unsupported';
665
+ }
666
+ item.waits.at(-1).public = structuredClone(h.wait);
667
+ this.write(data);
668
+ return this.snapshot(item);
669
+ });
670
+ }
671
+ recordWait(id, status, reason, operationId) {
672
+ return this.lock(() => {
673
+ const data = this.read(), item = this.usable(data, id), wait = this.selectWait(item, operationId);
674
+ if (wait.public.status !== 'pending')
675
+ fail('handoff_wait_terminal');
676
+ if (status === 'timed_out_unknown' && (wait.clockId !== this.clockId || this.clock.monotonic() < wait.cutoff))
677
+ fail('receipt_order_unprovable');
678
+ wait.public.status = status;
679
+ if (reason)
680
+ wait.public.reason = reason;
681
+ if (status === 'timed_out_unknown' && !item.handoff.observation.injectionObserved && item.handoff.ack.status !== 'acknowledged')
682
+ item.handoff.state = 'timed_out_unknown';
683
+ item.handoff.nextActions = ['reconcile'];
684
+ item.handoff.wait = structuredClone(item.waits.at(-1).public);
685
+ validateHandoff({ ...item.handoff, wait: wait.public });
686
+ this.write(data);
687
+ return operationId !== undefined ? this.operationSnapshot(item, wait) : this.snapshot(item);
688
+ });
689
+ }
690
+ commitAck(item, assurance) {
691
+ const h = item.handoff, origin = item.waits[0];
692
+ // Classify every pending ACK operation against one observed instant. A
693
+ // newer wait must not hide an older operation's deadline or clock loss.
694
+ const now = this.clock.monotonic();
695
+ const pending = item.waits.filter(wait => wait.public.status === 'pending' && wait.public.for === 'acknowledged');
696
+ if (pending.some(wait => wait.clockId !== this.clockId))
697
+ fail('receipt_order_unprovable');
698
+ let late = false;
699
+ if (origin) {
700
+ if (origin.public.status === 'timed_out_unknown')
701
+ late = true;
702
+ else if (origin.clockId === this.clockId)
703
+ late = now >= origin.cutoff;
704
+ else
705
+ fail('receipt_order_unprovable');
706
+ }
707
+ h.state = 'acknowledged';
708
+ h.ack = { status: 'acknowledged', assurance, receivedAtUtcMs: Math.floor(this.clock.utc()), late };
709
+ for (const wait of pending)
710
+ wait.public.status = now < wait.cutoff ? 'satisfied' : 'timed_out_unknown';
711
+ if (item.waits.length)
712
+ h.wait = structuredClone(item.waits.at(-1).public);
713
+ h.nextActions = ['reconcile'];
714
+ }
715
+ confirm(raw) {
716
+ const proof = validateConfirmation(raw);
717
+ return this.lock(() => {
718
+ const data = this.read(), item = this.usable(data, proof.correlationId);
719
+ if (data.epoch !== proof.ledgerEpoch || item.binding.generation !== proof.targetGeneration || item.handoff.submission.status !== 'submitted')
720
+ fail('confirmation_binding_invalid');
721
+ if (item.handoff.ack.status === 'acknowledged')
722
+ return this.snapshot(item);
723
+ this.commitAck(item, 'operator_confirmed');
724
+ this.write(data);
725
+ return this.snapshot(item);
726
+ });
727
+ }
728
+ // Caller must already validate a compatible private receipt-only producer.
729
+ // This returns authority for authorized private effect input only; never argv,
730
+ // environment, public output or persistence. The raw value is not recoverable.
731
+ mintCapability(id, bootstrap) {
732
+ if (bootstrap.privateConsumerValidated !== true || bootstrap.compatibleProducerValidated !== true)
733
+ fail('receipt_bootstrap_unsupported');
734
+ return this.lock(() => {
735
+ const data = this.read(), item = this.usable(data, id);
736
+ if (item.phase !== 'prepared' || item.binding.generation === null || item.capabilityHash || item.clockId !== this.clockId ||
737
+ this.clock.monotonic() - item.preparedMono >= HANDOFF_LIMITS.capabilityMs)
738
+ fail('receipt_authority_unavailable');
739
+ const capability = randomBytes(32).toString('base64url');
740
+ item.capabilityHash = payloadDigest(capability);
741
+ item.capabilityClockId = this.clockId;
742
+ item.handoff.ack.status = 'pending';
743
+ item.clockId = this.clockId;
744
+ this.write(data);
745
+ return capability;
746
+ });
747
+ }
748
+ acceptReceipt(raw) {
749
+ const proof = validateReceipt(raw);
750
+ return this.lock(() => {
751
+ const data = this.read(), item = this.usable(data, proof.correlationId);
752
+ const expected = Buffer.from(item.capabilityHash ?? '0'.repeat(64), 'hex'), actual = Buffer.from(payloadDigest(proof.capability), 'hex');
753
+ const authenticated = timingSafeEqual(expected, actual);
754
+ if (!authenticated || !item.capabilityHash || item.revoked || data.epoch !== proof.ledgerEpoch ||
755
+ item.binding.generation !== proof.targetGeneration || item.handoff.submission.status !== 'submitted')
756
+ fail('receipt_authentication_failed');
757
+ if (item.receiptId) {
758
+ if (item.receiptId !== proof.receiptId)
759
+ fail('receipt_already_committed');
760
+ return this.snapshot(item);
761
+ }
762
+ if (item.handoff.ack.status === 'acknowledged')
763
+ fail('receipt_already_committed');
764
+ if (item.capabilityClockId !== this.clockId || this.clock.monotonic() - item.preparedMono >= HANDOFF_LIMITS.capabilityMs)
765
+ fail('receipt_authority_expired');
766
+ this.commitAck(item, 'token_possession');
767
+ item.receiptId = proof.receiptId;
768
+ this.write(data);
769
+ return this.snapshot(item);
770
+ });
771
+ }
772
+ revoke(id) { this.lock(() => { const data = this.read(), item = this.usable(data, id); item.revoked = true; this.write(data); }); }
773
+ quarantine() { this.lock(() => { const data = this.read(); data.quarantined = true; this.write(data); }); }
774
+ prune() {
775
+ this.lock(() => {
776
+ const data = this.read();
777
+ for (const item of Object.values(data.records))
778
+ if (this.clock.utc() - item.preparedUtc >= HANDOFF_LIMITS.detailMs) {
779
+ item.expired = true;
780
+ item.phase = 'finished';
781
+ item.handoff = this.snapshot(item);
782
+ item.waits = [];
783
+ item.reserve = 0;
784
+ delete item.capabilityHash;
785
+ delete item.capabilityClockId;
786
+ delete item.receiptId;
787
+ }
788
+ this.write(data);
789
+ });
790
+ }
791
+ }