Skip to content

fix(memory): CLI memory search never picks up edited memory files - #180624

Merged
steipete merged 6 commits into
openclaw:mainfrom
Sedrak-Hovhannisyan:fix/memory-cli-search-sync-teardown
Oct 23, 2026
Merged

steipete merged 6 commits into
openclaw:mainfrom
Sedrak-Hovhannisyan:fix/memory-cli-search-sync-teardown

Conversation

@Sedrak-Hovhannisyan

@Sedrak-Hovhannisyan Sedrak-Hovhannisyan commented Oct 22, 2026 •

Copy link
Copy Markdown
Contributor

Closes #177685

What Problem This Solves

Fixes: after a memory file is edited, openclaw memory search run from the CLI never makes the edit searchable because the index refresh it starts fails when the command exits.

User Impact

A standalone openclaw memory search now finishes the index refresh it starts before the process exits, so the next search finds the edited text. The first search after an edit still answers from the existing index, as before. When the refresh has to compute embeddings, the command stays open until they finish, which is the same work openclaw memory index does.

Why This Change Was Made

A search that finds changed memory files answers from the published index and starts a refresh in the background. That refresh runs on a maintenance manager that writes through the CLI manager's database connection. Before this change, when the CLI manager closed, it skipped waiting for search-time refreshes, so it released that connection while the refresh was still running. On main the refresh fails with Memory database owner closed or changed before write admission; on 2026.10.5 it fails with Agent database resources are closing. In both cases the edit is never indexed.

The fix removes the CLI exemption from the manager's idle wait. Every manager, including the short-lived CLI one, now waits for the search-time work it started before it closes. The CLI prints results before it closes the manager, so output is not delayed.

The Gateway's memory.search RPC uses the same short-lived manager and closes it after responding, so it also waits now, after the response is sent. I did not run that path live.

The existing test keeps transient CLI search off the serving manager write path (renamed to publishes transient CLI search maintenance before close, off the serving write path) asserted the old behavior: close finished while the paused refresh was still running. It now checks that close waits for the refresh and that the next CLI search finds the edited file. On main it fails at the first of those checks.

Related draft #139230 renames the set of tracked background syncs and keeps the CLI exemption, so both PRs edit the same line in awaitManagerIdle.

Evidence

Setup: isolated HOME, OPENCLAW_STATE_DIR, and OPENCLAW_CONFIG_PATH; agents.defaults.workspace points at a scratch workspace; memory.search.provider: "none" (keyword search, no network). MEMORY.md starts with a # Memory heading and one line, The garden gate code is kestrel. Each run used a fresh state directory and ran the same script: index, append a line to MEMORY.md, then search twice for the new word.

Published [email protected] (npm):

$ openclaw --version
OpenClaw 2026.10.5 (1b58cb9)
$ openclaw memory index
Memory index updated (main): 1 file indexed.
$ printf '\nThe boat is named heron.\n' >> MEMORY.md
$ openclaw memory search heron --json   # run 1
{
  "results": []
}
[memory] sync failed (search): Error: Agent database resources are closing: <state>/agents/main/agent/openclaw-agent.sqlite
$ openclaw memory search heron --json   # run 2
{
  "results": []
}
[memory] sync failed (search): Error: Agent database resources are closing: <state>/agents/main/agent/openclaw-agent.sqlite

main at 4f6666a (built with OPENCLAW_FORCE_BUILD=1):

$ openclaw --version
OpenClaw 2026.10.5 (4f6666a)
$ openclaw memory index
Memory index updated (main): 1 file indexed.
$ printf '\nThe boat is named heron.\n' >> MEMORY.md
$ openclaw memory search heron --json   # run 1
{
  "results": []
}
[memory] sync failed (search): Error: Memory database owner closed or changed before write admission
$ openclaw memory search heron --json   # run 2
{
  "results": []
}
[memory] sync failed (search): Error: Memory database owner closed or changed before write admission

This branch at 8184f5c (built with OPENCLAW_FORCE_BUILD=1; memory-core has no changes between 4f6666a and the new base 936599f):

