Skip to content

fix(knowledge): truncate memory index labels without splitting surrogate pairs - #186996

Closed
wangmiao0668000666 wants to merge 2 commits into
openclaw:mainfrom
wangmiao0668000666:fix/knowledge-memory-index-label
Closed

wangmiao0668000666 wants to merge 2 commits into
openclaw:mainfrom
wangmiao0668000666:fix/knowledge-memory-index-label

Conversation

@wangmiao0668000666

@wangmiao0668000666 wangmiao0668000666 commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

The standing Knowledge index clips long record labels with raw UTF-16 String.prototype.slice in memory-index.ts:

// base, memory-index.ts:49 (upstream/main 7c87e3a892d)
return flat.length > max ? `${flat.slice(0, max - 1).trimEnd()}…` : flat;

promptLabel owns prompt-facing Knowledge labels (TITLE_MAX = 80, CLAIM_MAX = 110, HANDLE_MAX = 60), all below the 200-unit record-title contract, so valid labels really are clipped; when the clip falls between an astral character's halves the label ends with a lone high surrogate.

memory-index-hook.ts (readMemoryIndex -> pinIndex -> appendSystemContext: text) pins this index and appends it to the system prompt every turn, so the lone surrogate enters the prompt bytes and becomes U+FFFD at serialization for the session.

User Impact

A page or claim label whose 79/109/59-unit clip lands inside an emoji or other astral character is rendered to the model corrupted: its last visible character becomes U+FFFD while the trailing ellipsis still appears, so the model cannot match the label back to knowledge_lookup input. The pinned index repeats this every turn until compaction or a new session.

Why This Change Was Made

// candidate
return flat.length > max ? `${truncateUtf16Safe(flat, max - 1).trimEnd()}…` : flat;

truncateUtf16Safe is already the truncation owner across this plugin and keeps the width contract: the clip may stop one UTF-16 unit before the cap and the ellipsis still fits inside max. ASCII and in-cap labels are byte-identical to before. Behavior-preserving for well-formed input, behavior-completing for split pairs (Precedent: #186707).

Evidence

Pinned base: 7c87e3a892dffa9280b9618dc01792c955ad20d1; candidate head: f991ffeb00a342fc6082702fbbb6008c98cbed07.

The regression folds into two existing cases, adding no test lines (delta 0, as the test-lines ratchet requires):

  • memory-index-hook.test.ts (existing byte-stable index case) saves its second label as ${"p".repeat(78)}<U+1F3AF> review (87 units, valid under the 200-unit contract) and asserts the serialized hook result carries the clipped label. Real path: memoryFixture store, real node:sqlite, real before_prompt_build hook -> readMemoryIndex -> buildMemoryIndex. No mocks.

BEFORE (base tree, de-hardlinked so link counts are 1; original memory-index.ts md5 909910d99edef67babadf437d69909bf):

$ /data/openclaw-test/a1028/runr.sh /data/openclaw-test/a1028/trunc-base-1 \
    "node scripts/run-vitest.mjs run extensions/knowledge/src/memory-index.test.ts \
       extensions/knowledge/src/memory-index-hook.test.ts --maxWorkers=1"
FAIL memory-index-hook.test.ts > appends a byte-stable index for owner-private sessions until the cutoff moves
AssertionError: expected '{"appendSystemContext":"## Knowledge …' to contain
  '- note: <78 x p>…'
Received: … "- note: <78 x p>\ud83c…\n- note: Renamed playbook title\nAll pages are listed."}
FAIL memory-index.test.ts > renders instruction-like or markup labels as ID only
AssertionError: expected 'xxxxxxxx<U+FFFD>…' to be 'xxxxxxxx…'
Tests  2 failed | 10 passed (12)

The base JSON shows the split literally: the clipped label is 79 units ending in U+D83C, the high half of U+1F3AF, so the serialized result contains \ud83c before the ellipsis and is not well-formed.

AFTER (candidate tree, same command, same tree contents otherwise):

$ /data/openclaw-test/a1028/runr.sh /data/openclaw-test/a1028/trunc-1 \
    "node scripts/run-vitest.mjs run extensions/knowledge/src/memory-index.test.ts \
       extensions/knowledge/src/memory-index-hook.test.ts --maxWorkers=1"
Test Files  2 passed (2)
Tests  12 passed (12)

Candidate: the serialized hook result has - note: + 78 x p + U+2026 (pair dropped, not half-kept) and no \ud8 escape; promptLabel returns xxxxxxxx + ellipsis, not xxxxxxxx + U+D83C + ellipsis.

Controls still green in the same cases: the in-cap Brightpath analysis playbook and renamed labels are unchanged, and instruction-like or markup labels still return null.

Merge Danger

  • Three files, +5/-4: one production import and expression, three modified test lines, no added test lines (delta 0). No new files, exports, options, or helpers; only the truncation call changes, leaving the max contract, markup/instruction rejection, and empty-label null return untouched.
  • A preview may shrink by one UTF-16 unit when the boundary falls inside a pair, matching the "may stop one unit before its cap" behavior used elsewhere in the plugin.
  • No open PR in the 300-newest openpr_files-1028.tsv map touches memory-index.ts, memory-index-hook.ts, or memory-index.test.ts; fix(cron): include untruncated agent output in webhook delivery #186366 only edits docs/plugins/knowledge/*.md.
  • Not tested: no local full-suite, typecheck, or lint run (local test/build forbidden); only these two files ran, remotely.

