@agentropy/runtime 0.0.0-stage → 0.1.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 (85) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +39 -2
  3. package/dist/a2a-client.d.ts +111 -0
  4. package/dist/a2a-client.js +386 -0
  5. package/dist/a2a-history.d.ts +27 -0
  6. package/dist/a2a-history.js +67 -0
  7. package/dist/a2a-http.d.ts +46 -0
  8. package/dist/a2a-http.js +183 -0
  9. package/dist/a2a-protocol.d.ts +77 -0
  10. package/dist/a2a-protocol.js +148 -0
  11. package/dist/a2a-push-receiver.d.ts +24 -0
  12. package/dist/a2a-push-receiver.js +161 -0
  13. package/dist/a2a-push.d.ts +85 -0
  14. package/dist/a2a-push.js +385 -0
  15. package/dist/a2a-server.d.ts +82 -0
  16. package/dist/a2a-server.js +523 -0
  17. package/dist/a2a-sse.d.ts +5 -0
  18. package/dist/a2a-sse.js +36 -0
  19. package/dist/a2a.d.ts +41 -0
  20. package/dist/a2a.js +40 -0
  21. package/dist/app.d.ts +256 -0
  22. package/dist/app.js +541 -0
  23. package/dist/audit.d.ts +229 -0
  24. package/dist/audit.js +718 -0
  25. package/dist/bounded-body.d.ts +32 -0
  26. package/dist/bounded-body.js +124 -0
  27. package/dist/communication.d.ts +62 -0
  28. package/dist/communication.js +142 -0
  29. package/dist/compaction.d.ts +24 -0
  30. package/dist/compaction.js +202 -0
  31. package/dist/federation.d.ts +108 -0
  32. package/dist/federation.js +241 -0
  33. package/dist/http-path.d.ts +7 -0
  34. package/dist/http-path.js +14 -0
  35. package/dist/human-actions.d.ts +62 -0
  36. package/dist/human-actions.js +359 -0
  37. package/dist/implementation.d.ts +47 -0
  38. package/dist/implementation.js +138 -0
  39. package/dist/inbox.d.ts +101 -0
  40. package/dist/inbox.js +389 -0
  41. package/dist/index.d.ts +32 -0
  42. package/dist/index.js +32 -0
  43. package/dist/ingress.d.ts +35 -0
  44. package/dist/ingress.js +86 -0
  45. package/dist/lifecycle.d.ts +45 -0
  46. package/dist/lifecycle.js +57 -0
  47. package/dist/limits.d.ts +43 -0
  48. package/dist/limits.js +71 -0
  49. package/dist/mcp.d.ts +111 -0
  50. package/dist/mcp.js +308 -0
  51. package/dist/memory.d.ts +25 -0
  52. package/dist/memory.js +134 -0
  53. package/dist/model-routing.d.ts +66 -0
  54. package/dist/model-routing.js +80 -0
  55. package/dist/otel.d.ts +60 -0
  56. package/dist/otel.js +72 -0
  57. package/dist/outbox.d.ts +116 -0
  58. package/dist/outbox.js +327 -0
  59. package/dist/policy-cache.d.ts +69 -0
  60. package/dist/policy-cache.js +178 -0
  61. package/dist/priority.d.ts +27 -0
  62. package/dist/priority.js +28 -0
  63. package/dist/quotas.d.ts +19 -0
  64. package/dist/quotas.js +47 -0
  65. package/dist/reasoning.d.ts +54 -0
  66. package/dist/reasoning.js +307 -0
  67. package/dist/registry.d.ts +101 -0
  68. package/dist/registry.js +369 -0
  69. package/dist/remote.d.ts +130 -0
  70. package/dist/remote.js +473 -0
  71. package/dist/runtime.d.ts +167 -0
  72. package/dist/runtime.js +1035 -0
  73. package/dist/skills.d.ts +86 -0
  74. package/dist/skills.js +376 -0
  75. package/dist/task-service.d.ts +239 -0
  76. package/dist/task-service.js +790 -0
  77. package/dist/tools.d.ts +140 -0
  78. package/dist/tools.js +476 -0
  79. package/dist/wake-index.d.ts +9 -0
  80. package/dist/wake-index.js +11 -0
  81. package/dist/wakeups.d.ts +142 -0
  82. package/dist/wakeups.js +501 -0
  83. package/dist/workflow.d.ts +36 -0
  84. package/dist/workflow.js +101 -0
  85. package/package.json +48 -3