$ openclaw --version
OpenClaw 2026.10.5 (8184f5c)
$ openclaw memory index
Memory index updated (main): 1 file indexed.
$ printf '\nThe boat is named heron.\n' >> MEMORY.md
$ openclaw memory search heron --json   # run 1
{
  "results": []
}
$ openclaw memory search heron --json   # run 2
{
  "results": [
    {
      "path": "MEMORY.md",
      "startLine": 1,
      "endLine": 6,
      "score": 0.393939999999394,
      "textScore": 9.99999000001e-7,
      "snippet": "# Memory\n\nThe garden gate code is kestrel.\n\nThe boat is named heron.\n",
      "source": "memory",
      "provenance": {
        "originClass": "agent",
        "sessionKind": "unknown",
        "observedAt": 1792673989264
      }
    }
  ]
}

Tests (run on the same change before the rebase onto 936599f):

  • manager-search-orchestration.test.ts -t "transient CLI search": passes on this branch; fails on main (expected "vi.fn()" to not be called at all, meaning close finished while the refresh was paused).
  • 26 related test files (memory-core manager search, provider lifecycle, registry, CLI, and src/gateway/server-methods/memory-search.test.ts): 280 of 281 pass. The failure, manager-search-knn-subprocess.test.ts > queries the real source child across WAL writer visibility and source filters, also fails on main on this machine (KNN child loaded unrelated runtime: kysely).
  • pnpm tsgo:core, oxlint on the changed files, and git diff --check pass.
  • node scripts/check-changed.mjs --base origin/main --head HEAD: 29 of 31 gates pass, including typecheck extensions, typecheck extension tests, and lint extension changed files. The two failures name only files this PR does not touch: the max-lines suppression ratchet flags three ui/src/pages files, and the dead export scan lists 160 unused exports in other files.

Maintainer follow-up

Retains @Sedrak-Hovhannisyan's standalone refresh-drain fix and preserves prompt results for Gateway-routed CLI searches. The existing channel-read lifecycle now accepts the owner-validated search result before settling manager cleanup; the handler still awaits cleanup, including rejected acquisitions. Cleanup errors are logged without replacing an accepted result. Maintainer decision: standalone searches keep draining before exit; Gateway calls deliver ready results before that drain. No new maintenance owner, setting, dependency, or SDK contract.

The CLI drain regression now synchronizes at the actual idle boundary instead of sleeping. Gateway coverage gates cleanup, verifies early/exactly-once response delivery and awaited settlement, and covers authority revocation during acquisition. Both regressions fail on the original behavior and pass with the repair. The CLI docs explain result delivery versus process exit.

Validation on macOS with Node 26.12.1 and real Ollama nomic-embed-text (main baseline 16920345c878):

Entry point Main baseline Repaired behavior
Offline FTS after editing indexed MEMORY.md Both searches miss the edit (26.080s / 20.287s) First uses old index; second finds edit (20.865s / 22.453s)
Offline Ollama after the same edit Both return only old content (22.362s / 22.082s), with owner-closed write-admission error First returns old content and drains refresh; second finds edit (22.158s / 9.462s)
Gateway owner RPC with edited-document embedding gated Regression test shows zero responses while cleanup is gated Real RPC responds in 61ms; CLI JSON arrives before document gate/release and committed publication; next RPC finds edit (90ms)

The Gateway trace explicitly matches all three CLI calls to memory.search.owner. Relative ordering: request 94.102s → RPC response 94.195s → CLI JSON 94.199s → edited-document gate 94.322s → release 94.325s → real embedding HTTP 200 at 94.354s → committed edit observed 104.177s → next search finds edit. The gate was released by observing the response, not an elapsed sleep. CLI wall times include startup (7.505s / 15.135s for the two Gateway searches).

All 48 original focused tests passed (22 Gateway, 8 channel-read scope, 18 memory orchestration; 649.68s total including artifact preparation). Runtime build, production/test types, formatting, and scoped lint passed. The six other requested ratchets passed again after the CI follow-up; max-lines reproduces the same three unrelated UI suppression failures on the exact contributor base. Whole-PR delta: production +31/-19 (net +12), tests +75/-17 (net +58), docs +4. The small production growth connects the existing acceptance and cleanup owners; the public owner wrapper remains intact for its documented callers.

Limitations: macOS-only live proof. Commands used the supported built launcher pnpm exec node ./openclaw.mjs because the source wrapper completed indexing but stranded its launcher during teardown. The successful runtime build and offline proof were at 54a8a93450e; later commits only adjust tests, with identical production files. The Gateway retry records 69b4cdad633; its production files also match the final head. The contributor's reported source-child KNN/Kysely isolation failure predates this change (#172681); compiled-worker base control passes, while the bounded source-mode attempt did not reach assertions. It is separate from this repair.

