Skip to content

Commit df905a6

Browse files
steipeteampagent
andauthored
fix(sessions): preserve shared history across startup and repairs (#127241)
* fix(doctor): atomically repair session transcripts * fix(sessions): keep runtime reads and repairs on SQLite owners Resolve physical session databases once and carry that identity through startup, search, boards, maintenance, and Doctor. Remove automatic legacy JSON import from Gateway startup while preserving explicit Doctor upgrades. Publish repaired legacy transcripts with strict atomic replacement and preserve the source when backup, write, or rename fails. * fix(sessions): simplify startup ownership and diagnostics * test(sessions): migrate legacy history through Doctor in CLI proof --------- Co-authored-by: Amp <[email protected]>
1 parent 849e35c commit df905a6

75 files changed

Lines changed: 3132 additions & 2698 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎config/assertion-safety-baseline.txt‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3007,7 +3007,6 @@ src/gateway/server-startup-config-helpers.ts 1
30073007
src/gateway/server-startup-config.ts 1
30083008
src/gateway/server-startup-finish.ts 1
30093009
src/gateway/server-startup-post-attach.ts 1
3010-
src/gateway/server-startup-session-migration.ts 1
30113010
src/gateway/server-worker-placement-startup.ts 2
30123011
src/gateway/server.auth.control-ui.bootstrap-lifecycle.suite.ts 8
30133012
src/gateway/server.auth.control-ui.device-token.suite.ts 2

‎docs/cli/doctor.md‎

Lines changed: 50 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ Doctor has five postures:
3434
| Repair | `openclaw doctor --fix` | Applies supported repairs, using prompts unless non-interactive repair is safe. |
3535
| Lint | `openclaw doctor --lint [--json]` | Read-only findings with threshold-based exit codes for CI gates. |
3636
| Shared SQLite maintenance | `openclaw doctor --state-sqlite compact` | Explicitly checkpoints, compacts, and verifies the canonical shared state DB. |
37-
| Session SQLite migration | `openclaw doctor --session-sqlite <mode>` | Inspects, imports, validates, compacts, recovers, or restores session state. |
37+
| Session SQLite tools | `openclaw doctor --session-sqlite <mode>` | Inspects or maintains SQLite sessions and explicitly imports legacy history. |
3838

3939
Use `openclaw doctor --json` when an operator or script wants the advisory Doctor report as JSON. It exits successfully after producing a report; inspect `ok` and `findings` for health state. Use explicit `openclaw doctor --lint --json` when CI should exit nonzero for findings at the selected severity threshold. Prefer `--fix` when a human operator wants Doctor to edit config or state.
4040

@@ -96,8 +96,8 @@ openclaw channels status --probe
9696
| `--lint` | Run modernized health checks in read-only mode and emit diagnostic findings. |
9797
| `--post-upgrade` | Run post-upgrade plugin compatibility probes; findings go to stdout; exit code 1 if any error-level finding is present. |
9898
| `--state-sqlite <mode>` | Run explicit shared state SQLite maintenance. The only mode is `compact`. |
99-
| `--session-sqlite <mode>` | Run the targeted session SQLite migration mode: `inspect`, `dry-run`, `import`, `validate`, `compact`, `recover`, or `restore`. |
100-
| `--session-sqlite-store <path>` | With `--session-sqlite`: select one legacy `sessions.json` store path. |
99+
| `--session-sqlite <mode>` | Run targeted session SQLite maintenance or legacy import: `inspect`, `dry-run`, `import`, `validate`, `compact`, `recover`, or `restore`. |
100+
| `--session-sqlite-store <path>` | With `--session-sqlite`: select a SQLite database or legacy `sessions.json` source, subject to the mode's selection rules below. |
101101
| `--session-sqlite-agent <id>` | With `--session-sqlite`: select one configured agent. |
102102
| `--session-sqlite-all-agents` | With `--session-sqlite`: select configured and discovered agent stores. |
103103
| `--github-issue` | With `--session-sqlite recover`: prepare a sanitized openclaw/openclaw issue report; doctor creates it with `gh` after `--yes` or interactive confirmation. |
@@ -289,16 +289,19 @@ compatible backup or upgrade OpenClaw for a newer schema.
289289

290290
## Session SQLite migration
291291

292-
OpenClaw imports legacy session rows and transcript history into each agent's
293-
SQLite database automatically during gateway startup and during
294-
`openclaw doctor --fix`. `openclaw doctor --session-sqlite <mode>` is the
295-
targeted inspection and validation tool for that migration. Current runtime
296-
session rows live in
297-
`~/.openclaw/agents/<agentId>/agent/openclaw-agent.sqlite`. Legacy
298-
`sessions.json` files are migration sources. Hot transcript JSONL files are
299-
imported and archived out of the active sessions directory after successful
300-
import; archive-tier JSONL files remain support artifacts, not runtime
301-
fallbacks.
292+
Runtime session rows and transcripts live in SQLite, by default at
293+
`~/.openclaw/agents/<agentId>/agent/openclaw-agent.sqlite`. Gateway and local
294+
CLI startup do not import, restore, or rewrite legacy session JSON/JSONL files.
295+
When startup finds a legacy session store, it refuses readiness and prints a
296+
`doctor --fix` command for the active profile instead of serving empty history.
297+
298+
To upgrade history from an older file-backed installation, stop the Gateway,
299+
back up its state, and run `openclaw doctor --fix` before restarting it.
300+
`openclaw doctor --session-sqlite <mode>` provides targeted inspection,
301+
import, validation, and SQLite maintenance. Legacy `sessions.json` files are
302+
migration sources. Hot transcript JSONL files are imported and archived after
303+
successful import; archive-tier JSONL files remain support artifacts, not
304+
runtime fallbacks.
302305

303306
The import stages transcript payloads in a private, temporary SQLite database
304307
instead of retaining complete batches of histories in memory. Keep free space
@@ -323,7 +326,7 @@ Modes:
323326

324327
| Mode | Behavior |
325328
| ---------- | ---------------------------------------------------------------------------------------------------------------------- |
326-
| `inspect` | Read legacy and SQLite counts, plus unreferenced JSONL files, without importing. |
329+
| `inspect` | Read SQLite counts and any selected legacy-source diagnostics without importing; legacy files are not required. |
327330
| `dry-run` | Parse legacy entries and transcript JSONL files, count importable rows, and report issues without writing SQLite rows. |
328331
| `import` | Import legacy entries and transcript events into SQLite for the selected targets. |
329332
| `validate` | Compare the selected legacy sources against SQLite rows and transcript event counts. |
@@ -333,34 +336,44 @@ Modes:
333336

334337
Selectors:
335338

336-
- Default: the configured default agent store, when that legacy store file exists.
339+
- Default: the configured default agent store; SQLite inspection does not require a legacy file.
337340
- `--session-sqlite-agent <id>`: one configured agent.
338341
- `--session-sqlite-all-agents`: configured agent stores plus discovered agent stores.
339-
- `--session-sqlite-store <path>`: one explicit legacy `sessions.json` path.
342+
- `--session-sqlite-store <path>`: one explicit `.sqlite` database or legacy `sessions.json` path.
343+
344+
`dry-run`, `import`, and `validate` select existing legacy sources only. An
345+
explicit `.sqlite` path selects no legacy targets in those modes; it is never
346+
parsed or archived as JSON. Use `inspect`, `compact`, or corruption recovery
347+
with `recover` for a SQLite target. Recovering or restoring archived sources
348+
from migration manifests requires the original legacy selector or agent-store
349+
discovery that includes it. Legacy `sessions.json` selector paths remain
350+
supported and resolve to their corresponding SQLite stores for maintenance.
340351

341-
Manual inspection sequence:
352+
With the Gateway stopped and its state backed up, inspect and import legacy
353+
history:
342354

343355
```bash
344356
openclaw doctor --session-sqlite inspect --session-sqlite-all-agents
345357
openclaw doctor --session-sqlite dry-run --session-sqlite-all-agents --json
346358
openclaw doctor --session-sqlite import --session-sqlite-all-agents
347-
openclaw doctor --session-sqlite validate --session-sqlite-all-agents --json
348-
openclaw doctor --session-sqlite compact --session-sqlite-all-agents
349-
openclaw doctor --session-sqlite recover --github-issue
359+
openclaw doctor --session-sqlite inspect --session-sqlite-all-agents --json
350360
```
351361

352-
Back up the OpenClaw state directory before running `import` on an install with
353-
important history. `validate` exits non-zero when a selected legacy entry is
354-
missing from SQLite, a session id differs, or a transcript event count differs.
362+
`import` validates rows and transcript event counts before archiving its
363+
legacy sources. After a successful import, `validate` may select no legacy
364+
targets; use `inspect` to see the current SQLite state. While legacy sources
365+
remain, `validate` exits non-zero when a selected entry is missing from SQLite,
366+
a session id differs, or a transcript event count differs.
355367
When using `--session-sqlite-store <path>`, check that the report contains the
356-
expected target count; a nonexistent explicit store path selects no targets.
368+
expected target count; a nonexistent legacy source selects no targets for
369+
`dry-run`, `import`, or `validate`.
357370

358371
SQLite deletes reclaim pages inside the database first; they do not necessarily
359372
shrink the database file immediately. After deleting or archiving large
360373
transcripts, run `openclaw doctor --session-sqlite compact --session-sqlite-all-agents`
361374
to checkpoint WAL files, run `VACUUM`, and report before/after database and WAL
362-
sizes. Compaction requires a regular file with the current agent schema, the
363-
selected agent's durable owner metadata, and no open handle in the doctor
375+
sizes. Compaction requires a regular file with the current agent schema, its
376+
durable database owner metadata, and no open handle in the doctor
364377
process. The destructive `import`, `compact`, `recover`, and `restore` modes
365378
hold the same state ownership lock as Gateway startup for their full operation;
366379
`inspect`, `dry-run`, and `validate` remain read-only and do not take it. Stop
@@ -374,8 +387,8 @@ checks cover SQLite WAL, shared-memory, and rollback-journal sidecars.
374387

375388
Each import writes a manifest under
376389
`~/.openclaw/session-sqlite-migration-runs/` before moving transcript artifacts
377-
into the archive. If startup reports a failed session SQLite migration after
378-
artifacts moved, run recovery:
390+
into the archive. If an explicit import fails after artifacts moved, keep the
391+
Gateway stopped and run recovery:
379392

380393
```bash
381394
openclaw doctor --session-sqlite recover --github-issue
@@ -385,13 +398,16 @@ Recovery selects the latest failed migration manifest, restores only the
385398
manifest's archived artifacts, validates the affected targets, refreshes the
386399
sanitized `.failure.md` and `.failure.json` reports, and prepares a GitHub issue
387400
body that avoids transcript contents, raw environment, secrets, and unbounded
388-
config. When no failed migration manifest exists but a selected agent SQLite
389-
database is corrupt, not a database, or has journal sidecars without a main
390-
database, recovery copies the complete file set to a temporary inspection
391-
directory. SQLite can roll back a valid hot journal in that disposable copy
401+
config. When no failed migration manifest exists, recovery inspects selected
402+
SQLite databases using temporary copies of their complete file sets. SQLite
403+
can roll back a valid hot journal in that disposable copy
392404
before `quick_check`, `integrity_check`, and `foreign_key_check` run, while the
393-
original forensic files remain untouched. Failed integrity checks or orphaned
394-
sidecars preserve the DB, WAL, SHM, and rollback-journal files by renaming the
405+
original forensic files remain untouched during inspection. Recovery attempts
406+
to repair canonical index corruption in place after schema and owner validation.
407+
Schema, owner, and I/O errors, as well as failed or refused index repairs,
408+
leave the original database in place with a diagnostic. Other confirmed
409+
corruption or orphaned sidecars
410+
preserve the DB, WAL, SHM, and rollback-journal files by renaming the
395411
whole discovered set with one `.corrupt-<timestamp>` suffix. A caught rename
396412
failure rolls already-moved files back before reporting failure, so a
397413
recoverable file set is not silently split. Stop the Gateway before recovery;

‎docs/concepts/session.md‎

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -198,7 +198,7 @@ to start a replacement session.
198198

199199
## Where state lives
200200

201-
- **Runtime session rows:** `~/.openclaw/agents/<agentId>/agent/openclaw-agent.sqlite`
201+
- **Runtime session rows and transcripts:** `~/.openclaw/agents/<agentId>/agent/openclaw-agent.sqlite` by default
202202
- **Archived transcript files:** `~/.openclaw/agents/<agentId>/sessions/`
203203
- **Legacy row migration source:** `~/.openclaw/agents/<agentId>/sessions/sessions.json`
204204

@@ -210,15 +210,18 @@ timestamps:
210210
- `updatedAt`: last store-row mutation; useful for listing and pruning, but not
211211
authoritative for daily/idle reset freshness.
212212

213-
During migration from older installs, gateway startup and `openclaw doctor
214-
--fix` import legacy `sessions.json` rows and hot transcript JSONL history into
215-
SQLite automatically. Rows without `sessionStartedAt` are resolved from the
213+
To import legacy `sessions.json` rows and hot transcript JSONL history from an
214+
older installation, stop the Gateway, back up its state, and run
215+
`openclaw doctor --fix` before restarting it. Gateway and local CLI startup use
216+
SQLite without importing, restoring, or rewriting legacy session files.
217+
If startup finds a legacy store, it refuses readiness and prints the Doctor
218+
command for the active profile instead of silently starting with empty history.
219+
During Doctor import, rows without `sessionStartedAt` are resolved from the
216220
legacy transcript JSONL session header when available. If an older row also
217221
lacks `lastInteractionAt`, idle freshness falls back to that session start time,
218222
not to later bookkeeping writes. Use `openclaw doctor --session-sqlite inspect
219223
--session-sqlite-all-agents` and the [Doctor migration
220-
sequence](/cli/doctor#session-sqlite-migration) when you want explicit
221-
inspection or validation evidence.
224+
sequence](/cli/doctor#session-sqlite-migration) for inspection and validation.
222225

223226
## Session maintenance
224227

0 commit comments

Comments
 (0)