package/dist/audit.js ADDED
@@ -0,0 +1,718 @@
1
+ /**
2
+ * Mandatory audit intent (Security v1 PEP step 4, ADR-0022/0025, SEC-03).
3
+ *
4
+ * An intent row is written in the same Store transaction as the protected change it describes, so the change
5
+ * and its audit intent commit together or not at all. If the intent cannot be written the transaction aborts
6
+ * and the caller receives `AuditCommitUnavailable`: nothing is committed or reported as committed.
7
+ * `AuditForwarder` later hands committed intents to the external `AuditIntentWriter` sink, at least once, with a
8
+ * stable `details.auditId` the sink uses to deduplicate after a crash between delivery and the delivered mark.
9
+ */
10
+ import { AgentropyError, digestOf, enforcePolicy, METRICS, redactDetails, } from '@agentropy/core';
11
+ import { randomUUID } from 'node:crypto';
12
+ const GENESIS = 'sha256:genesis';
13
+ const chainHash = (prevHash, auditId, event) => digestOf({ prevHash, auditId, event });
14
+ /** Chain position of the newest row, counted from the log: for a store written before heads kept it. */
15
+ async function scannedPosition(tx, tenantId, rowCount) {
16
+ const last = (await tx.find('auditReceipts', {
17
+ where: { tenantId },
18
+ orderBy: 'seq',
19
+ descending: true,
20
+ limit: 1,
21
+ }))[0];
22
+ const rows = rowCount ??
23
+ (await tx.find('audit', { where: { tenantId } })).length;
24
+ return (last?.value.toPosition ?? 0) + rows;
25
+ }
26
+ /** Writes one intent row inside `tx`; any failure (including an injected one) is AuditCommitUnavailable. */
27
+ export async function recordAuditIntent(tx, auditId, event, faults) {
28
+ try {
29
+ faults?.checkpoint('audit.intent');
30
+ const details = redactDetails(event.details);
31
+ const stored = {
32
+ ...event,
33
+ ...(details && Object.keys(details).length ? { details } : {}),
34
+ };
35
+ // Same transaction as the previous link: Store transactions are serialized, so the chain cannot fork.
36
+ // The head row makes an append O(1) (FEAT-032.2); a store written before it existed is scanned once.
37
+ const head = await tx.get('auditHeads', event.tenantId);
38
+ let prevHash;
39
+ let prevPosition;
40
+ if (head) {
41
+ prevHash = head.value.hash;
42
+ prevPosition =
43
+ head.value.position ?? (await scannedPosition(tx, event.tenantId));
44
+ }
45
+ else {
46
+ const scanned = await tx.find('audit', {
47
+ where: { tenantId: event.tenantId },
48
+ orderBy: 'seq',
49
+ });
50
+ prevHash = scanned.at(-1)?.value.hash ?? GENESIS;
51
+ prevPosition = await scannedPosition(tx, event.tenantId, scanned.length);
52
+ }
53
+ const hash = chainHash(prevHash, auditId, stored);
54
+ await tx.insert('audit', auditId, {
55
+ auditId,
56
+ tenantId: event.tenantId,
57
+ type: event.type,
58
+ event: stored,
59
+ prevHash,
60
+ hash,
61
+ forwarded: 0,
62
+ attempts: 0,
63
+ });
64
+ const next = {
65
+ tenantId: event.tenantId,
66
+ auditId,
67
+ hash,
68
+ position: prevPosition + 1,
69
+ };
70
+ if (head)
71
+ await tx.update('auditHeads', event.tenantId, head.revision, next);
72
+ else
73
+ await tx.insert('auditHeads', event.tenantId, next);
74
+ }
75
+ catch (cause) {
76
+ throw new AgentropyError('AuditCommitUnavailable', 'Audit intent could not be committed', { details: { type: event.type }, cause });
77
+ }
78
+ }
79
+ export class AuditForwarder {
80
+ o;
81
+ constructor(o) {
82
+ this.o = o;
83
+ }
84
+ /**
85
+ * Forward committed intents in commit order; stops at the first failure. Returns how many were forwarded. Reads
86
+ * only rows not yet forwarded (indexed), a batch at a time, so a tick costs what is pending, not the whole log.
87
+ */
88
+ async drain() {
89
+ const batch = 200;
90
+ const at = () => Date.parse(this.o.now?.() ?? new Date().toISOString());
91
+ const started = at();
92
+ const spent = () => at() - started >= (this.o.drainBudgetMs ?? 5_000);
93
+ let n = 0;
94
+ for (;;) {
95
+ const rows = await this.o.store.transaction((tx) => tx.find('audit', {
96
+ where: { forwarded: 0 },
97
+ orderBy: 'seq',
98
+ limit: batch,
99
+ }));
100
+ const sent = await this.forward(rows, spent);
101
+ n += sent;
102
+ if (sent < batch || sent < rows.length || spent())
103
+ return n;
104
+ }
105
+ }
106
+ /**
107
+ * Rows the sink keeps refusing (`attempts` at or above `minAttempts`). Forwarding is in order and stops at the first
108
+ * refused row, so the oldest of them holds back every later one: what an operator or a readiness probe looks at
109
+ * (FEAT-075).
110
+ */
111
+ async stuck(minAttempts = 5) {
112
+ const rows = await this.o.store.transaction((tx) => tx.find('audit', {
113
+ where: { forwarded: 0 },
114
+ orderBy: 'seq',
115
+ limit: 100,
116
+ }));
117
+ return rows
118
+ .filter((r) => r.value.attempts >= minAttempts)
119
+ .map((r) => ({
120
+ auditId: r.value.auditId,
121
+ type: r.value.type,
122
+ attempts: r.value.attempts,
123
+ at: r.value.event.at,
124
+ }));
125
+ }
126
+ async forward(rows, spent) {
127
+ let n = 0;
128
+ for (const row of rows) {
129
+ try {
130
+ await this.o.sink.record({
131
+ ...row.value.event,
132
+ details: { ...row.value.event.details, auditId: row.value.auditId },
133
+ });
134
+ this.o.faults?.checkpoint('audit.markForwarded');
135
+ }
136
+ catch {
137
+ this.o.telemetry?.count(METRICS.auditForwardFailures, 1, {
138
+ 'agentropy.audit.type': row.value.type,
139
+ });
140
+ await this.o.store.transaction(async (tx) => {
141
+ const cur = await tx.get('audit', row.id);
142
+ if (cur && cur.value.forwarded === 0)
143
+ await tx.update('audit', cur.id, cur.revision, {
144
+ ...cur.value,
145
+ attempts: cur.value.attempts + 1,
146
+ });
147
+ });
148
+ return n;
149
+ }
150
+ await this.o.store.transaction(async (tx) => {
151
+ const cur = await tx.get('audit', row.id);
152
+ if (cur && cur.value.forwarded === 0)
153
+ await tx.update('audit', cur.id, cur.revision, {
154
+ ...cur.value,
155
+ forwarded: 1,
156
+ });
157
+ });
158
+ n++;
159
+ if (spent())
160
+ return n;
161
+ }
162
+ return n;
163
+ }
164
+ }
165
+ /** Pure chain check, usable offline on an export (archive integrity). */
166
+ export function verifyAuditChain(rows, startHash = GENESIS) {
167
+ let prev = startHash;
168
+ for (const v of rows) {
169
+ if (v.prevHash !== prev || v.hash !== chainHash(prev, v.auditId, v.event))
170
+ return { ok: false, brokenAt: v.auditId };
171
+ prev = v.hash;
172
+ }
173
+ return { ok: true };
174
+ }
175
+ const DAY = 86_400_000;
176
+ /**
177
+ * Audit read, integrity and lifecycle (D-21, D-22, ADR-0022). Every operation is tenant-scoped (another tenant's
178
+ * log is NotFound) and needs its own permission — read, verify, export, retention, hold, release-hold, anchor and
179
+ * dispose are independent actions. Each use is itself audited (`audit.*` events, recorded after the operation so
180
+ * reading the log does not recurse).
181
+ *
182
+ * Lifecycle: rows expire after the tenant's retention (never below the deployment floor). `dispose` removes only
183
+ * the oldest contiguous run of rows that are expired, already forwarded to the audit sink, and not matched by an
184
+ * active legal hold, and leaves a receipt with counts and boundary hashes so `verify` still links the remaining
185
+ * chain to genesis. `anchor` publishes the chain head to an external sink; `verify` checks such anchors, which
186
+ * detects truncation and wholesale rewriting that a hash chain alone cannot.
187
+ */
188
+ export class AuditService {
189
+ o;
190
+ constructor(o) {
191
+ this.o = o;
192
+ }
193
+ get page() {
194
+ return Math.max(1, Math.floor(this.o.pageSize ?? 500));
195
+ }
196
+ get checkWindow() {
197
+ return Math.max(1, Math.floor(this.o.checkWindow ?? 100_000));
198
+ }
199
+ /**
200
+ * The tenant's chain in pages of `pageSize` rows, each in its own transaction, so a long log is never read in one
201
+ * transaction (under SERIALIZABLE such a read conflicts with every acceptance of the tenant). Every page transaction
202
+ * also reads the disposal receipts committed since the previous one (all of them with the first page), so the
203
+ * receipts a page comes with are consistent with its rows (FIX-082): a disposal that commits between two pages may
204
+ * have removed rows past the reader's cursor, and its receipt, read with the next page, says where the chain goes
205
+ * on. With new receipts after the first page, `oldest` is the oldest row left in the log (`null` when none is),
206
+ * which must be the row right after the newest receipt and link to it; it is `undefined` when it was not read.
207
+ * Nothing is read twice and a read is never abandoned, however many disposals commit while it runs.
208
+ */
209
+ async pages(tenantId, each) {
210
+ let afterSeq = 0;
211
+ let receiptSeq = 0;
212
+ for (let page = 0;; page++) {
213
+ const read = await this.o.store.transaction(async (tx) => {
214
+ const receipts = await tx.find('auditReceipts', {
215
+ where: { tenantId },
216
+ orderBy: 'seq',
217
+ afterSeq: receiptSeq,
218
+ });
219
+ const oldest = page > 0 && receipts.length
220
+ ? ((await tx.find('audit', {
221
+ where: { tenantId },
222
+ orderBy: 'seq',
223
+ limit: 1,
224
+ }))[0]?.value ?? null)
225
+ : undefined;
226
+ const rows = await tx.find('audit', {
227
+ where: { tenantId },
228
+ orderBy: 'seq',
229
+ afterSeq,
230
+ limit: this.page,
231
+ });
232
+ return {
233
+ receipts: receipts.map((r) => r.value),
234
+ receiptSeq: receipts.at(-1)?.seq,
235
+ oldest,
236
+ rows: rows.map((r) => r.value),
237
+ seq: rows.at(-1)?.seq,
238
+ };
239
+ });
240
+ if (read.receiptSeq !== undefined)
241
+ receiptSeq = read.receiptSeq;
242
+ if (each(read) === false)
243
+ return;
244
+ if (read.rows.length < this.page || read.seq === undefined)
245
+ return;
246
+ afterSeq = read.seq;
247
+ }
248
+ }
249
+ now() {
250
+ return this.o.now?.() ?? new Date().toISOString();
251
+ }
252
+ id(kind) {
253
+ return this.o.newId?.() ?? `${kind}-${randomUUID()}`;
254
+ }
255
+ async authorize(caller, tenantId, action) {
256
+ if (!caller?.id || !caller.tenantId)
257
+ throw new AgentropyError('Unauthenticated', 'No trusted principal');
258
+ if (tenantId !== caller.tenantId)
259
+ throw new AgentropyError('NotFound', 'Audit log not found');
260
+ try {
261
+ await enforcePolicy(this.o.pdp, {
262
+ principal: caller,
263
+ action,
264
+ resource: { type: 'audit-log', id: tenantId, tenantId },
265
+ });
266
+ }
267
+ catch (err) {
268
+ // Denied audit access is itself an audit event (ADR-0022 §3).
269
+ if (err.code === 'PermissionDenied')
270
+ await this.o.store
271
+ .transaction((tx) => this.record(tx, caller, action, 'deny', { reason: 'policy' }))
272
+ .catch(() => undefined);
273
+ throw err;
274
+ }
275
+ }
276
+ record(tx, caller, action, decision, details) {
277
+ return recordAuditIntent(tx, this.id('audit'), {
278
+ type: `audit.${action.slice('audit:'.length)}`,
279
+ tenantId: caller.tenantId,
280
+ principalId: caller.id,
281
+ action,
282
+ resource: { type: 'audit-log', id: caller.tenantId },
283
+ decision,
284
+ at: this.now(),
285
+ ...(details ? { details } : {}),
286
+ });
287
+ }
288
+ rows(tx, tenantId) {
289
+ return tx.find('audit', {
290
+ where: { tenantId },
291
+ orderBy: 'seq',
292
+ });
293
+ }
294
+ async query(q, caller) {
295
+ await this.authorize(caller, q.tenantId, 'audit:read');
296
+ return this.o.store.transaction(async (tx) => {
297
+ // The newest N, read newest-first with a limit (not the whole log), returned oldest-first.
298
+ const rows = await tx.find('audit', {
299
+ where: { tenantId: q.tenantId, ...(q.type ? { type: q.type } : {}) },
300
+ orderBy: 'seq',
301
+ descending: true,
302
+ limit: Math.min(Math.max(q.limit ?? 100, 1), 1000),
303
+ });
304
+ const out = rows.reverse().map((r) => ({
305
+ ...r.value.event,
306
+ details: { ...r.value.event.details, auditId: r.value.auditId },
307
+ }));
308
+ await this.record(tx, caller, 'audit:read', 'allow', {
309
+ ...(q.type ? { filterType: q.type } : {}),
310
+ returned: out.length,
311
+ });
312
+ return out;
313
+ });
314
+ }
315
+ async verify(tenantId, caller, options = {}) {
316
+ await this.authorize(caller, tenantId, 'audit:verify');
317
+ const checker = new ChainChecker(tenantId, options.anchors ?? [], this.checkWindow);
318
+ let broken;
319
+ await this.pages(tenantId, ({ receipts, oldest, rows }) => {
320
+ broken = checker.dispose(receipts, oldest, rows[0]) ?? checker.feed(rows);
321
+ return broken === undefined;
322
+ });
323
+ const done = broken ?? checker.finish();
324
+ await this.o.store.transaction((tx) => this.record(tx, caller, 'audit:verify', 'allow', {
325
+ ok: done.ok,
326
+ ...(done.ok ? {} : { brokenAt: done.brokenAt }),
327
+ anchors: options.anchors?.length ?? 0,
328
+ }));
329
+ return done;
330
+ }
331
+ /** Archive bundle: rows with their links, verifiable offline with `verifyAuditChain(rows, startHash)`. */
332
+ async exportLog(tenantId, caller) {
333
+ await this.authorize(caller, tenantId, 'audit:export');
334
+ // The bundle starts after the newest receipt read: a disposal that commits while the log is read removes rows
335
+ // the export may already hold, so those are dropped again and the rest links to that receipt (FIX-082). Only
336
+ // receipts that pass verify's checks move the start: they chain on from the ones read before, one that ends at a
337
+ // row already held names that row's hash, and the oldest row left is the one right after the newest and links to
338
+ // it. Otherwise the export is refused. A broken row does not stop it: the bundle carries it and
339
+ // `verifyAuditChain` reports it offline.
340
+ const checker = new ChainChecker(tenantId, [], this.checkWindow);
341
+ const rows = [];
342
+ let start = { hash: GENESIS, position: 1 };
343
+ let broken;
344
+ await this.pages(tenantId, ({ receipts, oldest, rows: page }) => {
345
+ broken = checker.dispose(receipts, oldest, page[0]);
346
+ if (broken)
347
+ return false;
348
+ checker.feed(page);
349
+ const last = receipts.at(-1);
350
+ if (last) {
351
+ rows.splice(0, Math.max(0, last.toPosition + 1 - start.position));
352
+ start = { hash: last.lastHash, position: last.toPosition + 1 };
353
+ }
354
+ for (const r of page)
355
+ rows.push({
356
+ auditId: r.auditId,
357
+ event: r.event,
358
+ prevHash: r.prevHash,
359
+ hash: r.hash,
360
+ });
361
+ });
362
+ const refused = broken && !broken.ok ? broken : undefined;
363
+ await this.o.store.transaction((tx) => this.record(tx, caller, 'audit:export', 'allow', refused
364
+ ? {
365
+ ok: false,
366
+ brokenAt: refused.brokenAt,
367
+ ...(refused.reason ? { reason: refused.reason } : {}),
368
+ }
369
+ : { rows: rows.length }));
370
+ if (refused)
371
+ throw new AgentropyError('InvalidState', 'The audit chain does not hold across the disposal receipts read during the export', {
372
+ details: {
373
+ brokenAt: refused.brokenAt,
374
+ ...(refused.reason ? { reason: refused.reason } : {}),
375
+ },
376
+ });
377
+ return {
378
+ tenantId,
379
+ startHash: start.hash,
380
+ startPosition: start.position,
381
+ rows,
382
+ exportedAt: this.now(),
383
+ };
384
+ }
385
+ retention() {
386
+ return this.o.retention ?? { defaultDays: 365, floorDays: 30 };
387
+ }
388
+ /** Tenant retention override; can only lengthen relative to the deployment floor. */
389
+ async setRetention(tenantId, policy, caller) {
390
+ await this.authorize(caller, tenantId, 'audit:retention');
391
+ const { floorDays } = this.retention();
392
+ const all = [policy?.days, ...Object.values(policy?.perType ?? {})];
393
+ if (all.some((d) => !Number.isInteger(d) || d < floorDays))
394
+ throw new AgentropyError('SchemaViolation', `Retention must be whole days and at least the ${floorDays}-day floor`, { details: { reason: 'belowFloor', floorDays } });
395
+ await this.o.store.transaction(async (tx) => {
396
+ const cur = await tx.get('auditPolicies', tenantId);
397
+ const value = {
398
+ tenantId,
399
+ days: policy.days,
400
+ ...(policy.perType ? { perType: policy.perType } : {}),
401
+ };
402
+ if (cur)
403
+ await tx.update('auditPolicies', tenantId, cur.revision, value);
404
+ else
405
+ await tx.insert('auditPolicies', tenantId, value);
406
+ await this.record(tx, caller, 'audit:retention', 'allow', {
407
+ days: policy.days,
408
+ perTypeCount: Object.keys(policy.perType ?? {}).length,
409
+ });
410
+ });
411
+ }
412
+ async placeHold(tenantId, hold, caller) {
413
+ await this.authorize(caller, tenantId, 'audit:hold');
414
+ if (!hold?.holdId || !hold.reason)
415
+ throw new AgentropyError('SchemaViolation', 'holdId and reason are required');
416
+ return this.o.store.transaction(async (tx) => {
417
+ const id = `${tenantId}|${hold.holdId}`;
418
+ const existing = await tx.get('auditHolds', id);
419
+ if (existing?.value.status === 'active')
420
+ return existing.value;
421
+ const value = {
422
+ holdId: hold.holdId,
423
+ tenantId,
424
+ status: 'active',
425
+ reason: hold.reason,
426
+ ...(hold.types ? { types: [...hold.types] } : {}),
427
+ ...(hold.from ? { from: hold.from } : {}),
428
+ ...(hold.to ? { to: hold.to } : {}),
429
+ placedBy: caller.id,
430
+ placedAt: this.now(),
431
+ };
432
+ if (existing)
433
+ await tx.update('auditHolds', id, existing.revision, value);
434
+ else
435
+ await tx.insert('auditHolds', id, value);
436
+ await this.record(tx, caller, 'audit:hold', 'allow', {
437
+ holdId: hold.holdId,
438
+ });
439
+ return value;
440
+ });
441
+ }
442
+ /** Release returns matching rows to normal retention; it never deletes anything by itself. */
443
+ async releaseHold(tenantId, holdId, caller) {
444
+ await this.authorize(caller, tenantId, 'audit:release-hold');
445
+ return this.o.store.transaction(async (tx) => {
446
+ const doc = await tx.get('auditHolds', `${tenantId}|${holdId}`);
447
+ if (!doc)
448
+ throw new AgentropyError('NotFound', 'Hold not found');
449
+ if (doc.value.status === 'released')
450
+ return doc.value;
451
+ const value = {
452
+ ...doc.value,
453
+ status: 'released',
454
+ releasedBy: caller.id,
455
+ releasedAt: this.now(),
456
+ };
457
+ await tx.update('auditHolds', doc.id, doc.revision, value);
458
+ await this.record(tx, caller, 'audit:release-hold', 'allow', { holdId });
459
+ return value;
460
+ });
461
+ }
462
+ /** Publish the current chain head to the external anchor sink and return it. */
463
+ async anchor(tenantId, caller) {
464
+ await this.authorize(caller, tenantId, 'audit:anchor');
465
+ if (!this.o.anchorSink)
466
+ throw new AgentropyError('InvalidConfiguration', 'No audit anchor sink is configured');
467
+ // Record the anchoring first, so the anchor covers its own event.
468
+ const head = await this.o.store.transaction(async (tx) => {
469
+ await this.record(tx, caller, 'audit:anchor', 'allow');
470
+ // The chain head, which includes the event just recorded: no scan of the log (TASK-067).
471
+ const head = (await tx.get('auditHeads', tenantId)).value;
472
+ return {
473
+ tenantId,
474
+ position: head.position ?? (await scannedPosition(tx, tenantId)),
475
+ auditId: head.auditId,
476
+ hash: head.hash,
477
+ at: this.now(),
478
+ };
479
+ });
480
+ await this.o.anchorSink.publish(head);
481
+ return head;
482
+ }
483
+ /**
484
+ * Remove the oldest expired, forwarded, unheld rows (a contiguous prefix of the chain) and record a receipt.
485
+ * Returns undefined when nothing is eligible.
486
+ */
487
+ async dispose(tenantId, caller, options = {}) {
488
+ await this.authorize(caller, tenantId, 'audit:dispose');
489
+ // At most `maxRows` per call (default 1000), oldest first: a long prefix goes in several bounded transactions,
490
+ // each with its own receipt, and the caller repeats until nothing is eligible.
491
+ const maxRows = Math.max(1, Math.floor(options.maxRows ?? 1000));
492
+ const now = this.now();
493
+ return this.o.store.transaction(async (tx) => {
494
+ const retention = this.retention();
495
+ const tenantPolicy = (await tx.get('auditPolicies', tenantId))?.value;
496
+ const holds = (await tx.find('auditHolds', {
497
+ where: { tenantId, status: 'active' },
498
+ })).map((h) => h.value);
499
+ const daysFor = (type) => Math.max(retention.floorDays, tenantPolicy?.perType?.[type] ??
500
+ retention.perType?.[type] ??
501
+ tenantPolicy?.days ??
502
+ retention.defaultDays);
503
+ const held = (e) => holds.some((h) => (!h.types || h.types.includes(e.type)) &&
504
+ (!h.from || e.at >= h.from) &&
505
+ (!h.to || e.at <= h.to));
506
+ const rows = await tx.find('audit', {
507
+ where: { tenantId },
508
+ orderBy: 'seq',
509
+ limit: maxRows,
510
+ });
511
+ const prefix = [];
512
+ for (const r of rows) {
513
+ const v = r.value;
514
+ const expired = Date.parse(v.event.at) + daysFor(v.type) * DAY <= Date.parse(now);
515
+ if (!expired || v.forwarded !== 1 || held(v.event))
516
+ break;
517
+ prefix.push(r);
518
+ }
519
+ if (!prefix.length) {
520
+ await this.record(tx, caller, 'audit:dispose', 'allow', {
521
+ disposed: 0,
522
+ });
523
+ return undefined;
524
+ }
525
+ const lastReceipt = (await tx.find('auditReceipts', {
526
+ where: { tenantId },
527
+ orderBy: 'seq',
528
+ descending: true,
529
+ limit: 1,
530
+ }))[0]?.value;
531
+ const fromPosition = (lastReceipt?.toPosition ?? 0) + 1;
532
+ const countByType = {};
533
+ for (const r of prefix)
534
+ countByType[r.value.type] = (countByType[r.value.type] ?? 0) + 1;
535
+ const receipt = {
536
+ receiptId: this.id('receipt'),
537
+ tenantId,
538
+ fromPosition,
539
+ toPosition: fromPosition + prefix.length - 1,
540
+ startHash: prefix[0].value.prevHash,
541
+ lastHash: prefix.at(-1).value.hash,
542
+ countByType,
543
+ oldestAt: prefix[0].value.event.at,
544
+ newestAt: prefix.at(-1).value.event.at,
545
+ authorizedBy: caller.id,
546
+ at: now,
547
+ };
548
+ for (const r of prefix)
549
+ await tx.remove('audit', r.id, r.revision);
550
+ await tx.insert('auditReceipts', receipt.receiptId, receipt);
551
+ await this.record(tx, caller, 'audit:dispose', 'allow', {
552
+ disposed: prefix.length,
553
+ receiptId: receipt.receiptId,
554
+ });
555
+ return receipt;
556
+ });
557
+ }
558
+ }
559
+ /**
560
+ * The chain check fed page by page: the links and hashes of every row, the disposal receipts that start the chain,
561
+ * and the published anchors (truncation and wholesale rewriting). Only the rows at anchor positions are kept, and the
562
+ * hashes of at most the last `window` rows checked since the newest receipt read.
563
+ *
564
+ * Receipts are fed as they are read, with the page they were read with (FIX-082). They must chain from genesis
565
+ * (each `startHash` is the previous `lastHash`, positions contiguous). A receipt that ends at a row already checked
566
+ * must name that row's hash as its `lastHash`, and the oldest row left must be the one right after the newest
567
+ * receipt (the row checked there, or the next one to check), so a receipt read mid-read that misstates a disposal
568
+ * is caught; one that ends at a row that fell out of the window fails the read with a retryable `StaleRevision`
569
+ * (nothing is recorded). When the newest one ends past the rows checked so far, a disposal removed rows the reader had not
570
+ * reached: the check goes on from that receipt, as a verify that started after the disposal would.
571
+ * Rows checked and disposed since are counted as disposed, not as present.
572
+ *
573
+ * A broken receipt ends the check; a broken row ends it for `verify`, but `exportLog` reads on (its bundle carries
574
+ * the evidence, which `verifyAuditChain` reports offline) and stops only on a broken receipt.
575
+ */
576
+ class ChainChecker {
577
+ tenantId;
578
+ anchors;
579
+ window;
580
+ /** The hash the next row must link to, and the chain position of the last row checked or disposed. */
581
+ prev = GENESIS;
582
+ position = 0;
583
+ /** The newest receipt's last position and hash. */
584
+ disposed = 0;
585
+ receiptHead = GENESIS;
586
+ receipts = [];
587
+ /**
588
+ * Hashes of the last `window` rows checked, a ring indexed by position modulo `window`: the row at position `p`
589
+ * is held while `p >= this.held()`.
590
+ */
591
+ checked = [];
592
+ wanted = new Set();
593
+ seen = new Map();
594
+ /** A broken receipt chain (ends the check) and the first broken row. */
595
+ broken;
596
+ rowBroken;
597
+ constructor(tenantId, anchors, window) {
598
+ this.tenantId = tenantId;
599
+ this.anchors = anchors;
600
+ this.window = window;
601
+ for (const a of anchors)
602
+ if (a.tenantId === tenantId)
603
+ this.wanted.add(a.position);
604
+ }
605
+ /** The first position whose hash is held: rows checked since the newest receipt, at most the last `window`. */
606
+ held() {
607
+ return Math.max(this.disposed + 1, this.position - this.window + 1);
608
+ }
609
+ /**
610
+ * The hash of the row checked at `p` (a position the reader has checked past the newest receipt). A position that
611
+ * fell out of the window cannot be checked: the read is given up with a retryable error, never reported as sound
612
+ * or as tampered with.
613
+ */
614
+ hashAt(p) {
615
+ if (p < this.held())
616
+ throw new AgentropyError('StaleRevision', 'A disposal committed during the read ends at a row checked too long ago to compare; read again', {
617
+ details: { reason: 'checkWindow', position: p, window: this.window },
618
+ });
619
+ return this.checked[p % this.window];
620
+ }
621
+ /**
622
+ * Takes the receipts committed since the last page, read in the same transaction as the next page, `oldest`, the
623
+ * oldest row left in the log then (`null` for none, `undefined` when not read), and `next`, the first row of that
624
+ * page. `oldest` must link to the newest receipt and be the row right after it: the row the reader checked at that
625
+ * position, or `next` when the receipt ends at or past the reader's cursor. A result means the receipts do not
626
+ * hold (the check is over).
627
+ */
628
+ dispose(receipts, oldest, next) {
629
+ if (this.broken)
630
+ return this.broken;
631
+ if (!receipts.length)
632
+ return undefined;
633
+ for (const r of receipts) {
634
+ const broken = () => (this.broken = {
635
+ ok: false,
636
+ brokenAt: r.receiptId,
637
+ reason: 'receipt-chain',
638
+ });
639
+ if (r.startHash !== this.receiptHead ||
640
+ r.fromPosition !== this.disposed + 1 ||
641
+ r.toPosition < r.fromPosition)
642
+ return broken();
643
+ // A receipt that ends at a row already checked names that row's hash.
644
+ if (r.toPosition <= this.position &&
645
+ this.hashAt(r.toPosition) !== r.lastHash)
646
+ return broken();
647
+ this.receipts.push(r);
648
+ this.receiptHead = r.lastHash;
649
+ this.disposed = r.toPosition;
650
+ }
651
+ if (oldest && oldest.prevHash !== this.receiptHead)
652
+ return (this.broken = { ok: false, brokenAt: oldest.auditId });
653
+ // The oldest row left is the one right after the newest receipt: a row already checked, or the next to check.
654
+ if (oldest !== undefined &&
655
+ (this.disposed < this.position
656
+ ? oldest?.hash !== this.hashAt(this.disposed + 1)
657
+ : oldest?.auditId !== next?.auditId))
658
+ return (this.broken = oldest
659
+ ? { ok: false, brokenAt: oldest.auditId }
660
+ : {
661
+ ok: false,
662
+ brokenAt: receipts.at(-1).receiptId,
663
+ reason: 'receipt-chain',
664
+ });
665
+ if (this.disposed > this.position) {
666
+ // Rows past the reader's cursor were disposed: the chain goes on from the receipt.
667
+ this.prev = this.receiptHead;
668
+ this.position = this.disposed;
669
+ }
670
+ return undefined;
671
+ }
672
+ /**
673
+ * Checks the next rows. A result means the chain is broken: `verify` stops there, `exportLog` feeds on, and the
674
+ * first broken row stays the result.
675
+ */
676
+ feed(rows) {
677
+ if (this.broken)
678
+ return this.broken;
679
+ for (const v of rows) {
680
+ if (!this.rowBroken &&
681
+ (v.prevHash !== this.prev ||
682
+ v.hash !== chainHash(this.prev, v.auditId, v.event)))
683
+ this.rowBroken = { ok: false, brokenAt: v.auditId };
684
+ this.prev = v.hash;
685
+ this.position++;
686
+ this.checked[this.position % this.window] = v.hash;
687
+ if (this.wanted.has(this.position))
688
+ this.seen.set(this.position, { auditId: v.auditId, hash: v.hash });
689
+ }
690
+ return this.rowBroken;
691
+ }
692
+ finish() {
693
+ if (this.broken)
694
+ return this.broken;
695
+ if (this.rowBroken)
696
+ return this.rowBroken;
697
+ for (const a of this.anchors) {
698
+ if (a.tenantId !== this.tenantId)
699
+ continue;
700
+ if (a.position <= this.disposed) {
701
+ const end = this.receipts.find((r) => r.toPosition === a.position);
702
+ if (end && end.lastHash !== a.hash)
703
+ return { ok: false, brokenAt: a.auditId, reason: 'anchor-mismatch' };
704
+ continue;
705
+ }
706
+ const row = this.seen.get(a.position);
707
+ if (!row)
708
+ return { ok: false, brokenAt: a.auditId, reason: 'truncated' };
709
+ if (row.auditId !== a.auditId || row.hash !== a.hash)
710
+ return { ok: false, brokenAt: a.auditId, reason: 'anchor-mismatch' };
711
+ }
712
+ return {
713
+ ok: true,
714
+ count: this.position - this.disposed,
715
+ disposed: this.disposed,
716
+ };
717
+ }
718
+ }