Skip to content

feat: keep reset session history searchable#111194

Merged
steipete merged 3 commits into
mainfrom
claude/sessions-keep-history
Jul 19, 2026
Merged

feat: keep reset session history searchable#111194
steipete merged 3 commits into
mainfrom
claude/sessions-keep-history

Conversation

@steipete

@steipete steipete commented Jul 19, 2026

Copy link
Copy Markdown
Contributor

What Problem This Solves

/reset and /new previously destroyed the old conversation: rows were archived to a compressed file and deleted from SQLite, so past sessions disappeared from search and history. For a personal agent, sessions should be forever — the natural boundary is compaction, and old history should only be reclaimed under explicit deletion or disk pressure.

Why This Change Was Made

Follows the Codex philosophy (no scheduled resets; compaction is the boundary; extract/compress under pressure, never silently discard) adopted for OpenClaw's personal-agent architecture, building on #111140 (no automatic session resets by default). No DDL, no schema-version change, no new config: existing session.maintenance keys (maxDiskBytes 10gb default, highWaterBytes 80%) bound retained history physically.

User Impact

  • Reset keeps history: the live sessionKey -> sessionId mapping advances; previous generations' session, transcript, trajectory, and search rows stay in SQLite and remain searchable under the same key. Entry/session lists show only the live mapping.
  • Explicit deletion removes everything: every retained generation is archived (verified compressed export, one generation at a time — bounded memory) and then removed, with admission fencing (in-flight work aborts the deletion cleanly; retry completes it) and per-commit event publication.
  • Disk budget enforces physically: SQLite main + WAL + counted session files; over maxDiskBytes, enforcement checkpoints, prunes oldest archives, then extracts-and-evicts oldest unreferenced historical generations to highWaterBytes. Passes are serialized per store; entry writes/reset/delete kick a throttled (reset/delete: forced) background pass.