CI follow-up: the existing CLI ownership test revoked the owner while cleanup was blocked, after production had already accepted and sent the response. Its synthetic transport waits for handler teardown, hiding that timing. The test now blocks the search itself before revocation and retains the same rejection, no-output, and no-local-fallback assertions. The old gate reproduced the CI failure locally (446.37s including preparation); all 9 ownership tests pass with the corrected gate (138.05s total). Scoped types, lint, formatting, and affected ratchets pass. Production is unchanged.

Final-head (3efc0ef7e9f) isolated Codex review: scoped-clean, with no actionable P0–P2 findings.

A standalone `openclaw memory search` starts a background index refresh
when memory files change, prints the results, and closes its manager.
The close did not wait for that refresh, and the refresh writes through
the closing manager's connection, so it failed with "Memory database
owner closed or changed before write admission" and the edit never
became searchable.

Transient CLI managers now drain search-time maintenance before closing,
like persistent managers. Results are still printed first.

Fixes openclaw#177685
@clawsweeper

clawsweeper Bot commented Oct 22, 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.

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. labels Oct 22, 2026
@clawsweeper

clawsweeper Bot commented Oct 22, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR drains search-triggered indexing before standalone CLI exit while delivering Gateway-routed results before cleanup finishes.

Example: Append “The boat is named heron.” to indexed MEMORY.md, then run openclaw memory search heron --json twice.

  • Before: Both searches miss the edit because teardown interrupts the refresh.
  • After: The first search uses the existing index and finishes refreshing before exit; the second finds heron.

Review scores

Measure Result What it means
Overall readiness 🦞 diamond lobster (5/6) A focused, useful lifecycle repair with shipped-entry-point proof, meaningful regressions, and no actionable findings.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (terminal): Supplied isolated built-CLI runs exercise FTS and real Ollama refresh publication, and the real Gateway trace demonstrates early owner-RPC delivery followed by completed indexing; production matches the reviewed head, while production-handler regressions cover rejection after acquisition/search revocation and cleanup settlement.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Repeated standalone memory searches can keep returning an old index because command teardown interrupts the refresh started after a file edit.
Reason: The patch restores automatic freshness, preserves responsive Gateway results, and follows the recorded maintainer decision about standalone drainage.

Merge readiness

✅ Ready for maintainer review

Keep this PR open: it fixes a current memory-refresh lifecycle bug, resolves the earlier findings, and has sufficient runtime proof; exact-head CI remains pending.

Priority: P2
Reviewed head: 3efc0ef7e9f374407f707ffc267e3bafe6fc78c6

Before merge

None.

Findings

None.

Agent review details

How this fits together

Memory Core searches a published SQLite index and starts maintenance when files change; CLI and Gateway lifecycle owners retain the resources needed to publish that maintenance.

flowchart TD
  A[Edited memory files] --> B[Memory Core search]
  C[Standalone CLI or Gateway RPC] --> B
  B --> D[Published index results]
  B --> E[Tracked index maintenance]
  D --> F[Validated result delivery]
  E --> G[Drain before resource cleanup]
Loading

Technical review

Best possible solution:

Retain the existing maintenance and read-scope owners, drain standalone refreshes before resource release, and deliver authorized Gateway results before cleanup.

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

Current-main source exposes the teardown failure path, and supplied published-release and main-baseline CLI runs demonstrate lost refreshes; this read-only review ran no target code.

Is this the best way to solve the issue?

This is the smallest complete repair using existing owners: drain tracked work before closing its connection and preserve prompt Gateway delivery through the established acceptance callback.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 853e92c5110d.

Provenance checked

  • Transient CLI maintenance drainage changes intended behavior with a stated reason (a7766f1: Avoid waiting for detached maintenance after published search results are ready.)
  • Gateway-routed search acceptance and cleanup changes intended behavior with a stated reason (e40606f: Keep Memory CLI operations under the Gateway database owner, preserving authority, results, and cleanup.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit e40606f adds src/gateway/server-methods/memory-search.ts:292 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: e40606fdea96; files: src/gateway/server-methods/memory-search.ts)
  • Hoi Hin Adrian Ip: Raw commit a7766f1 adds extensions/memory-core/src/memory/manager-provider-lifecycle.ts:540 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: a7766f1d273f; files: extensions/memory-core/src/memory/manager-provider-lifecycle.ts)

PR surface

Source +12, Tests +58, Docs +4. Total +74 across 6 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 2 31 19 +12
Tests 3 75 17 +58
Docs 1 4 0 +4
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 6 110 36 +74

Review metrics

Metric Value Why it matters
Production versus test changes Production +31/-19; tests +75/-17 The production growth connects existing response acceptance and cleanup owners; test growth covers publication, response ordering, and revoked authority.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: The bug leaves CLI memory searches stale after file edits, while source files remain intact and explicit indexing provides a workaround.
  • rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • proof: sufficient: Contributor real behavior proof is sufficient.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

History

Review history (2 earlier review cycles)
  • reviewed 2026-10-22T13:20:45.563Z sha 8184f5c :: blocked before merge. :: [P2] Preserve prompt output for Gateway-routed CLI searches | [P3] Replace the fixed sleep with controlled lifecycle timing
  • reviewed 2026-10-23T04:24:12.809Z sha 90e3970 :: needs maintainer review before merge. :: none

Reviewed October 23, 2026, 12:50 AM ET / 04:50 UTC (Revision 3).

@steipete

Copy link
Copy Markdown
Contributor

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 23, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime size: S and removed size: XS labels Oct 23, 2026
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. clawsweeper:intake:bug Preliminary submission classification; full source review pending. labels Oct 23, 2026
@steipete

Copy link
Copy Markdown
Contributor

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 23, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@openclaw-barnacle openclaw-barnacle Bot added the cli CLI command changes label Oct 23, 2026
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. labels Oct 23, 2026
@steipete
steipete merged commit 16d1b9e into openclaw:main Oct 23, 2026
128 of 130 checks passed
@steipete

Copy link
Copy Markdown
Contributor

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 24, 2026
…enclaw#180624)

* fix(memory): keep CLI search refreshes from failing at exit

A standalone `openclaw memory search` starts a background index refresh
when memory files change, prints the results, and closes its manager.
The close did not wait for that refresh, and the refresh writes through
the closing manager's connection, so it failed with "Memory database
owner closed or changed before write admission" and the edit never
became searchable.

Transient CLI managers now drain search-time maintenance before closing,
like persistent managers. Results are still printed first.

Fixes openclaw#177685

* fix(memory): deliver routed search results before maintenance drains

* test(memory): use default deferred result type

* test(memory): mark disposable idle spy as intentionally unused

* test(memory): configure the disposable idle spy explicitly

* test(cli): revoke search authority before result acceptance

---------

Co-authored-by: Peter Steinberger <[email protected]>
@COOLBGT

COOLBGT commented Nov 1, 2026

Copy link
Copy Markdown

Confirmed the same failure on the published npm [email protected], Linux x64 / Node 24.22.1, with local embeddings. Release provenance is v2026.10.9 / 8b18b5578f66eab1501cba4cef2310d88bfb9a41.

Reproduction: stop the separately managed Gateway so there is only one indexing owner; edit a test-owned memory Markdown source after a successful index; run a standalone openclaw memory search --agent main --query "<existing query>" --json; check that teardown publishes the changed source for a subsequent search.

The search returned valid matches and exit status 0, but stderr reported Memory database owner closed or changed before write admission and the changed source was not published. Restoring the wait for tracked background search syncs allowed the real refresh to finish and publish the new source hash; two candidate/installed operation checks passed without that sync error.

The installed release and exact release-tag source still contain while (this.purpose !== "cli" && this.activeBackgroundSearchSyncs.size > 0). This PR already fixes that exact line and includes the important companion Gateway result-delivery/cleanup contract. I am reusing that fix and regression coverage rather than opening a duplicate original-bug PR.

GitHub comparison shows this merge and the release commit diverge, so this is evidence of a release/backport gap, not proof that this merged fix was included and then reverted. Please consider the complete change for the maintained release branch / next published fix release if applicable.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

cli CLI command changes docs Improvements or additions to documentation extensions: memory-core Extension: memory-core gateway Gateway runtime P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. size: S 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.

memory search: search-triggered sync is fire-and-forget and is lost when the CLI exits

3 participants