Skip to content

fix(agents): keep claimed hook replies in conversation history - #150078

Open
herefindalex wants to merge 30 commits into
openclaw:mainfrom
herefindalex:fix/persist-hook-claimed-replies
Open

herefindalex wants to merge 30 commits into
openclaw:mainfrom
herefindalex:fix/persist-hook-claimed-replies

Conversation

@herefindalex

@herefindalex herefindalex commented Sep 16, 2026 •

Copy link
Copy Markdown

Closes #149985

Related: #150011

What Problem This Solves

Fixes a case where plugin replies claimed by before_agent_reply can be delivered without being recorded in session history. Media-only and captioned replies also lose attachment references when a text-only transcript receipt suppresses downstream mirroring.

User Impact

Claimed replies remain available in conversation history and follow-up context without duplicate assistant entries. Media replies retain stable attachment filenames alongside captions. No configuration or schema migration is required.

Why Change Was Made

Both CLI and embedded early-return paths persist through the existing transcript owners before returning ownership and idempotency metadata. Media history uses the existing outbound-media transcript-mirror projection; delivered payloads are unchanged. Session writer guards and detached/room-event no-persistence behavior are retained. Run-current assertions now also reach asynchronous transcript commit admission.

Evidence

Conflict repair and validation (e38c83e212cf7da6a94603af26cd80722e8b4dfc)

Merged the fixed upstream main baseline 5dd456acfa35575c342b43b944a9d0dbb911b68e into the PR. Resolved four conflicts while retaining both the claimed-reply history tests and upstream's newer authority/diagnostic behavior:

  • Embedded claimed replies now reuse upstream's preReplyAssertCurrent through transcript preparation and final commit admission.
  • CLI transcript persistence retains both the PR's current-run assertion and upstream's onMessageCommitted handling.
  • The extracted embedded return keeps providerStarted: false, so hook-authored replies are not counted as model responses.
  • No new test cases, schema/configuration changes, dependency overrides, or weaker assertions were added.

Functional proof: 248 selected tests passed. The four-file runner/transcript/diagnostic run passed 245 tests across three shards (691.59 seconds wrapper wall time). A separate reliability selection passed the three existing “keeps a committed final reply successful” cases (63.63 seconds); its other 59 tests were excluded by the filter, not executed. Coverage includes claimed text/media delivery and real SQLite/history readback, once-only persistence, cancellation before commit, replaced-writer authority, silent claims, provider-started diagnostics, and post-commit ownership.

node scripts/run-vitest.mjs \
  src/agents/cli-runner.before-agent-reply-cron.test.ts \
  src/agents/cli-runner/cli-run-transcript.test.ts \
  src/agents/embedded-agent-runner/run.shared-integration.test.ts \
  src/agents/diagnostic-model-response.test.ts

node scripts/run-vitest.mjs \
  src/agents/cli-runner.reliability.test.ts \
  -t 'keeps a committed final reply successful'

Static proof and limitations: core production typecheck, agents-root and agents-other test typechecks, changed-file formatting and targeted type-aware lint passed. Conflict/line/assertion/SQLite/mock-export ratchets, dependency/config/plugin-boundary checks, coercion/deprecation checks, native schema, legacy-store, media, sidecar, import-cycle, webhook, and pairing guards passed. Staged git diff --check against the incorporated baseline passed.

The complete local changed-file gate is not green: it was deliberately stopped after the two relevant test type graphs passed, before completing the remaining 26 broad graphs (exit 143). Its remaining non-type checks were run separately. The unused-export check exited 1: 21 production findings and 9 full-tree findings, all in UI source, match the unmodified pinned upstream baseline exactly. Both candidate and baseline used the same repository scanner/configuration and Knip 6.32.2; the baseline was independently executed from an exported upstream source tree with the same installed dependencies. The script export scan passed on both. No UI exports, ignore rules, or scanner baselines were changed. Broad remaining type coverage belongs to the new-head CI; no full-local-gate success is claimed.

Static selection:

node scripts/check-changed.mjs --staged \
  --base 5dd456acfa35575c342b43b944a9d0dbb911b68e -- \
  src/agents/cli-runner.before-agent-reply-cron.test.ts \
  src/agents/cli-runner/cli-run-transcript.ts \
  src/agents/embedded-agent-runner/run-orchestrator.ts \
  src/agents/embedded-agent-runner/run.before-agent-reply-cron.test-support.ts \
  src/agents/embedded-agent-runner/run/handled-before-agent-reply-transcript.ts

Independent review: the candidate received a scoped-clean P0–P2 autoreview result with no actionable findings. Two status-only chunks could not assess source; the source-diff chunk reviewed the repair. No source edits followed review.

Environment: Node 24.21.0, repository-pinned pnpm 12.9.0; tested/reviewed candidate tree b0efdc6bd24b05a026799ff287cff9d297a02132.

The preceding head 45014fa84c8cc44de442725c47f88137e11073cf had green CI and ClawSweeper Revision 27 reported no findings. Those results do not certify this new merge commit. This update is local real-runner/SQLite proof, not a fresh installed-plugin, live-channel, or live-model capture. Earlier installed-plugin evidence below retains its original head labels. New-head hosted CI remains required.

Previous conflict repair and validation (45014fa84c8cc44de442725c47f88137e11073cf; historical)

Merged upstream main at 8c9999b298c4a5db2d60b531efff7f8ec20acbeb. Resolved conflicts in the CLI hook test, embedded run orchestrator, and reply normalization. Preserved upstream user-turn recording and exec-request context alongside claimed-reply history persistence. The claimed-history path now consumes upstream's canonical stripMixedSilentReplyTokens helper with ?? rawText for its nullable unchanged-text result; the duplicate helper is removed.

  • 304/304 tests passed across 9 files and 4 shards (896.11 seconds wrapper wall time). This includes CLI/embedded cancellation during and after transcript preparation, claimed text/media delivery with SQLite/history readback and once-only assertions, token normalization, pending-final delivery, and database-worker routing.
  • The previous head's BOOT compaction cleanup failure is covered by the passing agent-command.compaction-rotation.test.ts. Incorporated upstream fix 816dcc13e9ff0768c60f08bc6813e131c1c934ca routes this suite through the host-owned database worker.
  • Upstream removed run.terminal-timeout-delivery.integration.test.ts in 80239a7e6b2. It was not restored or counted as passing; the current runtime-refresh integration suite passed.
  • Static validation: production typecheck and all 28 core-test type graphs passed, along with formatting, ratchets, dependency/config/boundary checks, and the script unused-export scan. The repository-supported targeted type-aware lint passed for all 11 changed TypeScript files. Scripts lint and the remaining schema/storage/runtime/media/webhook/pairing guards passed. Full core lint did not complete: the repository's 900-second deadline terminated it with exit 124 and no lint diagnostics. The targeted lint result is separate evidence, not a passing full-core result.
  • The complete changed-file gate exited 1 at unused exports; it is not green. Exact-base main CI reports the same eight production findings with the same Knip version/config: captureSessionEntryMaintenanceAgeFact, SessionEntryMaintenanceAgeCapture, SqliteReclamationPreparedSource, GatewayApprovalEventPublisherV2, OpenClawAgentDatabaseWorkerCloseResult, two GitHubConnections exports, and GitHubConnectionsContent. Their definitions and scanner/config inputs are unchanged from the pinned base. The local full-tree scan also reports reconnectGateway in unchanged UI test-support source; base CI stopped at the production scan, so no base full-tree execution result is claimed. No unrelated exports or scanner rules were changed.
  • Independent review: the staged diff against the pinned main received a scoped-clean P0–P2 autoreview result, with no actionable findings. Two status-only chunks could not assess source; the source-diff chunk reviewed the repair. No source edits followed review.
  • Environment: Node 24.21.0, repository-pinned pnpm 12.9.0, @openclaw/fs-safe 0.26.0. Tested and reviewed candidate tree: 56e4b74f1b37031cee7290f8b1fa950aff910faf.

Functional validation:

node scripts/run-vitest.mjs \
  src/plugins/before-agent-reply.test.ts \
  src/agents/cli-runner.before-agent-reply-cron.test.ts \
  src/agents/cli-runner/cli-run-transcript.test.ts \
  src/agents/embedded-agent-runner/run.shared-integration.test.ts \
  src/agents/embedded-agent-runner/run.plugin-runtime-refresh.integration.test.ts \
  src/agents/agent-command.compaction-rotation.test.ts \
  src/auto-reply/reply/normalize-reply.heartbeat.test.ts \
  src/auto-reply/reply/pending-final-delivery.test.ts \
  test/scripts/database-worker-registry.test.ts

Static selection: node scripts/check-changed.mjs --staged --base 8c9999b298c4a5db2d60b531efff7f8ec20acbeb -- <the 12 PR-delta paths>. After its unused-export failure, the remaining commands from the same repository-generated plan were executed separately without skipping or weakening their guards. git diff --cached --check against that base passed.

This is local real-runner/SQLite evidence, not a new installed-plugin, live-channel, or live-model capture. Earlier installed-plugin evidence below remains labelled by its original head. Hosted CI must validate the new head; no all-green or merge-ready claim is made.

Previous conflict resolution and validation (cd4bfe4222412efde2fd1701f4bd77889cc68e28; historical)

Merged upstream main at 43856f78ec629f0c72180359a0ce85f06759974f. The only conflict was concurrent additions to test/vitest/vitest.database-worker-core-paths.mjs; the resolution keeps both the claimed-reply CLI test and upstream's cron-grant test exactly once. The PR's added/deleted patch is unchanged after ignoring diff context and line numbers, and the existing cancellation/commit assertions are retained.

  • 371/371 tests passed across 8 files and 5 shards (765.01 seconds wrapper wall time): the four claimed-reply/plugin/transcript files from the preceding validation, both previously failing integration files, test/scripts/database-worker-registry.test.ts, and test/scripts/ci-node-test-plan.test.ts. This includes all four cancellation-during/after-preparation regressions.
  • The earlier two integration warmup failures no longer reproduce on this merged tree: all 16 tests in run.plugin-runtime-refresh.integration.test.ts and run.terminal-timeout-delivery.integration.test.ts passed. Upstream bb5656bf89e230bb3d6c9040b1e9b86df0306439 routes these suites through host-owned database-worker forks; that change is retained.
  • The complete changed gate for the conflicted test-routing file passed using the staged merge against the incorporated upstream commit. Formatting, targeted lint, registry uniqueness/routing checks, and git diff --check also passed. This mechanical merge reuses the prior review of the unchanged PR patch.
  • These are local test results. Hosted CI for this new commit is not claimed complete; the older head-specific evidence below remains historical.
node scripts/check-changed.mjs --staged \
  --base 43856f78ec629f0c72180359a0ce85f06759974f -- \
  test/vitest/vitest.database-worker-core-paths.mjs

Revision 24: cancellation at transcript commit admission (f66173bdd5f63a7991600cede66b9c22f2891088)

A claimed reply could still add an assistant history event when the run was cancelled after transcript preparation but before asynchronous commit admission. CLI and embedded runners now pass their existing run-current assertion to the same transcript append/worker owner; session fences, write hooks, and idempotency remain unchanged. No schema or configuration change.

  • RED: on unfixed b974ef10871c10bd7accd406e4999ce0482314db, with the new tests and lockfile-matching dependencies, both "cancelled after transcript preparation" cases failed: real SQLite history contained one late claimed reply assistant event instead of zero.
  • GREEN: the CLI and embedded cancellation cases pass with zero assistant events. The full relevant files below passed 233/233 tests across 3 shards, including plugin hook behavior and adjacent CLI transcript handling.
  • Static gates: the complete changed-file gate against pinned upstream parent 214bb47b4ec0809e357d2e497e0bf8fd5d9f31eb exited 0, including core production typecheck, all 27 core-test type graphs, three unused-export scans, formatting, type-aware lint, ratchets, and boundary/legacy-store/import-cycle guards. git diff --check also passed.
  • Independent review: incremental four-file P0–P2 autoreview completed with scoped-clean and no findings. Reviewed source did not change afterward.
  • Environment: Node 24.21.0, repository-pinned pnpm 12.5.1, and @openclaw/fs-safe 0.23.0 matching the lockfile.

Functional revalidation:

node scripts/run-vitest.mjs \
  src/plugins/before-agent-reply.test.ts \
  src/agents/cli-runner.before-agent-reply-cron.test.ts \
  src/agents/cli-runner/cli-run-transcript.test.ts \
  src/agents/embedded-agent-runner/run.shared-integration.test.ts

Changed-file gate:

node scripts/check-changed.mjs \
  --base 214bb47b4ec0809e357d2e497e0bf8fd5d9f31eb -- \
  src/agents/before-agent-reply.test-support.ts \
  src/agents/cli-runner/cli-run-transcript.ts \
  src/agents/embedded-agent-runner/run.before-agent-reply-cron.test-support.ts \
  src/agents/embedded-agent-runner/run/handled-before-agent-reply-transcript.ts

Known failure, not claimed fixed: replaying both failed files from CI run 37199547039 produced the same two beforeAll suite failures on this repaired tree and on untouched upstream parent 214bb47b4ec0809e357d2e497e0bf8fd5d9f31eb:

node scripts/run-vitest.mjs \
  src/agents/embedded-agent-runner/run.plugin-runtime-refresh.integration.test.ts \
  src/agents/embedded-agent-runner/run.terminal-timeout-delivery.integration.test.ts

Both stop in shared harness warmup at run.workspace-ownership.test-support.ts:68 with real workspace consumer was exercised: expected 0 to be greater than 0; all 16 tests are skipped. The assertion can mask an earlier warmup error, so the underlying cause remains unresolved. These test/harness files are unchanged from that upstream parent. No retries, weaker assertions, or unrelated source changes were used to obtain green results.

This is real-runner/SQLite regression evidence, not a new installed-plugin, external-channel, or live-model trace. The head-labelled installed-plugin/local-channel-adapter proof below is historical. Hosted CI on the updated head remains the merge gate.

Earlier evidence (historical; see head labels)

  • Before the media repair, all three CLI media cases failed SQLite history assertions; text-only passed.
  • Registered plugin hooks exercise the real runner entrypoints and SQLite persistence for text-only, media-only, captioned, and multiple-attachment replies.
  • CLI delivery exercises the routeReply durable outbound pipeline, asserting unchanged transport arguments and once-only assistant history after delivery.
  • Dispatcher coverage verifies that transcript ownership disables downstream mirroring without dropping text/media payloads. Embedded coverage includes persistent turns, detached turns, room events, and replaced-writer rejection.
  • Relevant functional suites: 323 passed (CLI 41, embedded shared integration 136, dispatcher 139, hook boundary 7). After final test-only type/lint cleanup, CLI 41/41 and embedded hook regressions 17/17 passed again.
  • Independent review of the staged candidate found no actionable P0-P2 findings.
  • Core and all core-test typecheck shards passed; targeted repository lint, formatting, line-count ratchet, and git diff --check passed. The changed-file gate's earlier test type errors were corrected, and the failed typecheck plus remaining lint step reran successfully; other completed guards were retained.

Installed plugin -> claimed text/media -> delivery -> SQLite/history proof

Executed against exact PR head f57cd074e95ba2e0bbedb527d5c41ecfb7948cec with Node 24.19.0 and pnpm 12.4.0, using isolated HOME, config, state, and session storage.

  1. The production installer copied a local plugin package into state/extensions/claimed-reply-proof and enabled it. A fresh process reported plugin version 1.0.0, status: loaded, and channel claimed-proof. The plugin declared before_agent_reply, and the isolated operator config explicitly granted hooks.allowConversationAccess: true.
  2. A fresh openclaw agent --local --deliver --reply-channel claimed-proof process loaded that installed plugin. The hook claimed a captioned media reply before model execution. The configured model endpoint was the intentionally unreachable http://127.0.0.1:9/v1.
  3. The command returned the claimed text/media and successful routed delivery:
{
  "payloads": [
    {
      "text": "CLAIMED_TEXT_PR150078",
      "mediaUrl": "https://example.invalid/CLAIMED_MEDIA_PR150078.png",
      "mediaUrls": ["https://example.invalid/CLAIMED_MEDIA_PR150078.png"]
    }
  ],
  "deliveryStatus": {
    "requested": true,
    "attempted": true,
    "status": "sent",
    "succeeded": true,
    "resultCount": 1
  }
}
  1. The installed channel adapter recorded exactly one outbound call, preserving both caption and media URL:
{
  "delivery_count": 1,
  "kinds": ["media"],
  "texts": ["CLAIMED_TEXT_PR150078"],
  "mediaUrls": ["https://example.invalid/CLAIMED_MEDIA_PR150078.png"],
  "sequences": [1]
}
  1. The production loadTranscriptEvents history accessor read exactly one assistant message from the same SQLite-backed session, with the media filename projected into transcript text:
{
  "eventCount": 2,
  "assistantCount": 1,
  "assistantTexts": [["CLAIMED_TEXT_PR150078\nCLAIMED_MEDIA_PR150078.png"]],
  "idempotencyKeys": ["before-agent-reply:3d73e0fa-50d0-4b6b-8ad0-839f89d51be2"]
}
  1. A direct SQLite count independently confirmed assistant_count = 1 and distinct_idempotency_keys = 1 for that session.

This is a real disk installation and real routed-delivery adapter execution with SQLite/history readback. The adapter is a local proof channel; this is not a live external-channel API or live-model test.

Revalidated on PR head (2f60a04)

  • Merged upstream main fabbb3462b7e77c2207c44a4c0ace86254ab6a26 into the prior PR head. The two conflicts were an import moved into the upstream model-admission owner and a test-file routing list; the resolved PR diff retains the same claimed-reply persistence behavior.
  • Focused CLI, embedded-runner, dispatcher, and hook tests passed in 3 Vitest shards on the merged head.
  • A fresh openclaw agent --local --deliver --reply-channel claimed-proof process loaded the installed proof plugin from isolated test state. Its before_agent_reply hook claimed a captioned media reply. The configured model endpoint was unreachable (127.0.0.1:9), so no model response produced the reply. The CLI exited 0.
  • The installed local channel adapter recorded exactly 1 outbound media call with text CLAIMED_TEXT_PR150078 and media URL https://example.invalid/CLAIMED_MEDIA_PR150078.png.
  • The production loadTranscriptEvents accessor returned 2 events and exactly 1 assistant message, containing CLAIMED_TEXT_PR150078\nCLAIMED_MEDIA_PR150078.png with idempotency key before-agent-reply:812995e1-f3d1-473d-b498-fc8153298c00. Direct SQLite readback found 1 assistant event and 1 distinct idempotency key for the same session.
  • The isolated proof state was migrated from schema 21 with openclaw doctor --fix before this rerun; no operator state was used. This is real installed-plugin and local routed-delivery proof, not an external-channel API or live-model test.

Silent-claim follow-up and exact-head proof (348ff05)

ClawSweeper's Revision 10 found that a hook returning { handled: true } without reply could persist the synthetic NO_REPLY token as an assistant message. Both CLI and embedded runners now return the existing silent payload without appending an assistant transcript event; they mark that payload transcript-owned so downstream delivery cannot mirror it into history.

  • New CLI and embedded regressions use real session storage. Both failed before the fix because SQLite history contained a NO_REPLY assistant message, then passed after the fix with zero assistant messages for silent claims.
  • The focused silent tests passed: 2 tests in 2 files, Vitest duration 27.85s and wrapper wall time 86.30s. The final silent plus text/media selection passed 18 tests in 2 files, Vitest duration 33.13s and wrapper wall time 50.22s.
  • Core typecheck, core-test-agents-root, core-test-agents-other, focused oxlint/oxfmt, and git diff --check passed. An independent P0–P2 review of the follow-up diff found no actionable findings. Full exact-head CI remains the merge gate.
  • On this head, a fresh local CLI process loaded the installed proof plugin and returned deliveryStatus.status = sent with one payload result. Its local channel adapter recorded exactly one captioned-media outbound call. The production loadTranscriptEvents accessor returned 2 events, including exactly one assistant message containing CLAIMED_TEXT_PR150078\nCLAIMED_MEDIA_PR150078.png with idempotency key before-agent-reply:8c457f24-5170-4e51-8de6-dc96116e9286. Direct SQLite readback found one assistant event and one distinct idempotency key for the same session.

The installed-plugin proof uses an isolated local channel adapter and intentionally unreachable model endpoint, not an external-channel API or live-model test.

Cancellation authority and exact-head proof (31a58fd)

  • Revision 11 identified a stale-run write after an asynchronous before_agent_reply hook. CLI and embedded paths now check current run authority after the hook, immediately around transcript preparation, and after persistence returns, before releasing a claimed payload.
  • Real-session/SQLite regressions cancel a claimed turn (1) while the hook is pending and (2) inside transcript preparation, after the initial check but before the database write. The two new write-boundary cases failed on the preceding patch because SQLite contained one late claimed reply assistant event each; both pass now with zero assistant events. The focused before_agent_reply suites pass 63/63 tests across CLI and embedded entry points.
  • The final change passed core typecheck and the agents-root/agents-other test type graphs. The earlier full core-test typecheck passed all 25 graphs; after removing an unused test-support export, the affected graphs, focused lint, formatting, and tests passed again. The standalone dead-export scan passed all three scans; remaining changed-file static guards passed separately. Full exact-head CI is still the merge gate.
  • On this exact commit, a fresh local openclaw agent --local --deliver process loaded the installed proof plugin from isolated state. The plugin claimed a captioned-media reply; the local channel adapter recorded exactly one media send with unchanged caption CLAIMED_TEXT_PR150078 and media URL https://example.invalid/CLAIMED_MEDIA_PR150078.png. CLI reported deliveryStatus.status = sent, succeeded = true, and resultCount = 1.
  • Production loadTranscriptEvents read 2 session events, including exactly 1 assistant message with text CLAIMED_TEXT_PR150078\nCLAIMED_MEDIA_PR150078.png and one before-agent-reply idempotency key. A direct read-only SQLite query independently returned assistant count 1 and distinct idempotency-key count 1 for that session. This is installed-plugin/local-adapter proof, not an external-channel API or live-model test.

Explicit silent-token claim regression (941a8a3)

ClawSweeper Revision 14 identified a distinct edge: a plugin can return { handled: true, reply: { text: "NO_REPLY" } }. Outbound normalization suppresses that content-free payload, but both claimed-reply paths wrote an assistant NO_REPLY event. Both runners now use the shared payload-level silent-content decision before transcript persistence; media, other sendable content, heartbeat-owned replies, and the existing cancellation fences keep their prior paths.

  • Before fix, on c237892331314cdb5309159e832c7afa3a23c853: the new CLI and embedded runner tests each failed through the real runner entrypoint and SQLite history readback. Each found one assistant event containing NO_REPLY where zero were expected.
  • After fix, on 941a8a3bc30f1ad6b713697ec670b0c32d77f8a4: the same two targeted tests passed (2/2). The nearby before_agent_reply suites passed 65/65, including text/media persistence and cancellation/replaced-writer cases. Delivery normalization suites passed 102/102, including silent-token, media, and heartbeat cases.
  • Full affected files with one worker: pnpm test src/agents/cli-runner.before-agent-reply-cron.test.ts --maxWorkers=1 --reporter=dot passed 44/44 in 52.51s wall; pnpm test src/agents/embedded-agent-runner/run.shared-integration.test.ts --maxWorkers=1 --reporter=dot passed 167/167 in 213.50s wall. The shared embedded integration file is costly because it exercises the real runner/session/SQLite boundary and adjacent authority/media behavior; no new full-runner fixture was added.
  • Independent incremental P0–P2 review found no actionable findings. Formatting and git diff --check passed. Core typecheck, all 25 core-test type graphs, and all three unused-export scans completed successfully during check:changed. That broad local gate was interrupted during full-tree core lint after more than 30 minutes, so it is not claimed as a full pass. A separate lint command scoped to the six changed files completed without diagnostics. Exact-head GitHub CI remains the merge gate.

The prior installed-plugin captioned-media proof was collected on 31a58fd, not rerun on this incremental silent-token fix; the new SQLite regressions above ran on the pushed head.

Revision 15 follow-up: silent token with media (1a58c8cf89772187adbc0b45f3e18b2a04890473)

  • Before the fix (147394dfdb90c3e0915b98f257031510b8128810): the new registered-plugin CLI case delivered a media-only reply for { text: "NO_REPLY", mediaUrl: "https://example.com/photo.png" }, but its SQLite/history readback contained NO_REPLY\nphoto.png instead of photo.png. The new assertion failed on that exact mismatch.
  • After the fix: the transcript projection uses the same existing silent-text predicate as outbound normalization. In the CLI registered-plugin case, routed delivery sends the media with an empty text field, SQLite/history contains one assistant event with photo.png, and delivery does not add a second event. The embedded real-session matrix also reads back photo.png for persistent turns and preserves its existing non-persistent-turn expectations.
  • Local validation: node scripts/run-vitest.mjs src/agents/cli-runner.before-agent-reply-cron.test.ts src/agents/embedded-agent-runner/run.shared-integration.test.ts --maxWorkers=1 passed; targeted oxlint and oxfmt passed for all five changed files; tsconfig.core.json, agents-root, and agents-other typechecks passed; git diff --check passed. Independent incremental autoreview through P2 exited successfully.
  • The installed-plugin/local-channel captioned-media proof above predates this edge-case fix. The new token-plus-media evidence is from the registered-plugin CLI route and embedded real-session/SQLite tests, not a separate live external-channel run. Full check:changed was not rerun locally; exact-head CI is pending.

Upstream conflict resolution and revalidation (a0c2eb36ac86c73a7111386ee540b54f775e372e)

  • GitHub reported a real merge conflict after the Revision 15 fix was pushed. Merged upstream main at a1ba139b5697bef432ad0d2d28e0aba75b8a43a6; the only manual conflict was the CLI test import block. The resolution retains both the PR's registry/SQLite imports and upstream's test scheduler import.
  • On the merged tree, pnpm install --frozen-lockfile passed. The full CLI and embedded integration test files passed together with --maxWorkers=1 (about five minutes of local wall time, including worker rebuild). Focused oxfmt and oxlint on the five changed files, production core typecheck, agents-root and agents-other test typechecks, and staged git diff --check passed.
  • The token-plus-media proof above remains a registered-plugin CLI delivery and real-session/SQLite regression, not a new live external-channel or installed-plugin run. Full local check:changed was not rerun. Exact-head GitHub CI for this merge commit remains to be checked.

Mixed silent-token text alignment (e0010a48fd116ca88595d60033010e2d0c9f3ff7)

  • ClawSweeper Revision 17 identified a second history/delivery mismatch: for Hello NO_REPLY, delivery removes the trailing control token while the claimed-reply transcript previously retained it. This affects text-only replies and media captions.
  • Before fix: new registered-plugin CLI and embedded real-session cases for text-only and captioned media failed on the previous head a0c2eb36ac86c73a7111386ee540b54f775e372e. The transcript projection still passed the raw mixed text to SQLite.
  • After fix: delivery normalization and the claimed-reply transcript projection use one shared mixed-token stripping helper. The CLI cases verify routed delivery text Hello, SQLite/history text Hello or Hello\nphoto.png, and no second assistant event after delivery. Embedded real-session cases verify the same history projection for persistent turns and retain the non-persistent-turn expectations. The exact NO_REPLY plus media case remains covered.
  • Validation: the focused mixed-token runner cases passed; the complete CLI and embedded integration test files passed together with --maxWorkers=1 (240 seconds local wall time). The existing reply-normalization test file passed. Focused oxfmt, oxlint, production core typecheck, agents-root and agents-other test typechecks, git diff --check, and independent incremental review through P2 passed.
  • The runner cases are intentionally more expensive than helper-only tests because they exercise the registered hook, real session persistence, routed delivery, and SQLite readback in the same flow. This is not a new installed-plugin or live external-channel run. Full local check:changed was not rerun; exact-head GitHub CI remains pending.

Follow-up: heartbeat claim/history parity (96bfb9e)

  • Before: a registered hook reply with text "Hello HEARTBEAT_OK" was routed as "Hello" while its SQLite assistant transcript retained "Hello HEARTBEAT_OK"; the new CLI assertion failed on the prior head.
  • After: claimed-reply persistence applies the delivery heartbeat cleanup. The CLI registered-hook route and embedded runner tests cover mixed text, captioned media, media-only heartbeat content, and location; a content-free acknowledgment adds no assistant row. Opaque channelData keeps its prior history behavior because it has no generic text mirror.
  • Verification: focused CLI and embedded runner files passed after merging current main; the full CI planner test file passed on that merged tree. Core production typecheck, targeted lint/format, and git diff --check passed. The broad local check-changed run was interrupted during test-type graphs, so it is not claimed as complete. Exact-head GitHub CI is pending. This is local registered-plugin/SQLite/channel-adapter evidence, not a new live external-channel run.

Follow-up: opaque control-token history (4ea7434)

  • ClawSweeper Revision 19 identified that a claimed reply containing only HEARTBEAT_OK or NO_REPLY plus opaque channelData could deliver structured content while leaving a synthetic control-token assistant row in history. The new registered-hook CLI/SQLite cases failed on the prior head and passed after the projection returns no text mirror for those payloads. The payload still routes through the channel adapter once, and transcript ownership prevents a second mirror write. Embedded persistent and non-persistent runner cases cover the same history decision.
  • The prior CI auto-reply dispatch failures came from a PR-added test table that compared normalized routed payloads with unnormalized fixture inputs. The dispatch test now checks its own mirror:false policy with one representative CLI-owned reply; the existing registered-hook CLI cases retain per-payload delivery and SQLite assertions.
  • Verification on this head: the full CLI claimed-reply, embedded shared-integration, and dispatch-from-config test files passed together; core production and related agents-root, agents-other, and messaging test typechecks passed; targeted oxfmt, oxlint, git diff --check, and independent P2 review passed. This is local registered-plugin/channel-adapter/SQLite evidence, not a new live external-channel run. Exact-head GitHub CI remains pending.

Upstream sync and validation (e1ba7fa79a2)

  • Merged upstream main at 2aed86671065. This incorporates the upstream removal of extensions/voice-call/runtime-api.ts, which the previous CI head still expected in the SDK runtime API guardrail.
  • Resolved the CLI test-file conflict against upstream's hook-mock refactor while retaining the claimed-reply cron, media-delivery, and SQLite/history cases.
  • node scripts/run-vitest.mjs src/agents/cli-runner.before-agent-reply-cron.test.ts: 39/39 passed.
  • node scripts/run-vitest.mjs src/plugins/contracts/plugin-sdk-runtime-api-guardrails.test.ts test/scripts/run-vitest-bounded.test.ts src/infra/heartbeat-runner.isolated-session-mirror.test.ts src/agents/embedded-agent-runner/run.shared-integration.test.ts: passed.
  • Core production TypeScript check and the affected agents test TypeScript graph passed. Formatting and git diff --check passed; independent diff review found no actionable issue.
  • Exact-head CI finished with three failed test jobs; openclaw/ci-gate remains red. No CI success is claimed.
  • On untouched upstream base 2aed86671065, the subagent archive source-level test failed 1/25 with the same running versus terminal assertion as PR head (baseline used OPENCLAW_E2E_SKIP_BUILD=1); native SDK admission failed 1/1 with a state-database borrower leak on both base and PR head. Hosted CI instead reported a 5-second native admission probe stall, so a shared root cause is not established.
  • Gateway shutdown standalone passed 6/6 on both base and PR head. Its hosted fake-timer failure remains unattributed. These test-owner files are outside the PR diff; no unrelated test threshold or source fix was added.

@clawsweeper

clawsweeper Bot commented Sep 16, 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.

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: M labels Sep 16, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. 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. labels Sep 16, 2026
@herefindalex
herefindalex force-pushed the fix/persist-hook-claimed-replies branch 4 times, most recently from ddfd6a4 to c69c938 Compare September 16, 2026 14:00
@clawsweeper

clawsweeper Bot commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

The PR records plugin-claimed replies in CLI and embedded session history while preserving attachment filenames and preventing duplicate assistant entries.

Example: A before_agent_reply hook returns caption "caption" and media URL "https://example.com/photo.png".

  • Before: The reply is returned, but its assistant history entry or attachment reference can be missing.
  • After: History contains one assistant entry with "caption\nphoto.png", and delivery retains the original caption and media URL.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A useful, correct persistence repair with shipped-entry-point evidence and strong current-head regression coverage; repeated nonpersistent runner cases add avoidable test cost.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): Supplied installed-plugin proof exercises the shipped local agent CLI, claimed captioned-media delivery through a real local adapter, and once-only SQLite/history readback in isolated state; subsequent current-head runner regressions cover cancellation, writer replacement, silence, and token cleanup. The installed-plugin capture retains its historical head identity, and no live external-channel or model proof is claimed.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: A plugin can return a visible answer that is absent from conversation history and later context.
Reason: The linked reproduction and current source establish missing contract-defined persistence; the patch fixes both runner paths without changing configuration or public plugin APIs.

Merge readiness

✅ Ready for maintainer review

This PR fixes a conversation-history gap that remains on current main; the reviewed patch has no blocking findings and preserves the existing transcript ownership guards.

Priority: P2
Reviewed head: e38c83e212cf7da6a94603af26cd80722e8b4dfc

Before merge

None.

Findings

None.

Tests

  • Low-value test src/agents/embedded-agent-runner/run.before-agent-reply-cron.test-support.ts: The 13-payload matrix repeats the same no-persistence gate for both detached and room-event turns, adding 26 expensive runner cases; retain one representative case per nonpersistent lifetime and the full persistent-content matrix.
Agent review details

How this fits together

Agent runners invoke plugin reply hooks before model execution; claimed replies now pass through the existing session transcript owner before their payloads reach delivery.

flowchart TD
  A[User or scheduled turn] --> B[CLI or embedded runner]
  B --> C[Before agent reply hook]
  C --> D[Claimed reply projection]
  D --> E[Session transcript owner]
  E --> F[SQLite conversation history]
  D --> G[Reply delivery]
Loading

Technical review

Best possible solution:

Land the claimed-reply persistence repair through the existing transcript owners after the normal exact-head CI gates complete.

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

Current-main CLI and embedded handled-hook branches visibly bypass assistant persistence, matching the linked report's failing real-SQLite history assertion; this read-only review did not execute target code.

Is this the best way to solve the issue?

The repair addresses the early-return producer, reuses existing transcript append and mirroring contracts, and carries ownership metadata to prevent downstream duplicates.

AGENTS.md: found and applied where relevant.

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

Provenance checked

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

  • Current main still has the early-return gap: The CLI handled-hook branch returns payloads without calling assistant persistence; the embedded branch likewise returns before the normal attempt and transcript lifecycle. (src/agents/cli-runner/before-agent-reply.ts:60, 2c130c7039f2)
  • Persistence uses the existing owner and commit guard: The embedded adapter supplies the expected session, lifecycle revision, writer run, idempotency key, and current-run assertion to appendExactAssistantMessageToSessionTranscript; CLI reuses persistCliAssistantTranscript with the same assertion carried into append admission. (src/agents/embedded-agent-runner/run/handled-before-agent-reply-transcript.ts:46, e38c83e212cf)
  • Installed-plugin behavior proof: The full PR body records isolated production plugin installation and openclaw agent --local --deliver execution, one captioned-media adapter call, and production history plus independent SQLite readback showing exactly one assistant entry. The latest installed-plugin rerun is explicitly pinned to 31a58fd; newer head-specific runner regressions cover subsequent token and commit-guard repairs. (31a58fd33c10)
  • Current-head validation and previous findings: The body reports 248 selected passing tests on the reviewed head, including real SQLite history, once-only persistence, cancellation, replaced writers, silent claims, and provider-started diagnostics. Source inspection confirms the earlier control-token and final commit-admission findings remain addressed; no tests or additional reviewer were run in this review. (src/agents/embedded-agent-runner/run.before-agent-reply-cron.test-support.ts:73, e38c83e212cf)
  • Original hook contract: The merged ordinary-turn hook repair established runners as the canonical interception point and explicitly preserved synthetic replies, silence, and pre-model ordering; this PR preserves that intent while adding missing history persistence. (src/plugins/before-agent-reply.ts:49, 63b0cac9f083)
  • Exact-head CI remains pending: Authenticated reads confirm the reviewed head is mergeable and not a draft; openclaw/ci-gate remains pending, with checks still running and no observed failed code-validation check. The cancelled PR-context job does not establish a patch defect. (e38c83e212cf)

PR surface

Source +387, Tests +744. Total +1131 across 12 files. Added test files: 1.

View PR surface stats
Area Files Added Removed Net
Source 8 416 29 +387
Tests 4 764 20 +744
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 12 1180 49 +1131

Review metrics

Metric Value Why it matters
Production versus test growth Production +320/-29 lines; tests and fixtures +860/-20 lines Production growth implements pre-attempt persistence and shared content projection; most growth exercises real history and lifecycle boundaries, although the nonpersistent media matrix can be reduced.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #149985
Summary: This PR repairs the canonical claimed-reply history report; the closed alternative and adjacent reports do not replace its remaining work.

Members:

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

Labels

Label changes:

  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • remove rating: 🦞 diamond lobster: Current PR rating is rating: 🐚 platinum hermit, so this older rating label is no longer current.

Label justifications:

  • P2: Claimed replies can disappear from durable conversation history and follow-up context, with limited scope to plugin-intercepted turns.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • proof: sufficient: Contributor real behavior proof is sufficient.

Rank-up moves

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

  • Reduce the detached and room-event media matrix to one representative payload per lifetime while retaining persistent-content and cancellation coverage.

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 (27 earlier review cycles; latest 8 shown)
  • reviewed 2026-09-28T15:30:32.059Z sha 4ea7434 :: needs maintainer review before merge. :: none
  • reviewed 2026-09-29T06:55:03.977Z sha e1ba7fa :: needs maintainer review before merge. :: none
  • reviewed 2026-09-29T08:54:06.306Z sha e1ba7fa :: needs maintainer review before merge. :: none
  • reviewed 2026-09-30T14:22:01.399Z sha ae27b80 :: needs maintainer review before merge. :: none
  • reviewed 2026-10-04T11:47:34.800Z sha b974ef1 :: blocked before merge. :: [P2] [P2] Carry the run guard into final transcript commit admission
  • reviewed 2026-10-04T15:57:45.013Z sha f66173b :: needs maintainer review before merge. :: none
  • reviewed 2026-10-05T02:26:17.707Z sha cd4bfe4 :: needs maintainer review before merge. :: none
  • reviewed 2026-10-11T04:08:08.118Z sha 45014fa :: needs maintainer review before merge. :: none

Reviewed October 13, 2026, 11:21 PM ET / October 14, 2026, 03:21 UTC (Revision 28).

@herefindalex
herefindalex force-pushed the fix/persist-hook-claimed-replies branch 3 times, most recently from 7e00aa9 to 87d4811 Compare September 16, 2026 15:16
@clawsweeper clawsweeper Bot removed the merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. label Sep 18, 2026
@clawsweeper clawsweeper Bot added merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. 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. labels Oct 4, 2026
@clawsweeper clawsweeper Bot added 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. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Oct 4, 2026

This branch has not been deployed

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

Labels

agents Agent runtime and tooling P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: XL 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]: before_agent_reply claimed replies are delivered but missing from conversation history

1 participant