Consciously accepted tradeoffs (in-code comments pin each):

  • Under extreme pressure the hard cap wins: the pass may prune an archive it just extracted (oldest-first order; preferred over evicting additional sessions' rows).
  • Trajectory-only sessions are reclaimed without an archive artifact (diagnostic telemetry; no fake empty transcript archives).
  • Finite resetArchiveRetention continues to age archive artifacts only. Age-based expiry of retained rows needs a durable retirement timestamp (additive sessions column) — deliberately excluded; follow-up needs a schema decision.

Evidence

  • 125 focused tests green across session-history-eviction, store.session-lifecycle-mutation, store.pruning(.integration), disk-budget, lifecycle suites; pnpm tsgo:core clean; git diff --check clean.
  • 13 adversarial autoreview rounds (gpt-5.6-sol, xhigh); every accepted finding fixed in-branch: incremental per-generation deletion, path/admission fencing (preflight + authoritative in-transaction recheck), serialized enforcement passes, candidate-aware preview wouldMutate, checkpoint-delta reporting, budget-priority archive pruning, forced kicks after reset/delete with pending-force coalescing, migration-archive exclusion regression test.
  • Docs updated: docs/concepts/main-session.md, docs/reference/session-management-compaction.md.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation size: XL maintainer Maintainer-authored PR labels Jul 19, 2026
@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. labels Jul 19, 2026
@clawsweeper

clawsweeper Bot commented Jul 19, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge. Reviewed July 19, 2026, 6:33 AM ET / 10:33 UTC.

Summary
The branch keeps prior SQLite session generations searchable after /reset or /new, and introduces physical disk-budget enforcement that archives and evicts unreferenced historical generations.

PR surface: Source +454, Tests +559, Docs +2. Total +1015 across 27 files.

Reproducibility: not applicable. This PR proposes a new reset-history retention model rather than reporting a standalone current-main bug. Its intended behavior is nevertheless source-testable through reset, search, and physical-budget scenarios.

Review metrics: 1 noteworthy metric.

  • Retention control behavior: 1 existing retention setting narrowed. resetArchiveRetention continues to age archive files but no longer supplies a finite retirement path for searchable reset history retained in SQLite.

Stored data model
Persistent data-model change detected: migration/backfill/repair: src/config/sessions/disk-budget.test.ts, serialized state: src/config/sessions/artifacts.ts, serialized state: src/config/sessions/cleanup-service.ts, serialized state: src/config/sessions/disk-budget.test.ts, serialized state: src/config/sessions/disk-budget.ts, serialized state: src/config/sessions/session-accessor.conformance.test.ts, and 23 more. Confirm migration or upgrade compatibility proof before merge.

Merge readiness
Overall: 🧂 unranked krab
Proof: 🧂 unranked krab
Patch quality: 🦪 silver shellfish
Result: blocked until real behavior proof from a real setup is added.

Overall follows the weaker of proof and patch quality, so missing proof can cap an otherwise strong patch.

Rank-up moves:

  • Move disk-budget scheduling to every transcript post-commit path, including synchronous writes.
  • [P1] Obtain an owner decision and implement the chosen finite-retention upgrade contract.
  • [P1] Add redacted live proof of reset search retention and disk-pressure extraction/reclamation.

Proof guidance:

  • [P1] Needs real behavior proof before merge: The PR body reports unit/integration suites and static checks, but contains no inspected redacted live run proving searchable reset history and pressure-triggered archive/reclamation; add terminal output, logs, or a recording and update the PR body for re-review.

Risk before merge

  • [P1] A finite existing resetArchiveRetention setting can cease to bound reset-generated history after upgrade, particularly when maxDiskBytes is disabled.
  • [P1] Synchronous transcript commits can leave physical SQLite or WAL usage above maxDiskBytes until an unrelated asynchronous mutation, reset, deletion, or manual cleanup occurs.
  • [P1] The branch has no inspected real-runtime proof for searchable retained history and pressure-triggered reclamation.

Maintainer options:

  1. Preserve configured retention semantics (recommended)
    Before merge, make finite reset-retention settings continue to govern retained reset generations through an owner-approved durable retirement design.
  2. Accept disk-only retention intentionally
    A maintainer may approve the changed contract that existing finite archive retention no longer bounds SQLite reset history, provided the upgrade behavior is made explicit.
  3. Pause the branch for a narrower design
    Close or defer this retention-model change if the required stored-data policy and migration direction are not ready for approval.

Next step before merge

  • [P1] A maintainer must choose the retention-policy and stored-data direction; the contributor must also provide real runtime proof after the two mechanical blockers are addressed.

Maintainer decision needed

  • Question: Should a configured finite session.maintenance.resetArchiveRetention continue to retire reset-generated history after this PR moves that history from archive files into SQLite rows?
  • Rationale: The branch intentionally changes an existing retention control from a practical bound on reset artifacts to an archive-only setting, while implementing finite SQLite-history age retention would require an explicit stored-data and migration design decision.
  • Likely owner: steipete — They authored the related merged reset-policy change and the proposed retention-policy extension.
  • Options:
    • Preserve finite reset retention (recommended): Define and implement a durable retirement path for retained reset generations so existing finite retention intent continues to bound history after upgrade.
    • Adopt disk-only history retention: Explicitly approve the compatibility change that retained reset history is governed only by physical disk budget, including when prior operators configured finite archive retention.
    • Pause the retention-policy change: Keep current reset archiving behavior until a separately approved SQLite retention and migration design is ready.

Security
Cleared: No dependency, workflow, permission, artifact-download, or new code-execution surface is introduced by the supplied session-storage diff.

Review findings

  • [P1] Preserve finite reset-retention semantics — src/config/sessions/session-accessor.sqlite-lifecycle.ts:146
  • [P1] Kick budget enforcement after every transcript commit — src/config/sessions/session-accessor.sqlite-entry.ts:304-309
Review details

Best possible solution:

Preserve an explicit operator-controlled retention contract for reset-generated SQLite history, move physical-budget scheduling to a shared post-transcript-commit seam, and prove reset search plus disk-pressure reclamation with redacted live output before merge.

Do we have a high-confidence way to reproduce the issue?

Not applicable: this PR proposes a new reset-history retention model rather than reporting a standalone current-main bug. Its intended behavior is nevertheless source-testable through reset, search, and physical-budget scenarios.

Is this the best way to solve the issue?

No, not as written. A common post-transcript-commit enforcement seam and an owner-approved retention contract for existing finite settings are safer than the current asynchronous-hook and disk-only approach.

Full review comments:

  • [P1] Preserve finite reset-retention semantics — src/config/sessions/session-accessor.sqlite-lifecycle.ts:146
    A user with finite resetArchiveRetention and maxDiskBytes: false previously had reset archives age out; this reset path now leaves its historical SQLite rows indefinitely because no reset archive is created. Preserve a finite retirement path for retained generations, or obtain explicit maintainer approval for this compatibility change and its stored-data design.
    Confidence: 0.9
  • [P1] Kick budget enforcement after every transcript commit — src/config/sessions/session-accessor.sqlite-entry.ts:304-309
    These new hooks cover asynchronous entry patches only. The synchronous transcript commit path identified in the previous review can grow the SQLite file or WAL past maxDiskBytes without scheduling this pass, leaving the physical limit unenforced until an unrelated lifecycle mutation. Put the kick on a shared post-transcript-commit seam or cover the synchronous writer too.
    Confidence: 0.94

Overall correctness: patch is incorrect
Overall confidence: 0.88

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against b9c9140034d7.

Label changes

Label changes:

  • add rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🦪 silver shellfish.
  • remove rating: 🦪 silver shellfish: Current PR rating is rating: 🧂 unranked krab, so this older rating label is no longer current.

Label justifications:

  • P2: This is a meaningful session-retention feature with bounded but real upgrade and storage-policy impact, rather than an immediate outage.
  • merge-risk: 🚨 compatibility: The branch changes the effective upgrade behavior of existing reset-retention and disk-budget settings.
  • merge-risk: 🚨 session-state: The branch changes when historical session transcripts and trajectories are retained or reclaimed.
  • rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🦪 silver shellfish.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask. Needs real behavior proof before merge: The PR body reports unit/integration suites and static checks, but contains no inspected redacted live run proving searchable reset history and pressure-triggered archive/reclamation; add terminal output, logs, or a recording and update the PR body for re-review.
Evidence reviewed

PR surface:

Source +454, Tests +559, Docs +2. Total +1015 across 27 files.

View PR surface stats
Area Files Added Removed Net
Source 14 834 380 +454
Tests 10 647 88 +559
Docs 3 16 14 +2
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 27 1497 482 +1015

What I checked:

  • Existing setting semantics change: The PR body and updated session-management documentation state that resetArchiveRetention only ages archive artifacts while reset history now remains in SQLite; with maxDiskBytes: false, a user who configured finite reset retention has no remaining retirement path for reset-generated history. (src/config/sessions/session-accessor.sqlite-lifecycle.ts:146, 568ce44eba27)
  • Incomplete physical-budget trigger: The changed asynchronous entry-patch functions schedule the background budget pass, but the prior review identified a synchronous transcript-commit path through replaceSessionEntrySync that can grow the SQLite database or WAL without scheduling enforcement. The supplied latest file list does not include that writer path. (src/config/sessions/session-accessor.sqlite-entry.ts:304, 568ce44eba27)
  • Prior review continuity: The prior completed review cycle already raised the missing synchronous-transcript enforcement concern; the latest head still routes the new kick through asynchronous entry-patch functions rather than the common transcript post-commit seam. (src/config/sessions/session-accessor.sqlite-entry.ts:304, 340da9fbd988)
  • Related main-history provenance: The related reset-policy work was merged into current main as commit e23dde3de550753bbd09cb19979602ee03b24cf9, making its author a relevant owner for the reset lifecycle contract that this PR changes. (src/config/sessions/session-accessor.sqlite-lifecycle.ts:146, e23dde3de550)
  • Proof status: The PR body reports focused tests, type checks, and diff checks, but provides no inspectable after-fix run showing both a reset history search and a disk-pressure archive/reclaim result. (568ce44eba27)

Likely related people:

  • steipete: The supplied related-item history shows this person authored the merged reset-default implementation that establishes the lifecycle contract this PR extends. (role: introduced related reset-policy behavior; confidence: medium; commits: e23dde3de550; files: src/config/sessions/session-accessor.sqlite-lifecycle.ts, src/config/sessions/store-maintenance.ts)
What the crustacean ranks mean
  • 🦀 challenger crab: rare, exceptional readiness with strong proof, clean implementation, and convincing validation.
  • 🦞 diamond lobster: very strong readiness with only minor maintainer review expected.
  • 🐚 platinum hermit: good normal PR, likely mergeable with ordinary maintainer review.
  • 🦐 gold shrimp: useful signal, but proof or patch confidence is still limited.
  • 🦪 silver shellfish: thin signal; proof, validation, or implementation needs work.
  • 🧂 unranked krab: not merge-ready because proof is missing/unusable or there are serious correctness or safety concerns.
  • 🌊 off-meta tidepool: rating does not apply to this item.

Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

How this review workflow works
  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.
Review history (3 earlier review cycles)
  • reviewed 2026-07-19T04:19:12.134Z sha d5be1f5 :: needs real behavior proof before merge. :: [P1] Serialize archive pruning with lifecycle deletion | [P1] Restore physical budget enforcement during normal maintenance | [P2] Re-prune archives between SQLite eviction victims | [P2] Report checkpoint-only physical cleanup mutations
  • reviewed 2026-07-19T09:34:34.296Z sha 7e847b8 :: needs real behavior proof before merge. :: [P1] Prune every archive type counted by the budget | [P1] Schedule enforcement after synchronous transcript commits
  • reviewed 2026-07-19T09:41:14.200Z sha 340da9f :: needs real behavior proof before merge. :: [P1] Prune every archive type included in physical usage | [P1] Schedule enforcement after synchronous transcript commits

@steipete
steipete marked this pull request as ready for review July 19, 2026 09:27
@steipete
steipete force-pushed the claude/sessions-keep-history branch from c43fddc to 7e847b8 Compare July 19, 2026 09:30

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: c43fddcffc

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +322 to +324
const files = (await readSessionsDirFiles(path.dirname(params.storePath)))
.filter((file) => isRetainedSessionTranscriptArchiveName(file.name))
.toSorted((left, right) => left.mtimeMs - right.mtimeMs);

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.

P1 Badge Prune all archive types counted by the budget

When an upgraded store contains legacy *.jsonl.bak.* or sessions.json.bak.* archives, physical measurement counts those files, but this filter only permits reset and deleted archives to be removed. Enforcement can therefore evict searchable SQLite generations while leaving the older backup artifacts untouched, and may still finish above highWaterBytes; include every removable archive recognized by isSessionArchiveArtifactName, or exclude unsupported archive types from the measured total.

Useful? React with 👍 / 👎.

Comment on lines +305 to +309
kickSessionHistoryDiskBudgetMaintenance({
...(resolved.agentId ? { agentId: resolved.agentId } : {}),
storePath: resolveSessionStorePathForScope(scope),
...(options.maintenanceConfig ? { maintenanceConfig: options.maintenanceConfig } : {}),
});

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.

P2 Badge Schedule budget checks from every transcript write path

When transcript growth is committed through a synchronous writer, this async-entry-only hook never runs; for example, gateway/worker-environments/transcript-commit.ts:381 appends transcript data and calls replaceSessionEntrySync, which has no budget kick. If retained history is initially below the cap and worker commits later push the database or WAL over maxDiskBytes, it remains over budget until an unrelated reset, delete, async patch, or manual cleanup occurs, so the throttled check needs to live in a common transcript/post-commit seam or cover the sync writer too.

Useful? React with 👍 / 👎.

@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. labels Jul 19, 2026
@steipete
steipete force-pushed the claude/sessions-keep-history branch from 7e847b8 to 340da9f Compare July 19, 2026 09:38

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 340da9fbd9

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

}
}
const historicalArchivedTranscripts: SessionLifecycleArchivedTranscript[] = [];
for (const sessionId of historicalGenerationIds) {

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.

P1 Badge Validate delete guards before removing retained generations

When a guarded delete arrives with a stale expectedEntry, expectedSessionId, lifecycle revision, or timestamp, this loop archives and commits deletion of every retained generation before shouldDeleteSqliteSessionEntryLifecycle evaluates those guards in the final transaction. The call then returns deleted: false and preserves the live entry, but its reset history has already been removed from SQLite; validate the current entry against all requested guards before starting historical reclamation.

Useful? React with 👍 / 👎.

export async function measureSessionPhysicalDiskUsage(
storePath: string,
): Promise<SessionPhysicalDiskUsage> {
const sessionsDirFiles = await readSessionsDirFiles(path.dirname(storePath));

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.

P1 Badge Scope physical-budget files to the target store

When supported custom session.store targets share a directory, such as {agentId}.json, this directory-wide scan counts sibling SQLite/WAL files and unrelated files toward the current store's budget; archive pruning later scans the same shared directory. A large sibling store can therefore trigger enforcement for a small store, prune archives belonging to either store, and evict all history from the small store without relieving the actual source of pressure. Count and prune only artifacts owned by the resolved SQLite target/store.

Useful? React with 👍 / 👎.

@steipete
steipete force-pushed the claude/sessions-keep-history branch from 340da9f to a4d21b6 Compare July 19, 2026 10:15
@openclaw-barnacle openclaw-barnacle Bot added the gateway Gateway runtime label Jul 19, 2026
@steipete
steipete force-pushed the claude/sessions-keep-history branch from a4d21b6 to a7abdc7 Compare July 19, 2026 10:21
@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. labels Jul 19, 2026
@steipete
steipete force-pushed the claude/sessions-keep-history branch from a7abdc7 to b033563 Compare July 19, 2026 10:27
@steipete
steipete force-pushed the claude/sessions-keep-history branch from b033563 to 568ce44 Compare July 19, 2026 10:31
@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. labels Jul 19, 2026
@steipete
steipete merged commit ef91ce5 into main Jul 19, 2026
128 of 130 checks passed
@steipete
steipete deleted the claude/sessions-keep-history branch July 19, 2026 10:38
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Jul 20, 2026
* feat(sessions): retain reset history in sqlite with physical disk budget

* fix(sessions): satisfy test-types, knip export scan, and docs map

* fix(sessions): align behavioral suites and flip proof with retained history, route-aware cleanup plans
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

docs Improvements or additions to documentation gateway Gateway runtime maintainer Maintainer-authored PR merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P2 Normal backlog priority with limited blast radius. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. size: XL status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant