Skip to content

fix(memory): rank indexed sessions by source activity - #139112

Merged
steipete merged 2 commits into
mainfrom
codex/deslop-memory-timestamps
Sep 5, 2026
Merged

steipete merged 2 commits into
mainfrom
codex/deslop-memory-timestamps

Conversation

@steipete

@steipete steipete commented Sep 5, 2026 •

Copy link
Copy Markdown
Contributor

Closes #139094

Additional instructions

MUST: Keep Allow edits from maintainers enabled for this PR so maintainers
can help update the branch when needed.

What Problem This Solves

Fixes an issue where users searching indexed conversations would receive stale or incorrectly ordered recall results. Session recency could be lost, vector fallback could limit results before sorting their final scores, and short CJK substring matches could select an older session despite having its indexed activity timestamp.

This affects Memory Core retrieval through memory_search, including keyword-only, lexical, hybrid and FTS-unavailable vector paths. The built-in manager already enables recency weighting with a 30-day half-life; there is no new operator toggle.

Why This Change Was Made

Ranking now reads existing indexed source activity instead of trying to reconstruct a workspace filename for logical SQLite-backed session paths. The existing ranking pipeline applies that activity before selection, shares lexical finalization, and uses one tie-break comparator across exact and ordinary hybrid results.

Recall-only LIKE matches retain zero public confidence: their private ranking signal receives recency, importance and project weighting without turning substring recall into a scored semantic match. Positive and negative weighted confidence, raw retrieval diagnostics, exact-path precedence and message provenance remain intact.

User Impact

Indexed conversations and retained archives receive the expected recency weighting. Limited result windows select the correct final-ranked match, and unrelated workspace files cannot supply a session timestamp. Extra-memory file mtime behavior, evergreen exemptions and provider availability requirements are preserved.

The change removes 10 production lines overall: 88 added, 98 removed. Tests add 217 net lines; documentation adds five. No schema, migration, index layout, retention, configuration, SDK, public result shape, stored representation or embedding transport changes are introduced.

Evidence

Three failures were reproduced before their respective repairs using actual SQLite/session owners:

  • Identical session content with source activity 15 days apart produced an old/fresh score ratio of 1, rather than sqrt(0.5) ≈ 0.70710678. Keyword-only, configured-provider lexical and hybrid search now produce the expected ratio while retaining the original message provenance timestamps. The fixture independently verifies persisted activity and the absence of any workspace transcript file.
  • A colliding view in the temporary database makes the actual FTS initializer report unavailable. Even with correct decayed scores, vector fallback previously returned the old session first. Sorting final scores before truncation now makes maxResults=1 select the fresh session. No private availability override or unsupported hybrid-disable setting is used.
  • A supported trigram query 记忆 uses LIKE retrieval for two identical session transcripts. The existing API-shaped embedding fixture returns a valid all-zero vector, so both results retain public score=0, vectorScore=0 and textScore=0. Before repair, their private lexical tie-break bypassed decay and selected sessions/main/a-old.jsonl; afterward the manager and real memory_search tool select sessions/main/z-fresh.jsonl, including a one-result window. This connected gap predates the PR; the confidence contract is intentionally preserved.

The expanded affected suite passed 80 tests across six files, covering the six-mode source-recency regression, actual archive lifecycle, workspace decoys, real tool execution, provenance, KNN/scan retrieval, exact-path/MMR ranking, cancellation, visibility and search-generation lifetimes. The existing LIKE helper fixture now covers absent, positive and negative vector confidence, including negative-score exclusion.

OPENCLAW_VITEST_MAX_WORKERS=2 node scripts/run-vitest.mjs \
  extensions/memory-core/src/memory/manager-temporal-ranking.test.ts \
  extensions/memory-core/src/memory/temporal-decay.test.ts \
  extensions/memory-core/src/memory/hybrid.test.ts \
  extensions/memory-core/src/memory/manager-search-provenance.test.ts \
  extensions/memory-core/src/memory/manager-search-orchestration.test.ts \
  extensions/memory-core/src/tools.real-manager.test.ts

The full changed-file check passed, including formatting, production/test typechecking and declaration containment, doctor contracts, plugin boundaries, lint, dependency/coercion/deprecation/dead-export guards, database-first storage checks and zero runtime import cycles. A final mechanical consolidation then shared the identical tie-break comparator; all 35 manager/hybrid tests and targeted type-aware lint passed again on that final source. git diff --check passed. The full gate is attributed to the immediately preceding comparator-equivalent snapshot, rather than claimed as a repeated final run.

