Skip to content

fix(gates): bound promotion evidence references - #173

Merged
abogartz merged 3 commits into
abogartz:mainfrom
WhollyMindless:fix/bounded-evidence-163
Oct 29, 2026
Merged

abogartz merged 3 commits into
abogartz:mainfrom
WhollyMindless:fix/bounded-evidence-163

Conversation

@WhollyMindless

@WhollyMindless WhollyMindless commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

Every promoted write currently serializes the session's entire call history. The new regression test reproduces a 26,356-byte promotion line after 1,000 calls on main. This change keeps a bounded reference sample and records evidence_refs_count so the total remains visible.

The sample contains the ten most recent code-engagement calls, plus the latest gate check, the latest recorded gate FAIL/fix/PASS recovery, and the latest recorded tool FAIL/PASS retry: at most 16 distinct IDs. Trigger witnesses are retained when recorded, so an old recovery is not lost when it leaves the recent window. Plugin and init write contexts take a bounded snapshot without mapping the full ledger; the writer also caps legacy callers' full lists. The count includes all recorded calls, including non-code tools.

Audit-reference ordering: the sample is grouped by gate recovery, tool retry, latest gate check, then recent engagement, with duplicates removed in first-occurrence order. It is not chronological. Consequently, graph_drift.evidence points to the first reference in that prioritized sample, rather than the earliest recorded call in the session; it remains an audit pointer, not a new grounding predicate.

Grounding predicates, attribution, and the full in-memory call ledger are unchanged. This bounds repeated promotion telemetry; it does not cap the session ledger, rotate day-files, or rewrite historical evidence. The README explicitly documents leaving existing oversized files unchanged.

Closes #163.

Validation (Windows, Bun 1.4.4):

Overlap: this is based on main and includes none of the other open PRs. #158 changes the same write_promoted block and requires one merge-hunk resolution: retain its try/catch and evidenceError result, and use this PR's bounded evidence_refs and new evidence_refs_count fields inside that block. The other refactoring/cleanup PRs merge automatically in the integration trial.

This is an optional proposal. Please feel free to reject or close it without merging if this sampling policy or approach does not fit your plans for the project.

@abogartz abogartz left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

APPROVE — #163's four acceptance criteria are all met; the branch needs the merge hunk you already prescribed

Reviewed at head 839fa69 (base e32327a) and on a local trial merge with current main (58d2530, which now carries #158, #169, #170, #171). Nothing pushed; the trial lives only in a review worktree.

1. Red-first, measured on today's main rather than the old base

I copied test/write-evidence.test.ts into a clean 58d2530 checkout and ran it there:

(fail) 1,000 and 2,000 calls produce bounded promotion lines with honest totals
(fail) an old gate FAIL/edit/PASS and the latest gate check survive the recent window
(fail) tool retries and engagement remain auditable after non-code calls
(fail) another session cannot borrow grounding or refs; an empty planning session counts zero
(fail) evidence, status, and viewer readers accept the bounded record unchanged
 0 pass  5 fail

5 of 5 fail on main, exactly as the body says, and the growth number reproduces: the first promotion line is 26,370 bytes after 1,000 calls on current main (you measured 26,356 on the older base — the drift is per-run ids/timestamps, not the fix). With the fix the same lines are under the pinned 2 KiB and refs.length ≤ 16, while callsFor("long") still reports the full 2,000 — grounding and attribution really do keep the whole ledger.

2. The conflict is exactly the one you documented, and your prescription is the right resolution

src/gates.ts is the only conflicting file, and only because #158 wrapped the same write_promoted call in the try/catch that produces evidenceError. I resolved it your way — keep main's try/catch and { action: "promoted", ts, chain, evidenceError }, take this PR's two fields inside the block:

      evidence_refs: bracketList(ctx.evidenceCalls.slice(-MAX_WRITE_EVIDENCE_REFS)),
      evidence_refs_count: ctx.evidenceCallsCount ?? ctx.evidenceCalls.length,

Merged tree (683 pass / 12 skip / 0 fail = main's 678 + your 5; e2e 11 pass; tsc + biome clean; gate exit 0). So the merge is a two-line mechanical hunk, not a design question — gh pr update-branch and take that resolution. Your "combined trial … 686 unit tests" figure also matches my independent count (678 + 5 + 3 from #172).

3. The bound is enforced where it matters, and production no longer maps the ledger

  • writeEvidence() builds a Set of ≤ MAX_WRITE_EVIDENCE_REFS = RECENT_EVIDENCE_CALLS + 1 + 3 + 2 — the cap is derived from the bucket sizes, not a magic 16, so widening the window widens the cap with it.
  • Both production write contexts convert (index.ts gateCtx, init.ts runInit via spread), and evidenceCalls() is now called only by four test files — I grepped src/, so the O(calls) map per write is gone from the shipped paths.
  • write_blocked never carried evidence_refs (evidence.ts:132-149), so write_promoted was the only growing line and this closes the growth, not just one instance of it.
  • evidence_refs_count semantics are honest in both directions: the production path reports s.calls.length including non-code tools (my probe: 1 memory_list + 15 code calls → count=16), and a legacy caller that supplies a full list without a count gets the unsliced .length, because slice() does not mutate the array it measured.

4. Mutation probe — 7 of 8 killed

mutation to the sampling logic result
recent window 10 → 20 3 fail
stop pinning the gate FAIL/fix/PASS triple 1 fail
stop pinning the tool FAIL/PASS pair 1 fail
let non-code calls enter recent 1 fail
report refs.size instead of the true total 4 fail
drop the Set (no dedupe across buckets) 1 fail
remove the shift() (window unbounded) 2 fail
remove the writer-side slice(-MAX_WRITE_EVIDENCE_REFS) 5 pass — survives

The survivor is structural, not a coverage hole to fix: the production producer cannot exceed the cap, so no test can observe that slice. It exists for legacy/direct callers (and today's four test files are literally such callers), which the GateContext comment says out loud. Fine as defense-in-depth; noting it so the next reader does not go looking for a missing test.

5. Against #163's acceptance criteria — all four hold

  1. 1,000-call session, line under a pinned budget — expect(Buffer.byteLength(row.line)).toBeLessThan(2048), plus the size-delta check that normalises only the unrelated snapshot field.
  2. Grounding unchanged; a write backed only by the FAIL→PASS pair still promotes when the pair leaves the window — covered by the recovery test (remember("gate", "recovery") after 30 later calls, still Remembered:) and grounded_by=engagement asserted on the line.
  3. memory_status, blockedRecent, viewer accept the new shape without special-casing — that is the fifth test verbatim (memory_evidence shows evidence_refs_count=20, memory_status still surfaces ambiguous_memory, /api/data returns 200 with the expected row).
  4. A backfill/compaction note or an explicit decision to leave history alone — the README paragraph is that explicit decision, and it is a good sentence: "does not backfill, compact, or delete historical audit records."

So Closes #163 is justified. I also checked your two honesty caveats are true rather than hedging: the day-files really are not rotated, and the session ledger really is still uncapped (attribution needs it), and you say both.


Nit — the array's new order silently retargets a second audit field

writeEvidence() builds its Set in bucket order (gate recovery → tool retry → gate check → recent window), not chronological order. Nothing depends on that for evidence_refs itself, but ctx.evidenceCalls has one other consumer: src/gates.ts:367, graph_drift's audit line, reads evidence: ctx.evidenceCalls[0] ?? "-".

I probed both trees with the same scripted session (a non-code call first, then a gate FAIL→fix→PASS, then 12 reads):

main:    ctx.evidenceCalls[0] = "first-memory-list"     <- the session's first recorded call
branch:  ctx.evidenceCalls[0] = "failed-gate"           <- oldest pinned witness

So graph_drift.evidence moves from "earliest call in the session" to "oldest pinned witness, if any". Arguably better — a gate failure is more informative than the session's first memory_list — but it is a meaning change in a durable audit artifact that neither the body nor the README mentions, and it makes a second field's semantics depend on which optional buckets happen to be set. Two cheap ways to settle it: sort the sampled ids by their position in s.calls before returning (that also makes slice(-N) in gates.ts mean "the last N", which its wording already implies, at O(16) cost), or say the ordering out loud in the README line you added. Either is fine; I only object to the silence.

Approved — the sampling policy is sound, the accounting is honest, the tests fail before they pass, and the one open question is how to describe a pointer you improved by accident.

Conflicts:
	src/gates.ts

Resolved the write_promoted hunk as the PR body prescribes: keep main's
(abogartz#158) try/catch and evidenceError result, and apply this branch's bounded
evidence_refs plus the new evidence_refs_count field inside that block.
No other change to either side.

@abogartz abogartz left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review: APPROVED — merge conflicts resolved, fix verified red→green

I resolved the conflict against current main and pushed the merge to your branch as
3b2ebe1 (parents: 839fa69 fe619a8). mergeable=MERGEABLE, mergeStateStatus=CLEAN,
and lint / smoke / test / test-windows are all green on that head.

The merge hunk

Only src/gates.ts conflicted — exactly the one hunk your body predicted. I resolved it
as prescribed: kept #158's try/catch and evidenceError return, and applied this
branch's two fields inside that block. The resolution is purely mechanical; I added no
commentary of my own to the merged code. Net effect of the merge on main's gates.ts:

-      evidence_refs: bracketList(ctx.evidenceCalls),
+      evidence_refs: bracketList(ctx.evidenceCalls.slice(-MAX_WRITE_EVIDENCE_REFS)),
+      evidence_refs_count: ctx.evidenceCallsCount ?? ctx.evidenceCalls.length,

plus the MAX_WRITE_EVIDENCE_REFS import and the evidenceCallsCount? field on
GateContext. Taking this branch's side of the hunk instead would have compiled fine
(evidenceError is optional) but silently returned undefined on audit failure —
init.ts counts outcome.evidenceError !== undefined as unaudited, so that variant
would have quietly resurrected the #155 lie. Worth saying out loud because it means this
resolution is the only correct one of the three, not merely the tidy one.

Body claims, checked against the tree (not the prose)

Claim How verified Result
5 new tests fail on main, pass with the fix copied test/write-evidence.test.ts onto an origin/main worktree: 0 pass / 5 fail; same file on the merge: 5 pass ✅
1,000 / 2,000-call lines stay under a pinned 2 KiB expect(Buffer.byteLength(row.line)).toBeLessThan(2048) in test 1, green ✅
≤16 distinct IDs: 10 recent + gate check + FAIL/fix/PASS + tool retry RECENT_EVIDENCE_CALLS = 10, MAX_WRITE_EVIDENCE_REFS = 16 (src/triggers.ts:35-37), union through a Set in writeEvidence (src/triggers.ts:234-243) ✅
Plugin and init write contexts take a bounded snapshot ...writeEvidence(bound) at src/index.ts:308, ...writeEvidence(...) at src/init.ts:219; all four production runWriteGate sites (index.ts:440/678/1129/1541) go through gateContext, and trackCall (src/triggers.ts:40) is the only writer of s.calls — no path bypasses the sampler ✅
Grounding / attribution / full ledger unchanged hasEngagement/hasGateCheck untouched; test 1 asserts callsFor("long") === 2000 after sampling ✅
Writer also caps legacy callers' full lists probe (below) ✅ but untested
README documents leaving oversized day-files README diff paragraph ✅ (closes #163's 4th acceptance box)

Gates on the merge: tsc clean; biome lint exit 0 with identical counts to base
(400 warnings / 119 infos — you added no lint noise); unit 692 pass / 12 skip / 0 fail
vs base main 687 / 12 / 0 (exactly +5, zero regressions); e2e 11 pass / 0 fail. The
repo's pre-push merge gate also ran green. Your "625 unit tests" figure is against your
older base; main has moved since, but the delta is exactly your five tests.

Probes beyond your suite

Three throwaway probes (not committed, deleted after running):

  1. Legacy caller, 500 raw ids, no evidenceCallsCount → action=promoted refs=16 count=500 bytes=926. The writer-side cap does hold, as claimed.
  2. Gate FAIL → 400 intervening calls → PASS, then a promoted write → the promoted
    line is 444 bytes / 11 refs / count=402. Sampling behaves correctly under a real
    recovery witness at long-session scale. The same session's t4_learning line,
    however, came out at 3,244 bytes with 402 ids — see below.
  3. Two gate recoveries in one session → refs=[f2,e2,p2,f1,e1,p1]: the pinned slot
    keeps the latest recovery, and the older witnesses survive only while inside the
    bounded recent window. No unbounded accumulation. Matches "latest recorded".

Findings — none blocking

F1 (filed separately as #179, not your scope). The t4_learning line is the same
unbounded shape that #163 describes for write_promoted: pendingGate.chain accumulates
every call between a gate FAIL and the matching-family PASS, and evidence_chain
renders all of it — measured 3,244 bytes / 402 ids above. pendingGate also never
expires, so an unpaired FAIL holds that chain for the session's life and can pair with a
PASS 400 calls later (a weak signal anyway). #163's scope statement excludes it, so this
PR is right to close it; I filed #179 with the reproduction and a fix sketch mirroring
yours (bounded render + evidence_chain_count, plus expiring pendingGate).

N1 (nit). The claim "the writer also caps legacy callers' full lists"
(gates.ts:765's slice(-MAX_WRITE_EVIDENCE_REFS)) has no test, and production can
never reach it — writeEvidence's union is ≤16 by construction, so the slice is a
no-op there. That means a future refactor that drops it keeps the suite green while the
README sentence goes false. A five-line direct runWriteGate case (500-id
evidenceCalls, no evidenceCallsCount → refs.length ≤ 16, count === 500) would pin
the behavior my probe just checked by hand.

N2 (nit, informational). graph_drift's evidence: ctx.evidenceCalls[0]
(gates.ts:409) silently changes meaning with this PR: for a production context the
first element is now the oldest pinned witness (gate-recovery, else tool-recovery, else
recent[0]), not the session's earliest recorded call. It is still a valid audit pointer
and no test or reader depends on the old meaning, so no change required — but anyone
comparing evidence= across the upgrade boundary is comparing two different things, so
a half-sentence in the README paragraph you added would be cheap insurance. (Read from
the code, not probed: graph_drift needs canonical-graph drift to fire.)

Overall: the sampling policy is sound, the witnesses that GATE-4 actually reasons about
are pinned rather than reconstructed from a cropped tail, and the honest total survives as
a number. Ship it.

@abogartz
abogartz merged commit 5454f63 into abogartz:main Oct 29, 2026
4 checks passed
@abogartz-opencode-self-improvement

Copy link
Copy Markdown

🎉 This PR is included in version 0.14.19 🎉

The release is available on:

Your semantic-release bot 📦🚀

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

write_promoted re-serializes the whole session call ledger — evidence lines grow to 22 KB (O(n^2) per session)

2 participants