…ate pairs

The standing Knowledge index clips long record labels with String.slice at
TITLE_MAX/CLAIM_MAX. A clip that lands inside an emoji leaves a lone UTF-16
high surrogate in the rendered index, which the memory hook pins and injects
into the system prompt for the whole session; JSON/prompt serialization then
turns it into U+FFFD.

Use the existing truncateUtf16Safe helper so the clip stops one unit before
the cap, as other Knowledge projections already do.
@clawsweeper

clawsweeper Bot commented Oct 28, 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. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. 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. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. labels Oct 28, 2026
@clawsweeper

clawsweeper Bot commented Oct 28, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge.

What this changes

This PR uses the existing Unicode-safe truncation helper when clipping Knowledge index labels.

Example: A page title contains 78 lowercase p characters followed by 🎯 review.

  • Before: The index contains 78 p characters, a lone high surrogate, and an ellipsis.
  • After: The index contains 78 p characters and an ellipsis, without a broken surrogate pair.

Review scores

Measure Result What it means
Overall readiness 🦪 silver shellfish (2/6) The focused repair and real-storage regression are credible, but supplied evidence stops before the shipped prompt path.
Proof confidence 🦪 silver shellfish (2/6) Real behavior proof is necessary before merge. See Before merge.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Some otherwise valid emoji-containing record titles become malformed when shortened for the model's Knowledge index.
Reason: Preventing surrogate corruption restores expected text rendering without adding options, changing stored content, or altering intentional label limits.

Merge readiness

⛔ Blocked before merge - 1 item remains

Keep open: current main still splits surrogate pairs in Knowledge index labels, and this PR provides a focused repair with no identified correctness defect.

Priority: P2
Reviewed head: 4ea127953ce3e6b2ed3cde2244d3a5323656ef9c

Before merge

  • Add real behavior proof - The supplied terminal trace exercises the real Knowledge storage renderer through Vitest, but does not exercise the shipped Gateway prompt hook or provider-bound index text; the contributor should provide a redacted Gateway trace showing the corrected boundary label and short-label control, removing credentials, IPs, and non-public endpoints. After adding proof, update the PR body, then request a new review with @clawsweeper re-review. The PR author or someone with repository write access can request it.

Findings

None.

Tests

  • Missing end-to-end proof: Show the boundary title in a fresh authorized Gateway session's appended Knowledge index, with valid UTF-16 and unchanged short-label output.
Agent review details

How this fits together

Knowledge renders stored record labels into a bounded memory index, which its prompt hook pins and appends to authorized sessions' system context.

flowchart LR
  A[Stored Knowledge records] --> B[Storage memory index]
  B --> C[Label rendering]
  C --> D[Unicode safe truncation]
  D --> E[Pinned session index]
  E --> F[System prompt context]
Loading

Technical review

Best possible solution:

Keep the focused helper substitution and regression at the existing Knowledge index owner.

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

Source confirms that 78 p characters followed by 🎯 review produce a split pair at the 80-unit page-label cap; the contributor supplies a matching real-storage red/green trace, which was not independently executed during this read-only review.

Is this the best way to solve the issue?

The patch is the smallest complete rendering repair: it preserves clipping limits and filtering while reusing the established surrogate-safe helper.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Knowledge prompt-label clipping keeps the original intent (65ad180: The bundled Knowledge plugin uses bounded, filtered record labels in a session-pinned standing index.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

Likely related people:

  • Josh Lehman: Raw commit 65ad180 adds extensions/knowledge/src/memory-index.ts:48 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 65ad18005286; files: extensions/knowledge/src/memory-index.ts)
  • Peter Steinberger: Raw commit 75bffe4 adds extensions/knowledge/src/memory-index.ts:105 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: 75bffe44de05; files: extensions/knowledge/src/memory-index.ts)

PR surface

Source +1, Tests +27. Total +28 across 2 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 1 2 1 +1
Tests 1 27 0 +27
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 2 29 1 +28

Review metrics

Metric Value Why it matters
Production versus test LOC Production net +1; tests +27 The production change reuses an existing helper, and the added regression exercises valid ingestion and rendered output through existing storage fixtures.

Labels

Label changes:

  • add P2: A bounded Unicode rendering defect corrupts some Knowledge prompt labels without changing stored records or blocking agent turns.
  • add rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish and patch quality is 🐚 platinum hermit.
  • add status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Label justifications:

  • P2: A bounded Unicode rendering defect corrupts some Knowledge prompt labels without changing stored records or blocking agent turns.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish and patch quality is 🐚 platinum hermit.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Provide the shipped Gateway prompt-path evidence described above.

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.

Reviewed October 28, 2026, 4:04 PM ET / 20:04 UTC.

@obviyus

obviyus commented Oct 28, 2026