OPENCLAW_VITEST_MAX_WORKERS=2 node scripts/check-changed.mjs -- \
  docs/concepts/memory-search.md \
  extensions/memory-core/src/memory/hybrid.test.ts \
  extensions/memory-core/src/memory/hybrid.ts \
  extensions/memory-core/src/memory/manager-keyword-retrieval.ts \
  extensions/memory-core/src/memory/manager-search-orchestration.ts \
  extensions/memory-core/src/memory/manager-temporal-ranking.test.ts \
  extensions/memory-core/src/memory/temporal-decay.test.ts \
  extensions/memory-core/src/memory/temporal-decay.ts \
  extensions/memory-core/src/tools.real-manager.test.ts

The source lookup runs under the search-generation lease, constrained to session results and retained candidate paths through one bound JSON set. Current caps allow at most 800 candidate references / 600 distinct paths, with at most one returned row per unique path/source. Memory-only results skip the lookup. No per-hit query or session-history enumeration is added.

For the ClawSweeper data-model proof request: no persistent transition is introduced, so a migration/format-transition test is inapplicable. The unchanged shipped schema already defines mtime REAL NOT NULL and UNIQUE(path, source); the existing writer and parameterized reader retain those representations. The regressions verify those stored values before search. No compatibility shim or schema workaround is needed.

Validation used a task-local frozen dependency install, Node 26.8.1 and pinned pnpm 12.3.4; lockfile supply-chain policies and applicable package lifecycle checks passed. Final staged autoreview is scoped-clean through P2, and the root/peer source challenges found no remaining semantic defect. CI run 33973263252 passed for committed head 685a9be80176f6a21193fcc1de36ead6b14a2e21 (79 successful jobs, 16 skipped). The separate direct read-only review initially raised an MMR P2, then withdrew it after source/history/documentation review: LIKE strength is a shipped tie-break rather than MMR confidence, equal confidence and similarity retain recency order at every selection round, and the proposed example changed diversity. The original report is preserved with that disposition; no accepted findings remain through P2, and no code or tests changed for the adjudication. Earlier green CI at 1852e6f predates the added LIKE repair and is not claimed as proof of this final candidate.

Proof boundary: deterministic local tests invoke the real tool and SQLite/session/archive owners with fixture embeddings. A booted Gateway/browser, live external embedding endpoint and remote installation were not exercised. Embedding transport and Gateway ingress are unchanged. Exact-head CI passed; native landing validation remains under maintainer ownership.

@clawsweeper

clawsweeper Bot commented Sep 5, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@steipete
steipete marked this pull request as ready for review September 5, 2026 13:21
@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation extensions: memory-core Extension: memory-core size: M maintainer Maintainer-authored PR labels Sep 5, 2026
@steipete
steipete marked this pull request as draft September 5, 2026 13:44
@steipete
steipete marked this pull request as ready for review September 5, 2026 13:50
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Sep 5, 2026
@clawsweeper

clawsweeper Bot commented Sep 5, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge. Reviewed September 5, 2026, 11:02 AM ET / 15:02 UTC.

ClawSweeper review

What this changes

Memory Core ranks indexed conversations by recorded source activity, preserves lexical fallback confidence, and orders vector fallback results before limiting them.

Merge readiness

⛔ Blocked before merge - 1 item remains

This remains a useful fix for behavior still broken on current main. No blocking patch defects found; the earlier migration concern does not apply because the patch reads existing index metadata without changing stored representations.

Priority: P2
Reviewed head: 685a9be80176f6a21193fcc1de36ead6b14a2e21

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused owner-boundary repair with meaningful regression coverage and no blocking correctness findings.
Proof confidence 🌊 off-meta tidepool Not applicable: The supplied maintainer classification exempts this PR from the external-contributor proof gate, and no authority change triggers an exception; captured validation exercises the tool and SQLite owners with fixture embeddings at an earlier candidate.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: The supplied maintainer classification exempts this PR from the external-contributor proof gate, and no authority change triggers an exception; captured validation exercises the tool and SQLite owners with fixture embeddings at an earlier candidate.
Evidence reviewed 11 items Current main still exhibits the reported mechanism: Current main resolves session timestamps as workspace files and retains vector retrieval order after modifying scores. Logical SQLite session paths therefore receive no timestamp when the workspace file is absent, and vector fallback slices without sorting final scores.
Canonical timestamp producer: The existing session reader uses supplied source activity for SQLite transcripts and filesystem modification time for retained archives. The existing index writer persists entry.mtimeMs into memory_index_sources.mtime; individual message provenance remains separate.
Existing bounded source reader reused: Keyword, hybrid, and vector fallback paths supply indexed session timestamps through the existing source reader. Its query filters by source and candidate paths using sqliteStringSet; memory-only results skip the lookup.
Findings None None.
Security None None.

How this fits together

Memory Core retrieves notes and indexed conversations for the memory_search tool. It combines keyword and semantic matches, applies ranking, and passes results through session visibility filtering before returning them to the agent.

flowchart LR
  A[Memory search query] --> B[Keyword and semantic retrieval]
  C[Indexed source activity] --> D[Recency and importance ranking]
  B --> D
  D --> E[Hybrid diversity and result selection]
  E --> F[Session visibility filtering]
  F --> G[Results returned to agent]
Loading

Before merge

  • Add data-model compatibility proof - Confirm migration or upgrade compatibility proof before merge.
Agent review details

Security

None.

PR surface

Source -10, Tests +217, Docs +5. Total +212 across 9 files.

View PR surface stats
Area Files Added Removed Net
Source 4 88 98 -10
Tests 4 286 69 +217
Docs 1 5 0 +5
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 9 379 167 +212

Review metrics

Metric Value Why it matters
Production versus test delta Production −10 net lines; tests +217 net lines; docs +5 The repair absorbs timestamp handling and ranking changes without production growth while expanding boundary regression coverage.
Storage and configuration contracts 0 schema changes, 0 migrations, 0 new settings Existing indexed timestamps supply the repair, resolving the previous migration concern.

Stored data model

Persistent data-model change detected: unknown-data-model-change: extensions/memory-core/src/memory/hybrid.ts, unknown-data-model-change: extensions/memory-core/src/memory/manager-search-orchestration.ts, unknown-data-model-change: extensions/memory-core/src/memory/temporal-decay.ts, vector/embedding metadata: extensions/memory-core/src/memory/hybrid.ts, vector/embedding metadata: extensions/memory-core/src/memory/manager-keyword-retrieval.ts, vector/embedding metadata: extensions/memory-core/src/memory/manager-search-orchestration.ts, and 1 more. Confirm migration or upgrade compatibility proof before merge.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #139094
Summary: This PR is the implementation candidate for the linked open session-recency and vector-ordering report.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Technical review

Best possible solution:

Keep one Memory Core ranking flow that consumes authoritative indexed activity while preserving confidence, visibility, and existing storage contracts.

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

Yes, source-backed: current main looks for logical session paths under the workspace and slices vector results before final-score sorting. The supplied SQLite reproduction targets both defects; it was not executed during this review.

Is this the best way to solve the issue?

Yes. Reusing indexed source activity fixes the owning ranking boundary; reconstructing transcript filenames or substituting message timestamps would use the wrong source of recency.

AGENTS.md: found and applied where relevant.

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

Labels

Label justifications:

  • P2: Incorrect ordering affects optional indexed-conversation recall, with no demonstrated core outage or data loss.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🌊 off-meta tidepool and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: The supplied maintainer classification exempts this PR from the external-contributor proof gate, and no authority change triggers an exception; captured validation exercises the tool and SQLite owners with fixture embeddings at an earlier candidate.

Evidence

What I checked:

  • Current main still exhibits the reported mechanism: Current main resolves session timestamps as workspace files and retains vector retrieval order after modifying scores. Logical SQLite session paths therefore receive no timestamp when the workspace file is absent, and vector fallback slices without sorting final scores. (extensions/memory-core/src/memory/temporal-decay.ts:84, 12a3b102f507)
  • Canonical timestamp producer: The existing session reader uses supplied source activity for SQLite transcripts and filesystem modification time for retained archives. The existing index writer persists entry.mtimeMs into memory_index_sources.mtime; individual message provenance remains separate. (packages/memory-host-sdk/src/host/session-files.ts:584, 685a9be80176)
  • Existing bounded source reader reused: Keyword, hybrid, and vector fallback paths supply indexed session timestamps through the existing source reader. Its query filters by source and candidate paths using sqliteStringSet; memory-only results skip the lookup. (extensions/memory-core/src/memory/manager-keyword-retrieval.ts:215, 685a9be80176)
  • Ranking owner and sibling paths: The vector fallback sorts final scores before slicing. Hybrid ranking applies source decay while retaining exact-path precedence and zero public confidence for recall-only LIKE matches; lexical-only searches reuse keyword finalization without acquiring a semantic-provider lease. (extensions/memory-core/src/memory/manager-search-orchestration.ts:435, 685a9be80176)
  • Entry point and visibility boundary: The memory_search tool calls executeMemorySearchToolQuery, which requests ranked candidates, applies session visibility filtering, and then limits returned results. This patch changes neither corpus authorization nor visibility policy. (extensions/memory-core/src/memory-search-tool-query.ts:150, 685a9be80176)
  • Regression coverage inspected: The new six-case manager regression covers keyword-only, lexical, hybrid, archives, unavailable FTS, and LIKE-only hybrid retrieval. It checks indexed timestamps, the expected decay ratio, final ordering, a one-result window, unchanged message provenance, real tool execution, and workspace decoys. Existing hybrid, temporal, provenance, generation-lifetime, and visibility coverage was also inspected. (extensions/memory-core/src/memory/manager-temporal-ranking.test.ts:166, 685a9be80176)

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • SunnyShu: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
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.

