← Back to Pull requests

fix: declare the OpenClaw 2026.8.1 durable-turn contract (engine is currently degraded to legacy on every turn) #372

Merged
Marvinthebored merged 2 files (606 lines) on Sep 03, 2026 15:59 UTC
View on GitHub
Marvinthebored Marvinthebored commented on Aug 10, 2026 06:43 UTC
Author

Problem

On OpenClaw 2026.8.1, this plugin's context engine is never used. Every turn logs:

[context-engine] Context engine "libravdb-memory" degraded to "legacy" for this logical turn:
atomic idempotent turn advancement is not declared.

The plugin loads, registers in full mode, and is then silently bypassed — nothing is ingested. It worked on 2026.6.x.

Cause: OpenClaw changed the context-engine contract, deliberately

openclaw/openclaw#119325 (merged 2026-08-07, in 2026.8.1) added a required durable-turn contract for context engines:

  • info.transcriptSemantics.currentTurnFence: "before-current-turn-entry-v1"

  • info.transcriptSemantics.turnAdvancementIdempotency: "atomic-idempotent-v1"

  • a commitTurn() method
  • The host enforces it in resolveSelectionIssue() (src/agents/harness/context-engine-logical-turn.ts): an engine missing either field, or missing commitTurn, is degraded to legacy for the whole logical turn.

    This is intentional and is now canon, not an accident:

  • OpenClaw's own docs were updated in the same PR (docs/concepts/context-engine.md): "Without the full declaration and method, OpenClaw uses the legacy context path for the whole logical turn… OpenClaw tries the configured engine again on the next logical turn."

  • Their review bot blocked the PR at P1 specifically because it bundled "a new public context-engine contract" with unrelated work, and recorded "Owner decision: Required". The PR body then states: "Maintainer decision: retain the combined ContextEngine transcript/commitTurn contract in this PR." It was merged on that basis.
  • So the fallback to legacy is working as designed; the plugin simply has not adopted the contract yet.

    Current info (src/context-engine.ts) declares neither field, and there is no commitTurn:

    info: { id: "libravdb-memory", name: "LibraVDB Memory", ownsCompaction: true },
    

    What this PR does

    1. Declares both transcriptSemantics fields.
    2. Adds commitTurn(), delegating to the existing afterTurn.

    afterTurn is already atomic and idempotent for this purpose: it reloads the per-session manifest inside the serialized ingestion queue and slices from manifestStore.findOverlapIndex, so a replayed turn contributes no new messages. commitTurn therefore satisfies "atomic, idempotent, keyed by advancementKey" without reworking ingestion. A bounded Set of seen advancementKeys short-circuits an exact host retry so the host is answered duplicate rather than repeating the overlap scan.

    No behavior change on older OpenClaw versions: the extra info fields are inert, and commitTurn is only called by hosts that look for it.

    Evidence

    Typecheck and build clean:

    $ node node_modules/typescript/bin/tsc --noEmit       # exit 0
    $ tsc -p tsconfig.build.json && node scripts/bundle-entrypoint.mjs
    $ grep -c transcriptSemantics dist/index.js           # 1
    $ grep -c commitTurn dist/index.js                    # 1
    

    Live on OpenClaw 2026.8.1. I applied this same change to the built dist/index.js of the installed 1.10.21 and restarted the gateway.

    | | turns | degradations |
    |---|---|---|
    | stock 1.10.21 | 3 | 3 — "atomic idempotent turn advancement is not declared" |
    | with this change | 3 | 0 — engine selected, LibraVDB bootstrap ran, codex wrote a context-engine thread binding |

    It has been running on my production instance since, with no degradation warnings.

    Important caveat — this is necessary but not sufficient

    Two things remain, neither caused by this plugin and neither fixed here:

    1. A host bug blocks the receipt path. On 2026.8.1 the host also degrades every fresh turn with "current-turn transcript admission receipt is unavailable", because it checks for the receipt during turn preparation, before the user turn is persisted. That affects every third-party context engine, including a minimal reference engine that implements the contract in full. Filed as openclaw/openclaw#121460 with a fix in openclaw/openclaw#121461. Until that lands, this PR alone will not restore ingestion — you need both.
    2. I have not yet observed commitTurn or afterTurn actually firing under the Codex app-server runtime even with both fixes applied: no session manifest is written. I am still investigating whether that is a further host issue or something on the plugin side, and will follow up. I did not want to overstate this PR: it removes the contract-based degradation, which I have measured; it is not yet proof that ingestion is fully restored on that runtime.

    Also worth knowing

    info.acceptedHostParams is still undeclared. OpenClaw's docs say undeclared engines receive the pre-host-field legacy parameter set only through 2026-08-12, after which they receive every current host field. That may need attention separately.

    AI-assisted: investigated, implemented and tested with Claude (Claude Code).

    ---

    Update — durability defects found by review, now fixed

    Depends on #375.

    An adversarial review of this PR found that it promoted afterTurn's advisory semantics into a durability contract. afterTurn may skip, dedupe by content, or short-circuit. That was harmless while it only drove logging; it is load-bearing once commitTurn maps the result to {committed|duplicate}, because the host deletes the durable outbox row for both values and never retries either.

    The concrete defect: an excluded session returned "duplicate" for work that was never committed, and memoized the advancementKey as though it had been. So "duplicate" could mean "intentionally ignored and never stored" rather than "already committed", and the turn was gone.

    What changed

  • Resolving now means only "no further attempt will help", which is "committed". "duplicate" is decided solely by advancementKey matching — the host's own definition of the word — and never inferred from afterTurn's result.

  • Recording a key is gated separately on this call having queued an ingestion that then completed, tested via the ingestion handle rather than by classifying skip-reason strings. Reason strings fail open: an unrecognized, renamed or absent one would read as durable and memoize a commit that never happened.

  • A caller joining an in-flight commit reports "duplicate" only when the leader actually committed, so two concurrent excluded calls can no longer manufacture a prior commit between them.

  • Skips no longer memoize at all. That costs a manifest reload and overlap scan on a replayed key but no RPC, and afterTurn is idempotent against the persisted manifest, so it re-derives the same skip. The key set is a fast path, not the correctness mechanism.
  • Tests assert the absences

    The earlier tests covered only the happy paths, so they could not have caught this:

  • no "duplicate" for an excluded session, including on a replay of the same key

  • no "duplicate" when two concurrent excluded calls share a key

  • "duplicate" still reachable by replaying a key that did commit — so the two negative assertions above cannot pass vacuously
  • All three fail on the previous head and pass here.

    Dependency on #375

    commitTurn is only as trustworthy as the ingest beneath it. Two defects in afterTurn are not fixed here because they exist on main independently of this contract and are not this PR's concern — they are #375:

  • a daemon cursor confirming none of the batch still resolves normally, so this can report "committed" for a turn that was never stored

  • bootstrap deletes the in-flight asyncIngestionQueues entry, breaking per-session serialization
  • The first is recorded as a known limitation on the method's own documentation, so it stays visible if this lands first.

    Also documented rather than changed

    Both predate this PR and belong to afterTurn:

  • overlap detection compares message id hashes where it has them, but a multi-message overlap still matches on role and content alone, so two distinct turns whose messages are byte-identical dedupe and the second is not ingested

  • a daemon answering without a cursor is ACKed optimistically, so the manifest records what was sent rather than what was confirmed
  • Review

    Six adversarial passes on this change. Two of them found defects in the fix for the previous pass's finding — a reason-string gate that failed open, and an in-flight join that returned "duplicate" unconditionally — so one re-review after acting on findings would not have been enough here.

    AI-assisted throughout: written with Claude (Claude Code).

    <!-- This is an auto-generated comment: release notes by coderabbit.ai -->

    Summary

  • Added OpenClaw 2026.8.1 transcript semantics:

  • - currentTurnFence: "before-current-turn-entry-v1"
    - turnAdvancementIdempotency: "atomic-idempotent-v1"
  • Added commitTurn() with atomic, per-advancementKey idempotency.

  • Concurrent calls with the same key share one durable ingestion operation.

  • Keys are recorded only after durable ingestion succeeds.

  • Durable ingestion failures propagate and remain retryable.

  • Predictive compaction, caching, and embedding pre-warm failures remain best effort.

  • Added bounded oldest-first key tracking with a maximum of 4096 entries.

  • Repeated keys return "duplicate".

  • Added tests for concurrent calls, retries, and shared failure propagation.

  • Added an internal ingestion-promise capture hook for afterTurn.

  • Typecheck and build results are clean.
  • Complexity

  • Committed-key and in-flight-key lookups use average O(1) time.

  • Key insertion and deletion are O(1) amortized.

  • Bounded eviction is O(1) per evicted key, or O(k) for k evicted keys.

  • Concurrent duplicate calls use O(1) additional state per active key.

  • Committed-key state uses O(min(n, 4096)) space, where n is the number of unique advancement keys.

  • commitTurn() has higher cyclomatic complexity because it handles duplicate detection, in-flight coordination, durable failure propagation, retry cleanup, and successful commit recording.

  • afterTurn() has higher cyclomatic complexity because it separates durable ingestion from best-effort post-ingest work and captures ingestion outcomes.

  • Async ingestion queue handling adds branching for task outcome reporting while keeping queue chains non-rejecting.
  • Caveats

  • An OpenClaw receipt-path issue can still prevent ingestion.

  • commitTurn() and afterTurn() have not yet been observed under the Codex app-server runtime.

  • acceptedHostParams remains undeclared separately.

  • <!-- end of auto-generated comment: release notes by coderabbit.ai -->

    Diff: 606 lines (+573 / -33) across 2 files Reviewer: compoodment Review duration: 35116m
    All Vouch review confidence checks passed
    Residual risk 0.05 = Change Risk (0.43) × (1 − Review Confidence (0.87)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.43 · 606 lines diff across 2 files
    0.43
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.80 · 5 substantive comment(s)
    0.80
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    87%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.383
    Real PR Conversation Timeline
    11 items
    coderabbitai[bot] coderabbitai[bot] commented on Aug 10, 2026 06:43 UTC
    Bot

    <!-- This is an auto-generated comment: summarize by coderabbit.ai -->
    <!-- review_stack_entry_start -->

    ![Review Change Stack](https://app.coderabbit.ai/change-stack/xDarkicex/openclaw-memory-libravdb/pull/372?utm_source=github_walkthrough&utm_medium=github&utm_campaign=change_stack)

    <!-- review_stack_entry_end -->
    <!-- walkthrough_start -->

    <details>
    <summary>📝 Walkthrough</summary>

    Walkthrough

    The context engine now supports atomic, idempotent turn commits. It coordinates durable ingestion, joins concurrent retries, records successful advancement keys within a 4096-entry bound, and propagates failures for retry.

    Changes

    Turn commitment

    |Layer / File(s)|Summary|
    |---|---|
    |Transcript and advancement contract <br> src/context-engine.ts|Engine metadata declares transcript fencing and atomic idempotent advancement. Bounded state tracks committed and in-flight advancement keys.|
    |Durable ingestion coordination <br> src/context-engine.ts|Ingestion queues return task outcome promises. afterTurn exposes internal ingestion capture while keeping fire-and-forget behavior and isolating best-effort post-ingest work.|
    |Bounded idempotent turn commit <br> src/context-engine.ts, test/unit/context-engine.test.ts|commitTurn deduplicates keys, joins concurrent calls, records only successful commits, propagates shared failures, and supports retry after ingestion failure. Tests cover these paths.|

    Estimated code review effort: 4 (Complex) | ~45 minutes

    Sequence Diagram(s)

    sequenceDiagram
      participant Host
      participant CommitTurn as commitTurn
      participant AfterTurn as afterTurn
      participant IngestionQueue
      participant Daemon
      Host->>CommitTurn: Provide advancementKey and turn arguments
      CommitTurn->>AfterTurn: Start a new turn with capture hook
      AfterTurn->>IngestionQueue: Enqueue durable ingestion
      IngestionQueue->>Daemon: Persist turn
      Daemon-->>IngestionQueue: Return success or failure
      IngestionQueue-->>AfterTurn: Resolve ingestion promise
      AfterTurn-->>CommitTurn: Expose ingestion outcome
      CommitTurn-->>Host: Return committed or duplicate, or propagate failure
    

    Possibly related PRs

  • xDarkicex/openclaw-memory-libravdb#329: Both changes extend the asynchronous afterTurn ingestion flow.

  • xDarkicex/openclaw-memory-libravdb#281: Both changes modify duplicate-ingestion handling in afterTurn.

  • xDarkicex/openclaw-memory-libravdb#44: Both changes modify the turn-ingestion path in context-engine.ts.
  • Suggested labels: release:patch

    Suggested reviewers: xdarkicex

    Poem

    A rabbit tracks each turn with care,

    One key commits; repeats stay there.

    Failed hops may try again,

    While durable paths remain plain.

    Thump, thump—the queue is fair.

    </details>

    <!-- walkthrough_end -->
    <!-- pre_merge_checks_walkthrough_start -->

    <details>
    <summary>🚥 Pre-merge checks | ✅ 4 | ❌ 1</summary>

    ❌ Failed checks (1 warning)

    | Check name | Status | Explanation | Resolution |
    | :----------------: | :--------- | :------------------------------------------------------------------------------------ | :--------------------------------------------------------------------------------- |
    | Docstring Coverage | ⚠️ Warning | Docstring coverage is 66.67% which is insufficient. The required threshold is 80.00%. | Write docstrings for the functions missing them to satisfy the coverage threshold. |

    <details>
    <summary>✅ Passed checks (4 passed)</summary>

    | Check name | Status | Explanation |
    | :------------------------: | :------- | :---------------------------------------------------------------------------------------------------------- |
    | Linked Issues check | ✅ Passed | Check skipped because no linked issues were found for this pull request. |
    | Out of Scope Changes check | ✅ Passed | Check skipped because no linked issues were found for this pull request. |
    | Description Check | ✅ Passed | Check skipped - CodeRabbit’s high-level summary is enabled. |
    | Title check | ✅ Passed | The title clearly identifies the durable-turn contract update and the legacy-path degradation it addresses. |

    </details>

    </details>

    <!-- pre_merge_checks_walkthrough_end -->
    <!-- tips_start -->

    ---

    Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

    <details>
    <summary>❤️ Share</summary>

  • X

  • Mastodon

  • Reddit

  • LinkedIn
  • </details>

    <sub>Comment @coderabbitai help to get the list of available commands.</sub>

    <!-- tips_end -->

    coderabbitai[bot] coderabbitai[bot] commented on code on Aug 10, 2026 06:45 UTC
    Code Review
    src/context-engine.ts:1
    @@ -3306,6 +3320,47 @@ export function buildContextEngineFactory(
           };
           return await runCompaction(runArgs);
         },
    +    /**
    +     * OpenClaw >= 2026.8.1 durable turn advancement.
    +     *
    +     * The host requires one atomic, idempotent commit per accepted turn, keyed by
    +     * `advancementKey`, and may retry the same key after a process or plugin failure.
    +     * `afterTurn` is already idempotent: it reloads the per-session manifest inside the
    +     * serialized ingestion queue and slices off `findOverlapIndex`, so a replayed turn
    +     * contributes no new messages. The key set below only short-circuits an exact host
    +     * retry so the host is told "duplicate" rather than doing the overlap work again.
    +     */
    +    async commitTurn(args: {
    +      advancementKey: string;
    +      sessionId: string;
    +      sessionKey?: string;
    +      messages: OpenClawCompatibleMessage[];
    +      prePromptMessageCount?: number;
    +      isHeartbeat?: boolean;
    +      runtimeContext?: Record<string, unknown>;
    +    }): Promise<{ status: "committed" | "duplicate" }> {
    +      const key = args.advancementKey;
    +      if (key && committedAdvancementKeys.has(key)) {
    +        return { status: "duplicate" };
    +      }
    +      const result = await this.afterTurn({
    +        sessionId: args.sessionId,
    +        sessionKey: args.sessionKey,
    +        messages: args.messages,
    +        prePromptMessageCount: args.prePromptMessageCount,
    +        isHeartbeat: args.isHeartbeat,
    +        runtimeContext: args.runtimeContext,
    +      });
    +      if (key) {
    +        committedAdvancementKeys.add(key);
    +        if (committedAdvancementKeys.size > COMMITTED_ADVANCEMENT_KEY_LIMIT) {
    +          const oldest = committedAdvancementKeys.values().next().value;
    +          if (oldest !== undefined) committedAdvancementKeys.delete(oldest);
    +        }
    +      }
    +      return { status: result && (result as { skipped?: boolean }).skipped ? "duplicate" : "committed" };

    _🗄️ Data Integrity & Integration_ | _🟠 Major_ | _🏗️ Heavy lift_

    Do not mark the advancement key committed before durable ingestion succeeds.

    afterTurn resolves after it queues ingestion. It does not wait for afterTurnKernel or manifest persistence. It also catches queued failures internally. Line 3355 therefore records the key when the daemon write can still fail. A host retry then returns "duplicate" and cannot retry the lost ingestion.

    Two concurrent calls with the same advancementKey can also both pass line 3343 before either call reaches line 3355. Both calls then report "committed". This does not provide atomic idempotency.

    Use a per-key in-flight promise or lock. Keep it until a serialized ingestion operation confirms the daemon and manifest update. Delete the in-flight entry on failure. Record the committed key only after that success. Add tests for concurrent same-key calls and an afterTurnKernel failure followed by a retry.

    <details>
    <summary>🤖 Prompt for AI Agents</summary>

    Verify each finding against current code. Fix only still-valid issues, skip the
    rest with a brief reason, keep changes minimal, and validate.
    
    In `@src/context-engine.ts` around lines 3342 - 3361, The advancement handling
    around afterTurn must provide atomic per-key idempotency and only commit keys
    after durable ingestion succeeds. Replace the check-and-add flow in the relevant
    context-engine method with a per-key in-flight promise or lock that serializes
    identical advancementKey calls, keeps the entry until afterTurnKernel and
    manifest persistence succeed, removes it on failure, and records
    committedAdvancementKeys only after success. Ensure failures propagate so a
    later retry can run, and add coverage for concurrent same-key calls and retrying
    after an afterTurnKernel failure.
    

    </details>

    <!-- fingerprinting:phantom:poseidon:tapir -->

    <!-- cr-indicator-types:potential_issue -->

    <!-- cr-comment:v1:cdb310f9aedcdd9f724030d1 -->

    <!-- This is an auto-generated reply by CodeRabbit -->

    ✅ Addressed in commit 8ac9d9a

    coderabbitai[bot] coderabbitai[bot] commented on Aug 10, 2026 06:45 UTC
    Reviewer

    Actionable comments posted: 1

    <details>
    <summary>🤖 Prompt for all review comments with AI agents</summary>

    Verify each finding against current code. Fix only still-valid issues, skip the
    rest with a brief reason, keep changes minimal, and validate.
    
    Inline comments:
    In `@src/context-engine.ts`:
    - Around line 3342-3361: The advancement handling around afterTurn must provide
    atomic per-key idempotency and only commit keys after durable ingestion
    succeeds. Replace the check-and-add flow in the relevant context-engine method
    with a per-key in-flight promise or lock that serializes identical
    advancementKey calls, keeps the entry until afterTurnKernel and manifest
    persistence succeed, removes it on failure, and records committedAdvancementKeys
    only after success. Ensure failures propagate so a later retry can run, and add
    coverage for concurrent same-key calls and retrying after an afterTurnKernel
    failure.
    

    </details>

    <details>
    <summary>🪄 Autofix</summary>

    Fix all unresolved CodeRabbit comments on this PR:

  • <!-- {"checkboxId": "4b0d0e0a-96d7-4f10-b296-3a18ea78f0b9"} --> Push a commit to this branch (recommended)

  • <!-- {"checkboxId": "ff5b1114-7d8c-49e6-8ac1-43f82af23a33"} --> Create a new PR with the fixes
  • </details>

    ---

    <details>
    <summary>ℹ️ Review info</summary>

    <details>
    <summary>⚙️ Run configuration</summary>

    Configuration used: Organization UI

    Review profile: CHILL

    Plan: Pro Plus

    Run ID: 4e720b2a-2c0f-4a27-8afd-1f22e8dea9d6

    </details>

    <details>
    <summary>📥 Commits</summary>

    Reviewing files that changed from the base of the PR and between c883cf755609023cfc5b15c3acb04f08ed4d7c2c and 6e21ffce860ec537e7aa93b1b0646bee933fe9a9.

    </details>

    <details>
    <summary>📒 Files selected for processing (1)</summary>

  • src/context-engine.ts
  • </details>

    </details>

    <!-- This is an auto-generated comment by CodeRabbit for review status -->

    Marvinthebored Marvinthebored commented on code on Aug 10, 2026 08:07 UTC
    Code Review
    src/context-engine.ts:1
    @@ -3306,6 +3320,47 @@ export function buildContextEngineFactory(
           };
           return await runCompaction(runArgs);
         },
    +    /**
    +     * OpenClaw >= 2026.8.1 durable turn advancement.
    +     *
    +     * The host requires one atomic, idempotent commit per accepted turn, keyed by
    +     * `advancementKey`, and may retry the same key after a process or plugin failure.
    +     * `afterTurn` is already idempotent: it reloads the per-session manifest inside the
    +     * serialized ingestion queue and slices off `findOverlapIndex`, so a replayed turn
    +     * contributes no new messages. The key set below only short-circuits an exact host
    +     * retry so the host is told "duplicate" rather than doing the overlap work again.
    +     */
    +    async commitTurn(args: {
    +      advancementKey: string;
    +      sessionId: string;
    +      sessionKey?: string;
    +      messages: OpenClawCompatibleMessage[];
    +      prePromptMessageCount?: number;
    +      isHeartbeat?: boolean;
    +      runtimeContext?: Record<string, unknown>;
    +    }): Promise<{ status: "committed" | "duplicate" }> {
    +      const key = args.advancementKey;
    +      if (key && committedAdvancementKeys.has(key)) {
    +        return { status: "duplicate" };
    +      }
    +      const result = await this.afterTurn({
    +        sessionId: args.sessionId,
    +        sessionKey: args.sessionKey,
    +        messages: args.messages,
    +        prePromptMessageCount: args.prePromptMessageCount,
    +        isHeartbeat: args.isHeartbeat,
    +        runtimeContext: args.runtimeContext,
    +      });
    +      if (key) {
    +        committedAdvancementKeys.add(key);
    +        if (committedAdvancementKeys.size > COMMITTED_ADVANCEMENT_KEY_LIMIT) {
    +          const oldest = committedAdvancementKeys.values().next().value;
    +          if (oldest !== undefined) committedAdvancementKeys.delete(oldest);
    +        }
    +      }
    +      return { status: result && (result as { skipped?: boolean }).skipped ? "duplicate" : "committed" };

    Confirmed and fixed in 8ac9d9a — both halves were real.

    Recording before durability. You are right that afterTurn resolves once ingestion is queued and that the queued task caught its own failures, so the key was recorded while the daemon write could still fail. enqueueAsyncIngestion now returns a handle that settles with the task's real outcome, and commitTurn awaits it. The queue chain keeps its own .catch so one failed task cannot poison the tasks behind it, and that same catch means the handle can never surface as an unhandled rejection when afterTurn ignores it.

    I split the task rather than propagating everything: a failure in afterTurnKernel or the manifest write now rejects, but predictive compaction, the prediction cache and embedding pre-warm stay logged-and-swallowed. Those run after the turn is already durable, and asking the host to retry a durable turn is worse than losing a prediction. That matches how you scoped it — "confirms the daemon and manifest update".

    afterTurn itself is unchanged from the host's perspective: same return value, still fire-and-forget, still logs. The handle goes out through a symbol-keyed argument instead of being added to the result, so the public shape does not move. (Adding a field to the result was my first attempt; it also broke TypeScript's fresh-object-literal union normalisation for the inferred return type, which an existing test depends on for .skipped.)

    Non-atomic check-and-add. Identical advancementKeys are now serialized on one in-flight promise. Exactly one caller ingests; the others join it and resolve "duplicate" on success, or reject with the same error on failure — a joiner is never told the turn succeeded when it did not. The key is recorded only after the durable work succeeds, and there is no await between recording it and clearing the in-flight entry, so no caller can observe a window where the key is neither in flight nor committed. On failure nothing is recorded and the entry is deleted, so a retry does real work. The 4096 bound is unchanged, now with oldest-first eviction in a helper.

    Tests (test/unit/context-engine.test.ts), all three of which fail against the previous implementation:

  • concurrent same-key calls → exactly one afterTurnKernel call, statuses ["committed","duplicate","duplicate"], and a later retry short-circuits without touching the daemon. Pre-fix this returned ["duplicate","duplicate","duplicate"].

  • afterTurnKernel failure → the call rejects rather than reporting committed, the retry re-runs and commits, and only then does a third call report duplicate. Pre-fix: "Missing expected rejection".

  • shared failure → both the leader and the joiner reject, and the key is still retryable afterwards.
  • They set OPENCLAW_STATE_DIR to a temp dir. They assert on whether the daemon was called, which depends on an empty per-session manifest, and the default store is the developer's real ~/.openclaw/libravdb-manifests — a manifest left by an earlier run makes afterTurn short-circuit with no-new-messages and flips the assertions. Worth noting separately: two pre-existing afterTurn tests on main already fail for exactly that reason, independent of this PR.

    One limitation I want to be explicit about rather than paper over. This makes the commit atomic and durability-gated within a process. committedAdvancementKeys is in-memory, so a retry after a crash finds an empty set and re-runs afterTurn — which is safe because it reloads the manifest inside the serialized queue and slices at findOverlapIndex, so a replayed turn contributes no new messages. The key set is a fast path for exact in-process retries, not the durability mechanism; the manifest is. I have said so in the commitTurn doc comment.

    Verified: tsc --noEmit clean, tsc -p tsconfig.build.json && node scripts/bundle-entrypoint.mjs clean, contract still present in dist/index.js, and the unit suite is at the same two pre-existing failures as main with the three new tests passing.

    coderabbitai[bot] coderabbitai[bot] commented on code on Aug 10, 2026 08:07 UTC
    Code Review
    src/context-engine.ts:1
    @@ -3306,6 +3320,47 @@ export function buildContextEngineFactory(
           };
           return await runCompaction(runArgs);
         },
    +    /**
    +     * OpenClaw >= 2026.8.1 durable turn advancement.
    +     *
    +     * The host requires one atomic, idempotent commit per accepted turn, keyed by
    +     * `advancementKey`, and may retry the same key after a process or plugin failure.
    +     * `afterTurn` is already idempotent: it reloads the per-session manifest inside the
    +     * serialized ingestion queue and slices off `findOverlapIndex`, so a replayed turn
    +     * contributes no new messages. The key set below only short-circuits an exact host
    +     * retry so the host is told "duplicate" rather than doing the overlap work again.
    +     */
    +    async commitTurn(args: {
    +      advancementKey: string;
    +      sessionId: string;
    +      sessionKey?: string;
    +      messages: OpenClawCompatibleMessage[];
    +      prePromptMessageCount?: number;
    +      isHeartbeat?: boolean;
    +      runtimeContext?: Record<string, unknown>;
    +    }): Promise<{ status: "committed" | "duplicate" }> {
    +      const key = args.advancementKey;
    +      if (key && committedAdvancementKeys.has(key)) {
    +        return { status: "duplicate" };
    +      }
    +      const result = await this.afterTurn({
    +        sessionId: args.sessionId,
    +        sessionKey: args.sessionKey,
    +        messages: args.messages,
    +        prePromptMessageCount: args.prePromptMessageCount,
    +        isHeartbeat: args.isHeartbeat,
    +        runtimeContext: args.runtimeContext,
    +      });
    +      if (key) {
    +        committedAdvancementKeys.add(key);
    +        if (committedAdvancementKeys.size > COMMITTED_ADVANCEMENT_KEY_LIMIT) {
    +          const oldest = committedAdvancementKeys.values().next().value;
    +          if (oldest !== undefined) committedAdvancementKeys.delete(oldest);
    +        }
    +      }
    +      return { status: result && (result as { skipped?: boolean }).skipped ? "duplicate" : "committed" };

    @Marvinthebored, confirmed. The current implementation addresses both parts of this finding.

    commitTurn() now waits for the captured ingestion handle before it records advancementKey. Failures from afterTurnKernel or manifest persistence propagate, remove the in-flight entry, and leave the key retryable.

    inFlightAdvancements serializes concurrent calls for the same key. Joiners return "duplicate" only after the leader succeeds. They receive the leader’s failure if it fails.

    Keeping predictive compaction and cache warming as best-effort post-durability work is correct. The manifest overlap logic provides safe idempotency after a process restart.

    Thank you for adding coverage for concurrent commits and failed-ingestion retries.

    <!-- <review_comment_addressed> -->

    🐇 ✅

    ---

    <!-- This is an auto-generated comment: tweet message by coderabbit.ai -->

    If you found this review helpful, would you consider giving us a shout-out on X?

    Thank you for using CodeRabbit!

    <!-- end of auto-generated comment: tweet message by coderabbit.ai -->

    <sub>You are interacting with an AI system.</sub>

    <!-- This is an auto-generated reply by CodeRabbit -->

    coderabbitai[bot] coderabbitai[bot] commented on Aug 10, 2026 08:10 UTC
    Reviewer

    [!CAUTION]

    Some comments are outside the diff and can’t be posted inline due to platform limitations.

    >

    > <details>

    <summary>⚠️ Outside diff range comments (1)</summary><blockquote>

    > <details>

    <summary>src/context-engine.ts (1)</summary><blockquote>

    > 2768-2778: _🗄️ Data Integrity & Integration_ | _🟠 Major_ | _⚡ Quick win_

    > Update the installed OpenClaw SDK before relying on transcriptSemantics.

    > src/context-engine.ts declares supported semantics that require OpenClaw >= 2026.8.1, but package.json builds with openclawVersion / pluginSdkVersion 2026.4.23 and install.minHostVersion >=2026.4.23. Install / build with a 2026.8.1+ host SDK before relying on these fields to enable the durable logical turn path.

    > <details>

    <summary>🤖 Prompt for AI Agents</summary>

    >
    > Verify each finding against current code. Fix only still-valid issues, skip the
    > rest with a brief reason, keep changes minimal, and validate.
    > 
    > In `@src/context-engine.ts` around lines 2768 - 2778, Update the OpenClaw SDK
    > version configuration before relying on transcriptSemantics in the
    > libravdb-memory context engine declaration. Align package.json’s
    > openclawVersion, pluginSdkVersion, and install.minHostVersion with a
    > 2026.8.1-or-newer host SDK, then retain the transcriptSemantics fields in the
    > context-engine configuration.
    > 

    > </details>

    > <!-- cr-comment:v1:2652ed6f7d1a53f1e71d7662 -->

    > </blockquote></details>

    > </blockquote></details>

    <details>
    <summary>🧹 Nitpick comments (2)</summary><blockquote>

    <details>
    <summary>test/unit/context-engine.test.ts (1)</summary><blockquote>

    3444-3446: _📐 Maintainability & Code Quality_ | _🔵 Trivial_ | _💤 Low value_

    Assert that the failed concurrent attempt reached the daemon once.

    The test name claims a shared ingest, but the assertions only check that both callers reject. A regression that starts two ingests, where both fail, still passes. failAfterTurnKernel returns a calls() probe; the return value is discarded at Line 3432.

    <details>
    <summary>♻️ Proposed assertion</summary>

    -    failAfterTurnKernel(client, 1);
    +    const probe = failAfterTurnKernel(client, 1);
    

         const settled = await Promise.allSettled([call(), call()]);
         assert.equal(settled[0]?.status, "rejected", "the leader must reject");
         assert.equal(settled[1]?.status, "rejected", "a joiner must see the leader's failure, not success");
    +    assert.equal(probe.calls(), 1, "the joiner must share the leader's ingest, not start a second one");
    

    </details>

    <details>
    <summary>🤖 Prompt for AI Agents</summary>

    Verify each finding against current code. Fix only still-valid issues, skip the
    rest with a brief reason, keep changes minimal, and validate.
    
    In `@test/unit/context-engine.test.ts` around lines 3444 - 3446, Update the
    concurrent ingest test around failAfterTurnKernel and the settled assertions to
    retain its calls() probe and assert that the daemon was reached exactly once
    after both callers reject. Keep the existing rejection assertions while
    verifying the shared-ingest behavior.
    

    </details>

    <!-- cr-comment:v1:28bb76bd80c2978d840a8091 -->

    </blockquote></details>
    <details>
    <summary>src/context-engine.ts (1)</summary><blockquote>

    3393-3411: _🩺 Stability & Availability_ | _🔵 Trivial_ | _⚡ Quick win_

    Bind afterTurn without relying on this.

    ingestTurn calls this.afterTurn(...). This works only while the host invokes engine.commitTurn(...) as a method on the returned object. If the host destructures the hook, or wraps it (for example const { commitTurn } = engine; await commitTurn(args)), this is undefined and the call throws a TypeError before any ingestion runs. The other hooks in this object do not depend on this, so this is the only method that carries that constraint.

    Consider extracting the afterTurn body into a named function in the factory closure, then calling it from both afterTurn and commitTurn.

    <details>
    <summary>♻️ Minimal alternative: capture the object once</summary>

       return {
    +    // `engine` refers to this object so hooks stay callable when detached.
         info: {
    

    Then use engine.afterTurn(...) inside ingestTurn instead of this.afterTurn(...), where engine is a const bound to the returned object.
    </details>

    <details>
    <summary>🤖 Prompt for AI Agents</summary>

    Verify each finding against current code. Fix only still-valid issues, skip the
    rest with a brief reason, keep changes minimal, and validate.
    
    In `@src/context-engine.ts` around lines 3393 - 3411, Remove the `this` dependency
    from `ingestTurn` in the `commitTurn` flow by reusing a factory-scoped named
    after-turn function, or by capturing the returned engine object and calling its
    `afterTurn` property. Ensure `afterTurn` and `commitTurn` share the same
    implementation so destructured or wrapped `commitTurn` calls still await
    ingestion successfully.
    

    </details>

    <!-- cr-comment:v1:5ce8e925ed1b7be989726c9f -->

    </blockquote></details>

    </blockquote></details>

    <details>
    <summary>🤖 Prompt for all review comments with AI agents</summary>

    Verify each finding against current code. Fix only still-valid issues, skip the
    rest with a brief reason, keep changes minimal, and validate.
    
    Outside diff comments:
    In `@src/context-engine.ts`:
    - Around line 2768-2778: Update the OpenClaw SDK version configuration before
    relying on transcriptSemantics in the libravdb-memory context engine
    declaration. Align package.json’s openclawVersion, pluginSdkVersion, and
    install.minHostVersion with a 2026.8.1-or-newer host SDK, then retain the
    transcriptSemantics fields in the context-engine configuration.
    
    ---
    
    Nitpick comments:
    In `@src/context-engine.ts`:
    - Around line 3393-3411: Remove the `this` dependency from `ingestTurn` in the
    `commitTurn` flow by reusing a factory-scoped named after-turn function, or by
    capturing the returned engine object and calling its `afterTurn` property.
    Ensure `afterTurn` and `commitTurn` share the same implementation so
    destructured or wrapped `commitTurn` calls still await ingestion successfully.
    
    In `@test/unit/context-engine.test.ts`:
    - Around line 3444-3446: Update the concurrent ingest test around
    failAfterTurnKernel and the settled assertions to retain its calls() probe and
    assert that the daemon was reached exactly once after both callers reject. Keep
    the existing rejection assertions while verifying the shared-ingest behavior.
    

    </details>

    ---

    <details>
    <summary>ℹ️ Review info</summary>

    <details>
    <summary>⚙️ Run configuration</summary>

    Configuration used: Organization UI

    Review profile: CHILL

    Plan: Pro Plus

    Run ID: 9bf6b6e6-e6bc-4474-885b-133c2d30ceae

    </details>

    <details>
    <summary>📥 Commits</summary>

    Reviewing files that changed from the base of the PR and between 6e21ffce860ec537e7aa93b1b0646bee933fe9a9 and 8ac9d9a6c38cddc3464d1256969fb1fba7f0fca7.

    </details>

    <details>
    <summary>📒 Files selected for processing (2)</summary>

    src/context-engine.ts
    test/unit/context-engine.test.ts

    </details>

    </details>

    <!-- This is an auto-generated comment by CodeRabbit for review status -->

    compoodment compoodment commented on Aug 10, 2026 18:10 UTC
    Reviewer

    Vale Review — PR #372

    Quality: Q3/5 — promising
    Head: 8ac9d9a

    Findings:

  • src/context-engine.ts:3400 — commitTurn calls this.afterTurn(...), so the hook only works when invoked as a method on the returned engine object. If the host stores or wraps the hook as a bare function, this is undefined and the durable-turn path throws before it can ingest. Keep the shared after-turn implementation in the factory closure or call a captured engine object. minor

  • test/unit/context-engine.test.ts:3432 — The shared-failure test discards failAfterTurnKernel's call probe, so it proves both callers reject but does not prove they shared one daemon call. A regression that starts two failing ingests could still pass this test. nit
  • Proof gaps: I did not run a live OpenClaw 2026.8.1 runtime test or verify exactly how the host invokes commitTurn; the PR body still says full ingestion restoration is not proven on the target runtime.

    Verdict: comment-only — The contract fix is directionally right and the durability-gating regression is covered, but these edges should be tightened before relying on it as the durable-turn implementation.

    – Vale
    use @vale review

    Marvinthebored Marvinthebored commented on Aug 10, 2026 23:15 UTC
    Author

    Thanks — the this.afterTurn finding was right and is fixed.

    commitTurn now calls engine.afterTurn(...) through the closure instead of this. OpenClaw does bind it today (params.engine.commitTurn?.bind(params.engine) in context-engine-turn-outbox.ts), so this was latent rather than live — but nothing in the contract requires binding, and a host that stored the hook bare would have thrown before ingesting anything.

    Added a regression test that detaches commitTurn from the engine and calls it unbound. Verified both ways: it fails with this.afterTurn and passes with the closure reference.

    On the SDK-version point from CodeRabbit: I have deliberately not raised install.minHostVersion. transcriptSemantics and commitTurn are additive — older hosts ignore both, so the plugin still works there, and raising the floor would block installs that are currently fine. If you would rather gate it, that is your call and I will make the change.

    The nit about the shared-failure test not proving a single daemon call is fair; I have left it, since the behaviour it would pin is already covered by the serialization test above it. Happy to tighten it if you want it explicit.

    compoodment compoodment commented on Aug 12, 2026 18:12 UTC
    Reviewer

    Vale Review — PR #372

    Quality: Q4/5 — sharp
    Head: fae5bf0

    Findings:

  • None
  • Proof gaps: I did not run a live OpenClaw 2026.8.1 runtime test; focused unit coverage passed with isolated state, but the PR body still names the separate host receipt-path blocker.

    Verdict: approve — Current head fixes the prior unbound commitTurn edge and the durable-ingest/idempotency tests pass at this head.

    – Vale
    use @vale review

    compoodment compoodment approved these changes on Aug 14, 2026 18:10 UTC
    Approved Reviewer

    Vale Review — PR #372

    Quality: Q4/5 — sharp
    Head: c851377

    Findings:

  • None
  • Proof gaps: I did not run a live OpenClaw 2026.8.1 runtime test in this automation pass; the PR still depends on the separate host receipt-path fix for full runtime restoration.

    Verdict: approve — Current head fixes the prior unbound-hook edge and now carries the stricter afterTurn durability handling needed before mapping commits to the host contract.

    – Vale
    use @vale review

    Reviewers
    Assignees
    Marvinthebored Marvinthebored
    Labels
    risk: low confidence: 87.2% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 42.8% (MEDIUM) · Higher = larger blast radius
    42.8%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 87.2% · Lower = rushed or shallow review
    87.2%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 5.5% · Safe to merge
    5.5%