Copy link
Copy Markdown
Collaborator

NO-REPRO: shipped Gateway → OpenClaw/OpenAI standing-index path

Contributor head 4ea127953ce3e6b2ed3cde2244d3a5323656ef9c; unpatched main 110ebd63be37cb170d5b4392e19e7479ee0e9002. No source/test edits, commits or pushes were made during this investigation.

Both revisions installed/built in secretless node:24.22.1 Docker. Reusing the #186707 route, actual Gateway agent turns dispatched registered knowledge_save_page, knowledge_remember and knowledge_record tools to create and verify eight valid stored records. A new session then exercised the real standing-index prompt hook; the local Responses provider captured the exact request the model received. The probe message contains none of the fixture labels, so their presence in the provider request comes from the actual memory hook, not echoed user input. Fresh task profile/HOME/config/state/database paths were confirmed before each Gateway.

After one corrected capture retry, main twice and candidate twice completed normally. Each run used 13 real Knowledge tool calls, verified all eight original stored titles/bodies, then completed a separate prompt-probe turn. Both revisions supplied identical, well-formed labels to the provider:

label boundary / control           main twice                  candidate twice
page: 78 p + astral + review        78 p + ellipsis, 79 units    identical
page: 77 q + astral + review        intact pair + ellipsis, 80  identical
page: 81 ASCII r                   79 r + ellipsis, 80 units    identical
page: Budget + astral              unchanged, 9 units           identical
claim: 108 x + astral + trailer     108 x + ellipsis, 109 units  identical
claim: 107 y + astral + trailer     intact pair + ellipsis,110  identical
claim: 111 ASCII z                 109 z + ellipsis,110 units   identical
short Unicode claim                unchanged,14 units           identical

All 32 final observed labels were well-formed, with no U+FFFD in a UTF-8 round trip. This did not reproduce corruption in the provider-bound prompt, including both real clipping budgets (page80, claim110). The 60-unit lookup-handle path prefilters values above60 and therefore does not perform a truncating call.

Why the storage-renderer regression and this shipped path differ: the source renderer on main does use raw slice, but the existing model transport sanitizes unpaired surrogates before sending prompt text. sanitizeTransportPayloadText delegates to sanitizeSurrogates, which removes unpaired surrogate units and preserves valid pairs. On this observed path it already produces the same boundary label as the proposed producer fix. Relevant existing owner: transport text sanitizer, surrogate sanitizer.

The first harness attempt incorrectly asserted that the provider must receive malformed main text. It observed the already-safe page label and generated its own HTTP500 assertion failure; that is not product failure evidence. The corrected capture completed all four runs and retained exact provider requests, full standing-index context, original record reads, wire frames and final outcomes.

Evidence retained under proofs/186996/attempt-baseline-1-hooWR7/, attempt-baseline-2-Zrox4s/, attempt-candidate-1-1oNrPX/, attempt-candidate-2-Q0udfg/; harness prove.mjs, compare.sh; build logs. Pueue11563 builds and11573 final matrix succeeded. No real credentials, shared services, live model provider or system clock changes.

Scope of this NO-REPRO: the shipped OpenClaw harness with OpenAI Responses transport. It does not establish behavior for native CLI runtimes or other unexercised consumers, nor deny that raw pre-transport index text can contain a surrogate. I am not treating the storage-renderer-only difference as a demonstrated user-visible fix on this path; the maintainer can decide whether the raw-context invariant independently warrants the repair or a different shipped consumer needs proof.

…dex cases

Fold the regression into the prompt-label clip case and the byte-stable hook
case instead of adding a standalone test, so the PR's test-line delta stays
non-positive. The hook case now saves the label whose 80-unit clip falls
between the surrogate halves and asserts the serialized hook result contains
the clipped label with no lone surrogate.
@wangmiao0668000666

Copy link
Copy Markdown
Contributor Author

Closing after the NO-REPRO on the previous head, which matches the source: sanitizeSurrogates (packages/ai/src/utils/sanitize-unicode.ts) removes unpaired surrogate units and preserves valid pairs, and sanitizeTransportPayloadText (packages/ai/src/transports/transport-stream-shared.ts) applies it to prompt text. The standing-index text produced by promptLabel is consumed only by buildMemoryIndex, whose one caller is the before_prompt_build hook feeding appendSystemContext; the memoryIndex storage op has no other caller in the tree, so the raw pre-transport string is neither persisted nor sent anywhere else. On that path the sanitizer already yields the same label this change would produce, so there is no user-visible delta to prove. My Evidence measured the raw pre-transport string, which overstated the impact.

The branch keeps the fold into the two existing cases (memory-index.test.ts clip case, memory-index-hook.test.ts byte-stable case, +3/-3 test lines) in case a maintainer wants producer-side well-formedness as an invariant on its own merits. Closing rather than arguing an invariant with no shipped consumer.

@wangmiao0668000666
wangmiao0668000666 deleted the fix/knowledge-memory-index-label branch October 29, 2026 01:07
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

P2 Normal backlog priority with limited blast radius. plugin: knowledge rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. size: XS 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.

2 participants