@verax-ai/proxy 0.6.1 → 0.8.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/dist/proxy.js CHANGED
@@ -1,7 +1,6 @@
1
- import { existsSync } from "node:fs";
2
- import { join } from "node:path";
1
+ import { isProxyHalted } from "./process-halt.js";
3
2
  import { signDecisionRecord } from "@cedulon/core";
4
- import { approvePending, approvalsLogFor, createApprovalBudgetGuard, drainApprovalCommands, spentTodayMinorOf, } from "./approvals.js";
3
+ import { approvalDispatchArgs, approvalDispatchHash, approvePending, approvalsLogFor, createApprovalBudgetGuard, drainApprovalCommands, signedApprovalDispatch, spentTodayMinorOf, } from "./approvals.js";
5
4
  import { SerialQueue } from "./serial-queue.js";
6
5
  import { diskProbe } from "./disk.js";
7
6
  import { markEnded, markStarted, startedWithoutEnd } from "./in-flight-log.js";
@@ -11,9 +10,12 @@ import { controlUnchanged, createControlMemory, syncHaltControl } from "./contro
11
10
  import { createOperatorRemovalMemory, operatorRemovalUnchanged, syncOperatorRemovalControl } from "./operator-removal-sync.js";
12
11
  import { createRevokeMemory, revokeUnchanged, syncRevokeControl } from "./revoke-sync.js";
13
12
  import { countedWork, hasPrimaryEffect, lookupDecisionByRef, lookupReauthByHash, lookupResolvedBy, noteResolution, noteTenantRef, } from "./ledger.js";
13
+ import { argumentDepth, gateDataClasses, MAX_ARGUMENT_DEPTH, scanCallMeta } from "./data-classes.js";
14
+ import { gateResultClasses, gateThrownError } from "./result-classes.js";
14
15
  import { terminalText } from "./policy.js";
15
16
  import { spokenReason } from "./spoken-reason.js";
16
17
  import { tenantKey } from "./tenant.js";
18
+ import { isTextContent } from "./types.js";
17
19
  function scopedClaimsRef(principal, raw) {
18
20
  if (principal.iss || principal.tenant || principal.org) {
19
21
  return `${tenantKey(principal)}:${raw}`;
@@ -85,13 +87,16 @@ function effectUnrecorded(ref) {
85
87
  };
86
88
  }
87
89
  function isEffectUnrecorded(result) {
88
- return result.content.some((part) => part.text.startsWith("effect-unrecorded:"));
90
+ return result.content.some((part) => isTextContent(part) && part.text.startsWith("effect-unrecorded:"));
89
91
  }
90
92
  async function replayAfterEffect(ledger, ref) {
91
93
  const primary = (await ledger.effects()).find((e) => e.row.ref === ref && e.row.effectClass !== "duplicate-effect");
92
94
  if (primary?.row.effectClass.endsWith(":threw")) {
93
95
  return threwReplay(ref);
94
96
  }
97
+ if (primary?.row.effectClass.endsWith(":halted")) {
98
+ return denied("not-run-halted", ref);
99
+ }
95
100
  return allowedReplay(ref);
96
101
  }
97
102
  function deepFreeze(value) {
@@ -178,6 +183,17 @@ function toolCallOf(call) {
178
183
  delete args._ref;
179
184
  return { name: call.name, arguments: args };
180
185
  }
186
+ function inputsWithoutSource(inputs) {
187
+ return {
188
+ ...inputs,
189
+ inputs: inputs.inputs.map((row) => ({
190
+ id: row.id,
191
+ versionHash: row.versionHash,
192
+ validFromMs: row.validFromMs,
193
+ validUntilMs: row.validUntilMs,
194
+ })),
195
+ };
196
+ }
181
197
  export function createProxy(deps) {
182
198
  const inputsLog = deps.inputsLog ?? inputsLogFor(deps.ledger);
183
199
  const approvals = approvalsLogFor(deps.ledger);
@@ -276,7 +292,30 @@ export function createProxy(deps) {
276
292
  });
277
293
  return denied("spend-reauth-required", ref);
278
294
  }
279
- async function runInner(call, principal, ref, effectRecorded) {
295
+ // The allow is already on the chain. A halt that lands now must not leave
296
+ // that ref without a primary effect (retry would answer outcome-unknown)
297
+ // and must not leave a start mark for a run that never started.
298
+ async function recordHaltedAfterAllow(allowRef, dispatchedCall, principal, effectRecorded) {
299
+ const dispatchedHash = sha256Canonical(effectDescriptor(dispatchedCall.name, dispatchedCall.arguments));
300
+ const row = {
301
+ ref: allowRef,
302
+ effectHash: dispatchedHash,
303
+ effectClass: `${dispatchedCall.name}:halted`,
304
+ timestampMs: deps.now(),
305
+ actor: principal.brain,
306
+ };
307
+ try {
308
+ await deps.ledger.appendEffect(row, "self", sha256Canonical({ halted: true }));
309
+ if (effectRecorded)
310
+ effectRecorded.ok = true;
311
+ }
312
+ catch {
313
+ // Still refuse the run. A missing effect keeps the start mark, so a
314
+ // retry cannot start the tool.
315
+ }
316
+ return denied("halted", allowRef);
317
+ }
318
+ async function runInner(call, principal, ref, effectRecorded, bound) {
280
319
  const dispatchedName = call.name;
281
320
  const dispatchedArgs = deepFreeze(structuredClone(call.arguments));
282
321
  const dispatchedHash = sha256Canonical(effectDescriptor(dispatchedName, dispatchedArgs));
@@ -286,10 +325,14 @@ export function createProxy(deps) {
286
325
  arguments: dispatchedArgs,
287
326
  });
288
327
  let result;
328
+ if (stateDir && isProxyHalted(stateDir)) {
329
+ return recordHaltedAfterAllow(ref, frozenCall, principal, effectRecorded);
330
+ }
289
331
  try {
290
- result = await deps.inner(frozenCall, principal, ref);
332
+ result = await deps.inner(frozenCall, principal, ref, bound);
291
333
  }
292
334
  catch (err) {
335
+ const resultHash = sha256Canonical(thrownPayload(err));
293
336
  const row = {
294
337
  ref,
295
338
  effectHash: thrownHash,
@@ -298,13 +341,22 @@ export function createProxy(deps) {
298
341
  actor: principal.brain,
299
342
  };
300
343
  try {
301
- await deps.ledger.appendEffect(row, "self", sha256Canonical(thrownPayload(err)));
344
+ await deps.ledger.appendEffect(row, "self", resultHash);
302
345
  effectRecorded.ok = true;
303
346
  }
304
347
  catch (writeErr) {
305
348
  throw writeErr;
306
349
  }
307
- throw err;
350
+ // Without result classes the tool's own error leaves, untouched and not awaited.
351
+ if (!deps.policy.resultClasses && !deps.policy.media)
352
+ throw err;
353
+ const gated = await gateThrownError(err, dispatchedName, ref, resultHash, principal, {
354
+ policy: deps.policy,
355
+ nonce: deps.nonce,
356
+ now: deps.now,
357
+ writeRecord,
358
+ });
359
+ throw gated.error;
308
360
  }
309
361
  const row = {
310
362
  ref,
@@ -314,14 +366,15 @@ export function createProxy(deps) {
314
366
  actor: principal.brain,
315
367
  };
316
368
  const { effectReceipt, ...normalResult } = result;
369
+ const resultHash = sha256Canonical(normalResult);
317
370
  const signedRow = effectReceipt?.body?.effects?.[0];
318
371
  const external = effectReceipt?.body?.effects?.length === 1 && signedRow?.ref === ref &&
319
372
  signedRow.effectHash === dispatchedHash && signedRow.effectClass === dispatchedName;
320
373
  try {
321
374
  if (external)
322
- await deps.ledger.appendEffect(signedRow, "third-party", sha256Canonical(normalResult), effectReceipt);
375
+ await deps.ledger.appendEffect(signedRow, "third-party", resultHash, effectReceipt);
323
376
  else
324
- await deps.ledger.appendEffect(row, "self", sha256Canonical(normalResult));
377
+ await deps.ledger.appendEffect(row, "self", resultHash);
325
378
  effectRecorded.ok = true;
326
379
  }
327
380
  catch {
@@ -330,7 +383,12 @@ export function createProxy(deps) {
330
383
  // stays false) and a restart answers outcome-unknown instead of running again.
331
384
  return effectUnrecorded(ref);
332
385
  }
333
- return normalResult;
386
+ return gateResultClasses(normalResult, dispatchedName, ref, resultHash, principal, {
387
+ policy: deps.policy,
388
+ nonce: deps.nonce,
389
+ now: deps.now,
390
+ writeRecord,
391
+ });
334
392
  }
335
393
  async function resolveInputs(call, principal, timestampMs) {
336
394
  const declared = declaredInputs(call.arguments);
@@ -410,14 +468,14 @@ export function createProxy(deps) {
410
468
  });
411
469
  return denied(reasonCode, denyRef);
412
470
  }
413
- function launchInner(dispatchedCall, principal, allowRef, flightKey) {
471
+ function launchInner(dispatchedCall, principal, allowRef, flightKey, bound) {
414
472
  // Written before the tool runs, removed after the effect is recorded. A
415
473
  // mark that survives the process is what tells a restarted body that this
416
474
  // ref was already started (in-flight-log.ts).
417
475
  if (stateDir !== null)
418
476
  markStarted(stateDir, flightKey, dispatchedCall.name);
419
477
  const effectRecorded = { ok: false };
420
- const work = runInner(dispatchedCall, principal, allowRef, effectRecorded);
478
+ const work = runInner(dispatchedCall, principal, allowRef, effectRecorded, bound);
421
479
  inFlight.set(flightKey, work);
422
480
  return { kind: "run", work, key: flightKey, replayRef: allowRef, effectRecorded };
423
481
  }
@@ -517,45 +575,69 @@ export function createProxy(deps) {
517
575
  syncControlRecords,
518
576
  async call(call, principal) {
519
577
  if (stateDir) {
520
- await drainApprovalCommands(stateDir, async (cmd) => {
521
- const defer = await lookupDecisionByRef(deps.ledger, cmd.ref);
522
- if (!defer || defer.decision !== "defer")
523
- return;
524
- await approvePending({
525
- ledger: deps.ledger,
526
- recordSigner: deps.recordSigner,
527
- now: deps.now,
528
- nonce: deps.nonce,
529
- ref: cmd.ref,
530
- approverId: cmd.approverId,
531
- // A command with no `via` is an old queue file; treat it as a script, not a person.
532
- via: cmd.via === "cli" ? "cli" : "cli-script",
533
- policyHash: defer.policyHash,
534
- approvals,
535
- inputsLog,
536
- budgetGuard,
578
+ // Halt (file or process flag) is checked before the queue can authorize
579
+ // a spend or any other pending tool. approvePending uses the same gate.
580
+ if (!isProxyHalted(stateDir)) {
581
+ await drainApprovalCommands(stateDir, async (cmd) => {
582
+ const defer = await lookupDecisionByRef(deps.ledger, cmd.ref);
583
+ if (!defer || defer.decision !== "defer")
584
+ return;
585
+ await approvePending({
586
+ ledger: deps.ledger,
587
+ recordSigner: deps.recordSigner,
588
+ now: deps.now,
589
+ nonce: deps.nonce,
590
+ ref: cmd.ref,
591
+ approverId: cmd.approverId,
592
+ // A command with no `via` is an old queue file; treat it as a script, not a person.
593
+ via: cmd.via === "cli" ? "cli" : "cli-script",
594
+ policyHash: defer.policyHash,
595
+ approvals,
596
+ inputsLog,
597
+ budgetGuard,
598
+ });
537
599
  });
538
- });
600
+ }
539
601
  await syncControlRecords();
540
602
  }
541
603
  const dispatched = toolCallOf(call);
542
- const requestHash = sha256Canonical(dispatched);
604
+ const tooDeep = deps.policy.dataClasses !== undefined && argumentDepth(call.arguments) > MAX_ARGUMENT_DEPTH;
605
+ const requestHash = tooDeep
606
+ ? sha256Canonical({ name: dispatched.name, tooDeep: true })
607
+ : sha256Canonical(dispatched);
543
608
  const timestampMs = deps.now();
544
609
  const resolved = await resolveInputs(call, principal, timestampMs);
545
- if (stateDir && existsSync(join(stateDir, "halted"))) {
610
+ // A class in `_inputs` must not reach disk on the halt or disk-low
611
+ // record. Scan here only to scrub; the deny reason stays 0.7.0's.
612
+ const metaReason = deps.policy.dataClasses
613
+ ? scanCallMeta(call, deps.policy.dataClasses)
614
+ : null;
615
+ const preMetaInputs = metaReason
616
+ ? { principal: principalInputs(principal), inputs: [] }
617
+ : deps.policy.dataClasses
618
+ ? inputsWithoutSource(resolved.inputs)
619
+ : resolved.inputs;
620
+ async function denyIfHalted() {
621
+ if (!stateDir || !isProxyHalted(stateDir))
622
+ return null;
546
623
  const ref = deps.nonce();
547
624
  await writeRecord({
548
625
  decision: "deny",
549
626
  reasonCode: "halted",
550
627
  ref,
551
628
  requestHash,
552
- inputs: resolved.inputs,
629
+ inputs: preMetaInputs,
553
630
  effectHash: null,
554
631
  subject: call.name,
555
632
  timestampMs,
556
633
  });
557
634
  return denied("halted", ref);
558
635
  }
636
+ {
637
+ const halted = await denyIfHalted();
638
+ if (halted)
639
+ return halted;
640
+ }
559
641
  if (stateDir && diskProbe.freeBytes(stateDir) < deps.policy.limits.diskFreeBytes) {
560
642
  const ref = deps.nonce();
561
643
  await writeRecordOrUnrecorded({
@@ -563,7 +645,7 @@ export function createProxy(deps) {
563
645
  reasonCode: "ledger-disk-low",
564
646
  ref,
565
647
  requestHash,
566
- inputs: resolved.inputs,
648
+ inputs: preMetaInputs,
567
649
  effectHash: null,
568
650
  subject: call.name,
569
651
  timestampMs,
@@ -576,19 +658,42 @@ export function createProxy(deps) {
576
658
  if (stateDir)
577
659
  await syncControlRecords();
578
660
  // A call that waited here behind another admission reads the halt flag again.
579
- if (stateDir && existsSync(join(stateDir, "halted"))) {
661
+ {
662
+ const halted = await denyIfHalted();
663
+ if (halted)
664
+ return { kind: "done", result: halted };
665
+ }
666
+ if (tooDeep) {
667
+ const reasonCode = "data-class-unscanned";
580
668
  const ref = deps.nonce();
581
669
  await writeRecord({
582
670
  decision: "deny",
583
- reasonCode: "halted",
671
+ reasonCode,
584
672
  ref,
585
673
  requestHash,
586
- inputs: resolved.inputs,
674
+ inputs: { principal: principalInputs(principal), inputs: [] },
587
675
  effectHash: null,
588
676
  subject: call.name,
589
677
  timestampMs,
590
678
  });
591
- return { kind: "done", result: denied("halted", ref) };
679
+ return { kind: "done", result: denied(reasonCode, ref) };
680
+ }
681
+ if (deps.policy.dataClasses) {
682
+ const metaReason = scanCallMeta(call, deps.policy.dataClasses);
683
+ if (metaReason) {
684
+ const ref = deps.nonce();
685
+ await writeRecord({
686
+ decision: "deny",
687
+ reasonCode: metaReason,
688
+ ref,
689
+ requestHash,
690
+ inputs: { principal: principalInputs(principal), inputs: [] },
691
+ effectHash: null,
692
+ subject: call.name,
693
+ timestampMs,
694
+ });
695
+ return { kind: "done", result: denied(metaReason, ref) };
696
+ }
592
697
  }
593
698
  if (given === "invalid") {
594
699
  const ref = deps.nonce();
@@ -742,7 +847,46 @@ export function createProxy(deps) {
742
847
  });
743
848
  return { kind: "done", result: denied("tenant-mismatch", denyRef) };
744
849
  }
745
- return launchInner(dispatched, principal, allow.ref, scopedRef);
850
+ const toRun = snap
851
+ ? { name: dispatched.name, arguments: approvalDispatchArgs(snap) }
852
+ : dispatched;
853
+ // What is sent is what the signed defer committed to, with or
854
+ // without an approvals row: a missing row does not send the raw call.
855
+ const signedDispatch = await signedApprovalDispatch(deps.ledger, inputsLog, scopedRef, existing);
856
+ if (signedDispatch === null ||
857
+ sha256Canonical({ name: toRun.name, arguments: toRun.arguments }) !== signedDispatch.hash) {
858
+ return {
859
+ kind: "done",
860
+ result: await signedRetryDeny("hash-mismatch", requestHash, resolved.inputs, timestampMs, call.name, scopedRef),
861
+ };
862
+ }
863
+ if (deps.policy.dataClasses) {
864
+ const classGated = gateDataClasses(dispatched, deps.policy.dataClasses);
865
+ if (classGated.action === "deny") {
866
+ return {
867
+ kind: "done",
868
+ result: await signedRetryDeny(classGated.reasonCode, requestHash, resolved.inputs, timestampMs, call.name, scopedRef),
869
+ };
870
+ }
871
+ if (classGated.action === "forward") {
872
+ const snapHash = snap
873
+ ? approvalDispatchHash(snap)
874
+ : sha256Canonical({ name: dispatched.name, arguments: dispatched.arguments });
875
+ if (snapHash !== classGated.dataClasses.forwardedHash) {
876
+ return {
877
+ kind: "done",
878
+ result: await signedRetryDeny("data-class-changed", requestHash, resolved.inputs, timestampMs, call.name, scopedRef),
879
+ };
880
+ }
881
+ }
882
+ }
883
+ if (stateDir && isProxyHalted(stateDir)) {
884
+ return {
885
+ kind: "done",
886
+ result: await recordHaltedAfterAllow(allow.ref, toRun, principal),
887
+ };
888
+ }
889
+ return launchInner(toRun, principal, allow.ref, scopedRef, boundRows);
746
890
  }
747
891
  return { kind: "done", result: deferred(given) };
748
892
  }
@@ -806,6 +950,25 @@ export function createProxy(deps) {
806
950
  decision = "deny";
807
951
  reasonCode = "tenant-mismatch";
808
952
  }
953
+ let forwarded = dispatched;
954
+ let recordInputs = resolved.inputs;
955
+ let snapshotForwarded;
956
+ let snapshotDataClasses;
957
+ if (decision === "allow" || decision === "defer") {
958
+ const classGated = gateDataClasses(dispatched, deps.policy.dataClasses);
959
+ if (classGated.action === "deny") {
960
+ decision = "deny";
961
+ reasonCode = classGated.reasonCode;
962
+ }
963
+ else if (classGated.action === "forward") {
964
+ forwarded = { name: dispatched.name, arguments: classGated.arguments };
965
+ recordInputs = { ...resolved.inputs, dataClasses: classGated.dataClasses };
966
+ if (decision === "defer") {
967
+ snapshotForwarded = classGated.arguments;
968
+ snapshotDataClasses = classGated.dataClasses;
969
+ }
970
+ }
971
+ }
809
972
  const ref = typeof given === "string" ? scopedClaimsRef(principal, given) : deps.nonce();
810
973
  // What the brain is told: its own `_ref`, so a retry carries the same key back.
811
974
  const shown = typeof given === "string" ? given : ref;
@@ -815,8 +978,8 @@ export function createProxy(deps) {
815
978
  reasonCode,
816
979
  ref,
817
980
  requestHash,
818
- inputs: resolved.inputs,
819
- effectHash: allow ? sha256Canonical(effectDescriptor(dispatched.name, dispatched.arguments)) : null,
981
+ inputs: recordInputs,
982
+ effectHash: allow ? sha256Canonical(effectDescriptor(forwarded.name, forwarded.arguments)) : null,
820
983
  subject: call.name,
821
984
  timestampMs,
822
985
  });
@@ -825,14 +988,16 @@ export function createProxy(deps) {
825
988
  }
826
989
  if (decision === "defer") {
827
990
  const rule = deps.policy.rule(verdict.rule);
828
- const amount = dispatched.name === "spend" ? dispatched.arguments.amountMinor : dispatched.arguments.amount;
829
- const payee = dispatched.arguments.payee;
830
- const currency = dispatched.arguments.currency;
991
+ const amount = forwarded.name === "spend" ? forwarded.arguments.amountMinor : forwarded.arguments.amount;
992
+ const payee = forwarded.arguments.payee;
993
+ const currency = forwarded.arguments.currency;
831
994
  await approvals.append({
832
995
  ref,
833
996
  requestHash,
834
997
  subject: dispatched.name,
835
- args: dispatched.arguments,
998
+ args: forwarded.arguments,
999
+ ...(snapshotForwarded !== undefined ? { forwardedArgs: snapshotForwarded } : {}),
1000
+ ...(snapshotDataClasses !== undefined ? { dataClasses: snapshotDataClasses } : {}),
836
1001
  ruleId: verdict.rule,
837
1002
  ruleText: rule?.text ?? null,
838
1003
  inputsSummary: {
@@ -852,7 +1017,10 @@ export function createProxy(deps) {
852
1017
  if (!allow) {
853
1018
  return { kind: "done", result: denied(reasonCode, shown, call) };
854
1019
  }
855
- return launchInner(dispatched, principal, ref, ref);
1020
+ if (stateDir && isProxyHalted(stateDir)) {
1021
+ return { kind: "done", result: await recordHaltedAfterAllow(ref, forwarded, principal) };
1022
+ }
1023
+ return launchInner(forwarded, principal, ref, ref, resolved.inputs.inputs);
856
1024
  });
857
1025
  if (plan.kind === "done")
858
1026
  return plan.result;
@@ -1,5 +1,5 @@
1
1
  import type { EffectRow } from "@cedulon/effect-extract";
2
- import type { ApprovalRow } from "./approvals.ts";
2
+ import { type ApprovalRow } from "./approvals.ts";
3
3
  import type { LedgerEffect } from "./types.ts";
4
4
  export type ChannelRow = {
5
5
  channel: string;
@@ -67,6 +67,13 @@ export type CardCsvOpts = {
67
67
  };
68
68
  export declare function parseCardCsv(text: string, opts: CardCsvOpts): ParsedCardCsv;
69
69
  export declare function parseChannelJsonl(text: string): ChannelRow[];
70
+ /**
71
+ * forwardedHash on the inputs row each decision's inputsHash names, keyed by
72
+ * that decision's ref. Same files as `loadDecisionRequestHashesFromDir`.
73
+ * Null when no inputs row on disk hashes to the decision: a row appended
74
+ * after it, or an edited one, does not stand in for it.
75
+ */
76
+ export declare function loadSignedForwardedHashesFromDir(stateDir: string): Map<string, string | null>;
70
77
  /** Decision refs, read the same way `verifyLedger` lists decision files. */
71
78
  export declare function loadDecisionRefsFromDir(stateDir: string): Set<string>;
72
79
  /**
@@ -88,4 +95,6 @@ export declare function reconcile(channelRows: readonly ChannelRow[], effects: r
88
95
  decisionRefs?: ReadonlySet<string>;
89
96
  /** Effect ref to the requestHash on the signed decision of that ref. */
90
97
  decisionRequestHashes?: ReadonlyMap<string, string>;
98
+ /** Approval-row ref to the forwardedHash on that defer's signed inputs. */
99
+ decisionForwardedHashes?: ReadonlyMap<string, string | null>;
91
100
  }): ReconcileReport;
package/dist/reconcile.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { existsSync, readFileSync } from "node:fs";
3
3
  import { join } from "node:path";
4
+ import { approvalArgsBound, approvalDispatchArgs } from "./approvals.js";
4
5
  import { sha256Canonical } from "./hash.js";
5
6
  import { readLedgerManifest, requireLedgerPiecePath } from "./ledger-manifest.js";
6
7
  function asChannelRow(raw, line) {
@@ -243,6 +244,65 @@ function readDecisionLines(stateDir) {
243
244
  }
244
245
  return claims;
245
246
  }
247
+ function inputPaths(dir) {
248
+ const manifest = readLedgerManifest(dir);
249
+ if (manifest && Array.isArray(manifest.pieces) && manifest.pieces.length > 0) {
250
+ return manifest.pieces
251
+ .map((p) => requireLedgerPiecePath(dir, p.inputs))
252
+ .filter((p) => existsSync(p));
253
+ }
254
+ const tek = join(dir, "inputs.jsonl");
255
+ return existsSync(tek) ? [tek] : [];
256
+ }
257
+ /**
258
+ * forwardedHash on the inputs row each decision's inputsHash names, keyed by
259
+ * that decision's ref. Same files as `loadDecisionRequestHashesFromDir`.
260
+ * Null when no inputs row on disk hashes to the decision: a row appended
261
+ * after it, or an edited one, does not stand in for it.
262
+ */
263
+ export function loadSignedForwardedHashesFromDir(stateDir) {
264
+ const wanted = new Map();
265
+ for (const claims of readDecisionLines(stateDir)) {
266
+ if (typeof claims.ref !== "string" || typeof claims.inputsHash !== "string")
267
+ continue;
268
+ wanted.set(claims.ref, claims.inputsHash);
269
+ }
270
+ const out = new Map();
271
+ if (wanted.size === 0)
272
+ return out;
273
+ const found = new Set();
274
+ for (const path of inputPaths(stateDir)) {
275
+ let text = "";
276
+ try {
277
+ text = readFileSync(path, "utf8");
278
+ }
279
+ catch (err) {
280
+ if (err.code === "ENOENT")
281
+ continue;
282
+ throw err;
283
+ }
284
+ for (const line of text.split("\n")) {
285
+ if (line === "")
286
+ continue;
287
+ const row = JSON.parse(line);
288
+ if (typeof row.ref !== "string" || found.has(row.ref))
289
+ continue;
290
+ const expected = wanted.get(row.ref);
291
+ if (expected === undefined || row.inputs === undefined)
292
+ continue;
293
+ if (sha256Canonical(row.inputs) !== expected)
294
+ continue;
295
+ found.add(row.ref);
296
+ const hash = row.inputs.dataClasses?.forwardedHash;
297
+ if (typeof hash === "string" && hash !== "")
298
+ out.set(row.ref, hash);
299
+ }
300
+ }
301
+ for (const ref of wanted.keys())
302
+ if (!found.has(ref))
303
+ out.set(ref, null);
304
+ return out;
305
+ }
246
306
  /** Decision refs, read the same way `verifyLedger` lists decision files. */
247
307
  export function loadDecisionRefsFromDir(stateDir) {
248
308
  const refs = new Set();
@@ -313,7 +373,7 @@ function approvalForEffect(approvals, effectRef) {
313
373
  return approvals.find((r) => r.allowRef === effectRef || r.ref === effectRef);
314
374
  }
315
375
  /** The row may lend amount, currency and payee only when it still hashes to the signed request. */
316
- function boundApproval(effect, approvals, requestHashes) {
376
+ function boundApproval(effect, approvals, requestHashes, forwardedHashes) {
317
377
  if (!requestHashes)
318
378
  return undefined;
319
379
  const signed = requestHashes.get(effect.row.ref);
@@ -322,15 +382,18 @@ function boundApproval(effect, approvals, requestHashes) {
322
382
  const snap = approvalForEffect(approvals, effect.row.ref);
323
383
  if (!snap)
324
384
  return undefined;
325
- const rowHash = sha256Canonical({ name: snap.subject, arguments: snap.args });
326
- if (rowHash !== signed)
385
+ const signedForwarded = forwardedHashes?.get(snap.ref);
386
+ if (!approvalArgsBound(snap, signed, signedForwarded))
327
387
  return undefined;
328
388
  return snap;
329
389
  }
330
- function effectAmount(effect, approvals, requestHashes) {
331
- const snap = boundApproval(effect, approvals, requestHashes);
332
- const amountMinor = snap && typeof snap.args.amountMinor === "number" ? snap.args.amountMinor : undefined;
333
- const currency = snap && typeof snap.args.currency === "string" ? snap.args.currency : undefined;
390
+ function effectAmount(effect, approvals, requestHashes, forwardedHashes) {
391
+ const snap = boundApproval(effect, approvals, requestHashes, forwardedHashes);
392
+ if (!snap)
393
+ return {};
394
+ const args = approvalDispatchArgs(snap);
395
+ const amountMinor = typeof args.amountMinor === "number" ? args.amountMinor : undefined;
396
+ const currency = typeof args.currency === "string" ? args.currency : undefined;
334
397
  return { amountMinor, currency };
335
398
  }
336
399
  function amountsClose(a, b) {
@@ -353,16 +416,27 @@ function amountGate(row, fromSnap) {
353
416
  }
354
417
  return "match";
355
418
  }
356
- function descriptorsFor(effect, approvals, byPayee, requestHashes) {
419
+ function descriptorsFor(effect, approvals, byPayee, requestHashes, forwardedHashes) {
357
420
  if (!byPayee)
358
421
  return undefined;
359
- const snap = boundApproval(effect, approvals, requestHashes);
360
- const payee = snap && typeof snap.args.payee === "string" ? snap.args.payee : undefined;
361
- if (!payee)
422
+ const snap = boundApproval(effect, approvals, requestHashes, forwardedHashes);
423
+ if (!snap)
424
+ return undefined;
425
+ const payee = approvalDispatchArgs(snap).payee;
426
+ if (typeof payee !== "string")
362
427
  return undefined;
363
428
  const stamps = byPayee[payee];
364
429
  return stamps && stamps.length > 0 ? stamps : undefined;
365
430
  }
431
+ /**
432
+ * A signed not-run row is not treated as an external event. `:threw` does not
433
+ * mean the tool never ran: `inner` was called and a downstream side effect may
434
+ * have happened. Successful completion was not verified. Ghost classification
435
+ * stays cautious — ref matching must not hide a statement behind either suffix.
436
+ */
437
+ function isNotRunEffectClass(effectClass) {
438
+ return effectClass.endsWith(":halted") || effectClass.endsWith(":threw");
439
+ }
366
440
  export function reconcile(channelRows, effects, opts) {
367
441
  const toleranceMs = opts?.toleranceMs ?? 60_000;
368
442
  const decisionRefs = opts?.decisionRefs ?? new Set();
@@ -403,6 +477,7 @@ export function reconcile(channelRows, effects, opts) {
403
477
  if (typeof row.ref === "string" && row.ref !== "") {
404
478
  const findFor = (ref) => effects.findIndex((e, i) => !used.has(i) &&
405
479
  decided(e) &&
480
+ !isNotRunEffectClass(e.row.effectClass) &&
406
481
  (e.row.ref === ref || opts?.approvals?.some((a) => a.ref === ref && a.allowRef === e.row.ref)));
407
482
  let idx = findFor(row.ref);
408
483
  if (idx === -1) {
@@ -430,7 +505,7 @@ export function reconcile(channelRows, effects, opts) {
430
505
  ghost.push(asGhost(marked, effects));
431
506
  continue;
432
507
  }
433
- const fromSnap = effectAmount(effects[idx], opts?.approvals, opts?.decisionRequestHashes);
508
+ const fromSnap = effectAmount(effects[idx], opts?.approvals, opts?.decisionRequestHashes, opts?.decisionForwardedHashes);
434
509
  const gate = amountGate(row, fromSnap);
435
510
  if (gate === "unknown") {
436
511
  ghost.push(asGhost(marked, effects, "amount-unknown"));
@@ -456,7 +531,7 @@ export function reconcile(channelRows, effects, opts) {
456
531
  return false;
457
532
  if (Math.abs(row.occurredAtMs - e.row.timestampMs) > rowTol)
458
533
  return false;
459
- const stamps = descriptorsFor(e, opts?.approvals, opts?.descriptorsByPayee, opts?.decisionRequestHashes);
534
+ const stamps = descriptorsFor(e, opts?.approvals, opts?.descriptorsByPayee, opts?.decisionRequestHashes, opts?.decisionForwardedHashes);
460
535
  if (stamps) {
461
536
  const text = row.descriptor ?? "";
462
537
  if (!descriptorHits(text, stamps)) {
@@ -464,7 +539,7 @@ export function reconcile(channelRows, effects, opts) {
464
539
  return false;
465
540
  }
466
541
  }
467
- const fromSnap = effectAmount(e, opts?.approvals, opts?.decisionRequestHashes);
542
+ const fromSnap = effectAmount(e, opts?.approvals, opts?.decisionRequestHashes, opts?.decisionForwardedHashes);
468
543
  const gate = amountGate(row, fromSnap);
469
544
  if (gate === "unknown") {
470
545
  unknownNear = true;