Recovery moved the database aside but left every `.segments/*.json` routing
record in place. Each record names a Session whose row lived in the moved
database, so `list()` found a record without a row and refused with
`SESSION_STORAGE_MISSING` on every later call, permanently: not even a Session
created after the recovery could be listed, and `listStoredHeaders()` failed
with it.
`setAside()` now moves each routing record to `<hash>.json.unreadable-<stamp>`
with the bytes it names, so every record stays readable and none of them counts
as lost state. `list()` reads the directory again after the scan, because the
scan is what triggers recovery; without that the first call would still fail.
The extraction report for a missing database now says the records are kept, so a
restored database reads through them, which is what the code does.
`test: moves the routing records with a damaged database, so listing Sessions
works after recovery` writes a Session, damages the database, and asserts that
`list()` resolves and no `.json` record remains. It fails with
`SESSION_STORAGE_MISSING` when the two source files are reverted.
Also from the same review:
- `standIn`'s comment states that `time` resets per Segment, so a damaged first
frame reports the epoch.
- README documents `codec` 255 rows and the `session_segments` internal view.
- An unused `plan` helper is gone from the schema fixture.
A large `data` value ends mid-page, leaving the rest of its last page unused.
At 4 KiB that slack is 12.8% of a 370 MB corpus store; a 16 KiB page cuts it to
12.2% and the file to 362 MB from 366 MB, without changing any row, index, or
query. Tail reads and the flagship analytical query measure the same or slightly
faster. The pragma precedes WAL, which fixes the page size at the first write.
Small stores pay a little: the same 2,000-event session is 576 KB rather than
536 KB, because each page holds more slack. That is 40 KB against 4 MB saved on
the corpus.
README records the measured size trade and why per-event compression, not the
row layout, makes the store larger than frames: recompressing the same events in
groups of 64 reaches 183.8 MB against the frame layout's 186.7 MB, but a point
read would then decode its whole group, 19x slower for the reads a live Session
makes.
A lock is a live writer, not damage. SQLite holds its locks as operating-system
locks that the kernel releases when a process exits, so a lock that outlives the
busy timeout belongs to a process that is still inside it. Replacing its file
does not stop that writer: it keeps appending to the moved bytes while the new
database starts empty, splitting one history across two files.
Windows made the inconsistency visible: it refuses to move a file another handle
holds open, so the replacement could never work there, and the tests had to
assert different outcomes per platform. The rule is now uniform and simpler.
- `recovery: replace` keeps its meaning for damage only: a database this build
cannot read moves to `<name>.unreadable-<timestamp>` and an empty one takes
its place, so every byte survives and Sessions stay available.
- A lock always fails with `SESSION_STORAGE_LOCKED` after the busy timeout, on
every platform, and the database is left where it is.
- A damaged file whose move fails is never replaced either: returning false
reports the storage fault instead of discarding the only copy of the bytes.
- `ReplaceReason` and the `locked` tag are gone; only damage reaches the tag.
This matches SQLite's own SQLITE_BUSY contract, LevelDB's LOCK behaviour, and
Chrome's singleton lock handling, which reports an owner it cannot prove dead
rather than breaking a live one. README, upgrade guide, and the decision record
state the rule in both languages.
The Windows lock test expected the database to be moved aside, which Windows
refuses while a live writer holds the file. The open correctly reports the lock
and leaves the file in place, so the test now asserts that: no moved file, no
replacement report, and a `SESSION_STORAGE_LOCKED` failure. POSIX keeps the
move-and-replace assertion.
The move-failure handler is marked as platform-conditional: an absent journal
moves without error, and POSIX renames a file another handle holds open, so only
Windows under a live writer reaches it.
A live writer on Windows holds the database file open, so the rename that
moves a locked database aside fails. The failure escaped the recovery instead
of reporting the lock, which failed the Windows coverage job.
A failed move now reports the same lock outcome the caller already handles, so
the database stays in place rather than disappearing behind an unhandled error.
The Windows lock test asserts the platform's real behaviour: no moved file, and
a reported lock instead of a replacement.
Test-only assertions for the derived-object recovery could not run on Windows
for the same reason and are unchanged.
Close the six review findings against the event-row store, add provisioned
recovery, and make the derived tables' indexes actually reachable.
Data carried over from the frame layout:
- Carry over the readable prefix of a frame recorded longer than its lines.
The frame layout served whatever prefix a read asked for, so only a sequence
with no readable line gets a row no reader decodes.
- Drop lines past a frame's recorded range: the frame layout never read them,
so reporting them as damage would fail a read that used to succeed.
- Repeat the nearest readable event's `time` in the stand-in row instead of 0,
so `session_summary.last_event_time` stays a real instant.
- Tolerate an absent version 1 trigger or index. A build that narrowed the
frame layout dropped some, and losing a trigger costs no stored event.
- Refuse a child Segment that does not start where its parent ends instead of
giving it a history the frame layout rejected.
- Set aside a frame whose Segment row is absent, which the version 1 foreign
key never checked.
Derived tables:
- Compare every declared object (table, session view, indexes, further views)
so a dropped view or index is rebuilt rather than silently missing forever.
- Analyze once when no statistics exist and `PRAGMA optimize` on close. Without
statistics SQLite scanned every result in the Segment per tool call:
`session_tools` took 2.3 s on 84,000 tool calls against 22 ms analyzed.
Recovery, new `recovery` setting defaulting to `replace`:
- An absent database becomes a new empty one.
- A lock waits the busy timeout, then the file moves to
`<name>.locked-<timestamp>` and a new empty database takes its place.
- An unreadable file moves to `<name>.unreadable-<timestamp>` the same way.
- `report` keeps the previous refusal for a storage root another process
may write. A newer schema version is never replaced under either mode.
Documentation records the recovery setting, the raw-state damage behavior, the
compression limit on JSON queries, and the statistics step. 488 tests with full
coverage on the package sources.
The schema and every static statement of the SQLite Session store were
string literals in TypeScript, and the upgrade step from the frame layout
executed whatever the current schema constant held. They now live under
resources/sql: schema/vN.sql is the whole schema of one version and is
not edited once released, upgrade/A-to-B holds the statements of one
upgrade step, and store/ and derived/ hold the statements of the store
and of the derived-table runtime. src/sql.ts is their only reader.
Two internal views, segment_extents and session_heads, replace the SQL
fragments the store shared by string interpolation. Transaction control,
connection pragmas and the DDL generated from a derivation stay inline.
The upgrade from the frame layout replaced a whole frame when one of its
lines was unreadable, so a read that stopped before the damaged event
failed after the upgrade although it succeeded before. A frame that
splits into its recorded lines is now carried over event by event, and
only an unreadable event gets a stand-in row.
Drop the two indexes on sessions that no statement or documented query
uses, and state the cross-build limitation of derived tables exactly.
The opt-in SQLite Session store kept each durable write as one compressed
frame, so SQL could not see an event's sequence, type or time. It now
stores one row per event: the envelope members are columns and data is
JSON text, or one Zstandard frame when it is large. Segments use integer
ids and a segment_paths table that lists each Segment's history, so the
session_* views return a Session's events in one join, forks included.
Derived tables for model calls, tool calls, tool results and compactions
are written in the events' transaction and rebuilt from events when a
table is missing, its version changes, or its derivation was absent.
Opening a database runs ordered upgrade steps under src/migrations. The
first rewrites the frame layout (schema version 1) in place; a frame it
cannot read is set aside without blocking the other Sessions.
BREAKING CHANGE: the frameEvents setting is removed, and a database
upgraded to schema version 2 cannot be opened by earlier releases.
/side forks now record origin: 'side' in the child Session header. The
left Sidebar hides side-origin Sessions as it hides subagent children.
The V4 codec admits the side origin without changing the frozen V2
header codec; the persistence acknowledgement records the same-version
decision.
Co-authored-by: Dudu-0223 <290591114+Dudu-0223@users.noreply.github.com>
Co-authored-by: Kexin Liu <69756503+liukx0205@users.noreply.github.com>
* perf(session): merge short SQLite frames inside the append transaction
Live writes store one to three events per frame, so compression barely
works. When the newest short frames of a Segment reach frameEvents events,
the append transaction re-encodes them as full frames. The frames_no_delete
trigger is dropped from the unreleased schema and from existing databases.
Co-authored-by: Magolor <25860372+Magolor@users.noreply.github.com>
Co-authored-by: Kexin Liu <69756503+liukx0205@users.noreply.github.com>
* perf(session): read SQLite frame payloads only for a merge
Scan only frame ranges to decide whether the trailing short frames merge,
then read their payloads. Append decoded lines one by one so a large
frame size cannot exceed the argument limit.
Co-authored-by: Magolor <25860372+Magolor@users.noreply.github.com>
Co-authored-by: Kexin Liu <69756503+liukx0205@users.noreply.github.com>
* perf(session): cap SQLite frame merges by decoded bytes
A merge skips a run of short frames whose stored or decoded text exceeds
4 MiB, bounding how long it holds the event loop and the write lock. Tests
cover merged compression, the live event path, a failure after the merge's
delete, and large events; a seeded synthetic diagnostic measures size and
append cost. Documentation drops the one-frame-per-write wording and lists
the write stop after short-frame corruption.
Co-authored-by: Magolor <25860372+Magolor@users.noreply.github.com>
Co-authored-by: Kexin Liu <69756503+liukx0205@users.noreply.github.com>
* perf(session): store short SQLite frames uncompressed until merged
A short frame below min(64 KiB, 2 MiB / frameEvents) of JSON text is stored
as text; the merge compresses it together with its neighbours. This skips a
compression on every live append that the merge would redo, and keeps any run
of such frames within the 4 MiB merge limit.
Co-authored-by: Magolor <25860372+Magolor@users.noreply.github.com>
Co-authored-by: Kexin Liu <69756503+liukx0205@users.noreply.github.com>
* perf(session): seal short SQLite frames when a writer closes
* test(session): assert the reported seal failure without an untyped matcher
---------
Co-authored-by: Turtle <turtle1999@deepseek.com>
Co-authored-by: Magolor <25860372+Magolor@users.noreply.github.com>
Co-authored-by: Kexin Liu <69756503+liukx0205@users.noreply.github.com>
Co-authored-by: Magolor <magolor@qq.com>
Fixtures construct the store with the plugin's frame defaults and read
durable history through frames; existing tests query the frames table
and its triggers. New tests cover the frame codec, frame layout per
write and per setting, sliced reads across frame boundaries, decode
grouping, and the corruption refusals for a missing frame, a frame
shorter than its range, an unknown codec, and damaged bytes.
The SQLite README, the persistence subsystem page and the generated
configuration catalog describe `frameEvents` and the frame encoding
selected by `compression`.
* test(session): cover SQLite persistence and document the provider
* test(session): align coverage with the latest SQLite implementation
* test(session): adapt storage coverage to the current SQLite backend
* feat(session)!: pass fork source through agent creation
* refactor: prepare forks privately and append child segment events
* refactor: choose fork sharing in SQLite creation transaction
* fix(session): preserve caller-prepared fork seeds
* feat(session): flush fixed fork prefix before child creation
* fix(session): persist fork sources and await parent drain
* chore: remove test and documentation changes from fork PR
* refactor(agent-loop): reuse agent fork source type
* fix(session): retain SQLite handle and JSONL errors after rebase
* perf(session): create forks from the caller's history without reloading the parent
The fork source carries the complete child history from seq 0. A live
parent's log supplies the shared prefix; a cold parent's prefix is used as
persistence returned it to the caller. The factory no longer reopens the
parent, and the JSONL backend copies the supplied history instead of
decoding the parent log again. The SQLite backend drains a live parent
writer before sharing its persisted prefix, so the factory no longer flushes
the parent or tracks owner disposal during that wait; its fork creation
serializes child events without the read-side validation and reports
publication failures through the shared wrapper.
* refactor(session-query): report the persisted prefix length on live observations
A live observation reports its event count as the persisted prefix, so the
fork command's boundary fallback only covers observations from other
producers.
* test(session): exclude the SQLite POSIX lease from Windows coverage
The SQLite copy of the session write lease executes its POSIX face only off
Windows, matching the JSONL exclusion.
* test(session): report legacy opener failures on stderr
The two-process suite asserts only the error name; the message and cause now
reach the inherited stderr so a CI failure identifies the SQLite error.
* refactor(agent): keep seed as the constructor input and narrow the fork source
CreateAgentOptions.seed stays the only constructor history; source names the
parent and cut a seeded fork shares. The factory stores the constructed log
with that source at creation, so no fork-only seed selection remains in the
loop.
* test(session): complete fork regressions and documentation
* test(session): propagate current SQLite fixtures through fork regressions
* test(session): describe fork creation from the caller's history
The fork source now carries the complete child history and the factory no
longer reopens or flushes the parent, so the fake factories, source
expectations, and cancellation cases follow that flow: a sharing backend
drains the parent writer itself, JSONL copies the supplied history, and
observations always report the persisted prefix. Documentation, the upgrade
guide, and the generated catalogs describe the same behavior.
* test(session): cover fork creation without a factory flush
The in-process fork provider's cases no longer wait for a parent flush: the
live log supplies the completed prefix and cancellation is exercised while
child storage is pending. The Remote fork command's boundary fallback is
covered by an observation that omits its persisted count.
* test(session): drop redundant observation assertions in the fork fallback case
* test(session): describe fork creation with seed beside a parent source
The agent factory keeps seed as the constructor history and source names
only the parent and cut, so the fakes, source expectations, and documentation
follow that split; the case where a live parent replaced the supplied prefix
no longer applies.
* refactor(session): name the fork parent option parentSource
`CreateAgentOptions.source` and `SessionPersistenceCreateOptions.source`
become `parentSource`: the field names the parent Session a seeded fork
shares its prefix with, and the shorter name read as a generic origin.
* refactor(session-query): report persistedEventCount on cold observations only
A live observation holds the Session's own events, none of them read-time
repairs, so its stored prefix is its whole log and the field said nothing;
only a cold read appends interrupted-turn closers in memory and needs to
tell the fork cut where the stored prefix ends.
- document the exported SqliteStore prefix/suffix loaders (verify-export-jsdoc)
- share createStoredEventRead from session-persistence so the standalone
SQLite store stops duplicating the service helper (duplication gate)
- route replaceStored header upserts through writeRow (duplication gate)
- move replacement/conflict test SQL into closed test resources so the
SQLite SQL resource boundary test passes
Old runtimes meeting a newer session format now fail loud instead of
misreading: version refusal names the direction (newer: upgrade the
harness; older: no upgrade path) and points at the raw JSONL log, and an
event type outside the generated known vocabulary refuses resume unless
its envelope carries the new ignorable: true marker (default: required,
so a forgotten marker over-refuses instead of silently resuming a gutted
session). gen-persistence-catalog now also emits
KNOWN_SESSION_EVENT_TYPES; SQLite stores the marker in a dedicated
column (SCHEMA_VERSION 15). The versioning design (monotonic integer,
n->n+1 upgrader chain, migrate-on-continue) is recorded in the
session-log-version-mechanism Agent Note.
Machine-produced by `pnpm run rescope-vendor --apply` plus the regeneration it
prints: `pnpm install` for the lockfile, `pnpm run gen-third-party-notices`,
`verify-translation-pairing --write` for the touched bilingual pairs,
`gen-doc-graphs`, and one typert snapshot whose ids embed character offsets.
`pnpm run rescope-vendor --check` verifies the result.
Renames nine vendored packages (cordis, cosmokit, schemastery and the six
@cordisjs plugins) and every reference that resolves them: manifest names and
dependency keys, module specifiers including declare-module merges, cordis.yml
plugin names, tsconfig paths, every Markdown fence, and `docs/` prose.
Directory names, upstream versions, and dependency ranges are unchanged, so
vendor/README.md still reads as an upstream snapshot; its manifest table gains
an upstream-name column so THIRD_PARTY_NOTICES keeps MIT attribution pointed
at each fork's origin.
The tutorial tier follows the rename end to end: its yaml fences named plugins
the Loader can no longer resolve, its `ts ignore-check` fences disagreed with
the compiled fences beside them, and its prose quoted both. The contracts that
told readers to keep upstream names — the root convention and the vendoring
cookbook's tree comment and manifest invariant — now say to rescope instead.
Two rules read `@deepseek-ai/` as "another workspace plugin": the client bundle
purity gate now names the vendored libraries a browser bundle inlines, and the
files where a bare `cordis` is an agent-preset id keep that product data.
git mv the 12 packages from session-persistence/, session-projection/,
session-title/, and telemetry/ into one session/ group per the
regrouping RFC; merge the four group READMEs into one bilingual
triplet; rewrite the group segment in tsconfig references (intra-group
references shorten to ../<pkg>), tsconfig.base.json paths/globs,
knip.json keys, vitest include, gate scripts, and authored doc/note
citations; regenerate module graph, doc graphs, catalogs, and the
lockfile importer keys. No npm names change.
Full unit suite: 8779 passed; the 18 reported failures reproduce as
env flakes (ambient-proxy IPv6 tunneling, watched-dir inotify
timeouts under parallel load) — each passes in isolation with
NO_PROXY set, matching their known pre-existing behavior on master.