no-receipts 0.0.0-stage → 0.1.1

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,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 os1249399459
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,246 @@
1
- # Temporary Holding Version
1
+ # no-receipts
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ **Blocks an agent from saying "done" when its claims aren't backed by tool calls that actually succeeded.**
4
+
5
+ > *No receipts, no done.*
6
+
7
+ Zero dependencies. No model in the loop. ~1,000 lines, one job.
8
+
9
+ The name is the rule. In the culture this comes from, you don't get to make a claim without
10
+ producing the receipts — and a tool call that exited non-zero is not a receipt.
11
+
12
+ ```bash
13
+ npx no-receipts demo # three turns: one liar, one failed check, one real
14
+ npx no-receipts claims.json # exit 0 = complete, 1 = retry, 2 = abort
15
+ ```
16
+
17
+ ---
18
+
19
+ ## The failure this catches
20
+
21
+ Agent says: *"Fixed the bug and all tests pass."*
22
+
23
+ What actually happened: it ran the test suite, the suite failed, and it summarised anyway. Or it never ran anything. Either way the sentence is false, and you find out three commits later.
24
+
25
+ `no-receipts` makes that sentence impossible to end a turn with. The model must emit claims shaped like this:
26
+
27
+ ```json
28
+ {
29
+ "claims": [
30
+ {
31
+ "text": "all tests pass",
32
+ "status": "done",
33
+ "evidence_ids": ["ev_9f2c..."],
34
+ "verification": { "type": "cli", "command": "npx", "args": ["vitest", "run"] },
35
+ "open_questions": [],
36
+ "unverified_assumptions": []
37
+ }
38
+ ]
39
+ }
40
+ ```
41
+
42
+ and `ev_9f2c...` must resolve to a tool call that ran and **succeeded**. Four rules, checked in order:
43
+
44
+ | # | Rule | Verdict on violation |
45
+ |---|---|---|
46
+ | 1 | `done` must cite ≥1 `evidence_id` | `claim_invalid` |
47
+ | 2 | every cited id must exist in the ledger | `evidence_missing` |
48
+ | 3 | every cited id must have `ok: true` | `evidence_failed` |
49
+ | 4 | `unknown`/`blocked` must appear in `open_questions` or `unverified_assumptions` | `claim_invalid` |
50
+
51
+ Rule 4 is the subtle one. "I don't know" is a legitimate answer — but only when the user is told. An undisclosed `unknown` is the quietest fake completion, and the hardest to catch by reading the transcript.
52
+
53
+ ## Why not just trust a verifier
54
+
55
+ The gate has three outcomes and deliberately no fourth:
56
+
57
+ - `complete` — claims validated
58
+ - `feedback` — retryable; the exact issue list is handed back to the model
59
+ - `abort` — retries spent, or a divergence limit hit
60
+
61
+ There is no "pass because we ran out of ideas." A gate that fails open is decoration. The retry budget defaults to **1**, so a persistent liar is aborted rather than looped forever.
62
+
63
+ Divergence limits catch a different failure — the agent that keeps working and never converges:
64
+
65
+ | Limit | Default |
66
+ |---|---|
67
+ | steps per turn | 20 |
68
+ | tool calls per turn | 30 |
69
+ | consecutive no-progress steps | 3 |
70
+
71
+ "No progress" means the claim statuses and cited evidence ids are byte-identical to the previous step. Cheap to compute, hard to game.
72
+
73
+ ## Verifiers
74
+
75
+ A verifier either answers deterministically or returns `unknown`. Nothing here calls a model — a verifier that guesses is worse than no verifier, because the gate would trust it.
76
+
77
+ ### Status
78
+
79
+ | Verifier | Type key | Status | Notes |
80
+ |---|---|---|---|
81
+ | `FileVerifier` | `filesystem` | **Done** | existence + optional content SHA-256; `rootDir` confinement |
82
+ | `CliVerifier` | `cli` | **Done** | exit-code verdicts, explicit command allowlist, empty output → `unknown` |
83
+ | `BrowserVerifier` | `browser` | **Done** | injected client; asserts selector / text / state / url |
84
+ | `GroundingVerifier` | `grounding` | **Done** | injected client; a judge-only `pass` is downgraded to `unknown` |
85
+ | `HttpVerifier` | `http` | *To be continued* | status/JSON-path assertions against a live endpoint |
86
+ | `GitHubVerifier` | `github` | *To be continued* | PR/commit checks via the GitHub API; needs a token, so it is opt-in by construction |
87
+
88
+ The two "to be continued" entries are deliberately unimplemented rather than stubbed. A stub that returns `unknown` forever would silently degrade every claim that used it into an abort — worse than a missing verifier, because it looks like it works.
89
+
90
+ The two shipped-but-injected verifiers (`browser`, `grounding`) follow the same rule: the **client** is yours to supply (Playwright MCP, a FastAPI grounding service, whatever), because bundling a browser stack or a Python runtime would destroy the zero-dependency property for everyone who only needs file and command checks.
91
+
92
+ ```ts
93
+ import { FileVerifier, CliVerifier, BrowserVerifier, VerifierRegistry } from 'no-receipts'
94
+
95
+ const registry = new VerifierRegistry([
96
+ new FileVerifier({ rootDir: process.cwd() }),
97
+ new CliVerifier({ allowedCommands: ['npx', 'pytest', 'tsc'] }),
98
+ new BrowserVerifier(myPlaywrightClient), // { assert(spec) => { ok, observed?, error? } }
99
+ ])
100
+
101
+ const verdict = await registry.verify({
102
+ claimId: 'c1',
103
+ subject: { type: 'cli', command: 'npx', args: ['vitest', 'run'] },
104
+ evidenceRefs: [],
105
+ })
106
+ // → { kind: 'pass', evidenceRef: 'cli:...' } | { kind: 'fail', ... } | { kind: 'unknown', ... }
107
+ ```
108
+
109
+ `CliVerifier` requires an explicit allowlist. Without it the whole thing collapses into "the agent runs `true` and declares victory."
110
+
111
+ `FileVerifier` checks existence and, optionally, a content SHA-256 — the single most common fake completion is "I created the file" when no file exists.
112
+
113
+ Unregistered verification types return `unknown`, never `pass`.
114
+
115
+ ## Wiring it to your agent
116
+
117
+ The core has no host dependencies on purpose. Anything that can hand it `{ evidence, claims }` can gate a turn.
118
+
119
+ **CLI** (already works today — see `src/cli.ts`):
120
+
121
+ ```bash
122
+ RECEIPTS_MAX_RETRIES=1 RECEIPTS_LOG=./aborts.log npx no-receipts claims.json
123
+ ```
124
+
125
+ **As a library:**
126
+
127
+ ```ts
128
+ import { CompletionGate, FileLedger } from 'no-receipts'
129
+
130
+ const gate = new CompletionGate({
131
+ ledger: new FileLedger('.no-receipts/evidence.jsonl'),
132
+ maxRetries: 1,
133
+ onAbort: (record) => console.error(record.category, record.detail),
134
+ })
135
+
136
+ // as the agent runs:
137
+ gate.noteToolCall(turn)
138
+ await ledger.emit({ ok: exitCode === 0, toolName: 'vitest', detail: { exitCode } })
139
+
140
+ // at the turn boundary:
141
+ const decision = await gate.evaluate({ output: parsedClaims, turn })
142
+ if (decision.kind === 'abort') stop(decision.reason)
143
+ if (decision.kind === 'feedback') steer(decision.message)
144
+ ```
145
+
146
+ Claude Code, concretely — `~/.claude/settings.json`:
147
+
148
+ ```json
149
+ {
150
+ "hooks": {
151
+ "Stop": [
152
+ {
153
+ "hooks": [
154
+ { "type": "command", "command": "no-receipts claims.json" }
155
+ ]
156
+ }
157
+ ]
158
+ }
159
+ }
160
+ ```
161
+
162
+ Exit code 2 blocks the stop and shows stderr to the model; exit 0 lets the turn end.
163
+
164
+ ### Host lifecycle differences
165
+
166
+ These matter and are not glossed over:
167
+
168
+ | Host | Can hard-block a turn? | Mechanism |
169
+ |---|---|---|
170
+ | Claude Code | yes | `Stop` hook, `{"decision":"block","reason":...}` |
171
+ | Cursor | no | `stop` hook only supports `followup_message` (auto-retry, `loop_limit` default 5) |
172
+ | Codex CLI | unverified | — |
173
+
174
+ So on Cursor the correct integration is **degrade to retry**, not pretend-to-abort. The gate already expresses that distinction: `feedback` is a retry, `abort` is a stop.
175
+
176
+ ## Abort log
177
+
178
+ One abort = one line, same shape every time:
179
+
180
+ ```
181
+ [receipts] abort category=evidence_failed claim="all tests pass" evidence="ev_fail" counts=1/0 detail="retries exhausted (1/0)"
182
+ ```
183
+
184
+ Quote, backslash, and newline are escaped inside the values, so a claim text containing a newline cannot forge a second line. `grep '\[no-receipts\] abort'` gives you a complete history with no parsing.
185
+
186
+ ## Contributing
187
+
188
+ Two verifiers are declared in the status table above but not implemented: `http` and `github`. If you want one of them, that is the highest-leverage contribution available, and it is deliberately scoped small — a verifier is one class with a single `verify()` method, and `CliVerifier` is the reference at ~80 lines.
189
+
190
+ Newcomer-friendly entry points:
191
+
192
+ - **Implement `HttpVerifier`** — status code and JSON-path assertions against a live endpoint.
193
+ - **Implement `GitHubVerifier`** — PR/commit checks via the GitHub API. Needs a token, so it must be opt-in by construction.
194
+ - **Windows path handling in the CLI tests** — `chmod` and path separators are Unix-shaped today.
195
+ - **A third claim rule you think is missing** — explain the failure mode you have seen, not the rule you want.
196
+
197
+ Rules for a PR, in order of how much they matter:
198
+
199
+ 1. `npm test` stays green, and new behaviour arrives with a test that fails without it.
200
+ 2. A verifier that cannot check something returns `unknown`. Never `pass`.
201
+ 3. No new runtime dependency. That property is the whole reason this exists as a separate package.
202
+ 4. If you change a string the README quotes (an abort line, a command, an exit code), change both in the same commit. The README is a contract here, not marketing.
203
+
204
+ Open a discussion or an issue if you are unsure whether something fits — an idea that gets rejected in an issue costs nothing; a rejected PR costs a weekend.
205
+
206
+ ## Where this came from
207
+
208
+ This is a rewrite of a harness I built for one specific agent runtime in late 2026. That original lived inside a plugin entry point (~290 lines of host glue) with five verifiers, an OpenTelemetry evidence ledger, and a repetition guard. All of it worked, and none of it was removable — the gate logic was tangled with the host's lifecycle API.
209
+
210
+ Everything below is what survived the extraction. The design debts are inherited, and named:
211
+
212
+ - **The four claim rules** come from watching the same failure repeat: an agent that runs a failing test, then writes a paragraph that quietly omits the failure. The rules are phrased as *what must be true*, not *what must be said*, because the second is unbounded.
213
+ - **The three-state decision (`complete` / `feedback` / `abort`)** exists because two different hosts have very different powers. One can hard-block a turn boundary; another can only enqueue a follow-up message. A pass/fail gate would have had to lie about one of them. See [the host table](#host-lifecycle-differences).
214
+ - **Divergence limits** (steps, tool calls, consecutive no-progress) came from a specific deadlock: an agent re-running the same failing command with identical arguments until the token window closed. The fix that survived is cheap — compare claim statuses and evidence ids to the previous step — because anything more elaborate needed state the host did not expose.
215
+ - **Rule 4 (undisclosed `unknown`)** is the one I did not anticipate. It came from noticing that the most dangerous outputs were not confident lies but silent omissions.
216
+ - **Refusing to guess** in verifiers is the single strongest opinion in this repo. It cost an OTel ledger (dropped: nothing in this package needs spans) to keep.
217
+
218
+ ### Related work
219
+
220
+ None of this is a new idea; the neighbourhood is crowded and I checked it before writing:
221
+
222
+ - [`crucible`](https://github.com/krzemienski/crucible) — evidence-gated task planning for Claude Code, requires quorum-approved proof. Took the idea that completion should need *proof*, left the voting (solo devs voting with themselves is theatre).
223
+ - [`proof-of-done`](https://www.npmjs.com/package/proof-of-done) — diffs before/after to catch deleted or skipped tests. The best idea in the space for *regression* detection; deliberately out of scope here because it requires both sides of a change.
224
+ - [`agent-guardrails`](https://github.com/jzOcb/agent-guardrails) and [`verify-gate-mcp`](https://www.npmjs.com/package/verify-gate-mcp) — mechanical enforcement and prover≠verifier separation. Took the "enforcement must be code, not instructions" rule; skipped the MCP requirement.
225
+ - [Anthropic's Claude Code hook docs](https://code.claude.com/docs/en/hooks) and [Cursor's hooks reference](https://cursor.com/docs/hooks) — the two lifecycle models that forced the three-state design.
226
+ - The OTel-span evidence ledger in the original was patterned on OpenTelemetry's span-attribute conventions; it is not in this package because a `Map` and a JSONL file do the same job here without the dependency.
227
+
228
+ If you want the full comparison (including what this deliberately does *not* do), see [COMPARISON.md](./COMPARISON.md).
229
+
230
+ ## What this is not
231
+
232
+ - **Not a test runner.** It reads verdicts; it does not produce them.
233
+ - **Not an LLM judge.** No model decides whether a claim is honest.
234
+ - **Not a sandbox.** It cannot stop an agent from lying in a file it writes — only from ending a turn on the lie.
235
+ - **Not complete.** See the verifier status table: `http` and `github` are not implemented.
236
+
237
+ ## Install / develop
238
+
239
+ ```bash
240
+ npm install
241
+ npm run typecheck
242
+ npm test # 39 tests
243
+ npm run build
244
+ ```
245
+
246
+ MIT.
@@ -0,0 +1,11 @@
1
+ import type { AbortDetail } from './gate.js';
2
+ export declare function formatAbortLine(detail: AbortDetail): string;
3
+ export interface AbortSinkOptions {
4
+ /** Append the line to this file, in addition to stderr. */
5
+ logPath?: string;
6
+ /** Where stderr goes; defaults to console.error. */
7
+ write?: (line: string) => void;
8
+ }
9
+ /** Emit exactly one line per abort. Returns the line for testing. */
10
+ export declare function emitAbortLine(detail: AbortDetail, options?: AbortSinkOptions): string;
11
+ //# sourceMappingURL=abort.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"abort.d.ts","sourceRoot":"","sources":["../src/abort.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,WAAW,CAAA;AAM5C,wBAAgB,eAAe,CAAC,MAAM,EAAE,WAAW,GAAG,MAAM,CAK3D;AAED,MAAM,WAAW,gBAAgB;IAC/B,2DAA2D;IAC3D,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB,oDAAoD;IACpD,KAAK,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,CAAA;CAC/B;AAED,qEAAqE;AACrE,wBAAgB,aAAa,CAAC,MAAM,EAAE,WAAW,EAAE,OAAO,GAAE,gBAAqB,GAAG,MAAM,CAYzF"}
package/dist/abort.js ADDED
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Abort line formatting and sink.
3
+ *
4
+ * One abort = one line, same shape every time, so `grep '\[receipts\] abort'`
5
+ * gets you a complete history with no parsing. Escaping is deliberate: a claim
6
+ * text containing quotes or newlines must not be able to forge a second line.
7
+ */
8
+ import { appendFileSync } from 'node:fs';
9
+ function quote(value) {
10
+ return `"${value.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\n/g, '\\n').replace(/\r/g, '\\r')}"`;
11
+ }
12
+ export function formatAbortLine(detail) {
13
+ const claim = detail.claim_text ? `claim=${quote(detail.claim_text)}` : 'claim=-';
14
+ const evidence = detail.evidence_ids?.length ? `evidence=${detail.evidence_ids.map(quote).join(',')}` : 'evidence=-';
15
+ const counts = detail.counts ? `counts=${detail.counts.actual}/${detail.counts.limit}` : 'counts=-';
16
+ return `[no-receipts] abort category=${detail.category} ${claim} ${evidence} ${counts} detail=${quote(detail.detail)}`;
17
+ }
18
+ /** Emit exactly one line per abort. Returns the line for testing. */
19
+ export function emitAbortLine(detail, options = {}) {
20
+ const line = formatAbortLine(detail);
21
+ const write = options.write ?? ((text) => console.error(text));
22
+ write(line);
23
+ if (options.logPath) {
24
+ try {
25
+ appendFileSync(options.logPath, line + '\n', 'utf8');
26
+ }
27
+ catch (error) {
28
+ write(`[no-receipts] abort log write failed: ${String(error)}`);
29
+ }
30
+ }
31
+ return line;
32
+ }
33
+ //# sourceMappingURL=abort.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"abort.js","sourceRoot":"","sources":["../src/abort.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,OAAO,EAAE,cAAc,EAAE,MAAM,SAAS,CAAA;AAGxC,SAAS,KAAK,CAAC,KAAa;IAC1B,OAAO,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC,OAAO,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,KAAK,CAAC,GAAG,CAAA;AAC7G,CAAC;AAED,MAAM,UAA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;IACD,OAAO,IAAI,CAAA;AACb,CAAC"}
package/dist/cli.d.ts ADDED
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env node
2
+ import type { ClaimDocument } from './types.js';
3
+ export type { ClaimDocument };
4
+ //# sourceMappingURL=cli.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cli.d.ts","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":";AAqBA,OAAO,KAAK,EAAE,aAAa,EAAkB,MAAM,YAAY,CAAA;AAgH/D,YAAY,EAAE,aAAa,EAAE,CAAA"}
package/dist/cli.js ADDED
@@ -0,0 +1,114 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Reference host adapter — a CLI that runs the gate over a JSON file.
4
+ *
5
+ * This exists to prove the core has no host dependencies. Anything that can
6
+ * hand the gate `{ evidence[], claims }` can gate a turn: a CI job, a shell
7
+ * wrapper around another agent, a post-commit hook.
8
+ *
9
+ * Input shape:
10
+ * {
11
+ * "turn": 1,
12
+ * "evidence": [{ "ref": "ev_abc", "ok": true, "toolName": "vitest" }],
13
+ * "claims": [{ "text": "...", "status": "done", "evidence_ids": ["ev_abc"],
14
+ * "verification": {}, "open_questions": [],
15
+ * "unverified_assumptions": [] }]
16
+ * }
17
+ *
18
+ * Exit codes: 0 = complete, 1 = feedback (retryable), 2 = abort.
19
+ */
20
+ import { readFileSync } from 'node:fs';
21
+ import { CompletionGate, MemoryLedger, emitAbortLine, formatAbortLine } from './index.js';
22
+ async function main() {
23
+ const path = process.argv[2];
24
+ if (path === 'demo' || path === undefined) {
25
+ return demo();
26
+ }
27
+ let input;
28
+ try {
29
+ input = JSON.parse(readFileSync(path, 'utf8'));
30
+ }
31
+ catch (error) {
32
+ console.error(`no-receipts: cannot read ${path}: ${String(error)}`);
33
+ return 2;
34
+ }
35
+ const ledger = new MemoryLedger();
36
+ for (const record of input.evidence ?? []) {
37
+ await ledger.emit({ ...record, ok: record.ok !== false });
38
+ }
39
+ const gate = new CompletionGate({
40
+ ledger,
41
+ maxRetries: Number(process.env['RECEIPTS_MAX_RETRIES'] ?? 1),
42
+ onAbort: (record) => {
43
+ emitAbortLine(record, { ...(process.env['RECEIPTS_LOG'] ? { logPath: process.env['RECEIPTS_LOG'] } : {}) });
44
+ },
45
+ });
46
+ // The documented input shape carries `claims` as a bare array, but the gate
47
+ // validates a `{ claims: [...] }` document. Accept both: without this the
48
+ // documented `npx no-receipts claims.json` can never return 0.
49
+ const rawClaims = input.claims;
50
+ const document = Array.isArray(rawClaims) ? { claims: rawClaims } : rawClaims;
51
+ const decision = await gate.evaluate({
52
+ output: document,
53
+ turn: input.turn ?? 1,
54
+ ...(input.sessionId ? { sessionId: input.sessionId } : {}),
55
+ });
56
+ if (decision.kind === 'complete') {
57
+ console.log('[no-receipts] complete');
58
+ return 0;
59
+ }
60
+ if (decision.kind === 'feedback') {
61
+ console.log(decision.message);
62
+ return 1;
63
+ }
64
+ // onAbort already printed the canonical line.
65
+ return 2;
66
+ }
67
+ /**
68
+ * `no-receipts demo` — the whole pitch in one screen, no JSON file needed.
69
+ * Runs the same gate over three claims: a lie, a failed check, and a real one.
70
+ */
71
+ async function demo() {
72
+ const cases = [
73
+ { label: 'agent says "tests pass" and cites nothing', evidence: false, cite: null, ok: false },
74
+ { label: 'agent cites a test run that FAILED', evidence: true, cite: 'ev_failed', ok: false },
75
+ { label: 'agent cites a test run that succeeded', evidence: true, cite: 'ev_ok', ok: true },
76
+ ];
77
+ console.log('no-receipts demo — three agents finish a turn. One of them is lying.\n');
78
+ for (const [index, item] of cases.entries()) {
79
+ const ledger = new MemoryLedger();
80
+ if (item.evidence) {
81
+ await ledger.emit({ ref: item.cite, ok: item.ok, toolName: 'vitest', detail: { exitCode: item.ok ? 0 : 1 } });
82
+ }
83
+ const gate = new CompletionGate({ ledger, maxRetries: 0 });
84
+ const decision = await gate.evaluate({
85
+ output: {
86
+ claims: [{
87
+ text: 'all tests pass',
88
+ status: 'done',
89
+ evidence_ids: item.cite ? [item.cite] : [],
90
+ verification: {},
91
+ open_questions: [],
92
+ unverified_assumptions: [],
93
+ }],
94
+ },
95
+ turn: 1,
96
+ });
97
+ const verdict = decision.kind === 'complete'
98
+ ? 'ALLOWED'
99
+ : decision.kind === 'abort'
100
+ ? `BLOCKED (${decision.abortDetail.category})`
101
+ : `RETRY (${decision.issues[0]?.code ?? 'invalid'})`;
102
+ console.log(`${index + 1}. ${item.label}`);
103
+ console.log(` → ${verdict}`);
104
+ if (decision.kind === 'abort')
105
+ console.log(` ${formatAbortLine(decision.abortDetail)}`);
106
+ console.log('');
107
+ }
108
+ console.log('Exit codes when wired to a host: 0 = complete, 1 = retry with feedback, 2 = abort.');
109
+ return 0;
110
+ }
111
+ void main().then((code) => {
112
+ process.exitCode = code;
113
+ });
114
+ //# sourceMappingURL=cli.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cli.js","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":";AACA;;;;;;;;;;;;;;;;;GAiBG;AACH,OAAO,EAAE,YAAY,EAAE,MAAM,SAAS,CAAA;AACtC,OAAO,EAAE,cAAc,EAAE,YAAY,EAAE,aAAa,EAAE,eAAe,EAAE,MAAM,YAAY,CAAA;AAUzF,KAAK,UAAU,IAAI;IACjB,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAA;IAC5B,IAAI,IAAI,KAAK,MAAM,IAAI,IAAI,KAAK,SAAS,EAAE,CAAC;QAC1C,OAAO,IAAI,EAAE,CAAA;IACf,CAAC;IAED,IAAI,KAAY,CAAA;IAChB,IAAI,CAAC;QACH,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,YAAY,CAAC,IAAI,EAAE,MAAM,CAAC,CAAU,CAAA;IACzD,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,OAAO,CAAC,KAAK,CAAC,4BAA4B,IAAI,KAAK,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC,CAAA;QACnE,OAAO,CAAC,CAAA;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AK,IAAI,EAAE,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE;IACxB,OAAO,CAAC,QAAQ,GAAG,IAAI,CAAA;AACzB,CAAC,CAAC,CAAA"}
package/dist/gate.d.ts ADDED
@@ -0,0 +1,104 @@
1
+ /**
2
+ * The completion gate.
3
+ *
4
+ * Called by a host right before a turn is allowed to end. Returns one of three
5
+ * decisions — and deliberately has no fourth:
6
+ *
7
+ * complete → the claims are backed by evidence that resolved and succeeded
8
+ * feedback → retryable; hand this text back to the model and continue
9
+ * abort → stop the turn; record why
10
+ *
11
+ * There is no "pass because we ran out of ideas". When the retry budget is
12
+ * spent, or a divergence limit is hit, the gate aborts. A gate that fails open
13
+ * is decoration.
14
+ */
15
+ import type { ClaimIssue } from './types.js';
16
+ import type { EvidenceLedger, ClaimDocument } from './types.js';
17
+ export declare const ABORT_CATEGORIES: readonly ["claim_invalid", "evidence_missing", "evidence_failed", "retry_exhausted", "step_budget_exceeded", "tool_call_budget_exceeded", "no_progress_exceeded"];
18
+ export type AbortCategory = (typeof ABORT_CATEGORIES)[number];
19
+ export interface AbortDetail {
20
+ category: AbortCategory;
21
+ detail: string;
22
+ claim_text?: string;
23
+ evidence_ids?: string[];
24
+ counts?: {
25
+ actual: number;
26
+ limit: number;
27
+ };
28
+ issues?: ClaimIssue[];
29
+ }
30
+ export type GateDecision = {
31
+ kind: 'complete';
32
+ } | {
33
+ kind: 'feedback';
34
+ message: string;
35
+ issues: ClaimIssue[];
36
+ attempts: number;
37
+ maxRetries: number;
38
+ } | {
39
+ kind: 'abort';
40
+ reason: string;
41
+ abortDetail: AbortDetail;
42
+ };
43
+ export interface SuspensionRecord extends AbortDetail {
44
+ sessionId?: string;
45
+ turn: number;
46
+ attempts: number;
47
+ maxRetries: number;
48
+ at: string;
49
+ }
50
+ export interface CompletionGateConfig {
51
+ ledger: EvidenceLedger;
52
+ /** Invalid outputs allowed before aborting. Default 1. */
53
+ maxRetries?: number;
54
+ /** Model steps per turn before the divergence limit trips. Default 20. */
55
+ maxStepsPerTurn?: number;
56
+ /** Tool calls per turn before the divergence limit trips. Default 30. */
57
+ maxToolCallsPerTurn?: number;
58
+ /** Consecutive no-progress steps. Default 3. */
59
+ maxConsecutiveNoProgressSteps?: number;
60
+ /** Called once per abort, after the decision is built. */
61
+ onAbort?: (record: SuspensionRecord) => void;
62
+ /** Override the clock (tests). */
63
+ now?: () => Date;
64
+ }
65
+ export interface CompletionRequest {
66
+ /** Whatever the host extracted from the model's final message. */
67
+ output: unknown;
68
+ turn: number;
69
+ sessionId?: string;
70
+ }
71
+ export declare const DEFAULT_MAX_RETRIES = 1;
72
+ export declare const DEFAULT_MAX_STEPS = 20;
73
+ export declare const DEFAULT_MAX_TOOL_CALLS = 30;
74
+ export declare const DEFAULT_MAX_NO_PROGRESS = 3;
75
+ export declare class CompletionGate {
76
+ private readonly ledger;
77
+ private readonly maxRetries;
78
+ private readonly maxStepsPerTurn;
79
+ private readonly maxToolCallsPerTurn;
80
+ private readonly maxConsecutiveNoProgressSteps;
81
+ private readonly onAbort?;
82
+ private readonly now;
83
+ private attempts;
84
+ private turn;
85
+ private stepsThisTurn;
86
+ private toolCallsThisTurn;
87
+ private consecutiveNoProgress;
88
+ private previousProgress;
89
+ constructor(config: CompletionGateConfig);
90
+ /** Record tool activity so divergence detection sees it. Call per tool call. */
91
+ noteToolCall(turn: number): void;
92
+ /** Record a model step. Call once per step, before or after the model speaks. */
93
+ noteStep(turn: number, document?: ClaimDocument): void;
94
+ private syncTurn;
95
+ /** Evaluate a turn's final claims. Never throws on malformed input. */
96
+ evaluate(request: CompletionRequest): Promise<GateDecision>;
97
+ private checkDivergence;
98
+ private abort;
99
+ /** Diagnostics only — no setter, gate policy is immutable after construction. */
100
+ get attemptCount(): number;
101
+ }
102
+ /** The exact text handed back to the model on a retry. */
103
+ export declare function renderFeedback(issues: readonly ClaimIssue[], attempts: number, maxRetries: number): string;
104
+ //# sourceMappingURL=gate.d.ts.map
@@ -0,0 +1 @@
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