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