@verax-ai/proxy 0.1.0 → 0.1.2

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/LICENSE ADDED
@@ -0,0 +1,192 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the
44
+ purposes of this License, Derivative Works shall not include works
45
+ that remain separable from, or merely link (or bind by name) to
46
+ the interfaces of, the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of,
58
+ the Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as
159
+ a result of this License or out of the use or inability to use
160
+ the Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ Copyright 2026 VERAX TEKNOLOJİ LİMİTED ŞİRKETİ
181
+
182
+ Licensed under the Apache License, Version 2.0 (the "License");
183
+ you may not use this file except in compliance with the License.
184
+ You may obtain a copy of the License at
185
+
186
+ http://www.apache.org/licenses/LICENSE-2.0
187
+
188
+ Unless required by applicable law or agreed to in writing, software
189
+ distributed under the License is distributed on an "AS IS" BASIS,
190
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
191
+ See the License for the specific language governing permissions and
192
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,46 @@
1
+ # @verax-ai/proxy
2
+
3
+ The decision proxy behind Verax. Every tool call goes through a policy that
4
+ denies what it does not name, leaves a signed decision record before the
5
+ call runs, and an effect row after it did. The records live in a ledger on
6
+ local disk, and `explain` reads that ledger back and reports what it finds,
7
+ including a record whose effect does not match it.
8
+
9
+ Part of [Verax](https://github.com/verax-ai/verax) by
10
+ [VERAX Teknoloji](https://verax-ai.com). Most callers want
11
+ [`@verax-ai/body`](https://www.npmjs.com/package/@verax-ai/body), the MCP
12
+ server built on this package. What the code carries and what stays unproven
13
+ is stated in
14
+ [`docs/STATUS.md`](https://github.com/verax-ai/verax/blob/main/docs/STATUS.md).
15
+
16
+ ## Install
17
+
18
+ ```sh
19
+ npm install @verax-ai/proxy
20
+ ```
21
+
22
+ Node 22.6 or newer. Decision records use the Cedulon record format
23
+ (`@cedulon/core`, `@cedulon/audit`).
24
+
25
+ ## Use
26
+
27
+ ```js
28
+ import { createProxy, loadPolicy, FileLedger, explain } from "@verax-ai/proxy";
29
+ ```
30
+
31
+ - `loadPolicy` reads a policy file. `policy/default.json` in this package is
32
+ the one the body starts from.
33
+ - `createProxy` wraps tool functions: each call is decided and recorded, then
34
+ run or refused.
35
+ - `FileLedger` and `MemoryLedger` hold the records, one `FileLedger` per
36
+ directory.
37
+ - `explain` reads a ledger and reports the chain, its signatures and its
38
+ findings.
39
+ - `approvePending`, `reconcile` and `parseCardCsv` are what the body's
40
+ `approve` and `reconcile` commands call.
41
+
42
+ The exports map is the whole public surface; deep imports are not in it.
43
+
44
+ ## License
45
+
46
+ Apache-2.0.
@@ -6,7 +6,7 @@ export declare const approvalFs: {
6
6
  export declare const drainMetrics: {
7
7
  renameBusy: number;
8
8
  };
9
- import type { ApprovalChannel, InputsLog, Ledger, RecordSigner } from "./types.ts";
9
+ import type { ApprovalChannel, InputsLog, Ledger, Policy, RecordSigner } from "./types.ts";
10
10
  export type ApprovalRow = {
11
11
  ref: string;
12
12
  requestHash: string;
@@ -68,7 +68,25 @@ export type ApproveResult = {
68
68
  } | {
69
69
  ok: false;
70
70
  reason: string;
71
+ allowRef?: string;
71
72
  };
73
+ export declare function spentTodayMinorOf(rows: Array<{
74
+ subject: string;
75
+ status: string;
76
+ createdAtMs?: number;
77
+ expiresAtMs: number;
78
+ args: Record<string, unknown>;
79
+ }>, nowMs: number, currency: string, approvalTtlMs: number): number;
80
+ export declare function createApprovalBudgetGuard(opts: {
81
+ policy: Policy;
82
+ approvals: ApprovalsLog;
83
+ now: () => number;
84
+ }): (snap: ApprovalRow) => Promise<{
85
+ ok: true;
86
+ } | {
87
+ ok: false;
88
+ reason: "budget-exceeded";
89
+ }>;
72
90
  export declare function approvePending(opts: {
73
91
  ledger: Ledger;
74
92
  recordSigner: RecordSigner;
@@ -81,6 +99,17 @@ export declare function approvePending(opts: {
81
99
  policyHash: string;
82
100
  approvals: ApprovalsLog;
83
101
  inputsLog?: InputsLog;
102
+ budgetGuard?: (snap: ApprovalRow) => {
103
+ ok: true;
104
+ } | {
105
+ ok: false;
106
+ reason: "budget-exceeded";
107
+ } | Promise<{
108
+ ok: true;
109
+ } | {
110
+ ok: false;
111
+ reason: "budget-exceeded";
112
+ }>;
84
113
  }): Promise<ApproveResult>;
85
114
  export type ApprovalCommand = {
86
115
  ref: string;
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 { inputsLogFor } from "./inputs.js";
12
+ import { SerialQueue } from "./serial-queue.js";
12
13
  function lastByRef(rows) {
13
14
  const map = new Map();
14
15
  for (const row of rows)
@@ -105,6 +106,56 @@ export function loadApprovalsFromDir(dir) {
105
106
  throw err;
106
107
  }
107
108
  }
109
+ const APPROVAL_LOCK = Symbol.for("verax.approvalLock");
110
+ function approvalLockFor(ledger) {
111
+ const bag = ledger;
112
+ if (!bag[APPROVAL_LOCK])
113
+ bag[APPROVAL_LOCK] = new SerialQueue();
114
+ return bag[APPROVAL_LOCK];
115
+ }
116
+ export function spentTodayMinorOf(rows, nowMs, currency, approvalTtlMs) {
117
+ const d = new Date(nowMs);
118
+ const start = Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate());
119
+ const end = start + 86_400_000;
120
+ let sum = 0;
121
+ for (const row of rows) {
122
+ if (row.subject !== "spend")
123
+ continue;
124
+ if (row.status !== "pending" && row.status !== "approved")
125
+ continue;
126
+ const created = row.createdAtMs ?? row.expiresAtMs - approvalTtlMs;
127
+ if (created < start || created >= end)
128
+ continue;
129
+ if (row.args.currency !== currency)
130
+ continue;
131
+ const amt = row.args.amountMinor;
132
+ if (typeof amt === "number")
133
+ sum += amt;
134
+ }
135
+ return sum;
136
+ }
137
+ export function createApprovalBudgetGuard(opts) {
138
+ return async (snap) => {
139
+ if (snap.subject !== "spend")
140
+ return { ok: true };
141
+ const dailyMax = opts.policy.rule(snap.ruleId)?.spend?.dailyMaxMinor;
142
+ if (dailyMax === undefined)
143
+ return { ok: true };
144
+ const currency = typeof snap.args.currency === "string" ? snap.args.currency : "";
145
+ const amount = typeof snap.args.amountMinor === "number" ? snap.args.amountMinor : 0;
146
+ // Sibling pending rows are not authorized yet. Counting them here would
147
+ // deadlock two 100-unit pendings against a later 150 cap; approved spend
148
+ // plus this amount is what the operator is about to commit.
149
+ const others = (await opts.approvals.listAll()).filter((row) => row.ref !== snap.ref && row.status === "approved");
150
+ const spent = spentTodayMinorOf(others, opts.now(), currency, opts.policy.approvalTtlMs);
151
+ if (spent + amount > dailyMax)
152
+ return { ok: false, reason: "budget-exceeded" };
153
+ return { ok: true };
154
+ };
155
+ }
156
+ function alreadyResolved(allowRef) {
157
+ return { ok: false, reason: "already-resolved", ...(allowRef ? { allowRef } : {}) };
158
+ }
108
159
  async function hasResolves(inputsLog, ledger, deferRef) {
109
160
  const indexed = ledger;
110
161
  if (typeof indexed.lookupResolvedBy === "function") {
@@ -120,20 +171,25 @@ async function hasResolves(inputsLog, ledger, deferRef) {
120
171
  return false;
121
172
  }
122
173
  export async function approvePending(opts) {
174
+ return approvalLockFor(opts.ledger).enqueue(() => approvePendingUnlocked(opts));
175
+ }
176
+ async function approvePendingUnlocked(opts) {
123
177
  const inputsLog = opts.inputsLog ?? inputsLogFor(opts.ledger);
124
178
  const defer = await lookupDecisionByRef(opts.ledger, opts.ref);
125
179
  if (!defer || defer.decision !== "defer")
126
180
  return { ok: false, reason: "unknown-ref" };
127
181
  const snap = await opts.approvals.get(opts.ref);
128
- if (snap && snap.status !== "pending")
129
- return { ok: false, reason: "already-resolved" };
182
+ if (snap && snap.status !== "pending") {
183
+ const hit = lookupResolvedBy(opts.ledger, opts.ref);
184
+ return alreadyResolved(snap.allowRef ?? (hit?.kind === "allow" ? hit.ref : undefined));
185
+ }
130
186
  const resolved = lookupResolvedBy(opts.ledger, opts.ref);
131
187
  if (resolved || (await hasResolves(inputsLog, opts.ledger, opts.ref))) {
132
188
  const hit = resolved ?? lookupResolvedBy(opts.ledger, opts.ref);
133
189
  if (snap?.status === "pending" && hit) {
134
190
  await opts.approvals.updateStatus(opts.ref, hit.kind === "allow" ? "approved" : "expired", hit.kind === "allow" ? { allowRef: hit.ref } : undefined);
135
191
  }
136
- return { ok: false, reason: "already-resolved" };
192
+ return alreadyResolved(hit?.kind === "allow" ? hit.ref : snap?.allowRef);
137
193
  }
138
194
  if (!snap)
139
195
  return { ok: false, reason: "snapshot-missing" };
@@ -172,6 +228,11 @@ export async function approvePending(opts) {
172
228
  await opts.approvals.updateStatus(opts.ref, "expired");
173
229
  return { ok: false, reason: "expired" };
174
230
  }
231
+ if (opts.budgetGuard) {
232
+ const guarded = await opts.budgetGuard(snap);
233
+ if (!guarded.ok)
234
+ return guarded;
235
+ }
175
236
  const allowRef = opts.nonce();
176
237
  const prior = await inputsLog.get(opts.ref);
177
238
  const inputs = {
@@ -0,0 +1 @@
1
+ export declare function writeFileAtomic(path: string, text: string): void;
@@ -0,0 +1,65 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import { chmodSync, mkdirSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
3
+ import { dirname } from "node:path";
4
+ /**
5
+ * Replace a file's contents in one step, so a reader sees the old bytes or the
6
+ * new ones and never a half-written file.
7
+ *
8
+ * Writing in place is not that: measured on 11 Sep 2026, a reader polling this
9
+ * path every 20 ms while the file was rewritten 60 times got 12 unparseable
10
+ * reads. The listen file is read by another process — that is its whole job —
11
+ * and a torn read becomes `null`, which the caller cannot tell from "nothing
12
+ * is running".
13
+ *
14
+ * The rename needs the retry. On Windows it fails with EPERM while a reader
15
+ * holds the destination open, and in the same measurement 26 of 60 plain
16
+ * renames failed that way. Retrying briefly lost none of them and still let no
17
+ * torn read through.
18
+ *
19
+ * The temporary name carries this process and a random suffix. A fixed `.tmp`
20
+ * next to the destination is what two writers, or a crashed writer, collide
21
+ * on.
22
+ */
23
+ const napper = new Int32Array(new SharedArrayBuffer(4));
24
+ /**
25
+ * Sleep without spinning. An earlier retry burned the processor between
26
+ * attempts, which is the worst thing to do while waiting for another process
27
+ * to let go of a file: under the unit suite's own load the spin starved the
28
+ * reader it was waiting on, the retries ran out in 200 ms, and the write
29
+ * threw EPERM. Atomics.wait yields the core instead.
30
+ */
31
+ function napSync(ms) {
32
+ Atomics.wait(napper, 0, 0, ms);
33
+ }
34
+ export function writeFileAtomic(path, text) {
35
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
36
+ const tmp = `${path}.${process.pid}.${randomBytes(8).toString("hex")}.tmp`;
37
+ writeFileSync(tmp, text, { encoding: "utf8", mode: 0o600 });
38
+ try {
39
+ for (let attempt = 0;; attempt += 1) {
40
+ try {
41
+ renameSync(tmp, path);
42
+ chmodSync(path, 0o600);
43
+ return;
44
+ }
45
+ catch (err) {
46
+ const code = err.code;
47
+ // Two seconds of patience. A reader holds this file for microseconds
48
+ // when the machine is idle; the budget is for the machine that is not.
49
+ if (attempt >= 100 || (code !== "EPERM" && code !== "EACCES" && code !== "EBUSY")) {
50
+ throw err;
51
+ }
52
+ napSync(20);
53
+ }
54
+ }
55
+ }
56
+ catch (err) {
57
+ try {
58
+ unlinkSync(tmp);
59
+ }
60
+ catch {
61
+ // rename may already have moved it
62
+ }
63
+ throw err;
64
+ }
65
+ }
package/dist/index.d.ts CHANGED
@@ -1,8 +1,9 @@
1
1
  export { createProxy, LedgerDenyUnrecorded } from "./proxy.ts";
2
2
  export { loadPolicy } from "./policy.ts";
3
- export { FileLedger, MemoryLedger } from "./ledger.ts";
3
+ export { FileLedger, MemoryLedger, readLedgerTail } from "./ledger.ts";
4
+ export { indexCoverage, listPieceFiles } from "./ledger-manifest.ts";
4
5
  export { explain } from "./explain.ts";
5
- export { approvePending, approvalsLogFor, enqueueApprovalCommand, loadApprovalsFromDir } from "./approvals.ts";
6
+ export { approvePending, approvalsLogFor, createApprovalBudgetGuard, enqueueApprovalCommand, loadApprovalsFromDir, } from "./approvals.ts";
6
7
  export { loadEffectsFromDir, parseCardCsv, parseChannelJsonl, reconcile } from "./reconcile.ts";
7
8
  export { tenantKey } from "./tenant.ts";
8
9
  export { diskProbe } from "./disk.ts";
@@ -11,4 +12,5 @@ export { signEffectAttestation } from "./ledger.ts";
11
12
  export { spokenReason } from "./spoken-reason.ts";
12
13
  export type { ApprovalRow, ApproveResult } from "./approvals.ts";
13
14
  export type { CardCsvOpts, ChannelRow, ReconcileReport } from "./reconcile.ts";
15
+ export type { FileLedgerOpts, LedgerCounts } from "./ledger.ts";
14
16
  export type { EffectSigner, ExplainChain, ExplainPair, ExplainFinding, ExplainOpts, ExplainResult, ExplainTrustRoot, ExplainWarning, ExtractWindow, Ledger, LedgerEffect, Policy, PolicyDecision, Principal, ProxyDeps, RecordSigner, ToolCall, ToolResult, WitnessClass, } from "./types.ts";
package/dist/index.js CHANGED
@@ -1,8 +1,9 @@
1
1
  export { createProxy, LedgerDenyUnrecorded } from "./proxy.js";
2
2
  export { loadPolicy } from "./policy.js";
3
- export { FileLedger, MemoryLedger } from "./ledger.js";
3
+ export { FileLedger, MemoryLedger, readLedgerTail } from "./ledger.js";
4
+ export { indexCoverage, listPieceFiles } from "./ledger-manifest.js";
4
5
  export { explain } from "./explain.js";
5
- export { approvePending, approvalsLogFor, enqueueApprovalCommand, loadApprovalsFromDir } from "./approvals.js";
6
+ export { approvePending, approvalsLogFor, createApprovalBudgetGuard, enqueueApprovalCommand, loadApprovalsFromDir, } from "./approvals.js";
6
7
  export { loadEffectsFromDir, parseCardCsv, parseChannelJsonl, reconcile } from "./reconcile.js";
7
8
  export { tenantKey } from "./tenant.js";
8
9
  // The body writes checkpoints and signs its own effect attestations. Both were
package/dist/inputs.d.ts CHANGED
@@ -6,7 +6,13 @@ export declare class MemoryInputsLog implements InputsLog {
6
6
  }
7
7
  export declare class FileInputsLog implements InputsLog {
8
8
  private readonly dir;
9
- constructor(dir: string);
9
+ private readonly resolve;
10
+ private readonly note;
11
+ constructor(dir: string, resolve?: () => {
12
+ active: string;
13
+ all: string[];
14
+ }, note?: (ref: string, inputs: DecisionInputs) => void);
15
+ private paths;
10
16
  append(ref: string, inputs: DecisionInputs): Promise<void>;
11
17
  get(ref: string): Promise<DecisionInputs | null>;
12
18
  }
package/dist/inputs.js CHANGED
@@ -11,29 +11,44 @@ export class MemoryInputsLog {
11
11
  }
12
12
  export class FileInputsLog {
13
13
  dir;
14
- constructor(dir) {
14
+ resolve;
15
+ note;
16
+ constructor(dir, resolve, note) {
15
17
  this.dir = dir;
18
+ this.resolve = resolve;
19
+ this.note = note;
20
+ }
21
+ paths() {
22
+ if (this.resolve)
23
+ return this.resolve();
24
+ const root = join(this.dir, "inputs.jsonl");
25
+ return { active: root, all: [root] };
16
26
  }
17
27
  async append(ref, inputs) {
18
- await appendDurable(join(this.dir, "inputs.jsonl"), `${JSON.stringify({ ref, inputs })}\n`);
28
+ await appendDurable(this.paths().active, `${JSON.stringify({ ref, inputs })}\n`);
29
+ // Handed to the ledger in memory: the decision that follows needs the
30
+ // principal for its index line and must not read this file back.
31
+ this.note?.(ref, inputs);
19
32
  }
20
33
  async get(ref) {
21
- let text;
22
- try {
23
- text = await ledgerFs.readFile(join(this.dir, "inputs.jsonl"), "utf8");
24
- }
25
- catch (err) {
26
- if (err.code === "ENOENT")
27
- return null;
28
- throw err;
29
- }
30
34
  let found = null;
31
- for (const line of text.split("\n")) {
32
- if (line === "")
33
- continue;
34
- const row = JSON.parse(line);
35
- if (row.ref === ref)
36
- found = row.inputs;
35
+ for (const path of this.paths().all) {
36
+ let text;
37
+ try {
38
+ text = await ledgerFs.readFile(path, "utf8");
39
+ }
40
+ catch (err) {
41
+ if (err.code === "ENOENT")
42
+ continue;
43
+ throw err;
44
+ }
45
+ for (const line of text.split("\n")) {
46
+ if (line === "")
47
+ continue;
48
+ const row = JSON.parse(line);
49
+ if (row.ref === ref)
50
+ found = row.inputs;
51
+ }
37
52
  }
38
53
  return found;
39
54
  }
@@ -43,7 +58,9 @@ export function inputsLogFor(ledger) {
43
58
  const bag = ledger;
44
59
  if (bag[STASH])
45
60
  return bag[STASH];
46
- const log = typeof bag.dir === "string" ? new FileInputsLog(bag.dir) : new MemoryInputsLog();
61
+ const resolve = typeof bag.inputsPaths === "function" ? () => bag.inputsPaths() : undefined;
62
+ const note = typeof bag.noteInputs === "function" ? (ref, inputs) => bag.noteInputs(ref, inputs) : undefined;
63
+ const log = typeof bag.dir === "string" ? new FileInputsLog(bag.dir, resolve, note) : new MemoryInputsLog();
47
64
  bag[STASH] = log;
48
65
  return log;
49
66
  }
@@ -0,0 +1,26 @@
1
+ import { open as fsOpen } from "node:fs/promises";
2
+ export type TailVisit = "take" | "skip" | "stop";
3
+ export type TailOpts = {
4
+ /**
5
+ * Bytes read per step from the end. Default 64 KiB: measured on a 194 MB
6
+ * file, 64 KiB, 256 KiB and 1 MiB read the whole of it in the same time,
7
+ * and the small step keeps a small window's cost small.
8
+ */
9
+ chunkBytes?: number;
10
+ /** The file opener, so a seam or a test can count what was read. */
11
+ open?: typeof fsOpen;
12
+ /**
13
+ * Walk backwards from this byte instead of the file's end. A window that
14
+ * starts inside a piece uses this after a timestamp seek so the walk does
15
+ * not cross every later row.
16
+ */
17
+ endOffset?: number;
18
+ };
19
+ export declare function readJsonlTail<T>(path: string, visit: (row: T) => TailVisit, opts?: TailOpts): Promise<T[]>;
20
+ /**
21
+ * The start of the first row whose stamp is at or after `targetMs`, or the
22
+ * file size when none is. Rows are treated as time-ordered (one writer, the
23
+ * clock's `now()`); a 60 s slack on the caller covers a clock set back.
24
+ * Each probe reads from the mid offset until the first complete line.
25
+ */
26
+ export declare function seekOffsetByTimestamp<T>(path: string, targetMs: number, tsOf: (row: T) => number, opts?: TailOpts): Promise<number>;