Workflow

  • 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.

History

Review history (4 earlier review cycles)
  • reviewed 2026-09-05T13:49:57.951Z sha 871ddef872a4d742a6d03330124fd59985222cbc :: blocked before merge. :: none
  • reviewed 2026-09-05T13:57:08.390Z sha 871ddef872a4d742a6d03330124fd59985222cbc :: blocked before merge. :: none
  • reviewed 2026-09-05T14:04:22.164Z sha 871ddef872a4d742a6d03330124fd59985222cbc :: blocked before merge. :: none
  • reviewed 2026-09-05T14:12:55.898Z sha 1852e6f :: blocked before merge. :: none

@steipete
steipete force-pushed the codex/deslop-memory-timestamps branch from 871ddef to 1852e6f Compare September 5, 2026 14:06
@steipete

steipete commented Sep 5, 2026

Copy link
Copy Markdown
Contributor Author

Final review of 685a9be80176f6a21193fcc1de36ead6b14a2e21 is complete. CI 33973263252 passed, including the required gate. The PR body now covers the connected LIKE tie-order repair and distinguishes the 80-test/full-check snapshot from the final comparator-equivalent 35-test/lint rerun. The complete change removes 10 production lines.

The latest ClawSweeper data-model checklist is addressed: this reads the existing memory_index_sources.mtime through the existing bounded reader. Schema, writer, representation, indexes, retention and migrations are unchanged; the real SQLite regressions verify the stored timestamps before search. There is no persistent transition requiring migration proof.

The separate direct review initially proposed feeding private LIKE strength into MMR relevance. We withdrew that finding after checking the shipped unweighted tie-break contract and documented diversity policy: equal confidence and similarity preserve recency order at every MMR round, while different similarity may intentionally favor a diverse result. No ranking-policy change is warranted. The original report and disposition are retained; no accepted P2 findings remain.

Proof exercises the real memory tool and SQLite/session/archive owners with fixture embeddings; it does not claim a live external embedding service or full Gateway deployment. Native stamped review validation passed. Proceeding through the repository prepare/merge workflow.

@steipete
steipete merged commit 8c0c270 into main Sep 5, 2026
146 checks passed
@steipete
steipete deleted the codex/deslop-memory-timestamps branch September 5, 2026 15:18
@steipete

steipete commented Sep 5, 2026

Copy link
Copy Markdown
Contributor Author

Merged via squash.

vincentkoc added a commit to aniruddhaadak80/openclaw that referenced this pull request Sep 5, 2026
* origin/main: (46 commits)
  fix(gateway): keep chat metadata responsive across auth refresh (openclaw#139192)
  fix(doctor): keep Workshop relocation lint read-only (openclaw#139193)
  perf(ui): retain unchanged forwarded avatar publications (openclaw#139181)
  fix(config): guide exec policy migration repairs (openclaw#139143)
  test(i18n): refresh representative Watch key (openclaw#139197)
  fix(agents): preserve recovered scheduled-run outcomes (openclaw#139037)
  refactor(acp): simplify pending operation accounting (openclaw#139189)
  fix(plugin-sdk): harden account scope for pairing requests and challenges (openclaw#139142)
  perf(gateway): avoid redundant PR landing ancestry checks (openclaw#139186)
  perf(ui): release captured audio cache leases directly (openclaw#139174)
  fix(skills): validate names in library forms (openclaw#139184)
  fix(sessions): reduce cold catalog listing delays (openclaw#139146)
  perf(cron): scan preserved action output once (openclaw#139163)
  fix(agents): keep fresh tool results readable under context pressure (openclaw#139165)
  fix(compaction): heartbeat sessions ignore the active transcript byte cap (openclaw#136533)
  perf(agents): reuse snapshotted web search result rows (openclaw#139162)
  fix(onboarding): keep Tauri setup recoverable and verify model results (openclaw#139140)
  fix(memory): rank indexed sessions by source activity (openclaw#139112)
  perf(terminal): avoid rebuilding sanitized link fallbacks (openclaw#139159)
  perf(agents): bound retained tool result projection data (openclaw#139157)
  ...
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 6, 2026
* fix(memory): rank session recall by source recency

* fix(memory): weight lexical fallback ordering by recency
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 extensions: memory-core Extension: memory-core maintainer Maintainer-authored PR P2 Normal backlog priority with limited blast radius. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: L status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Bug: indexed session recall ignores recency and misorders vector results

1 participant