@verax-ai/proxy 0.6.0 → 0.7.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/approvals.js CHANGED
@@ -9,6 +9,7 @@ import { signDecisionRecord } from "@cedulon/core";
9
9
  import { appendDurable, lookupDecisionByRef, lookupResolvedBy, noteResolution } from "./ledger.js";
10
10
  import { effectDescriptor, sha256Canonical } from "./hash.js";
11
11
  import { terminalText } from "./policy.js";
12
+ import { isProxyHalted } from "./process-halt.js";
12
13
  import { inputsLogFor } from "./inputs.js";
13
14
  import { SerialQueue } from "./serial-queue.js";
14
15
  function withStatus(cur, status, extra) {
@@ -237,7 +238,7 @@ function approvalsHalted(ledger) {
237
238
  const dir = ledgerStateDir(ledger);
238
239
  if (!dir)
239
240
  return false;
240
- return existsSync(join(dir, "halted"));
241
+ return isProxyHalted(dir);
241
242
  }
242
243
  async function approvePendingUnlocked(opts) {
243
244
  if (approvalsHalted(opts.ledger))
@@ -213,7 +213,13 @@ function parseHistoryLine(raw, line) {
213
213
  return null;
214
214
  if (typeof row.by !== "string" || row.by.length === 0 || row.by.length > 256)
215
215
  return null;
216
- const via = row.via === "http" ? "http" : row.via === "file" ? "file" : "cli";
216
+ const via = row.via === "http" || row.via === "file"
217
+ ? row.via
218
+ : row.via === "integrity"
219
+ ? "integrity"
220
+ : "cli";
221
+ // via: integrity is copied as claimed. verax verify accepts it only for
222
+ // action halt by verax:memory-integrity; any other pair is unsigned/failed.
217
223
  const parsed = { action: row.action, atMs: row.atMs, by: row.by, via, line };
218
224
  // The signature is copied as the line carries it, not judged here: a body
219
225
  // that dropped a bad one would turn a forged line into a quiet unsigned one.
package/dist/explain.js CHANGED
@@ -31,6 +31,59 @@ async function pairFor(ledger, decisions, record, inputsLog, approvals) {
31
31
  return { defer: null, resolution: null };
32
32
  }
33
33
  const WINDOW_COVERAGE = "window-coverage";
34
+ function allowedClassOf(record) {
35
+ const named = record.claims.effectClass;
36
+ if (typeof named === "string" && named !== "")
37
+ return named;
38
+ return undefined;
39
+ }
40
+ function extractSettlementRow(extract) {
41
+ if (!extract || typeof extract !== "object")
42
+ return undefined;
43
+ const body = extract.body;
44
+ const effects = body?.effects;
45
+ // One row or nothing: with more, the row a finding came from is unknown.
46
+ if (!Array.isArray(effects) || effects.length !== 1)
47
+ return undefined;
48
+ const row = effects[0];
49
+ if (!row || typeof row !== "object")
50
+ return undefined;
51
+ return row;
52
+ }
53
+ function isBoundHaltedRow(row, record) {
54
+ const allowedClass = allowedClassOf(record);
55
+ if (!row || !allowedClass || record.claims.decision !== "allow")
56
+ return false;
57
+ return (row.ref === record.claims.ref &&
58
+ typeof row.effectHash === "string" &&
59
+ row.effectHash === record.claims.effectHash &&
60
+ row.effectClass === `${allowedClass}:halted`);
61
+ }
62
+ function selfOrSameOrg(witnessClass) {
63
+ return witnessClass === "self" || witnessClass === "same-org";
64
+ }
65
+ /**
66
+ * Every row the audit saw for a ref: the ledger row, plus the extract that
67
+ * was presented for the explained ref (the caller's, or the stored receipt).
68
+ */
69
+ function auditedRows(effect, explainedRef, presentedExtract) {
70
+ const rows = [effect.row];
71
+ if (effect.row.ref === explainedRef && presentedExtract !== undefined) {
72
+ rows.push(extractSettlementRow(presentedExtract));
73
+ }
74
+ return rows;
75
+ }
76
+ function dropBoundHaltedClassMismatch(findings, decisions, effects, explainedRef, presentedExtract) {
77
+ return findings.filter((finding) => {
78
+ if (finding.code !== "effect-class-mismatch")
79
+ return true;
80
+ const record = decisions.find((d) => d.claims.ref === finding.id);
81
+ const effect = effects.find((e) => e.row.ref === finding.id && e.row.effectClass !== "duplicate-effect");
82
+ if (!record || !effect || !selfOrSameOrg(effect.witnessClass))
83
+ return true;
84
+ return !auditedRows(effect, explainedRef, presentedExtract).every((row) => isBoundHaltedRow(row, record));
85
+ });
86
+ }
34
87
  function resolveIssuerTrust(opts) {
35
88
  if (opts?.issuerTrust) {
36
89
  return {
@@ -99,7 +152,8 @@ export async function explain(ledger, ref, opts) {
99
152
  throw new Error(`explain-unknown-ref:${ref}`);
100
153
  }
101
154
  const effect = effects.find((e) => e.row.ref === ref && e.row.effectClass !== "duplicate-effect") ?? null;
102
- const presentedExtract = opts?.extract ?? effect?.receipt;
155
+ const userExtract = opts?.extract;
156
+ const presentedExtract = userExtract ?? effect?.receipt;
103
157
  const extractPresented = Boolean(presentedExtract);
104
158
  const resolvedTrust = resolveIssuerTrust(opts);
105
159
  const issuerTrust = resolvedTrust.pin;
@@ -133,12 +187,8 @@ export async function explain(ledger, ref, opts) {
133
187
  .map((f) => f.code)),
134
188
  ]
135
189
  : [];
136
- const applicable = dropWindow
137
- ? report.findings.filter((f) => f.code !== WINDOW_COVERAGE)
138
- : report.findings;
139
- const applicableWarnings = dropWindow
140
- ? report.warnings.filter((f) => f.code !== WINDOW_COVERAGE)
141
- : report.warnings;
190
+ const applicable = dropBoundHaltedClassMismatch(dropWindow ? report.findings.filter((f) => f.code !== WINDOW_COVERAGE) : report.findings, decisions, effects, ref, presentedExtract);
191
+ const applicableWarnings = dropBoundHaltedClassMismatch(dropWindow ? report.warnings.filter((f) => f.code !== WINDOW_COVERAGE) : report.warnings, decisions, effects, ref, presentedExtract);
142
192
  const refFindings = applicable.filter((f) => f.id === ref);
143
193
  const issuerFinding = applicable.find((f) => f.code === "issuer-key-mismatch" || f.id === "issuer") ??
144
194
  applicableWarnings.find((f) => f.code === "issuer-key-mismatch") ??
@@ -186,27 +236,39 @@ export async function explain(ledger, ref, opts) {
186
236
  const inputsMissing = typeof record.claims.inputsHash === "string" && inputsDoc === null;
187
237
  if (inputsMissing)
188
238
  conditions.push("inputs document missing");
189
- const balanced = refFindings.length === 0 && !chainBreak && !issuerMismatch && !inputsMismatch && !inputsMissing;
239
+ const haltedUnbound = effect !== null &&
240
+ auditedRows(effect, ref, presentedExtract).some((row) => typeof row?.effectClass === "string" && row.effectClass.endsWith(":halted") && !isBoundHaltedRow(row, record));
241
+ const balanced = refFindings.length === 0 &&
242
+ !chainBreak &&
243
+ !issuerMismatch &&
244
+ !inputsMismatch &&
245
+ !inputsMissing &&
246
+ !haltedUnbound;
190
247
  const code = chainBreak
191
248
  ? "receipt-chain-break"
192
249
  : inputsMismatch
193
250
  ? "inputs-hash-mismatch"
194
251
  : inputsMissing
195
252
  ? "inputs-document-missing"
196
- : (hit?.code ?? null);
253
+ : haltedUnbound
254
+ ? (hit?.code ?? "effect-class-mismatch")
255
+ : (hit?.code ?? null);
197
256
  const detail = chainBreak
198
257
  ? `receipt-chain-break at ${breakAt ?? "unknown"} (${brk?.reason ?? "broken"})`
199
258
  : inputsMismatch
200
259
  ? "inputs document hash does not match claims.inputsHash"
201
260
  : inputsMissing
202
261
  ? "claims.inputsHash is on the record; the inputs document is not on disk"
203
- : (hit?.detail ?? null);
262
+ : haltedUnbound && !hit
263
+ ? "halted effect is not bound to the same allow"
264
+ : (hit?.detail ?? null);
204
265
  const findingCount = chainBreak
205
266
  ? Math.max(refFindings.length, 1)
206
267
  : refFindings.length +
207
268
  (issuerMismatch && pinned ? 1 : 0) +
208
269
  (inputsMismatch ? 1 : 0) +
209
- (inputsMissing ? 1 : 0);
270
+ (inputsMissing ? 1 : 0) +
271
+ (haltedUnbound && refFindings.length === 0 ? 1 : 0);
210
272
  const guarantee = guaranteeWithConditions(report.guarantee, conditions);
211
273
  const summary = balanced
212
274
  ? balancedSummary(guarantee, conditions, report.summary)
package/dist/index.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  export { createProxy, LedgerDenyUnrecorded } from "./proxy.ts";
2
+ export { clearProcessHalted, isProcessHalted, markProcessHalted, persistHaltedSwitch } from "./process-halt.ts";
2
3
  export { effectDescriptor, sha256Canonical } from "./hash.ts";
3
4
  export { samePublicKey, thirdPartyReceiptRejection } from "./third-party.ts";
4
5
  export { loadPolicy, TERMINAL_CONTROL_CLASS, DISPLAY_ESCAPE_CLASS, terminalText, terminalLines } from "./policy.ts";
@@ -7,7 +8,7 @@ export { FileLedger, MemoryLedger, readLedgerTail, lockHolderAlive, lockState, l
7
8
  export { indexCoverage, listPieceFiles } from "./ledger-manifest.ts";
8
9
  export { explain } from "./explain.ts";
9
10
  export { approvePending, approvalsLogFor, createApprovalBudgetGuard, enqueueApprovalCommand, loadApprovalsFromDir, } from "./approvals.ts";
10
- export { loadDecisionRefsFromDir, loadEffectsFromDir, parseCardCsv, parseChannelJsonl, reconcile } from "./reconcile.ts";
11
+ export { loadDecisionRefsFromDir, loadDecisionRequestHashesFromDir, loadEffectsFromDir, parseCardCsv, parseChannelJsonl, reconcile, } from "./reconcile.ts";
11
12
  export { tenantKey } from "./tenant.ts";
12
13
  export { diskProbe } from "./disk.ts";
13
14
  export { checkpointsPath, readCheckpointFile } from "./checkpoints.ts";
package/dist/index.js CHANGED
@@ -1,4 +1,5 @@
1
1
  export { createProxy, LedgerDenyUnrecorded } from "./proxy.js";
2
+ export { clearProcessHalted, isProcessHalted, markProcessHalted, persistHaltedSwitch } from "./process-halt.js";
2
3
  export { effectDescriptor, sha256Canonical } from "./hash.js";
3
4
  export { samePublicKey, thirdPartyReceiptRejection } from "./third-party.js";
4
5
  export { loadPolicy, TERMINAL_CONTROL_CLASS, DISPLAY_ESCAPE_CLASS, terminalText, terminalLines } from "./policy.js";
@@ -6,7 +7,7 @@ export { FileLedger, MemoryLedger, readLedgerTail, lockHolderAlive, lockState, l
6
7
  export { indexCoverage, listPieceFiles } from "./ledger-manifest.js";
7
8
  export { explain } from "./explain.js";
8
9
  export { approvePending, approvalsLogFor, createApprovalBudgetGuard, enqueueApprovalCommand, loadApprovalsFromDir, } from "./approvals.js";
9
- export { loadDecisionRefsFromDir, loadEffectsFromDir, parseCardCsv, parseChannelJsonl, reconcile } from "./reconcile.js";
10
+ export { loadDecisionRefsFromDir, loadDecisionRequestHashesFromDir, loadEffectsFromDir, parseCardCsv, parseChannelJsonl, reconcile, } from "./reconcile.js";
10
11
  export { tenantKey } from "./tenant.js";
11
12
  // The body writes checkpoints and signs its own effect attestations. Both were
12
13
  // reached through a relative path into this package, which only exists inside
@@ -0,0 +1,9 @@
1
+ export declare const HALT_SWITCH = "halted";
2
+ export declare function haltSwitchPath(stateDir: string): string;
3
+ export declare function isHaltedSwitchFile(stateDir: string): boolean;
4
+ export declare function markProcessHalted(stateDir: string): void;
5
+ export declare function isProcessHalted(stateDir: string): boolean;
6
+ export declare function clearProcessHalted(stateDir: string): void;
7
+ /** If the process flag is set and the switch path is free, write the empty file. A written file owns the halt; the flag is then dropped. */
8
+ export declare function persistHaltedSwitch(stateDir: string): boolean;
9
+ export declare function isProxyHalted(stateDir: string): boolean;
@@ -0,0 +1,68 @@
1
+ import { existsSync, mkdirSync, statSync, writeFileSync } from "node:fs";
2
+ import { join, resolve } from "node:path";
3
+ /**
4
+ * Process-wide halt gate. The on-disk switch is `<stateDir>/halted`. The
5
+ * process flag is only for a halt whose file could not be written; once the
6
+ * file is there it is the single source of truth and the flag is cleared.
7
+ * The set lives on `globalThis` so source and dist copies of this module
8
+ * share one flag.
9
+ */
10
+ const FLAG = Symbol.for("verax.process-halt");
11
+ export const HALT_SWITCH = "halted";
12
+ function bag() {
13
+ const g = globalThis;
14
+ const existing = g[FLAG];
15
+ if (existing)
16
+ return existing;
17
+ const created = { dirs: new Set() };
18
+ g[FLAG] = created;
19
+ return created;
20
+ }
21
+ function keyOf(stateDir) {
22
+ return resolve(stateDir);
23
+ }
24
+ export function haltSwitchPath(stateDir) {
25
+ return join(stateDir, HALT_SWITCH);
26
+ }
27
+ export function isHaltedSwitchFile(stateDir) {
28
+ try {
29
+ return statSync(haltSwitchPath(stateDir)).isFile();
30
+ }
31
+ catch {
32
+ return false;
33
+ }
34
+ }
35
+ export function markProcessHalted(stateDir) {
36
+ bag().dirs.add(keyOf(stateDir));
37
+ }
38
+ export function isProcessHalted(stateDir) {
39
+ return bag().dirs.has(keyOf(stateDir));
40
+ }
41
+ export function clearProcessHalted(stateDir) {
42
+ bag().dirs.delete(keyOf(stateDir));
43
+ }
44
+ /** If the process flag is set and the switch path is free, write the empty file. A written file owns the halt; the flag is then dropped. */
45
+ export function persistHaltedSwitch(stateDir) {
46
+ if (isHaltedSwitchFile(stateDir)) {
47
+ clearProcessHalted(stateDir);
48
+ return true;
49
+ }
50
+ if (!isProcessHalted(stateDir))
51
+ return false;
52
+ const path = haltSwitchPath(stateDir);
53
+ try {
54
+ mkdirSync(stateDir, { recursive: true, mode: 0o700 });
55
+ if (existsSync(path))
56
+ return false;
57
+ writeFileSync(path, "", { encoding: "utf8", mode: 0o600 });
58
+ clearProcessHalted(stateDir);
59
+ return true;
60
+ }
61
+ catch {
62
+ return false;
63
+ }
64
+ }
65
+ export function isProxyHalted(stateDir) {
66
+ persistHaltedSwitch(stateDir);
67
+ return isHaltedSwitchFile(stateDir) || isProcessHalted(stateDir);
68
+ }
package/dist/proxy.js CHANGED
@@ -1,5 +1,4 @@
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
3
  import { approvePending, approvalsLogFor, createApprovalBudgetGuard, drainApprovalCommands, spentTodayMinorOf, } from "./approvals.js";
5
4
  import { SerialQueue } from "./serial-queue.js";
@@ -92,6 +91,9 @@ async function replayAfterEffect(ledger, ref) {
92
91
  if (primary?.row.effectClass.endsWith(":threw")) {
93
92
  return threwReplay(ref);
94
93
  }
94
+ if (primary?.row.effectClass.endsWith(":halted")) {
95
+ return denied("not-run-halted", ref);
96
+ }
95
97
  return allowedReplay(ref);
96
98
  }
97
99
  function deepFreeze(value) {
@@ -276,7 +278,30 @@ export function createProxy(deps) {
276
278
  });
277
279
  return denied("spend-reauth-required", ref);
278
280
  }
279
- async function runInner(call, principal, ref, effectRecorded) {
281
+ // The allow is already on the chain. A halt that lands now must not leave
282
+ // that ref without a primary effect (retry would answer outcome-unknown)
283
+ // and must not leave a start mark for a run that never started.
284
+ async function recordHaltedAfterAllow(allowRef, dispatchedCall, principal, effectRecorded) {
285
+ const dispatchedHash = sha256Canonical(effectDescriptor(dispatchedCall.name, dispatchedCall.arguments));
286
+ const row = {
287
+ ref: allowRef,
288
+ effectHash: dispatchedHash,
289
+ effectClass: `${dispatchedCall.name}:halted`,
290
+ timestampMs: deps.now(),
291
+ actor: principal.brain,
292
+ };
293
+ try {
294
+ await deps.ledger.appendEffect(row, "self", sha256Canonical({ halted: true }));
295
+ if (effectRecorded)
296
+ effectRecorded.ok = true;
297
+ }
298
+ catch {
299
+ // Still refuse the run. A missing effect keeps the start mark, so a
300
+ // retry cannot start the tool.
301
+ }
302
+ return denied("halted", allowRef);
303
+ }
304
+ async function runInner(call, principal, ref, effectRecorded, bound) {
280
305
  const dispatchedName = call.name;
281
306
  const dispatchedArgs = deepFreeze(structuredClone(call.arguments));
282
307
  const dispatchedHash = sha256Canonical(effectDescriptor(dispatchedName, dispatchedArgs));
@@ -286,8 +311,11 @@ export function createProxy(deps) {
286
311
  arguments: dispatchedArgs,
287
312
  });
288
313
  let result;
314
+ if (stateDir && isProxyHalted(stateDir)) {
315
+ return recordHaltedAfterAllow(ref, frozenCall, principal, effectRecorded);
316
+ }
289
317
  try {
290
- result = await deps.inner(frozenCall, principal, ref);
318
+ result = await deps.inner(frozenCall, principal, ref, bound);
291
319
  }
292
320
  catch (err) {
293
321
  const row = {
@@ -410,14 +438,14 @@ export function createProxy(deps) {
410
438
  });
411
439
  return denied(reasonCode, denyRef);
412
440
  }
413
- function launchInner(dispatchedCall, principal, allowRef, flightKey) {
441
+ function launchInner(dispatchedCall, principal, allowRef, flightKey, bound) {
414
442
  // Written before the tool runs, removed after the effect is recorded. A
415
443
  // mark that survives the process is what tells a restarted body that this
416
444
  // ref was already started (in-flight-log.ts).
417
445
  if (stateDir !== null)
418
446
  markStarted(stateDir, flightKey, dispatchedCall.name);
419
447
  const effectRecorded = { ok: false };
420
- const work = runInner(dispatchedCall, principal, allowRef, effectRecorded);
448
+ const work = runInner(dispatchedCall, principal, allowRef, effectRecorded, bound);
421
449
  inFlight.set(flightKey, work);
422
450
  return { kind: "run", work, key: flightKey, replayRef: allowRef, effectRecorded };
423
451
  }
@@ -517,32 +545,38 @@ export function createProxy(deps) {
517
545
  syncControlRecords,
518
546
  async call(call, principal) {
519
547
  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,
548
+ // Halt (file or process flag) is checked before the queue can authorize
549
+ // a spend or any other pending tool. approvePending uses the same gate.
550
+ if (!isProxyHalted(stateDir)) {
551
+ await drainApprovalCommands(stateDir, async (cmd) => {
552
+ const defer = await lookupDecisionByRef(deps.ledger, cmd.ref);
553
+ if (!defer || defer.decision !== "defer")
554
+ return;
555
+ await approvePending({
556
+ ledger: deps.ledger,
557
+ recordSigner: deps.recordSigner,
558
+ now: deps.now,
559
+ nonce: deps.nonce,
560
+ ref: cmd.ref,
561
+ approverId: cmd.approverId,
562
+ // A command with no `via` is an old queue file; treat it as a script, not a person.
563
+ via: cmd.via === "cli" ? "cli" : "cli-script",
564
+ policyHash: defer.policyHash,
565
+ approvals,
566
+ inputsLog,
567
+ budgetGuard,
568
+ });
537
569
  });
538
- });
570
+ }
539
571
  await syncControlRecords();
540
572
  }
541
573
  const dispatched = toolCallOf(call);
542
574
  const requestHash = sha256Canonical(dispatched);
543
575
  const timestampMs = deps.now();
544
576
  const resolved = await resolveInputs(call, principal, timestampMs);
545
- if (stateDir && existsSync(join(stateDir, "halted"))) {
577
+ async function denyIfHalted() {
578
+ if (!stateDir || !isProxyHalted(stateDir))
579
+ return null;
546
580
  const ref = deps.nonce();
547
581
  await writeRecord({
548
582
  decision: "deny",
@@ -556,6 +590,11 @@ export function createProxy(deps) {
556
590
  });
557
591
  return denied("halted", ref);
558
592
  }
593
+ {
594
+ const halted = await denyIfHalted();
595
+ if (halted)
596
+ return halted;
597
+ }
559
598
  if (stateDir && diskProbe.freeBytes(stateDir) < deps.policy.limits.diskFreeBytes) {
560
599
  const ref = deps.nonce();
561
600
  await writeRecordOrUnrecorded({
@@ -576,19 +615,10 @@ export function createProxy(deps) {
576
615
  if (stateDir)
577
616
  await syncControlRecords();
578
617
  // A call that waited here behind another admission reads the halt flag again.
579
- if (stateDir && existsSync(join(stateDir, "halted"))) {
580
- const ref = deps.nonce();
581
- await writeRecord({
582
- decision: "deny",
583
- reasonCode: "halted",
584
- ref,
585
- requestHash,
586
- inputs: resolved.inputs,
587
- effectHash: null,
588
- subject: call.name,
589
- timestampMs,
590
- });
591
- return { kind: "done", result: denied("halted", ref) };
618
+ {
619
+ const halted = await denyIfHalted();
620
+ if (halted)
621
+ return { kind: "done", result: halted };
592
622
  }
593
623
  if (given === "invalid") {
594
624
  const ref = deps.nonce();
@@ -742,7 +772,13 @@ export function createProxy(deps) {
742
772
  });
743
773
  return { kind: "done", result: denied("tenant-mismatch", denyRef) };
744
774
  }
745
- return launchInner(dispatched, principal, allow.ref, scopedRef);
775
+ if (stateDir && isProxyHalted(stateDir)) {
776
+ return {
777
+ kind: "done",
778
+ result: await recordHaltedAfterAllow(allow.ref, dispatched, principal),
779
+ };
780
+ }
781
+ return launchInner(dispatched, principal, allow.ref, scopedRef, boundRows);
746
782
  }
747
783
  return { kind: "done", result: deferred(given) };
748
784
  }
@@ -852,7 +888,10 @@ export function createProxy(deps) {
852
888
  if (!allow) {
853
889
  return { kind: "done", result: denied(reasonCode, shown, call) };
854
890
  }
855
- return launchInner(dispatched, principal, ref, ref);
891
+ if (stateDir && isProxyHalted(stateDir)) {
892
+ return { kind: "done", result: await recordHaltedAfterAllow(ref, dispatched, principal) };
893
+ }
894
+ return launchInner(dispatched, principal, ref, ref, resolved.inputs.inputs);
856
895
  });
857
896
  if (plan.kind === "done")
858
897
  return plan.result;
@@ -69,6 +69,11 @@ export declare function parseCardCsv(text: string, opts: CardCsvOpts): ParsedCar
69
69
  export declare function parseChannelJsonl(text: string): ChannelRow[];
70
70
  /** Decision refs, read the same way `verifyLedger` lists decision files. */
71
71
  export declare function loadDecisionRefsFromDir(stateDir: string): Set<string>;
72
+ /**
73
+ * requestHash on each decision, keyed by that decision's ref.
74
+ * Same files as `loadDecisionRefsFromDir`, still without the ledger lock.
75
+ */
76
+ export declare function loadDecisionRequestHashesFromDir(stateDir: string): Map<string, string>;
72
77
  export declare function loadEffectsFromDir(stateDir: string): LedgerEffect[];
73
78
  export declare function reconcile(channelRows: readonly ChannelRow[], effects: readonly LedgerEffect[], opts?: {
74
79
  toleranceMs?: number;
@@ -81,4 +86,6 @@ export declare function reconcile(channelRows: readonly ChannelRow[], effects: r
81
86
  descriptorsByPayee?: Readonly<Record<string, readonly string[]>>;
82
87
  /** Effect refs that have a decision. Absent means none: an effect is not a match. */
83
88
  decisionRefs?: ReadonlySet<string>;
89
+ /** Effect ref to the requestHash on the signed decision of that ref. */
90
+ decisionRequestHashes?: ReadonlyMap<string, string>;
84
91
  }): 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 { sha256Canonical } from "./hash.js";
4
5
  import { readLedgerManifest, requireLedgerPiecePath } from "./ledger-manifest.js";
5
6
  function asChannelRow(raw, line) {
6
7
  if (raw === null || typeof raw !== "object") {
@@ -221,9 +222,8 @@ function decisionPaths(dir) {
221
222
  const tek = join(dir, "decisions.jsonl");
222
223
  return existsSync(tek) ? [tek] : [];
223
224
  }
224
- /** Decision refs, read the same way `verifyLedger` lists decision files. */
225
- export function loadDecisionRefsFromDir(stateDir) {
226
- const refs = new Set();
225
+ function readDecisionLines(stateDir) {
226
+ const claims = [];
227
227
  for (const path of decisionPaths(stateDir)) {
228
228
  let text = "";
229
229
  try {
@@ -238,12 +238,35 @@ export function loadDecisionRefsFromDir(stateDir) {
238
238
  if (line === "")
239
239
  continue;
240
240
  const row = JSON.parse(line);
241
- if (typeof row.claims?.ref === "string")
242
- refs.add(row.claims.ref);
241
+ claims.push(row.claims ?? {});
243
242
  }
244
243
  }
244
+ return claims;
245
+ }
246
+ /** Decision refs, read the same way `verifyLedger` lists decision files. */
247
+ export function loadDecisionRefsFromDir(stateDir) {
248
+ const refs = new Set();
249
+ for (const claims of readDecisionLines(stateDir)) {
250
+ if (typeof claims.ref === "string")
251
+ refs.add(claims.ref);
252
+ }
245
253
  return refs;
246
254
  }
255
+ /**
256
+ * requestHash on each decision, keyed by that decision's ref.
257
+ * Same files as `loadDecisionRefsFromDir`, still without the ledger lock.
258
+ */
259
+ export function loadDecisionRequestHashesFromDir(stateDir) {
260
+ const hashes = new Map();
261
+ for (const claims of readDecisionLines(stateDir)) {
262
+ if (typeof claims.ref !== "string")
263
+ continue;
264
+ if (typeof claims.requestHash !== "string" || claims.requestHash === "")
265
+ continue;
266
+ hashes.set(claims.ref, claims.requestHash);
267
+ }
268
+ return hashes;
269
+ }
247
270
  export function loadEffectsFromDir(stateDir) {
248
271
  try {
249
272
  const text = readFileSync(join(stateDir, "effects.jsonl"), "utf8");
@@ -289,8 +312,23 @@ function approvalForEffect(approvals, effectRef) {
289
312
  return undefined;
290
313
  return approvals.find((r) => r.allowRef === effectRef || r.ref === effectRef);
291
314
  }
292
- function effectAmount(effect, approvals) {
315
+ /** The row may lend amount, currency and payee only when it still hashes to the signed request. */
316
+ function boundApproval(effect, approvals, requestHashes) {
317
+ if (!requestHashes)
318
+ return undefined;
319
+ const signed = requestHashes.get(effect.row.ref);
320
+ if (typeof signed !== "string" || signed === "")
321
+ return undefined;
293
322
  const snap = approvalForEffect(approvals, effect.row.ref);
323
+ if (!snap)
324
+ return undefined;
325
+ const rowHash = sha256Canonical({ name: snap.subject, arguments: snap.args });
326
+ if (rowHash !== signed)
327
+ return undefined;
328
+ return snap;
329
+ }
330
+ function effectAmount(effect, approvals, requestHashes) {
331
+ const snap = boundApproval(effect, approvals, requestHashes);
294
332
  const amountMinor = snap && typeof snap.args.amountMinor === "number" ? snap.args.amountMinor : undefined;
295
333
  const currency = snap && typeof snap.args.currency === "string" ? snap.args.currency : undefined;
296
334
  return { amountMinor, currency };
@@ -315,16 +353,25 @@ function amountGate(row, fromSnap) {
315
353
  }
316
354
  return "match";
317
355
  }
318
- function descriptorsFor(effect, approvals, byPayee) {
356
+ function descriptorsFor(effect, approvals, byPayee, requestHashes) {
319
357
  if (!byPayee)
320
358
  return undefined;
321
- const snap = approvalForEffect(approvals, effect.row.ref);
359
+ const snap = boundApproval(effect, approvals, requestHashes);
322
360
  const payee = snap && typeof snap.args.payee === "string" ? snap.args.payee : undefined;
323
361
  if (!payee)
324
362
  return undefined;
325
363
  const stamps = byPayee[payee];
326
364
  return stamps && stamps.length > 0 ? stamps : undefined;
327
365
  }
366
+ /**
367
+ * A signed not-run row is not treated as an external event. `:threw` does not
368
+ * mean the tool never ran: `inner` was called and a downstream side effect may
369
+ * have happened. Successful completion was not verified. Ghost classification
370
+ * stays cautious — ref matching must not hide a statement behind either suffix.
371
+ */
372
+ function isNotRunEffectClass(effectClass) {
373
+ return effectClass.endsWith(":halted") || effectClass.endsWith(":threw");
374
+ }
328
375
  export function reconcile(channelRows, effects, opts) {
329
376
  const toleranceMs = opts?.toleranceMs ?? 60_000;
330
377
  const decisionRefs = opts?.decisionRefs ?? new Set();
@@ -365,6 +412,7 @@ export function reconcile(channelRows, effects, opts) {
365
412
  if (typeof row.ref === "string" && row.ref !== "") {
366
413
  const findFor = (ref) => effects.findIndex((e, i) => !used.has(i) &&
367
414
  decided(e) &&
415
+ !isNotRunEffectClass(e.row.effectClass) &&
368
416
  (e.row.ref === ref || opts?.approvals?.some((a) => a.ref === ref && a.allowRef === e.row.ref)));
369
417
  let idx = findFor(row.ref);
370
418
  if (idx === -1) {
@@ -392,7 +440,7 @@ export function reconcile(channelRows, effects, opts) {
392
440
  ghost.push(asGhost(marked, effects));
393
441
  continue;
394
442
  }
395
- const fromSnap = effectAmount(effects[idx], opts?.approvals);
443
+ const fromSnap = effectAmount(effects[idx], opts?.approvals, opts?.decisionRequestHashes);
396
444
  const gate = amountGate(row, fromSnap);
397
445
  if (gate === "unknown") {
398
446
  ghost.push(asGhost(marked, effects, "amount-unknown"));
@@ -418,7 +466,7 @@ export function reconcile(channelRows, effects, opts) {
418
466
  return false;
419
467
  if (Math.abs(row.occurredAtMs - e.row.timestampMs) > rowTol)
420
468
  return false;
421
- const stamps = descriptorsFor(e, opts?.approvals, opts?.descriptorsByPayee);
469
+ const stamps = descriptorsFor(e, opts?.approvals, opts?.descriptorsByPayee, opts?.decisionRequestHashes);
422
470
  if (stamps) {
423
471
  const text = row.descriptor ?? "";
424
472
  if (!descriptorHits(text, stamps)) {
@@ -426,7 +474,7 @@ export function reconcile(channelRows, effects, opts) {
426
474
  return false;
427
475
  }
428
476
  }
429
- const fromSnap = effectAmount(e, opts?.approvals);
477
+ const fromSnap = effectAmount(e, opts?.approvals, opts?.decisionRequestHashes);
430
478
  const gate = amountGate(row, fromSnap);
431
479
  if (gate === "unknown") {
432
480
  unknownNear = true;
package/dist/types.d.ts CHANGED
@@ -119,7 +119,7 @@ export type DecisionInputRow = {
119
119
  export type ControlInput = {
120
120
  action: "halt" | "resume";
121
121
  by: string;
122
- via: "cli" | "http" | "file";
122
+ via: "cli" | "http" | "file" | "integrity";
123
123
  atMs: number;
124
124
  line: number;
125
125
  lineHash: string;
@@ -224,7 +224,10 @@ export type ProxyDeps = {
224
224
  ledger: Ledger;
225
225
  now: () => number;
226
226
  nonce: () => string;
227
- inner: (call: ToolCall, principal: Principal, ref?: string) => Promise<ToolResult>;
227
+ inner: (call: ToolCall, principal: Principal, ref?: string, bound?: ReadonlyArray<{
228
+ id: string;
229
+ versionHash: string;
230
+ }>) => Promise<ToolResult>;
228
231
  inputsLog?: InputsLog;
229
232
  resolveInput?: (id: string, principal?: Principal) => Promise<ResolvedInput | null>;
230
233
  /** True when the call names another tenant's memory id or decision ref. */
@@ -24,11 +24,16 @@
24
24
  * shared with record/effect/witness signers are refused. Without
25
25
  * a third-party pin the row is named unchecked and is not bound.
26
26
  * For self/same-org rows, a
27
- * thrown call relaxes only the hash, and only for the tool that
28
- * was allowed: some decision on that ref has `decision: "allow"`
29
- * and this row's class is exactly that decision's `effectClass`
30
- * plus `:threw`. A deny, or an allow of a different tool, does
31
- * not bind. The signature is still required. A
27
+ * thrown call relaxes only the hash, and only for the
28
+ * tool that was allowed: some decision on that ref has
29
+ * `decision: "allow"` and this row's class is exactly that
30
+ * decision's `effectClass` plus `:threw`. A halted call does
31
+ * not relax the hash: the same allow must have matching `ref`,
32
+ * matching `effectHash`, and this row's class is exactly that
33
+ * allow's `effectClass` plus `:halted`. The allow class is
34
+ * explicit and non-empty; `subject` is not a fallback. A deny,
35
+ * or an allow of a different tool, does not bind. The signature
36
+ * is still required. A
32
37
  * `duplicate-effect` row is bound to the decision by ref and to
33
38
  * the fixed refusal hash the writer stores, not to the
34
39
  * decision's effectHash; the signature is still required.
@@ -987,6 +992,25 @@ function isDecisionRow(row) {
987
992
  const claims = row.claims;
988
993
  return claims !== null && typeof claims === "object";
989
994
  }
995
+ function isThrownEffectClass(effectClass) {
996
+ return effectClass.endsWith(":threw");
997
+ }
998
+ function haltedBindsToSameAllow(ref, effectHash, effectClass, records) {
999
+ if (ref === null || effectHash === null)
1000
+ return false;
1001
+ for (const r of records) {
1002
+ if (r.claims.ref !== ref || r.claims.decision !== "allow")
1003
+ continue;
1004
+ const cls = r.claims.effectClass;
1005
+ if (typeof cls !== "string" || cls === "")
1006
+ continue;
1007
+ if (r.claims.effectHash !== effectHash)
1008
+ continue;
1009
+ if (effectClass === `${cls}:halted`)
1010
+ return true;
1011
+ }
1012
+ return false;
1013
+ }
990
1014
  export async function verifyLedger(dir, opts = {}) {
991
1015
  try {
992
1016
  return await verifyLedgerUnchecked(dir, opts);
@@ -1102,12 +1126,15 @@ async function verifyLedgerUnchecked(dir, opts = {}) {
1102
1126
  // An effect is bound only when a decision with that ref records the same
1103
1127
  // effectHash. A `:threw` row relaxes the hash and nothing else: it binds
1104
1128
  // only when some decision on that ref is an allow and the row's class is
1105
- // exactly that decision's effectClass plus `:threw`. A deny did not throw,
1106
- // and an allow of a different tool is not this class. A `duplicate-effect`
1107
- // row must carry the writer's fixed refusal hash. The attestation plus
1108
- // receipt still verify under one effect key. A mismatch is named and counts
1109
- // as orphaned. A second primary row for a ref that already has one is named
1110
- // and is not bound, even when the first row itself did not bind.
1129
+ // exactly that decision's effectClass plus `:threw`. A `:halted` row keeps
1130
+ // the hash: the same allow must match ref, effectHash, and class plus
1131
+ // `:halted`. A deny did not throw or halt, and an allow of a different tool
1132
+ // is not this class. A
1133
+ // `duplicate-effect` row must carry the writer's fixed refusal hash. The
1134
+ // attestation plus receipt still verify under one effect key. A mismatch is
1135
+ // named and counts as orphaned. A second primary row for a ref that already
1136
+ // has one is named and is not bound, even when the first row itself did not
1137
+ // bind.
1111
1138
  const refler = new Set();
1112
1139
  const hashesByRef = new Map();
1113
1140
  const allowedClassesByRef = new Map();
@@ -1224,23 +1251,34 @@ async function verifyLedgerUnchecked(dir, opts = {}) {
1224
1251
  primarySeen.add(ref);
1225
1252
  const hashes = ref === null ? undefined : hashesByRef.get(ref);
1226
1253
  const hashMatch = effectHash !== null && hashes?.has(effectHash) === true;
1227
- if (e.witnessClass !== "third-party" && effectClass.endsWith(":threw")) {
1254
+ if (e.witnessClass !== "third-party" && isThrownEffectClass(effectClass)) {
1228
1255
  const allowed = ref === null ? undefined : allowedClassesByRef.get(ref);
1229
- let thrownOk = false;
1256
+ let threwOk = false;
1230
1257
  if (allowed) {
1231
1258
  for (const cls of allowed) {
1232
1259
  if (`${cls}:threw` === effectClass) {
1233
- thrownOk = true;
1260
+ threwOk = true;
1234
1261
  break;
1235
1262
  }
1236
1263
  }
1237
1264
  }
1238
- if (!thrownOk) {
1265
+ if (!threwOk) {
1239
1266
  effectsOrphaned += 1;
1240
1267
  problems.push(`thrown effect does not match an allowed decision: ref ${ref ?? "(missing)"}`);
1241
1268
  continue;
1242
1269
  }
1243
1270
  }
1271
+ else if (e.witnessClass !== "third-party" && effectClass.endsWith(":halted")) {
1272
+ if (!haltedBindsToSameAllow(ref, effectHash, effectClass, records)) {
1273
+ effectsOrphaned += 1;
1274
+ const stem = effectClass.slice(0, -":halted".length);
1275
+ const classWouldMatch = ref !== null && (allowedClassesByRef.get(ref)?.has(stem) ?? false);
1276
+ problems.push(classWouldMatch && ref !== null
1277
+ ? `effect hash does not match its decision: ref ${ref}`
1278
+ : `halted effect does not match an allowed decision: ref ${ref ?? "(missing)"}`);
1279
+ continue;
1280
+ }
1281
+ }
1244
1282
  else if (!hashMatch) {
1245
1283
  effectsOrphaned += 1;
1246
1284
  problems.push(ref === null || !refler.has(ref)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@verax-ai/proxy",
3
- "version": "0.6.0",
3
+ "version": "0.7.0",
4
4
  "license": "Apache-2.0",
5
5
  "type": "module",
6
6
  "engines": {