Skip to content

refactor(agent-session-journal): move the session journal onto SQLite - #18652

Merged
brennanb2025 merged 9 commits into
mainfrom
brennanb2025/sqlite-journal
Sep 4, 2026
Merged

brennanb2025 merged 9 commits into
mainfrom
brennanb2025/sqlite-journal

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Sep 4, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 35 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​2496 $\color{#cf222e}{\Huge{\mathbf{−}}}$​2398 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​98
Prod 64 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1433 $\color{#cf222e}{\Huge{\mathbf{−}}}$​2572 $\color{#cf222e}{\Huge{\mathbf{−}}}$​1139

What this changes

src/main/native-chat/agent-session-journal/ kept one session's durable state in three hand-rolled file formats: an append-only log.jsonl with torn-tail repair, a snapshot.json holding folded state plus a retained tail, and byte-quarantine files for anything unreadable. This replaces all of it with one SQLite database per session — journal.db beside the existing blobs/ directory — through src/main/sqlite/sync-database.ts and the open/pragma/migrate/harden pattern src/main/runtime/orchestration/db/ already uses.

Two tables. journal_rows is the append-only log keyed by (session_id, epoch, seq); journal_sessions is the derived projection, upserted in the same transaction as every row insert. Rows stay JSON in one column, so journal-row-schema.ts, the v upcast chain and journal-reducer.ts survive byte for byte.

Deleted: journal-log-file.ts (365 lines), journal-compaction.ts, journal-corruption-quarantine.ts, and the public compact() / compactionBoundary / autoCompact members — none had a non-test caller.

No importer. Existing log.jsonl / snapshot.json journals are deliberately abandoned: a session created on the old path stops working. experimentalStructuredNativeChat is off by default, so the blast radius is small by construction.

Nothing crosses the remote wire. This directory has zero src/relay/ and zero renderer importers — no RPC params, no stream opcodes, no change to what the host publishes. node:sqlite is a Node builtin, so there is no electron-builder entry, no native rebuild, and no glibc floor to hold.

The physical quota is repriced, because SQLite does not charge like a file

The 256 MiB per-session bound is unchanged — still physical bytes under the session directory, still enforced by the same typed journal_bound_exceeded. The arithmetic under it could not survive the swap.

SQLite grows the database in pages and the WAL in frames, and the checkpoint that copies the WAL forward holds the same pages in both files at once, so a transaction's peak is about twice its content, not equal to it. Meanwhile a transaction that reuses already-allocated pages grows the directory by zero, and the old arithmetic charged its full JSON length anyway. Admission now charges the candidate transaction's own page cost, computed from the rows it will insert, and that formula is validated by a sweep kept as a regression test rather than by reasoning about the allocator.

Four behaviours are load-bearing rather than tuning, each measured:

Why it is not tuning
auto_vacuum = INCREMENTAL set before journal_mode = WAL Set it after and it is ignored with no error: reclamation silently becomes a no-op and the file never shrinks again. Both halves are asserted — the production order reads back 2, and a WAL-first open reads back 0.
wal_autocheckpoint = 0 plus an explicit wal_checkpoint(TRUNCATE) ending every write path At the 1000-page default a checkpoint can fire inside any commit, so a transaction's physical cost depends on how many commits preceded it.
Reclamation in bounded, individually-checkpointed chunks A single unbounded incremental_vacuum took a 252 MB directory to 504 MB — the reclamation added to defend the bound would have breached it. PRAGMA incremental_vacuum(N) also frees exactly one page unless stepped to completion, which leaves every size assertion green while recovering almost nothing, so the freed page count is asserted directly.
Charging the deferred copy when a checkpoint cannot run A busy checkpoint leaves the WAL on disk together with the database growth it already copied. Reading the settled size alone under-charges by up to the whole WAL. The term is zero whenever the last checkpoint succeeded, so the uncontended path admits and refuses an identical set.

The epoch discard is DELETE FROM journal_rows with no WHERE clause, which takes SQLite's truncate optimization: measured at ~0.26% of the database in WAL bytes across three row-size mixes, where the WHERE session_id = ? form rewrote every emptied leaf at up to 99%. One database per session is what makes the unqualified form correct.

Lifecycle reservations move onto the same currency, so a token granted for a terminal write actually covers its page cost rather than its JSON length.

A new floor. An open, empty journal costs 57,344 bytes before a single row exists. A configured maxSessionBytes below JOURNAL_MIN_SESSION_BYTES now fails at open with the existing journal_bound_exceeded, naming the floor, instead of being discovered as a run of identical append failures. No production caller configures one — every non-test use takes DEFAULT_JOURNAL_PAYLOAD_LIMITS — so the affected surface is test fixtures, each rescaled to the smallest value that restores the relationship its case proves.

One deliberate behaviour change

Compaction was not only substrate. It was the one mechanism that shed bytes inside an epoch, and journal-row-writer.ts called it precisely so an append at the bound was not refused.

The SQLite-shaped replacement — a bounded prefix DELETE — cannot be used. Compaction folded shed rows into snapshot.json before truncating, so the conversation they carried survived; with the snapshot gone the surviving rows are the state, and dropping the oldest of them loses the oldest transcript silently at the next reopen. Keeping the fold would mean persisting rendered state again, which is the machinery this change exists to delete.

So: no row is ever shed inside an epoch, and a session whose row bytes alone reach the bound now refuses every append with journal_bound_exceeded where it previously compacted and continued. Trading a loud typed refusal for silent transcript loss is the worse of the two.

What still sheds is unreferenced blob bytes — the dominant and unbounded byte source, since a row's inline payload is capped at 16 KiB while the remainder of a 40 MB tool result is a whole file. The escape from the hard stop is the fold that already exists, replaceEpochItems, which now actually returns bytes to the filesystem instead of leaving them on the freelist.

The prune's protected set is a union, and that is a regression test

pruneJournalBlobs removes every file outside the set it is handed, and the write path never rewrites an existing digest. Protecting only live reducer state therefore has a concrete failure: a superseded row carries digest D, its file is still on disk, D is absent from live state because a higher revision won, and this append reuses D — which happens whenever an identical bounded payload recurs across revisions or across the geometric streaming checkpoints. The prune deletes D, the transaction inserts a row citing it, and the next reopen renders an item whose blob is gone.

The set is live digests ∪ every digest the candidate row carries — its blobs argument and its own body, including those cited only by a nested lifecycle-batch mutation, because a row can cite a digest that is not in that argument at all. journal-store-blob-budget.test.ts pins it and goes red when the set is narrowed back.

Handle ownership

A file handle used to be opened and closed per append. A SQLite handle is held for the session's lifetime, which is the one genuinely new lifecycle obligation here — and on Windows an open handle blocks the rename and unlink that recovery, workspace cleanup and every temp-root test perform, while on POSIX every such leak is silent.

Every path that can open a connection now has exactly one owner. The open function owns its raw connection until it returns (a transferred flag plus a finally). The store owns its retained connection and releases it in a new close(), and open() closes it on any throw after it exists. Every other connection is closed by the call that opened it — the standalone loadJournal probe self-closes, and the attach, recovery, eviction, map-overwrite and host-teardown paths close what they drop. Two callback types became () => Promise<void> and are now awaited, because "close before delete" means nothing when the delete returns while the close is still queued.

Host teardown is restructured to be failure-complete: the sink-barrier flush throws by design, so a trailing "close every journal" statement would be skipped on exactly the path that leaks. Each phase's failure is captured, every journal is closed with allSettled, only entries whose close fulfilled are removed from the map, and an AggregateError carries the originals out.

close() has a stated contract with five parts:

  1. Closed-state admission happens at enqueue, once, and is permanent. An append offered in the same turn as close() is admitted and runs to completion; anything offered afterwards is refused before it joins the queue, so no write is ever chained behind a close.
  2. The close step shares that queue and bypasses the gate — a close that consulted the flag it had just set would refuse itself.
  3. Concurrent callers share one in-flight attempt.
  4. Fulfilment is terminal; rejection is not. A second DatabaseSync.close() raises ERR_INVALID_STATE, so re-entering after success is the bug, not the fix.
  5. The trailing checkpoint carries a completion flag; the release itself is last and deliberately unguarded, so a retry re-enters it. There is no way to ask whether a db.close() that threw released the handle first, and guarding the step would skip it on retry — guaranteeing a permanent leak in exactly the case where it did not release.

journal_closed joins the error union for a write after close(). Grep confirms zero files outside the directory reference any of these codes, so widening it is additive.

Migration and version refusal

Two independent version axes, both fail closed.

  • Database shape — PRAGMA user_version, read first, on a connection that has set no persistent pragma and run no DDL, because CREATE TABLE IF NOT EXISTS and both header-writing pragmas would all violate the "no write, no delete" promise a future-schema file is owed. A latched open closes that connection and reopens { readonly: true, fileMustExist: true }.
  • Row body shape — the existing v field and the parseJournalRow upcast chain, unchanged. A same-user_version database can still hold a row this build cannot read.

assertJournalWritable / journal_read_only are untouched; only the trigger moves, and it now fires before the first read rather than mid-load. Byte-copy quarantine is deleted rather than ported: with one database per session the file is the preserved bytes, and nothing writes to a latched one. Production recovery stays exactly where it lives, in the wire layer — a future-schema journal is rehydrated into the -recovered-v<N> sibling and never merged back.

The (session_id, epoch, seq) primary key also makes a duplicate sequence a constraint failure instead of a silent double-write. The lease fence already prevented two writers; the failure mode is just louder.

Tests

210 tests pass in the journal directory, 8,347 across the journal, wire, codex and runtime suites.

Five in-directory suites pass completely unchanged and are the primary regression proof: the 464-line reducer suite, item identity, cursor resume, row schema, and lifecycle capacity — 76 tests, no edits.

Behaviour assertions elsewhere are preserved. The twelve edited external files get a shared tracked-close teardown helper; tracking every opened instance rather than a variable is the point, since one suite reassigns its module-level journal to a second store mid-suite. Five of those also needed fixture surgery — raw log.jsonl writes become row inserts, and a hole punched in a log becomes a deleted mid-sequence row, which is the same logical hole findSequenceGap already detects.

New suites, each pinning something a green run alone would not prove:

  • The charge sweep — single rows from 1 byte to 40 MiB, multi-row transactions up to 1,000 rows, a mixed replacement, each against a fresh and a grown database, asserting the charge is never below the observed peak delta. This is what caught the formula defect described below.
  • The escape, with two negative controls: with reclamation stubbed out the directory must not shrink and the next append must stay refused (verified red), and the chunked loop must not become one unbounded statement.
  • The hard bound per row kind, sampling the peak — including the mid-checkpoint moment — not just the settled size.
  • The bound under WAL contention, with a second connection pinned in a read transaction so no checkpoint can drain, plus the control that the deferred-checkpoint term costs nothing when no reader is held.
  • Handle ownership, as forced-failure cases: fifty repeated probes leave no sidecars and the directory renames and removes; a blocked migration, a failing lifecycle rebuild and a sub-floor quota each leave nothing open.
  • The close contract, including the three queue positions, every write entry point, a rejected close that retries and re-enters the release, and models of the two rejected contract readings showing each fails where the real one holds.
  • The stale-digest reuse regression, verified red against a live-state-only protected set.

One thing to look at

The measured page charge needed a larger fixed-page allowance than the design assumed. Running the sweep against a 256 MB database showed a transaction can dirty more existing pages than newly allocated ones — the WAL carries the modified interior chains of all four b-trees this schema has (journal_rows and journal_sessions are each a table plus the implicit unique index their composite primary key creates), plus page 1 and the pointer map. The worst measured requirement was 13 pages; the constant is 24, and the sweep is what keeps it honest. Without the correction the sweep failed by ~4 KB on a 6-row transaction, which is a small breach of a bound whose entire job is to cap disk.

The agent-session journal kept its state in three hand-rolled file formats: an
append-only `log.jsonl` with torn-tail repair, a `snapshot.json` holding folded
state plus a retained tail, and byte-quarantine files for anything unreadable.
This replaces all of it with one SQLite database per session — `journal.db`
beside the existing `blobs/` store — using the in-house adapter and the
open/pragma/migrate/harden pattern the orchestration database already follows.

Two tables: `journal_rows` (the append-only log, keyed by
`(session_id, epoch, seq)`) and `journal_sessions` (the derived projection,
upserted in the SAME transaction as every insert). Rows stay JSON in one
column, so the row schema, the version upcast chain, and the reducer survive
byte for byte — `journal-reducer.test.ts` and four other suites pass unchanged
and are the regression proof.

Deleted: `journal-log-file.ts`, `journal-compaction.ts`,
`journal-corruption-quarantine.ts`, and the public `compact()` /
`compactionBoundary` / `autoCompact` members, none of which had a non-test
caller.

Existing `log.jsonl` / `snapshot.json` journals are deliberately abandoned. No
importer: a session created on the old path stops working, which is acceptable
because the feature is off by default.

## The physical quota is repriced, because SQLite does not charge like a file

The 256 MiB per-session bound is unchanged, but the arithmetic under it could
not survive: SQLite grows the database in pages and the WAL in frames, and the
checkpoint that copies the WAL forward holds the same pages in both files at
once, so a transaction's peak is about twice its content. Admission now charges
the candidate transaction's own measured page cost, validated against a sweep
that runs as a regression test (`journal-database-space.test.ts`) rather than
derived from reasoning about the allocator.

Four things are load-bearing rather than tuning, each measured:

- `auto_vacuum = INCREMENTAL` must be set BEFORE `journal_mode = WAL`. Set it
  after and it is ignored with no error, reclamation silently becomes a no-op,
  and the file never shrinks again. Both halves are asserted.
- `wal_autocheckpoint = 0` plus an explicit `wal_checkpoint(TRUNCATE)` at the
  end of every write path, so the one moment the same pages live in two files is
  a moment the charge accounts for.
- Reclamation runs in bounded chunks. A single unbounded `incremental_vacuum`
  took a 252 MB directory to 504 MB — the reclamation added to defend the bound
  would have breached it. `PRAGMA incremental_vacuum(N)` also frees exactly one
  page unless it is stepped to completion, which no size assertion catches, so
  the freed page count is asserted directly.
- A blocked checkpoint leaves the WAL on disk together with the database growth
  it already copied, so admission charges that deferred copy explicitly. The
  term is zero whenever the last checkpoint succeeded, so the uncontended path
  admits and refuses an identical set.

The epoch discard is `DELETE FROM journal_rows` with no WHERE clause, which
takes SQLite's truncate optimization: measured at ~0.26% of the database in WAL
bytes where the `WHERE session_id = ?` form rewrote every emptied leaf at up to
99%. One database per session is what makes the unqualified form correct.

An open, empty journal costs 57,344 bytes before a single row exists, so a
configured quota below `JOURNAL_MIN_SESSION_BYTES` now fails loudly at open with
the existing `journal_bound_exceeded` instead of as a run of identical append
failures. No production caller configures one; the affected surface is test
fixtures, rescaled to the smallest value that restores what each case proves.

## One deliberate behaviour change

Compaction was the only mechanism that shed bytes inside an epoch, and the write
path called it precisely so an append at the bound was not refused. The
SQLite-shaped replacement — a bounded prefix delete — cannot be used: with the
snapshot gone the surviving rows ARE the state, so dropping the oldest of them
loses the oldest transcript silently at the next reopen. So no row is ever shed
inside an epoch, and a session whose row bytes alone reach the bound now refuses
every append where it previously compacted and continued. A loud typed refusal
beats silent data loss.

What still sheds is unreferenced BLOB bytes — the dominant and unbounded byte
source — on the same write-path hook. The escape from the hard stop is the fold
that already exists, `replaceEpochItems`, which now actually returns bytes to
the filesystem instead of leaving them on the freelist.

The prune's protected set is a union of live reducer digests AND the candidate
row's own digests, including those cited only by a nested lifecycle-batch
mutation. Content addressing never rewrites a digest already on disk, so
protecting live state alone deletes the blob the append is about to cite — a
dangling reference that surfaces one reopen later as an empty expansion on an
item the user can see. `journal-store-blob-budget.test.ts` pins it, and it goes
red when the set is narrowed back.

## Handle ownership

A file handle used to be opened and closed per append; a SQLite handle is held
for the session's lifetime. Every path that can open a connection now has one
owner: the open function owns its raw connection until it returns, the store
owns its retained one and releases it in a new `close()`, and every other
connection is closed by the call that opened it. The attach, recovery,
eviction, map-overwrite and host-teardown paths close what they drop, and host
teardown is failure-complete — the sink-barrier flush throws by design, so a
trailing close statement would be skipped on exactly the path that leaks.

`close()` has a stated contract: admission at enqueue and permanent, the close
step on the same queue past that gate, one shared in-flight attempt, fulfilment
terminal, and the release last and deliberately unguarded so a retry re-enters
it. Guarding the release would skip it on retry, guaranteeing a permanent leak
in exactly the case where it did not release.

`journal_closed` joins the error union for a write after `close()`; no file
outside the directory references any of these codes.
@coderabbitai

coderabbitai Bot commented Sep 4, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Team

Run ID: 4732e275-aa92-4654-84bc-0ec00d9aa82f

📥 Commits

Reviewing files that changed from the base of the PR and between a35daa4 and ba55993.

📒 Files selected for processing (4)
  • src/main/native-chat/agent-session-journal/journal-legacy-import.test.ts
  • src/main/native-chat/agent-session-journal/journal-legacy-import.ts
  • src/main/native-chat/agent-session-wire/agent-session-journal-recovery.test.ts
  • src/main/native-chat/agent-session-wire/agent-session-journal-recovery.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 7 remain after this review.


📝 Walkthrough

Walkthrough

The journal storage model changes from snapshot and log files to a SQLite database with epoch rows and session projections. Journal writes, epoch replacement, rollover, replay, quarantine, quota checks, WAL handling, and space reclamation now use database transactions and physical page accounting. Blob pruning protects referenced and candidate digests. Journal closure and wire-layer teardown now close handles, support retries, and aggregate failures. Tests now use tracked openers and direct SQLite fixtures.

Merge Risk: 🟡 Moderate · up to ba559

This changes session persistence to SQLite and adds recovery behavior for empty provider history. Recovery-marker handling is covered, but unresolved journal replay-integrity and quota/lifecycle concerns remain; these should be addressed before merge to avoid retaining corrupted session state or unnecessarily refusing session writes.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description provides extensive technical context, rationale, behavior changes, and testing details. However, it omits required template sections, including ELI5, Why, Linked Issue, Visual Proof or… Add the missing template sections. Include a linked issue using Fixes #..., provide N/A with a reason if no visual proof applies, document manual testing and tested platforms, complete the AI Disclosure, Review, Agent skill upstream bou…
Docstring Coverage ⚠️ Warning Docstring coverage is 29.88% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 164 functions across 64 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely summarizes the primary change: moving the session journal onto SQLite.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Full details: Description check

Explanation

The description provides extensive technical context, rationale, behavior changes, and testing details. However, it omits required template sections, including ELI5, Why, Linked Issue, Visual Proof or N/A, checklist items, and review notes.

Resolution

Add the missing template sections. Include a linked issue using Fixes #..., provide N/A with a reason if no visual proof applies, document manual testing and tested platforms, complete the AI Disclosure, Review, Agent skill upstream boundary, Notes, and Checklist sections.

✨ Finishing Touches 💡 2
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🛠️ Fix failing CI checks 💡
  • Create stacked PR
  • Commit on current branch

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 12

🧹 Nitpick comments (3)
src/main/native-chat/agent-session-journal/journal-epoch-rollover.ts (1)

101-107: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Charge the WAL only once.

journalDirectoryBytes(input.journalDir) already includes the database -wal sidecar, while journalWalBytes(input.dbPath) reads that same file. This double-counts the existing WAL and can cause premature journal_bound_exceeded refusals during checkpoint contention. Remove the separate WAL term or exclude sidecars from measured.

src/main/native-chat/agent-session-journal/journal-database-space.test.ts (1)

193-211: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Release reader in a finally block.

If any assertion between lines 197 and 208 fails, lines 210-211 never run and the second SQLite handle stays open. The afterEach hook closes only opened.db, so rm(root, ...) then runs with a live handle on the database file. On Windows that removal fails and reports an error that hides the assertion that actually failed.

Wrap the reader in try/finally, or register it with the same tracking the other suites use.

src/main/native-chat/agent-session-journal/journal-write-guards.ts (1)

94-102: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Make assertLifecycle delegate to assert. The test is the only remaining caller, and both methods perform the same size check and rate check. Delegation prevents future drift.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Team

Run ID: dd36a1fa-4495-4091-aa61-94a5146d0f37

📥 Commits

Reviewing files that changed from the base of the PR and between 637dc30 and 016e4df.

📒 Files selected for processing (64)
  • src/main/native-chat/agent-session-journal/journal-compaction.ts
  • src/main/native-chat/agent-session-journal/journal-corruption-quarantine.ts
  • src/main/native-chat/agent-session-journal/journal-crash-boundary.test.ts
  • src/main/native-chat/agent-session-journal/journal-cursor.ts
  • src/main/native-chat/agent-session-journal/journal-database-schema.ts
  • src/main/native-chat/agent-session-journal/journal-database-space.test.ts
  • src/main/native-chat/agent-session-journal/journal-database-space.ts
  • src/main/native-chat/agent-session-journal/journal-database.test.ts
  • src/main/native-chat/agent-session-journal/journal-database.ts
  • src/main/native-chat/agent-session-journal/journal-epoch-controller.ts
  • src/main/native-chat/agent-session-journal/journal-epoch-replacement.test.ts
  • src/main/native-chat/agent-session-journal/journal-epoch-replacement.ts
  • src/main/native-chat/agent-session-journal/journal-epoch-rollover.ts
  • src/main/native-chat/agent-session-journal/journal-handle-ownership.test.ts
  • src/main/native-chat/agent-session-journal/journal-legacy-import.test.ts
  • src/main/native-chat/agent-session-journal/journal-lifecycle-admission.ts
  • src/main/native-chat/agent-session-journal/journal-lifecycle-capacity.ts
  • src/main/native-chat/agent-session-journal/journal-log-file.test.ts
  • src/main/native-chat/agent-session-journal/journal-log-file.ts
  • src/main/native-chat/agent-session-journal/journal-open.ts
  • src/main/native-chat/agent-session-journal/journal-paths.ts
  • src/main/native-chat/agent-session-journal/journal-physical-quota.test.ts
  • src/main/native-chat/agent-session-journal/journal-physical-quota.ts
  • src/main/native-chat/agent-session-journal/journal-quota-test-peak.ts
  • src/main/native-chat/agent-session-journal/journal-row-table.ts
  • src/main/native-chat/agent-session-journal/journal-row-writer.test.ts
  • src/main/native-chat/agent-session-journal/journal-row-writer.ts
  • src/main/native-chat/agent-session-journal/journal-store-blob-budget.test.ts
  • src/main/native-chat/agent-session-journal/journal-store-close.test.ts
  • src/main/native-chat/agent-session-journal/journal-store-close.ts
  • src/main/native-chat/agent-session-journal/journal-store-collaborators.ts
  • src/main/native-chat/agent-session-journal/journal-store-contracts.ts
  • src/main/native-chat/agent-session-journal/journal-store-escape.test.ts
  • src/main/native-chat/agent-session-journal/journal-store-open.ts
  • src/main/native-chat/agent-session-journal/journal-store-schema.test.ts
  • src/main/native-chat/agent-session-journal/journal-store-test-open.ts
  • src/main/native-chat/agent-session-journal/journal-store.test.ts
  • src/main/native-chat/agent-session-journal/journal-store.ts
  • src/main/native-chat/agent-session-journal/journal-wal-contention.test.ts
  • src/main/native-chat/agent-session-journal/journal-write-guards.ts
  • src/main/native-chat/agent-session-wire/agent-session-history-page.test.ts
  • src/main/native-chat/agent-session-wire/agent-session-journal-recovery.test.ts
  • src/main/native-chat/agent-session-wire/agent-session-journal-recovery.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-attach-flow.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-attach-orchestration.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-attach.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-eviction.test.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-eviction.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-handoff.test.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-host-handoff.test.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-host-lifetime.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-host-teardown.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-host.test.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-host.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-journal-handles.test.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-send-idempotency.test.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-subscribers.test.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-turns.test.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-wire-admission.test.ts
  • src/main/native-chat/agent-session-wire/structured-tui-transcript-catchup.test.ts
  • src/main/runtime/orchestration/db/database-file-permissions.ts
  • src/main/runtime/structured-agent-session-integration-replay.test.ts
  • src/main/runtime/structured-agent-session-integration.test.ts
  • src/main/sqlite/harden-database-files.ts
💤 Files with no reviewable changes (5)
  • src/main/native-chat/agent-session-journal/journal-store-contracts.ts
  • src/main/native-chat/agent-session-journal/journal-log-file.ts
  • src/main/native-chat/agent-session-journal/journal-log-file.test.ts
  • src/main/native-chat/agent-session-journal/journal-corruption-quarantine.ts
  • src/main/native-chat/agent-session-journal/journal-compaction.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 9 remain after this review.

Comment on lines +87 to +100
/** Bumps `user_version` only on success, so the database is never half-migrated. */
function migrateJournalDatabase(db: Database.Database, stored: number): void {
if (stored >= JOURNAL_DB_SCHEMA_VERSION) {
return
}
db.exec('BEGIN IMMEDIATE')
try {
db.pragma(`user_version = ${JOURNAL_DB_SCHEMA_VERSION}`)
db.exec('COMMIT')
} catch (error) {
db.exec('ROLLBACK')
throw error
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Preserve the original migration error

If SQLite has already ended the transaction after PRAGMA user_version = ... or COMMIT fails, SyncDatabase.exec delegates ROLLBACK to DatabaseSync.exec, which throws cannot rollback - no transaction is active. Expose DatabaseSync.isTransaction through SyncDatabase, roll back only when active, and rethrow the original error.

Comment on lines +63 to +66
} catch (error) {
input.db.exec('ROLLBACK')
throw error
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Guard ROLLBACK in both epoch transaction catches. Node’s SQLite driver may automatically roll back after COMMIT errors such as SQLITE_FULL or SQLITE_IOERR. The unconditional ROLLBACK in publishNewEpoch and replaceJournalEpoch can then throw a no-active-transaction error and replace the original error. Expose DatabaseSync.isTransaction through SyncDatabase and roll back only when it is true.

Comment on lines +340 to +348
private requireDatabase(): OpenJournalDatabase {
if (!this.database) {
throw new AgentSessionJournalError(
'journal_closed',
`agent-session journal for ${this.identity.sessionId} is not open`
)
}
return this.database
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

#!/bin/bash
# Description: Find readSince call sites and their relationship to journal close.
set -euo pipefail

rg -n -C 6 '\breadSince\s*\(' src/main
rg -n -C 4 'isReleased' src/main

Repository: stablyai/orca

Length of output: 10229


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '%s\n' '--- journal-store.ts ---'
sed -n '1,380p' src/main/native-chat/agent-session-journal/journal-store.ts

printf '%s\n' '--- journal-store-close.ts ---'
sed -n '1,180p' src/main/native-chat/agent-session-journal/journal-store-close.ts

printf '%s\n' '--- journal-store-collaborators.ts ---'
sed -n '1,110p' src/main/native-chat/agent-session-journal/journal-store-collaborators.ts

printf '%s\n' '--- read helper bindings ---'
rg -n -C 8 'function readJournalRowsAfterCursor|const readJournalRowsAfterCursor|readJournalRowsAfterCursor|class JournalLifecycleAdmission|interface OpenJournalDatabase|type OpenJournalDatabase' src/main/native-chat/agent-session-journal

Repository: stablyai/orca

Length of output: 38710


🤖 get_repo_knowledge executed:

get_repo_knowledge stablyai/orca /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4/learnings

Length of output: 12465


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '%s\n' '--- journal-cursor.ts ---'
sed -n '1,220p' src/main/native-chat/agent-session-journal/journal-cursor.ts

printf '%s\n' '--- journal-store close-related tests ---'
rg -n -C 10 'close\(|journal_closed|readSince' src/main/native-chat/agent-session-journal/journal-store.test.ts src/main/native-chat/agent-session-journal/*close*.test.ts 2>/dev/null || true

printf '%s\n' '--- lifecycle admission database usage ---'
sed -n '1,180p' src/main/native-chat/agent-session-journal/journal-lifecycle-admission.ts

printf '%s\n' '--- database wrapper close contract ---'
rg -n -C 12 'class Database|close\(\)|isOpen|connection is not open|not open' src/main/sqlite src/main/native-chat/agent-session-journal/journal-database.ts

printf '%s\n' '--- relevant diff summary ---'
git diff --stat -- src/main/native-chat/agent-session-journal/journal-store.ts
git diff -- src/main/native-chat/agent-session-journal/journal-store.ts | sed -n '1,180p'

Repository: stablyai/orca

Length of output: 50369


Gate requireDatabase() on JournalConnectionCloser.isReleased.

After close() succeeds, database remains non-null while readSince() can call readJournalRowsAfterCursor without the write queue. A valid read after close can therefore use the released handle and expose a raw driver error instead of journal_closed. Add a regression test for readSince() after close().

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

ℹ️ No critical issues — one minor nit inline and one rollout note below.

Reviewed changes

  • Session journal moved onto SQLite — the append-only log.jsonl / folded snapshot.json / byte-quarantine substrate is replaced by one journal.db per session (journal_rows + journal_sessions), opened through src/main/sqlite/sync-database.ts. Rows stay JSON in row_json, so the row schema, upcast chain, and reducer are untouched.
  • Physical quota re-derived as page arithmetic — journalTxnPhysicalCost / journalReclaimBandBytes / a deferred-checkpoint walBytes term replace the old JSON-length charge, with a sweep test pinning the fixed-page constant.
  • Compaction deleted; blob pruning is the new shed — journal-compaction.ts, journal-corruption-quarantine.ts, and the public compact() / compactionBoundary / autoCompact surface are removed; replaceEpochItems reclaims pages, and pruneJournalBlobs protects a live-state ∪ candidate-row digest union.
  • Handle ownership + a five-part close() contract — JournalConnectionCloser / JournalWriteQueue with a tracked-close test harness, and a failure-complete host teardown.

The SQLite accounting is load-bearing here, and it is the one thing I scrutinized hardest: the walBytes term is not a double-count — it reserves the deferred copy (a busy checkpoint leaves the WAL on disk while its frames will still grow the DB at the next successful checkpoint, so the peak is db + 2·wal). The uncontended path zeroes it. That, plus auto_vacuum-before-WAL ordering and the stepped incremental_vacuum, is asserted with genuine negative controls, not just green paths. Solid.

ℹ️ Abandoned legacy files still count against the new quota

The migration deliberately has no importer, but the old substrate's files are not just ignored — journalDirectoryBytes recursively counts every file in the session directory, so a session upgraded from the old path keeps its log.jsonl, snapshot.json, and any quarantine-* bytes charged against the new maxSessionBytes with no code path that removes them (the epoch discard only frees DB pages, and pruneJournalBlobs only touches blobs/). Orphaned blobs do eventually get pruned; the log/snapshot/quarantine files do not.

Technical details
# Abandoned legacy journal files consume quota with no cleanup path

## Affected sites
- `journal-physical-quota.ts:9` — `journalDirectoryBytes` counts every file, including legacy `log.jsonl` / `snapshot.json` / `quarantine-*`.
- No importer and no delete of these files anywhere in the diff.

## Required outcome
- Decide whether abandoned files should be (a) charged-and-cleaned, (b) excluded from the count, or (c) documented as permanent budget loss for upgraded sessions.

## Open questions for the human
- Is `experimentalStructuredNativeChat` ever enabled in the field today? If not, this is theoretical and a comment may be enough.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

…g valid rows, and keep rejected closes retryable

Six review findings on the SQLite journal migration.

1. A successful COMMIT is now the point of no return. The ordinary append,
   the epoch roll and the epoch replacement each adopt the committed row or
   epoch BEFORE any post-commit filesystem work; checkpoint, reclaim, blob
   prune and directory measurement run through `runJournalPostCommit`, which
   is best-effort by design and falls back to the transaction's own charge as
   a conservative footprint. Previously a post-COMMIT scan failure rejected a
   durable append and the next one reused its sequence, and a failed epoch
   housekeeping step left the store writing into a prefix already deleted.

2. Corruption repair preserves instead of destroying. A rejected suffix is
   copied into a new `journal_quarantine` table and removed from the live
   epoch in ONE transaction per chunk, charged against the session bound
   before a byte is written; a journal that cannot afford the copy refuses to
   open rather than falling back to deletion. The repair state is exposed as
   `journal.repair` and the rows are readable through
   `recoverQuarantinedRows()`, so Orca-owned submission, receipt and
   lifecycle identity survives a gap or a malformed row.

3. The physical charge covers the B-tree key payload. `session_id` and
   `epoch` are stored in both tables and both primary-key indexes and appear
   nowhere in `row_json`, so the journal boundary now bounds them and
   `journalTxnPhysicalCost` charges those bounds plus the projection upsert.
   The charge sweep runs the exact production transaction at maximum admitted
   key sizes.

4. A rejected `close()` no longer orphans its handle. Callers hand the
   journal to `agentSessionJournalCloseRetries` instead of swallowing the
   rejection, the attach map replacement is ABORTED when the previous
   journal will not close, host teardown retries what the registry holds, and
   a failed runtime teardown is retained so the next stop is a real retry.

5. `journalWalBytes()` returns zero only for ENOENT and propagates every
   other stat error, so admission and reclamation fail closed.

6. The WAL contention test closes the writer before removing its temp root
   and asserts the directory is removable once handles close.

Regression coverage: post-commit divergence (4), corruption repair (5),
key bounds (5), WAL stat (8), close retry (5), plus a runtime stop-retry
case. Each fix was ablated on this head and the matching tests go red.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 3


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Team

Run ID: 28d89f39-93c1-4d31-ad21-0a56643d8a3f

📥 Commits

Reviewing files that changed from the base of the PR and between 016e4df and dd4be6a.

📒 Files selected for processing (32)
  • src/main/native-chat/agent-session-journal/journal-close-retry.ts
  • src/main/native-chat/agent-session-journal/journal-corruption-repair.test.ts
  • src/main/native-chat/agent-session-journal/journal-database-schema.ts
  • src/main/native-chat/agent-session-journal/journal-database-space.test.ts
  • src/main/native-chat/agent-session-journal/journal-database-space.ts
  • src/main/native-chat/agent-session-journal/journal-database.test.ts
  • src/main/native-chat/agent-session-journal/journal-epoch-controller.ts
  • src/main/native-chat/agent-session-journal/journal-epoch-replacement.test.ts
  • src/main/native-chat/agent-session-journal/journal-epoch-replacement.ts
  • src/main/native-chat/agent-session-journal/journal-epoch-rollover.ts
  • src/main/native-chat/agent-session-journal/journal-key-bounds.test.ts
  • src/main/native-chat/agent-session-journal/journal-key-bounds.ts
  • src/main/native-chat/agent-session-journal/journal-post-commit-divergence.test.ts
  • src/main/native-chat/agent-session-journal/journal-post-commit.ts
  • src/main/native-chat/agent-session-journal/journal-row-table.ts
  • src/main/native-chat/agent-session-journal/journal-row-writer.test.ts
  • src/main/native-chat/agent-session-journal/journal-row-writer.ts
  • src/main/native-chat/agent-session-journal/journal-store-collaborators.ts
  • src/main/native-chat/agent-session-journal/journal-store-open.ts
  • src/main/native-chat/agent-session-journal/journal-store-restore.ts
  • src/main/native-chat/agent-session-journal/journal-store.test.ts
  • src/main/native-chat/agent-session-journal/journal-store.ts
  • src/main/native-chat/agent-session-journal/journal-suffix-quarantine.ts
  • src/main/native-chat/agent-session-journal/journal-wal-bytes.test.ts
  • src/main/native-chat/agent-session-journal/journal-wal-contention.test.ts
  • src/main/native-chat/agent-session-wire/agent-session-journal-recovery.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-attach-orchestration.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-attach.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-close-retry.test.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-host-teardown.ts
  • src/main/runtime/structured-agent-session-runtime.test.ts
  • src/main/runtime/structured-agent-session-runtime.ts
🚧 Files skipped from review as they are similar to previous changes (5)
  • src/main/native-chat/agent-session-journal/journal-row-writer.test.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-attach-orchestration.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-attach.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-host-teardown.ts
  • src/main/native-chat/agent-session-wire/agent-session-journal-recovery.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 9 remain after this review.

Comment on lines +139 to +141
await journal.close()
await rm(root, { recursive: true, force: true })
await expect(stat(root)).rejects.toMatchObject({ code: 'ENOENT' })

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Release the held reader before removing the directory.

The separate reader connection remains open until afterEach. On Windows, rm() at Line 140 can fail after journal.close() because that reader still holds SQLite files. Release it before the removal assertion.

Proposed fix
+    await releaseReader()
     await journal.close()
     await rm(root, { recursive: true, force: true })
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
await journal.close()
await rm(root, { recursive: true, force: true })
await expect(stat(root)).rejects.toMatchObject({ code: 'ENOENT' })
await releaseReader()
await journal.close()
await rm(root, { recursive: true, force: true })
await expect(stat(root)).rejects.toMatchObject({ code: 'ENOENT' })

…ine append-only, and charge it in bytes

Three ways the corruption quarantine still lost rows it was written to keep.

Replay validated contiguity from the first row that HAPPENED to remain, so an
epoch missing only its sequence-1 row declared the leftovers contiguous and set
no `truncateFrom`. The load was still corrupt, so recovery imported provider
history and `replaceEpochItems` deleted every live row — including Orca-minted
submission, receipt and lifecycle identity that no transcript can reconstruct,
and that nothing had quarantined. Replay now anchors at sequence 1, so a missing
epoch row rejects the whole surviving range before any replacement runs.

`journal_quarantine` was keyed on `(session_id, epoch, seq)` and copied with
`INSERT OR REPLACE`. A repair frees the sequences it removed and the live epoch
reuses them, so a second repair in the same epoch silently deleted what the
first preserved. The table is now keyed on a surrogate `quarantine_id`, the copy
is a plain append, and `(epoch, seq)` is metadata; existing v1 databases are
rekeyed in the migration that already bumps `user_version`.

The admission charge read `length(row_json)`, which counts CHARACTERS for a TEXT
value where `journalTxnPhysicalCost` expects physical UTF-8 bytes. A multibyte
suffix was charged at up to a third of what it writes, which defeats the
pre-write physical bound — over a megabyte on a maximum-size lifecycle batch.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Important

One must-address charge bug in the new quarantine path: the copy is charged from length(row_json), which counts characters, not bytes, so multi-byte content undercharges the physical bound.

Reviewed changes

  • Made a COMMIT final — runJournalPostCommit moves checkpoint/reclaim/prune/measure after the store adopts the committed state, so a post-commit scan failure can no longer strand the store on a deleted epoch or reuse a sequence (journal-epoch-rollover.ts, journal-epoch-replacement.ts, journal-row-writer.ts).
  • Replaced suffix deletion with quarantine — a rejected suffix is copied into a new journal_quarantine table (charged up front, one transaction per chunk) and only then removed from journal_rows; rows stay recoverable via recoverQuarantinedRows instead of being destroyed.
  • Added a process-wide close-retry registry — rejected journal closes are retained and retried by teardown rather than dropping the SQLite handle (journal-close-retry.ts, structured-agent-session-host-teardown.ts, structured-agent-session-runtime.ts).
  • Bounded the SQLite keys — session_id (512 B) and epoch (128 B) are asserted at open/mint, and their per-row + projection page cost is folded into journalTxnPhysicalCost.
  • Made journalWalBytes fail closed — non-ENOENT stat errors now propagate instead of silently reading as an empty WAL.

The post-commit ordering and the close-retry contract are sound, with genuine negative controls (journal-post-commit-divergence.test.ts, journal-close-retry.ts). The one load-bearing arithmetic defect is below.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Team

Run ID: 299bb7e5-c214-4092-b6d7-19c1cf6ed877

📥 Commits

Reviewing files that changed from the base of the PR and between dd4be6a and c4563fa.

📒 Files selected for processing (8)
  • src/main/native-chat/agent-session-journal/journal-corruption-repair.test.ts
  • src/main/native-chat/agent-session-journal/journal-database-schema.ts
  • src/main/native-chat/agent-session-journal/journal-database.test.ts
  • src/main/native-chat/agent-session-journal/journal-database.ts
  • src/main/native-chat/agent-session-journal/journal-open.ts
  • src/main/native-chat/agent-session-journal/journal-row-table.ts
  • src/main/native-chat/agent-session-journal/journal-suffix-quarantine.ts
  • src/main/native-chat/agent-session-wire/agent-session-journal-recovery.test.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/main/native-chat/agent-session-journal/journal-database.test.ts
  • src/main/native-chat/agent-session-journal/journal-suffix-quarantine.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 8 remain after this review.

const gap = findSequenceGap(
tailRows.map((row) => row.seq),
oldest
rows.map((row) => row.seq),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Validate the sequence stored in journal_rows.

Line 90 trusts parsed.row.seq instead of the SQLite row sequence. If database rows have sequences [1, 3] but the valid JSON at sequence 3 contains seq: 2, replay sees a contiguous [1, 2] range. It then applies the mismatched row and does not quarantine the physical sequence-3 row.

Reject a parsed row when its embedded sequence differs from entry.seq. Use the database sequence as the quarantine boundary.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

ℹ️ No new issues in this delta. Approval withheld for one prior finding that is still open.

Reviewed changes

  • Charged the quarantine copy in bytes — SELECT_SUFFIX_LENGTHS now uses length(CAST(row_json AS BLOB)), so multi-byte suffixes are charged by physical size, with a multibyte regression test.
  • Rekeyed journal_quarantine onto a surrogate — schema bumped to v2 with a quarantine_id surrogate key plus a v1→v2 rekey migration, so a later repair reusing freed sequences no longer overwrites an earlier repair's preserved rows; the copy is a plain append now.
  • Anchored replay at sequence 1 — replayJournal validates contiguity from FIRST_JOURNAL_SEQUENCE rather than the first surviving row, so a missing epoch row quarantines the whole surviving range instead of declaring it contiguous.

The prior charge bug is fully addressed, and the two additional fixes are correct — the migration handles both v1 states, and the replay anchoring is sound given compaction is gone.

ℹ️ Prior finding still open — assertLifecycle is dead code

The earlier review's note at journal-write-guards.ts:94 is unchanged: assertLifecycle is byte-identical to assert (both are wouldExceedSize + assertRate) and its only remaining references are its own test in journal-row-writer.test.ts. It is not called anywhere in the production path, so it reads as part of the write path while being a duplicate guard. Delete it (and its test assertions) before this merges.

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

…he v1 quarantine migration doubling the file

Replay validated numeric contiguity from sequence 1 but never that sequence 1
IS the epoch row. When the anchor was missing the repair set aside every
surviving row, and if provider-history import then failed — a transcript that
is temporarily gone is enough — the journal reopened as a clean, row-less
epoch: an ordinary append took sequence 1, replay accepted it, read-restore
published it as history, and automatic recovery never ran again while the
user's real messages sat in quarantine.

Replay now rejects an unanchored prefix, the open publishes an
`unreconcilable_prefix` anchor for an epoch its repair emptied, and that anchor
keeps reporting corrupt — so provider history is retried on every attach —
until the timeline is rebuilt or the session writes content of its own. A
repair also discloses rows it set aside when no line was unreadable at all,
which is the case that removes the most.

The v1 quarantine rekey copied every legacy row into the new table inside one
transaction and dropped the old one. A quarantine holds whole rejected rows: a
single 8 MiB row nearly doubled the database past the physical bound the open
had already checked, the dropped pages only reached the freelist, and the next
open refused the session it had just migrated. The v1 table is renamed and
frozen instead, and reads take both generations. Table creation also moves
inside the migration transaction, so a crash can no longer leave a v2-shaped
database still reporting version 0 for an older build to write into.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Team

Run ID: df430cd9-15d9-4bf7-b410-d8841d288c98

📥 Commits

Reviewing files that changed from the base of the PR and between c4563fa and a35daa4.

📒 Files selected for processing (13)
  • src/main/native-chat/agent-session-journal/journal-corruption-repair.test.ts
  • src/main/native-chat/agent-session-journal/journal-database-schema.ts
  • src/main/native-chat/agent-session-journal/journal-database.test.ts
  • src/main/native-chat/agent-session-journal/journal-database.ts
  • src/main/native-chat/agent-session-journal/journal-open.ts
  • src/main/native-chat/agent-session-journal/journal-repair-disclosure.ts
  • src/main/native-chat/agent-session-journal/journal-row-table.ts
  • src/main/native-chat/agent-session-journal/journal-store-collaborators.ts
  • src/main/native-chat/agent-session-journal/journal-store-open.ts
  • src/main/native-chat/agent-session-journal/journal-store-restore.ts
  • src/main/native-chat/agent-session-journal/journal-store.test.ts
  • src/main/native-chat/agent-session-journal/journal-store.ts
  • src/main/native-chat/agent-session-wire/agent-session-journal-recovery.test.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 8 remain after this review.

function repairText(input: { malformedRows: number; quarantinedRows: number }): string {
const preserved =
input.quarantinedRows > 0
? `${input.quarantinedRows} row${input.quarantinedRows === 1 ? '' : 's'} after it were set aside and remain recoverable`

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Correct the preserved-row description.

When a malformed row and one following row are quarantined, quarantinedRows is 2. Line 42 tells the user that two rows after the malformed row were set aside. The malformed row itself is also preserved and recoverable. Describe the total quarantined rows instead.

…g the repair marker

A transcript that exists but decodes to zero messages was imported as a
success: the import published an empty `legacy_import` replacement that
deleted the `unreconcilable_prefix` anchor and its disclosure, so the next
probe read the session as clean and every later attach skipped provider
recovery while the user's rows sat in quarantine for good.

The import now leaves the epoch untouched when nothing decodes, reporting
`replaced: false`, and recovery treats that like a transcript it could not
read — the marker stands and a later attach with real history rebuilds the
timeline.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

ℹ️ No new issues in this delta. Approval is still withheld for one open prior finding — assertLifecycle dead code — which this commit does not touch.

Reviewed changes

  • Anchored replay at the epoch row — replayJournal now treats a non-epoch row at sequence 1 (or a missing/empty epoch) as corrupt via a new unanchored term, not just a sequence gap, so a repaired journal can no longer silently adopt an ordinary row as its anchor (journal-open.ts).
  • Kept the repair epoch asking for history — awaitsProviderHistory marks an unreconcilable_prefix epoch corrupt while it holds nothing but its anchor and the disclosure row, so provider-history recovery keeps retrying until the session writes content of its own.
  • Republished an anchor after a total repair — openJournalStoreState mints a fresh unreconcilable_prefix epoch when the replayed epoch folds to lastSequence === 0, so an ordinary append can never take sequence 1.
  • Froze the v1 quarantine instead of copying it — the migration renames the sequence-keyed table to journal_quarantine_v1 and reads the union, avoiding the copy that nearly doubled the file; table creation and the user_version bump now share one transaction.
  • Widened the repair disclosure — it now fires on quarantined rows (gaps set aside valid rows), not only malformed rows, and moved into journal-repair-disclosure.ts with a stable item id.

The replay-anchoring change is the risky one and it holds up: the unanchored term only trips when the epoch row is absent or non-epoch (a healthy epoch always folds seq 1 as the epoch row, so lastSequence is never 0 otherwise), and the awaitsProviderHistory predicate stops the moment any non-disclosure row lands. The migration freeze is strictly better than the copy it replaces — the frozen table keeps the same bytes it already held rather than doubling them. The negative controls (crash-before-version-bump leaves no tables, both quarantine generations survive a rekey, the 4 MiB legacy row migrates without breaching the bound) are genuine.

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

ℹ️ No new issues in this delta. The standing blocker is still the previously-flagged assertLifecycle dead code, which none of these commits touch.

Reviewed changes

  • Stopped an empty transcript from rolling the epoch — importLegacyTranscriptIntoJournal now returns replaced: false when the provider transcript decodes to zero messages, leaving the epoch (and its repair anchor/disclosure) untouched instead of publishing an empty replacement epoch.
  • Kept the repair marker asking — rehydrate treats a non-replaced import the same as an unreadable one: it reports an error with imported: 0, so the corrupt probe still returns true on the next attach and recovery is retried.

This is the right fix and the shape is clean: the replaced flag is required on the sole ok: true variant, so !result.ok || !result.replaced narrows correctly and no caller can forget to check it. The negative control is genuine — it seeds a repairable session, opens against an empty transcript, and asserts the epoch still carries its unreconcilable_prefix anchor and disclosure, that loadJournal still reports corrupt: true, and that a later transcript with content still rebuilds the timeline.

One observation worth noting, not a blocker: the two non-recovery callers (structured-agent-session-host-handoff.ts and structured-tui-transcript-catchup.ts) check only imported.ok before emitting reset('epoch_changed'). With replaced: false they now force a subscriber reset for an epoch that did not change. That is a strict improvement over the previous behavior — which rolled a fresh empty epoch and wiped the timeline on an empty transcript — so nothing to fix, but the reset is now a no-op reload rather than a genuine epoch change.

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Re-validated in the running app after the four fix rounds — 7/7 PASS

Head ba55993dabc. Isolated dev instance with its own user-data directory and private renderer
port, driven over CDP. Port owner verified by lsof plus the Electron bundle path in this
worktree, and by fetching an untracked file of this worktree through the dev server and getting
the real transformed module back. App identity over IPC:
devBranch = brennanb2025/sqlite-journal-electron2.

The feature is off by default, so it was turned on through the real Settings UI —
Chat UI → Default view = Chat UI → Use updated structured native chat — and the
values were confirmed in the persisted profile before anything else was tested. (The structured
toggle only renders once the default view is Chat UI, so all three had to be set.)

settings

# Path Verdict
1 Start a structured Codex chat; send, stream, render PASS
2 History persists across reload and reopen PASS
3 Cancel a turn mid-stream; UI settles PASS
4 Hard kill + restart with a session open, then reattach PASS
5 journal.db present; no log.jsonl / snapshot.json anywhere PASS
6 Large tool output exercises payload bounds and blob spill PASS
7 No journal errors, unhandled rejections or handle-leak warnings PASS

1 — send, stream, render

journal.db appeared under the userData journal directory the moment the session was created,
and held 10 rows over sequences 1–10 after the first turn.

first turn

3 — cancel mid-stream

Interrupted at Working for 9 seconds. The stream stopped, the partial reply was kept, the
header settled to Worked for 15 seconds, Cancellation requested. rendered, and the next turn
went through normally.

cancelled

6 — payload bounds and blob spill

A tool call producing 60,000 padded lines (~2.6 MB). The citing row is 17,364 bytes of JSON —
the 16 KiB inline head plus envelope — and the remainder went to one content-addressed blob of
1,048,607 bytes under blobs/. Every other row in the session is under 3.2 KB.

large tool output

4 — hard kill and reattach

SIGKILL to the main process with the tab open and 82 rows on disk. After relaunch the tab was
re-projected and the whole transcript returned in order — both early turns, the cancelled turn,
the later turn, and the large tool-output block. DOM occurrence counts matched exactly one
prompt plus one reply per marker, so nothing was duplicated; on disk the epoch was unchanged,
sequences 1–91, quarantine empty, blob intact. The session then accepted a new turn.

after hard kill

Re-proven a second time after a further clean quit and cold restart, rebuilt from the database
alone:

cold restart

5 — one database per session

<userData>/agent-session-journal/<workspace>/<session>/journal.db, plus blobs/ where a
payload spilled. A recursive search of the entire user-data directory for log.jsonl or
snapshot.json returned zero matches. Tables journal_rows, journal_sessions,
journal_quarantine; PRAGMA user_version = 2.

The fix-round behaviours, exercised directly

Corruption repair preserves rejected rows. A 25-row session was crashed, row 14's body was
overwritten with unparseable JSON directly in the database, and the app was restarted and the
session attached. The rejected suffix — sequences 14 through 25, 12 rows, including the
unreadable one, verbatim
— moved into journal_quarantine. Nothing was deleted.

A repair that empties an epoch republishes an anchor and recovers from provider history. The
same repair opened a new epoch anchored at sequence 1 with reason legacy_import, and the
transcript came back complete over the wire: all three turns, prompts and replies, in order.

A corrupt journal is not silently accepted as readable. Before that attach the corrupted
sessions were deliberately not published as restorable tabs at startup, and their rows were left
untouched on disk — the corrupt state is kept so recovery is retried on a later attach, which is
exactly what then happened.

Handle ownership. With one session attached, exactly one journal's journal.db, -shm and
-wal were open in the main process and no others. Closing the chat tab took that to zero
open journal handles and left journal.db alone in the directory — WAL checkpointed and
truncated, as the close contract promises.

Notes

  • The The status bar hit an error. banner visible in the screenshots is a pre-existing
    Maximum update depth exceeded loop in PortsStatusSegment. It reproduces on a fresh profile
    before any chat session exists and is unrelated to this change.
  • The only recurring main-process warning,
    MaxListenersExceededWarning: 11 closed listeners added to [BrowserWindow], fires at startup
    in every app generation including the first, before any workspace or session exists, so it is
    not attributable to this change either.
  • Not exercised: the 256 MiB per-session refusal (would need a multi-hundred-megabyte session;
    the machine had ~4 GB free), the post-commit filesystem-failure path (no product surface for
    injecting a fault between COMMIT and the following filesystem call), and Windows / WSL / SSH
    (the feature is gated to local macOS and Linux).

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Review and validation record

This landed through a plan-first process. Recording it here so a reviewer can see what was checked rather than re-deriving it.

Plan. Written up front and put through six independent verification rounds before any code was written. Rounds resolved, in order: whether the hand-rolled machinery was genuinely deleted rather than ported; connection and blob ownership; SQLite allocation semantics (page/WAL growth invalidated the original quota arithmetic); the per-transaction physical charge; busy-checkpoint and close() contracts; and plan-text consistency. Every quota number in the final plan came from file-backed node:sqlite reproductions, not reasoning.

Code review. Four rounds, eleven findings, converging 6 → 3 → 2 → 1, with each round's fixes independently confirmed by the next reviewer before it looked for new ground. The findings worth knowing about:

  • A successful COMMIT was not the point of no return — a post-commit measurement failure could reject an append whose row was already durable, after which the next append reused the sequence and hit the primary key.
  • Corruption repair deleted valid rows. The previous file-backed journal never deleted on corruption; it set bytes aside. Repair now copies the rejected suffix into journal_quarantine before removing it, in one transaction per chunk.
  • Quarantine was keyed on (session_id, epoch, seq) with INSERT OR REPLACE, so a second repair silently destroyed what the first preserved. It is now append-only on a surrogate key.
  • Quarantine admission used SQLite length() on a TEXT column, which counts characters, undercharging non-ASCII transcripts by up to 3×.
  • A repair that emptied an epoch could leave a row-less epoch that a later append normalised, dropping prior messages from the timeline while they sat in quarantine. Every live epoch is now anchored at sequence 1 and keeps reporting corrupt until it is genuinely rebuilt.
  • A provider transcript that existed but decoded to zero messages was treated as a successful import, permanently retiring that corrupt state. It now leaves the epoch untouched and retryable.
  • Retryable close() rejections were discarded by callers, orphaning handles — which blocks directory removal on Windows.

Every fix carries regression coverage that was ablated: each new test was proven to fail against the pre-fix code, with the red counts recorded per fix.

Live validation. The full seven-path suite ran twice in a real dev instance driven over CDP, passing 7/7 both times, most recently on the fixed head. That included two hard SIGKILL restarts (one mid-turn) with 8 submission and 8 dispatch rows for 8 messages sent, a 220 KB tool output spilling to a blob while the largest inline row stayed under 18 KB, auto_vacuum=2 and journal_mode=wal confirmed on the live database, the -wal file at zero bytes at every observation, and journal handles returning to zero on tab close with no sidecars left behind. Screenshots are in the visual-proof comment above.

Two accepted decisions

Sessions created before this change stop loading. This is intended and was explicitly chosen: there is no importer for the previous log.jsonl/snapshot.json format. The feature is off by default behind two nested experimental settings, so the affected population is opt-in only. A readiness pass flagged this as release-blocking against a generic bar; it is a deliberate product decision, not an oversight.

One known unrelated defect. After a mid-turn SIGKILL, a recovered turn shows a "Working for N seconds" indicator that counts up indefinitely and is not cleared by Stop. This was ablated against the base commit and reproduces identically there on the previous file-backed journal, so it is pre-existing and out of scope. Cause, for whoever picks it up: a turn settles by tombstoning its running turnLifecycle item rather than writing a completed row, so a kill before completion leaves the running item alive regardless of storage substrate.

…ill and rate limit

Match what comparable implementations do: the journal is an unbounded
append-only SQLite log with no side tables and no admission control.

Corruption: the rejected suffix is DELETED rather than copied into a
quarantine table. The load still reports `corrupt` and recovery still
rebuilds the epoch from provider history, so the observable outcome is
unchanged — only the preservation half is gone. The schema is back to one
version with two tables; no v1 database exists outside unmerged commits of
this branch, so the rekey migration and the two-generation read path go with
it. Sequence-1 epoch anchoring and the empty-provider-transcript retry are
kept: both are about the corrupt signal being correct.

Size: no `maxSessionBytes`, so no page-cost arithmetic, reclaim band,
incremental vacuum, lifecycle byte reservations or `journal_bound_exceeded`.
`auto_vacuum` and `wal_autocheckpoint = 0` existed only to make a
transaction's physical cost predictable for that charge; with the charge gone
SQLite's default checkpointing is what the journal wants, and the explicit
pre-close checkpoint is redundant with the one `db.close()` performs. WAL,
`synchronous = FULL` and `busy_timeout` stay.

Payloads: an oversized body is truncated at the existing inline cap with the
existing marker and the remainder is discarded, bounded at the translation
layer that already calls these helpers. The truncation point and message do
not change; the content-addressed blob directory and all digest tracking do.

Rate: no `maxAppendsPerWindow` and no `journal_rate_exceeded`.

`JournalPayloadLimits` is now just the inline cap.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Important

The simplification itself is clean and consistent — typecheck passes, the journal (156), codex (186), and agent-session-wire (255) suites are green, and grep confirms no dangling references to any deleted module. The blockers are that the PR description still documents machinery this commit deleted, and two load-bearing protections (a durable size bound and full tool-output retention) are gone with no replacement and no acknowledgement in the description.

Reviewed changes

  • Removed the physical byte bound and its page arithmetic — journal-database-space.ts, auto_vacuum, wal_autocheckpoint, the checkpoint/reclaim loop, and the maxSessionBytes / maxAppendsPerWindow / appendWindowMs limits are all gone; JournalRowWriter.enqueue is now a single insert + upsert + COMMIT transaction with no quota or rate gate.
  • Removed the byte-quarantine — a rejected suffix is deleted rather than preserved (deleteJournalRowSuffix), the journal_quarantine table and the v1→v2 migration are dropped, and JOURNAL_DB_SCHEMA_VERSION returns to 1.
  • Removed the blob store and the blobs channel — journal-blob-store.ts is deleted; boundPayload now discards overflow instead of spilling it, and appendItem / tryAppendItem / appendCodexLifecycleItem drop their blobs argument across the codex translation and the sink.
  • Deleted the lifecycle / rate-limit machinery — JournalAppendBudget, JournalLifecycleAdmission, JournalLifecycleCapacity, and the key bounds (journal-key-bounds.ts) are removed.

⚠️ The PR description describes machinery this commit deleted

The body's "physical quota is repriced" section (page arithmetic, JOURNAL_TXN_FIXED_PAGES = 24, auto_vacuum = INCREMENTAL, wal_autocheckpoint = 0, the charge sweep), the byte-quarantine ("handle ownership", the journal_quarantine table), the blob spill, and the rate limit are all removed by b795704. The description still claims "the 256 MiB per-session bound is unchanged" and walks through four load-bearing behaviours that no longer exist. A reviewer merging on the strength of the body would be approving a design that is not in the code. The description needs to be rewritten to the much smaller scope — one SQLite database per session, an append-only journal_rows table, an inline 16 KiB payload head, and deletion-on-corruption with provider-history recovery.

Technical details
# PR description is stale

## Affected sites
- PR body — still documents `maxSessionBytes`, `auto_vacuum`, `wal_autocheckpoint`,
  the quota sweep, `JOURNAL_MIN_SESSION_BYTES`, byte-quarantine, blob spill, and the
  rate limit; all deleted by `b795704`.

## Required outcome
- Rewrite the description to describe the journal that actually ships: two tables
  (`journal_rows` + `journal_sessions`), schema version 1, WAL/FULL/foreign_keys,
  no disk bound, no rate limit, no quarantine, overflow truncated to `inlineHeadBytes`.

⚠️ Durable journal growth is now unbounded

Removing maxSessionBytes, the rate limit, compaction, and auto_vacuum together means a long-lived or looping session grows journal.db (and its WAL) without limit. deleteAllJournalRows takes SQLite's truncate optimization but leaves freed pages on the freelist, so epoch rollovers no longer shrink the file, and rollEpoch is only ever triggered by corruption/fork — never by size. The deleted comment at the top of journal-payload-bounds.ts ("a looping agent must not be able to fill the host disk") shows this was a deliberate prior guarantee that is now dropped with no replacement. Worth an explicit confirmation that unbounded durable growth is an intended tradeoff here (and, if it is, a line in the description saying so).

Technical details
# No durable size bound

## Affected sites
- `journal-row-writer.ts` — enqueue does insert + upsert + COMMIT with no size/rate check.
- `journal-database.ts` — no `auto_vacuum`, so freed pages are never returned to the filesystem.
- `journal-payload-bounds.ts` — `JournalPayloadLimits` is now only `{ inlineHeadBytes }`.

## Required outcome
- Confirm the removal of the durable bound is intended and document it, or restore a
  bound (page-cost charge or a simple directory-size gate) for the append path.

ℹ️ Oversized tool output is now truncated, not spilled

With journal-blob-store.ts gone, boundPayload keeps only the 16 KiB inline head and discards the remainder; the digest and byteLength it still records describe bytes nothing can read back. Previously a 40 MB tool result was retained whole and recoverable after reconnect; the durable reconnect ceiling for a single tool result is now 16 KiB. This is inherent to "drop blob spill" and is a reasonable simplification, but it is a user-visible behaviour change worth stating plainly in the description alongside the other two.

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Fresh visual proof at b79570429f3 — supersedes the earlier run — 7/7 PASS

This replaces the earlier visual-proof comment. That run was captured at ba55993dabc, before the scope reduction that removed quarantine, the per-session byte bound, blob spill and the append rate limit. Its screenshots show a build whose behaviour no longer merges, so they should not be read as evidence for this head. Everything below was captured fresh on b79570429f3.

Rig. Isolated dev instance on its own userData root and its own renderer port, driven over CDP. Port ownership was checked against the launching process's bundle path before the first command, and the renderer was pinned by fetching a file that exists only in this worktree. No pre-existing profile, no other instance touched.

The feature is off by default — all three gates turned on through the real Settings UI

Chat UI on → Default view set to Chat UI (which is what makes the third control appear) → structured native chat on.

Settings with all three gates enabled

Read back from the on-disk profile: experimentalNativeChat: true, openAgentTabsInChatByDefault: true, experimentalStructuredNativeChat: true.


1. Start a structured Codex chat — send, stream, render — PASS

New Codex chat tab in a folder workspace. The message sends, the turn streams, and the reply renders.

First turn rendered

journal.db is created under the session's journal directory the moment the session opens.

2. History persists across a reload — PASS

Fingerprinted the transcript, reloaded the window, fingerprinted again. All five landmarks came back, in the same relative order, with no duplicates.

Transcript intact after reload

3. Cancel a turn mid-stream — PASS

Stopped a long turn while it was still streaming. The UI settles immediately: Cancellation requested. renders, the stop control disappears, the working indicator clears, and the composer re-enables.

Cancelled turn settled

4. Hard kill, restart, reattach — PASS

SIGKILL to the running app with the chat open, then a fresh launch against the same profile.

rows epoch transcript landmarks
before kill 76 02432ab2… 2 / 1 / 1 / 1 / 1
after restart 76 02432ab2… (same) 2 / 1 / 1 / 1 / 1

PRAGMA integrity_check on the killed database returns ok, with the whole tail still in the write-ahead log. The chat tab is restored, nothing is duplicated, nothing is lost — and the reattached session still accepts new turns and appends them to the same transcript:

New turn after crash recovery

5. One database per session, and nothing else — PASS

Every file under the journal root after the whole run:

journal.db
journal.db-shm
journal.db-wal

A search of the entire profile for log.jsonl, snapshot.json, or any blobs/ directory returns nothing. The database carries exactly two tables — journal_rows and journal_sessions — with no quarantine table.

6. A large output is truncated with a visible marker, and the row stays small — PASS

This is the behaviour that changed since the last run: there is no blob file any more, so the remainder is simply discarded and the cut is announced in the text itself.

A 28,892-byte reply is clipped to a 16 KiB head and the marker is rendered on screen:

Truncation marker rendered in the transcript

[Orca: output truncated — 28892 bytes total, digest 89242da93c7b]

The stored row is 16,746 bytes — head plus marker, remainder gone.

The same holds for a large tool result. A shell command producing 348,894 bytes stores head at exactly 16,384 bytes with truncated: true, the original byteLength, and the digest; the row is 20,416 bytes.

One honest gap, and it is not from this change: a tool result also carries a byte-count marker, but the transcript's own tool-detail display clamp cuts the rendered text at 4,000 characters, so that particular marker never reaches the screen. That clamp is untouched here — the three files involved are byte-identical to main. The journal-level truncation is correct in both cases; only the tool-result marker's visibility is affected, and it was already like that before this PR.

Also confirmed: the store is unbounded. Nothing was refused for space at any point.

7. No journal errors, unhandled rejections or handle leaks — PASS

Across both app generations: zero journal or SQLite errors, zero unhandled rejections, zero uncaught exceptions, and no journal entries in the structured main-process trace.

Handle ownership measured directly, since a retained connection is the one new lifecycle obligation here:

open descriptors under the journal root
one session 5
second session opened 9
second session closed 5

The closed session's descriptors are gone entirely and only the live session's remain — the connection is released, not leaked.

One startup warning does appear — a listener-count warning for the app window — but it is emitted before any journal exists, and this change adds no window listeners. Unrelated. A recoverable render error in the status bar's ports segment also fires on startup; it is likewise outside this change, which touches no renderer file at all.


Overall: PASS (7/7). Sessions created before this change are intentionally not migrated and were not exercised, as designed.

…ulti-block tool input

A repair that keeps its prefix had nothing durable to show for the suffix it
deleted: a sequence gap costs no malformed row, so no disclosure is appended,
and the surviving rows keep their epoch anchor. The next probe read a
contiguous anchored prefix, called it clean, and the deleted stretch of
timeline was never asked for again — silent loss, with the deletion already
committed. The deletion now writes a `journal_repairs` marker in the SAME
transaction, and replay keeps reporting corrupt while it stands. It retires
under exactly the rule the emptied-epoch anchor takes: a fresh epoch carries
the rebuild, or the session writes content of its own past the sequence the
repair left free. The repair's own disclosure is not that content.

Legacy import bounded a tool call's input only when it was the message's sole
block; the multi-block path returned `tool-call` unchanged, so a mixed message
from Claude, Grok or an omp execution cell persisted the whole input despite
`inlineHeadBytes`. `boundBlock` now routes it through `boundToolInput`.

Also drops canonical comments describing quarantine, snapshot files, blob
storage and blob compaction — none of which exist any more.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

ℹ️ No new issues in this delta. Approval is still withheld for the three standing findings from the prior review (stale PR description, unbounded durable growth, truncated tool output) — none of which this commit touches.

Reviewed changes

  • Added a durable partial-repair marker — a new journal_repairs table (schema bumped to v2) records the first sequence a repair left free when it keeps a prefix, so a sequence gap with no malformed row and no disclosure still replays as corrupt instead of a clean contiguous prefix (journal-repair-marker.ts, journal-open.ts, journal-database-schema.ts).
  • Retired the marker on every epoch transition — replaceJournalEpoch and publishNewEpoch clear it inside the same transaction, and the marker is epoch-scoped, so a superseded epoch's marker never leaks onto the live one.
  • Bounded multi-block tool input in legacy import — boundBlock now routes tool-call blocks through boundToolInput, closing the gap where a Claude/Grok/omp message carrying a tool call alongside narration imported unbounded (journal-legacy-import.ts).

The partial-repair mechanism is the risky part and it holds up. contentFrom is derived as lastSequence + 1, and the awaitsRebuild predicate exempts the disclosure row it appends, so a repair's own disclosure cannot retire its own marker. The retirement rule mirrors the emptied-epoch anchor: a fresh epoch (from provider-history rebuild) or a session write at contentFrom ends the retry. The negative controls are genuine — a pure sequence gap has no disclosure to pin the corruption on, and the test proves the next probe still reports corrupt until the suffix is rebuilt. Journal directory plus recovery suites (172 tests) and pnpm tc:node are green.

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

loadJournal runs on a sync-database connection and returns JournalLoad | null, so both wire call sites were awaiting a non-Promise. The type-aware code-quality gate flags it; the native gate does not.
@brennanb2025

Copy link
Copy Markdown
Contributor Author

Fresh visual proof at 11affd925f7 — supersedes the previous run — 5/5 PASS

This replaces the previous visual-proof comment. That run was captured at b79570429f3, before the two fixes on this head. It is still accurate for what it covered, but it predates the journal_repairs marker, so it cannot speak to the behaviour that changed — this run is the one that does. Targeted at the delta rather than a full repeat: the seven-path run above already passed at the previous head, and the two commits since touch journal internals only, with zero renderer files in git diff origin/main...HEAD -- src/renderer.

Rig. Isolated dev instance on its own userData root and its own renderer port, driven over CDP. The CDP port's LISTEN owner was checked against the launching bundle path before the first command, and the renderer was pinned by fetching an untracked file that exists only in this worktree (real content back; a peer worktree's path returns the SPA fallback). No pre-existing profile, no other instance touched.

The feature is off by default — all three gates turned on through the real Settings UI

Chat UI on → Default view set to Chat UI (which is what makes the third control appear) → structured native chat on.

Settings with all three gates enabled

Read back from the on-disk profile: experimentalNativeChat: true, openAgentTabsInChatByDefault: true, experimentalStructuredNativeChat: true.


1. Smoke — send, stream, render, reload — PASS

Four turns in a new Codex chat inside a folder workspace. Each sends, streams, and renders.

Four turns streamed and rendered

journal.db is created the moment the session opens; the four turns land as 37 rows under a single epoch. Reloading the window returns the history in the same order, with nothing dropped or duplicated:

History ordered after reload


2. Corruption repair with the new marker — PASS (this is the fix)

A second session, four turns, 35 rows under epoch 37a5e392…:

Second session before corruption

Closed the tab (the journal closes cleanly — -wal and -shm are gone, journal.db stands alone), then deleted row seq = 20 from journal_rows. That is a plain sequence gap: no malformed row, no unreadable bytes, nothing that would produce a disclosure on its own — exactly the shape that used to be lost silently.

Replay before the repair, read through the product's own loadJournal:

{ "corrupt": true, "truncateFrom": 21, "lastSequence": 19, "malformedRows": 0 }

Reopened the session through a real product path — a surface taking a hold (agentSession.hold) — with provider history that held nothing to restore. What the repair left on disk:

before after the repair
rows 34 (1–19, 21–35) 19 (1–19)
journal_repairs rows 0 1
journal_repairs: session=codex_d7cb21dc…  epoch=37a5e392…  content_from=20

The rejected suffix is gone and the marker naming the first free sequence was written in the same transaction.

The second probe still reports corrupt. The surviving rows are a contiguous, anchored prefix — no gap, no malformed row — so the only thing keeping it corrupt is the standing marker:

{ "corrupt": true, "truncateFrom": <absent>, "lastSequence": 19, "malformedRows": 0 }

Ablation, on a byte copy of that same database with only the marker row deleted:

{ "corrupt": false, "lastSequence": 19, "malformedRows": 0 }

That is the old outcome in one line: a contiguous anchored prefix, reported clean, with two turns already deleted and nothing left asking for them. The marker is the whole difference.

It survives a full app shutdown. Quit the app, relaunch: the on-disk journal still replays corrupt: true, so the retry is owed on a later attach rather than settled.

Then the session recovers. Restored full provider history and attached again. The recovery rebuilt the timeline in place:

value
new epoch da6db4f5…, anchored at seq 1, reason legacy_import
journal_repairs empty — retired by the fresh epoch
rows 9 (anchor + 4 user + 4 assistant)

All four turns are back, including the two that were inside the deleted suffix, served through the same agentSession.history call the transcript pages with:

seq 2  user       Reply with exactly: ECHO-ONE
seq 3  assistant  ECHO-ONE
seq 4  user       Reply with exactly: FOXTROT-TWO
seq 5  assistant  FOXTROT-TWO
seq 6  user       Reply with exactly: GOLF-THREE     ← was deleted
seq 7  assistant  GOLF-THREE                          ← was deleted
seq 8  user       Reply with exactly: HOTEL-FOUR      ← was deleted
seq 9  assistant  HOTEL-FOUR                          ← was deleted

Rendered, in Session History — first prompt ECHO-ONE, last agent line HOTEL-FOUR, 8 messages:

Recovered session in Session History

Both arms of the contract therefore hold: while provider history had nothing to give, the marker stood and the retry stayed owed; once it did, the epoch was republished and the marker retired.


3. A large output is still truncated, the marker is visible, the row stays small — PASS

A 28,892-byte reply is clipped to a 16 KiB head with the cut announced in the text itself, rendered on screen:

Truncation marker rendered in the transcript

[Orca: output truncated — 28892 bytes total, digest 89242da93c7b]

Stored row: 16,746 bytes.

Same for a tool result: a shell command producing 348,894 bytes stores head at exactly 16,384 bytes with truncated: true, the original byteLength and the digest — the row is 20,380 bytes, about 6% of the raw output.

The same honest gap as last time, and still not from this change: the transcript's tool-detail display clamp cuts rendered tool text at 4,000 characters, so a tool result's marker never reaches the screen. Those files are byte-identical to main. The journal-level truncation is correct in both cases.

The multi-block half of the second fix — a tool call's input bounded when it sits alongside narration rather than alone in the message — is exercised by the legacy-import suite rather than by a live Codex turn, which emits the sole-block shape. 14 test files, 161 tests pass in the journal directory at this head.


4. One database per session, and nothing else — PASS

Every file under the journal root after the whole run:

agent-session-journal/<workspace>/<session>/journal.db
agent-session-journal/<workspace>/<session>/journal.db-shm     (while open)
agent-session-journal/<workspace>/<session>/journal.db-wal     (while open)

A search of the entire profile for log.jsonl, snapshot.json, or any blobs/ directory returns nothing. PRAGMA user_version reads 2, and the database carries exactly three tables — journal_rows, journal_sessions, journal_repairs.


5. No journal errors, unhandled rejections or handle-leak warnings — PASS

Across three app generations: zero journal or SQLite errors, zero unhandled rejections, and no journal entries in the structured main-process trace. No journal_bound_exceeded, journal_closed, journal_read_only or journal_stale_fence anywhere in the logs.

Handle ownership measured directly, since the retained connection is the one new lifecycle obligation here: after every clean close — closing the chat tab, and quitting the app — journal.db-wal and journal.db-shm are gone, leaving journal.db alone. The connection is released, not leaked.

Two startup conditions do appear, both outside this change: a listener-count warning for the app window, emitted deterministically at the same point of every launch before any journal exists; and a recoverable render error in the status bar's ports segment. This PR adds no window listeners and touches no renderer file at all.


Overall: PASS (5/5).

Two things worth stating plainly rather than leaving implied:

  • A session whose journal is corrupt is deliberately not published as a restorable tab at startup — read-restore refuses it so recovery is retried on a later attach. That is pre-existing and by design, but it means the repair has to be reached through an attach, which is what the hold above is. The recovered session's own tab was not re-published because I had closed it before corrupting the journal, so it was no longer in the tab inventory; its recovered transcript is shown through Session History and the history RPC instead.
  • Sessions created before this change are intentionally not migrated and were not exercised, as designed.

@brennanb2025
brennanb2025 merged commit f4c2821 into main Sep 4, 2026
28 checks passed
brennanb2025 pushed a commit that referenced this pull request Sep 5, 2026
#18652 moved the session journal onto SQLite with no importer, so a chat whose
history is a `log.jsonl` founds a fresh empty journal beside it and is
indistinguishable from one created seconds ago — the epoch reason it records
even says `session_created`.

No importer here either: the history is not replayed, it is explained. One
`status` row says the format is unreadable, names the transcript still on disk,
and says how to continue — the session attaches on the record's own provider
handle, so the agent still holds the conversation the transcript no longer
shows. The row carries the same stable identity the repair disclosure uses, so a
reopen upserts it rather than adding another.

Read restore has to stop dropping these sessions or the message has nowhere to
appear: an unpublished chat is also what prunes its tab out of the saved
workspace, so the tab disappears before anything can explain itself. Absence of
a database is not absence of history.

Nothing is read from the remnant beyond its existence, and nothing moves,
rewrites or deletes it.
brennanb2025 pushed a commit that referenced this pull request Sep 5, 2026
Second review pass, on the first pass's own fix.

Re-offering the notice when the epoch holds nothing reads `loaded.state`, which
is the PRE-repair load — so a journal this same open just emptied looks
identical to one that lost its append. The repair's `unreconcilable_prefix`
epoch is the durable marker that history was deleted and never rebuilt, and
`awaitsRebuild` retires it the moment any row that is not the repair's own
disclosure appears. Appending here therefore stopped the session ever asking the
provider for that history again, while the journal still held none — and handed
the user two contradictory explanations in one transcript.

Reachability was not limited to the affected users: every session predating
#18652 has a `log.jsonl` beside it and nothing deletes it, so any later
corruption in any of those directories hit this.

Guarded on `!loaded.corrupt`, which preserves the crash-window case exactly — a
committed `session_created` epoch whose append was lost loads `corrupt: false`.

The regression test needed the right fixture to bite: a malformed row costs a
repair disclosure, which fills `items` and hides the branch. Deleting the epoch
anchor leaves everything unanchored, so the repair publishes an empty epoch and
appends nothing — the one state where this branch and a repair meet. Verified
red without the guard.

Also from the pass: the status text now goes through `boundJournalStatusText`
like every other status body, and a latched (newer-schema) journal is pinned to
write nothing, since it loads empty and reaches the same branch where an append
would throw and make the session unopenable rather than read-only.
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…stablyai#18652)

* refactor(agent-session-journal): move the session journal onto SQLite

The agent-session journal kept its state in three hand-rolled file formats: an
append-only `log.jsonl` with torn-tail repair, a `snapshot.json` holding folded
state plus a retained tail, and byte-quarantine files for anything unreadable.
This replaces all of it with one SQLite database per session — `journal.db`
beside the existing `blobs/` store — using the in-house adapter and the
open/pragma/migrate/harden pattern the orchestration database already follows.

Two tables: `journal_rows` (the append-only log, keyed by
`(session_id, epoch, seq)`) and `journal_sessions` (the derived projection,
upserted in the SAME transaction as every insert). Rows stay JSON in one
column, so the row schema, the version upcast chain, and the reducer survive
byte for byte — `journal-reducer.test.ts` and four other suites pass unchanged
and are the regression proof.

Deleted: `journal-log-file.ts`, `journal-compaction.ts`,
`journal-corruption-quarantine.ts`, and the public `compact()` /
`compactionBoundary` / `autoCompact` members, none of which had a non-test
caller.

Existing `log.jsonl` / `snapshot.json` journals are deliberately abandoned. No
importer: a session created on the old path stops working, which is acceptable
because the feature is off by default.

## The physical quota is repriced, because SQLite does not charge like a file

The 256 MiB per-session bound is unchanged, but the arithmetic under it could
not survive: SQLite grows the database in pages and the WAL in frames, and the
checkpoint that copies the WAL forward holds the same pages in both files at
once, so a transaction's peak is about twice its content. Admission now charges
the candidate transaction's own measured page cost, validated against a sweep
that runs as a regression test (`journal-database-space.test.ts`) rather than
derived from reasoning about the allocator.

Four things are load-bearing rather than tuning, each measured:

- `auto_vacuum = INCREMENTAL` must be set BEFORE `journal_mode = WAL`. Set it
  after and it is ignored with no error, reclamation silently becomes a no-op,
  and the file never shrinks again. Both halves are asserted.
- `wal_autocheckpoint = 0` plus an explicit `wal_checkpoint(TRUNCATE)` at the
  end of every write path, so the one moment the same pages live in two files is
  a moment the charge accounts for.
- Reclamation runs in bounded chunks. A single unbounded `incremental_vacuum`
  took a 252 MB directory to 504 MB — the reclamation added to defend the bound
  would have breached it. `PRAGMA incremental_vacuum(N)` also frees exactly one
  page unless it is stepped to completion, which no size assertion catches, so
  the freed page count is asserted directly.
- A blocked checkpoint leaves the WAL on disk together with the database growth
  it already copied, so admission charges that deferred copy explicitly. The
  term is zero whenever the last checkpoint succeeded, so the uncontended path
  admits and refuses an identical set.

The epoch discard is `DELETE FROM journal_rows` with no WHERE clause, which
takes SQLite's truncate optimization: measured at ~0.26% of the database in WAL
bytes where the `WHERE session_id = ?` form rewrote every emptied leaf at up to
99%. One database per session is what makes the unqualified form correct.

An open, empty journal costs 57,344 bytes before a single row exists, so a
configured quota below `JOURNAL_MIN_SESSION_BYTES` now fails loudly at open with
the existing `journal_bound_exceeded` instead of as a run of identical append
failures. No production caller configures one; the affected surface is test
fixtures, rescaled to the smallest value that restores what each case proves.

## One deliberate behaviour change

Compaction was the only mechanism that shed bytes inside an epoch, and the write
path called it precisely so an append at the bound was not refused. The
SQLite-shaped replacement — a bounded prefix delete — cannot be used: with the
snapshot gone the surviving rows ARE the state, so dropping the oldest of them
loses the oldest transcript silently at the next reopen. So no row is ever shed
inside an epoch, and a session whose row bytes alone reach the bound now refuses
every append where it previously compacted and continued. A loud typed refusal
beats silent data loss.

What still sheds is unreferenced BLOB bytes — the dominant and unbounded byte
source — on the same write-path hook. The escape from the hard stop is the fold
that already exists, `replaceEpochItems`, which now actually returns bytes to
the filesystem instead of leaving them on the freelist.

The prune's protected set is a union of live reducer digests AND the candidate
row's own digests, including those cited only by a nested lifecycle-batch
mutation. Content addressing never rewrites a digest already on disk, so
protecting live state alone deletes the blob the append is about to cite — a
dangling reference that surfaces one reopen later as an empty expansion on an
item the user can see. `journal-store-blob-budget.test.ts` pins it, and it goes
red when the set is narrowed back.

## Handle ownership

A file handle used to be opened and closed per append; a SQLite handle is held
for the session's lifetime. Every path that can open a connection now has one
owner: the open function owns its raw connection until it returns, the store
owns its retained one and releases it in a new `close()`, and every other
connection is closed by the call that opened it. The attach, recovery,
eviction, map-overwrite and host-teardown paths close what they drop, and host
teardown is failure-complete — the sink-barrier flush throws by design, so a
trailing close statement would be skipped on exactly the path that leaks.

`close()` has a stated contract: admission at enqueue and permanent, the close
step on the same queue past that gate, one shared in-flight attempt, fulfilment
terminal, and the release last and deliberately unguarded so a retry re-enters
it. Guarding the release would skip it on retry, guaranteeing a permanent leak
in exactly the case where it did not release.

`journal_closed` joins the error union for a write after `close()`; no file
outside the directory references any of these codes.

* fix(agent-session-journal): make a COMMIT final, stop repairs deleting valid rows, and keep rejected closes retryable

Six review findings on the SQLite journal migration.

1. A successful COMMIT is now the point of no return. The ordinary append,
   the epoch roll and the epoch replacement each adopt the committed row or
   epoch BEFORE any post-commit filesystem work; checkpoint, reclaim, blob
   prune and directory measurement run through `runJournalPostCommit`, which
   is best-effort by design and falls back to the transaction's own charge as
   a conservative footprint. Previously a post-COMMIT scan failure rejected a
   durable append and the next one reused its sequence, and a failed epoch
   housekeeping step left the store writing into a prefix already deleted.

2. Corruption repair preserves instead of destroying. A rejected suffix is
   copied into a new `journal_quarantine` table and removed from the live
   epoch in ONE transaction per chunk, charged against the session bound
   before a byte is written; a journal that cannot afford the copy refuses to
   open rather than falling back to deletion. The repair state is exposed as
   `journal.repair` and the rows are readable through
   `recoverQuarantinedRows()`, so Orca-owned submission, receipt and
   lifecycle identity survives a gap or a malformed row.

3. The physical charge covers the B-tree key payload. `session_id` and
   `epoch` are stored in both tables and both primary-key indexes and appear
   nowhere in `row_json`, so the journal boundary now bounds them and
   `journalTxnPhysicalCost` charges those bounds plus the projection upsert.
   The charge sweep runs the exact production transaction at maximum admitted
   key sizes.

4. A rejected `close()` no longer orphans its handle. Callers hand the
   journal to `agentSessionJournalCloseRetries` instead of swallowing the
   rejection, the attach map replacement is ABORTED when the previous
   journal will not close, host teardown retries what the registry holds, and
   a failed runtime teardown is retained so the next stop is a real retry.

5. `journalWalBytes()` returns zero only for ENOENT and propagates every
   other stat error, so admission and reclamation fail closed.

6. The WAL contention test closes the writer before removing its temp root
   and asserts the directory is removable once handles close.

Regression coverage: post-commit divergence (4), corruption repair (5),
key bounds (5), WAL stat (8), close retry (5), plus a runtime stop-retry
case. Each fix was ablated on this head and the matching tests go red.

* fix(agent-session-journal): anchor replay at sequence 1, make quarantine append-only, and charge it in bytes

Three ways the corruption quarantine still lost rows it was written to keep.

Replay validated contiguity from the first row that HAPPENED to remain, so an
epoch missing only its sequence-1 row declared the leftovers contiguous and set
no `truncateFrom`. The load was still corrupt, so recovery imported provider
history and `replaceEpochItems` deleted every live row — including Orca-minted
submission, receipt and lifecycle identity that no transcript can reconstruct,
and that nothing had quarantined. Replay now anchors at sequence 1, so a missing
epoch row rejects the whole surviving range before any replacement runs.

`journal_quarantine` was keyed on `(session_id, epoch, seq)` and copied with
`INSERT OR REPLACE`. A repair frees the sequences it removed and the live epoch
reuses them, so a second repair in the same epoch silently deleted what the
first preserved. The table is now keyed on a surrogate `quarantine_id`, the copy
is a plain append, and `(epoch, seq)` is metadata; existing v1 databases are
rekeyed in the migration that already bumps `user_version`.

The admission charge read `length(row_json)`, which counts CHARACTERS for a TEXT
value where `journalTxnPhysicalCost` expects physical UTF-8 bytes. A multibyte
suffix was charged at up to a third of what it writes, which defeats the
pre-write physical bound — over a megabyte on a maximum-size lifecycle batch.

* fix(agent-session-journal): keep a repaired epoch anchored and stop the v1 quarantine migration doubling the file

Replay validated numeric contiguity from sequence 1 but never that sequence 1
IS the epoch row. When the anchor was missing the repair set aside every
surviving row, and if provider-history import then failed — a transcript that
is temporarily gone is enough — the journal reopened as a clean, row-less
epoch: an ordinary append took sequence 1, replay accepted it, read-restore
published it as history, and automatic recovery never ran again while the
user's real messages sat in quarantine.

Replay now rejects an unanchored prefix, the open publishes an
`unreconcilable_prefix` anchor for an epoch its repair emptied, and that anchor
keeps reporting corrupt — so provider history is retried on every attach —
until the timeline is rebuilt or the session writes content of its own. A
repair also discloses rows it set aside when no line was unreadable at all,
which is the case that removes the most.

The v1 quarantine rekey copied every legacy row into the new table inside one
transaction and dropped the old one. A quarantine holds whole rejected rows: a
single 8 MiB row nearly doubled the database past the physical bound the open
had already checked, the dropped pages only reached the freelist, and the next
open refused the session it had just migrated. The v1 table is renamed and
frozen instead, and reads take both generations. Table creation also moves
inside the migration transaction, so a crash can no longer leave a v2-shaped
database still reporting version 0 for an older build to write into.

* fix(agent-session-journal): stop an empty provider transcript retiring the repair marker

A transcript that exists but decodes to zero messages was imported as a
success: the import published an empty `legacy_import` replacement that
deleted the `unreconcilable_prefix` anchor and its disclosure, so the next
probe read the session as clean and every later attach skipped provider
recovery while the user's rows sat in quarantine for good.

The import now leaves the epoch untouched when nothing decodes, reporting
`replaced: false`, and recovery treats that like a transcript it could not
read — the marker stands and a later attach with real history rebuilds the
timeline.

* style(agent-session-journal): merge the duplicate journal-database-space import

* refactor(agent-session-journal): drop quarantine, byte bound, blob spill and rate limit

Match what comparable implementations do: the journal is an unbounded
append-only SQLite log with no side tables and no admission control.

Corruption: the rejected suffix is DELETED rather than copied into a
quarantine table. The load still reports `corrupt` and recovery still
rebuilds the epoch from provider history, so the observable outcome is
unchanged — only the preservation half is gone. The schema is back to one
version with two tables; no v1 database exists outside unmerged commits of
this branch, so the rekey migration and the two-generation read path go with
it. Sequence-1 epoch anchoring and the empty-provider-transcript retry are
kept: both are about the corrupt signal being correct.

Size: no `maxSessionBytes`, so no page-cost arithmetic, reclaim band,
incremental vacuum, lifecycle byte reservations or `journal_bound_exceeded`.
`auto_vacuum` and `wal_autocheckpoint = 0` existed only to make a
transaction's physical cost predictable for that charge; with the charge gone
SQLite's default checkpointing is what the journal wants, and the explicit
pre-close checkpoint is redundant with the one `db.close()` performs. WAL,
`synchronous = FULL` and `busy_timeout` stay.

Payloads: an oversized body is truncated at the existing inline cap with the
existing marker and the remainder is discarded, bounded at the translation
layer that already calls these helpers. The truncation point and message do
not change; the content-addressed blob directory and all digest tracking do.

Rate: no `maxAppendsPerWindow` and no `journal_rate_exceeded`.

`JournalPayloadLimits` is now just the inline cap.

* fix(agent-session-journal): mark a partial repair pending and bound multi-block tool input

A repair that keeps its prefix had nothing durable to show for the suffix it
deleted: a sequence gap costs no malformed row, so no disclosure is appended,
and the surviving rows keep their epoch anchor. The next probe read a
contiguous anchored prefix, called it clean, and the deleted stretch of
timeline was never asked for again — silent loss, with the deletion already
committed. The deletion now writes a `journal_repairs` marker in the SAME
transaction, and replay keeps reporting corrupt while it stands. It retires
under exactly the rule the emptied-epoch anchor takes: a fresh epoch carries
the rebuild, or the session writes content of its own past the sequence the
repair left free. The repair's own disclosure is not that content.

Legacy import bounded a tool call's input only when it was the message's sole
block; the multi-block path returned `tool-call` unchanged, so a mixed message
from Claude, Grok or an omp execution cell persisted the whole input despite
`inlineHeadBytes`. `boundBlock` now routes it through `boundToolInput`.

Also drops canonical comments describing quarantine, snapshot files, blob
storage and blob compaction — none of which exist any more.

* fix(agent-session-wire): stop awaiting the synchronous journal probe

loadJournal runs on a sync-database connection and returns JournalLoad | null, so both wire call sites were awaiting a non-Promise. The type-aware code-quality gate flags it; the native gate does not.

---------

Co-authored-by: Merge Sim <sim@local>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant