Skip to content

fix: compaction loses track of the active user request - #178477

Closed
dmitryvostryakov wants to merge 4 commits into
openclaw:mainfrom
dmitryvostryakov:fix/compaction-human-request-provenance
Closed

dmitryvostryakov wants to merge 4 commits into
openclaw:mainfrom
dmitryvostryakov:fix/compaction-human-request-provenance

Conversation

@dmitryvostryakov

@dmitryvostryakov dmitryvostryakov commented Oct 20, 2026 •

Copy link
Copy Markdown

What Problem This Solves

Fixes completed requests being revived, or the current human request being lost, when a conversation is compacted after tool, automated, or split-turn messages.

User Impact

Conversations retain the current human request and bounded source facts across compaction, fallback summaries, and session reload. No configuration change or data migration is required.

Why This Change Was Made

Select the pending human request from its recorded provenance and pass that same request through each compaction path. Preserve useful historical source context in its own bounded section, so completed requests do not become pending work again. Existing compaction and summary-quality owners retain the policy; no parallel cache, schema, or request-selection service is introduced.

Evidence

  • 149 focused tests passed, covering request selection, split turns, small context limits, degraded summaries, persisted reload, provider fallback, and prompt-prefix stability.
  • Targeted TypeScript checks, type-aware lint, format parity, and the parent-relative file-size gate passed. Two unsafe casts were removed and the assertion-safety baseline was updated to the actual count.
  • One fresh independent review found no actionable P0–P2 findings. The subsequent mechanical move of two unchanged pure helpers into the existing quality module passed the affected checks again.
  • Hosted CI for this new head is pending. Two UI retry timeouts on the earlier head remain unclassified; local passing UI checks do not establish their cause or waive hosted CI.
  • These are isolated regression and boundary checks. A real-provider Telegram compaction replay and production delivery have not been demonstrated by this PR.
Change size and ownership

Against the merge base: production +224/−77 lines; tests and support +632/−22 lines across 21 files.

The remaining production growth carries human-request provenance and bounded source context through existing compaction owners. The test growth covers distinct selection, budget, fallback, persistence, and caller boundaries. The two helper moves only consolidate existing pure summary transformations; their bodies are unchanged.

@clawsweeper

clawsweeper Bot commented Oct 20, 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 Oct 20, 2026
@dmitryvostryakov
dmitryvostryakov marked this pull request as ready for review October 20, 2026 14:29
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-20T14:40:28.963397Z 3f6c8b8 Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 3f6c8b8b82

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +66 to +69
const message = findLatestCompactionUserMessage(
messages,
(m) => getCompactionContent(m.content).text,
);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Preserve internal split-turn sources in fallback

When the cut splits a turn started by inter_session, internal_system, synthetic, or operator input and summary generation fails, this external-user-only selector returns empty for compactWithoutSummary (compaction.ts:636-643). That fallback then commits a boundary after dropping turnPrefixMessages without carrying the turn's source at all, so the retained assistant/tool suffix loses the task it belongs to; use a source-preserving selector, with an origin label, for this fallback instead of the user-request selector.

Useful? React with 👍 / 👎.

Comment on lines +334 to +338
return messages.findLast(
(message): message is Extract<AgentMessage, { role: "user" }> =>
message.role === "user" &&
isCompactionUserRequest(message) &&
Boolean(getText(message).trim()),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Scope user-request lookup to the admitted run

When compaction marks a fresh internal-only run unresolved—for example, a cron or independent sessions_send turn after older human work completed—this unbounded findLast skips the admitted input and selects the old external turn. src/agents/embedded-agent-runner/compaction-session-execution.ts:504-506 can set that state for overflow runs regardless of input origin, and src/agents/sessions/agent-session-compaction.ts:424-430 then tells the summarizer the selected text is current work, so completed tasks can be resurrected; scope selection to the current admission/turn and return no external ask for independent internal runs.

AGENTS.md reference: AGENTS.md:L20-L20

Useful? React with 👍 / 👎.

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. 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: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Oct 20, 2026
@clawsweeper

clawsweeper Bot commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge.

What this changes

This PR distinguishes external user requests from internal user-role messages when selecting requests and rendering compaction context.

Example: A user asks “Review the patch; do not deploy it,” followed by an inter-session update saying “Worker result: tests passed.”

  • Before: Compaction can record the worker update as the latest unresolved user request.
  • After: Compaction retains the human request and labels the worker update as inter-session input.

Review scores

Measure Result What it means
Overall readiness 🧂 unranked krab (1/6) The repair has clear user value and focused ownership, but two source-verified regressions block correctness and the required product-path proof is absent.
Proof confidence 🧂 unranked krab (1/6) Real behavior proof is necessary before merge. See Before merge.
Patch quality 🦪 silver shellfish (2/6) 2 actionable review findings remain.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Compaction can replace a pending human request with an internal update and steer subsequent work toward the wrong task.
Reason: Recorded input provenance already distinguishes these sources, so preserving that distinction at compaction repairs an existing conversation-continuity contract.

Merge readiness

⛔ Blocked before merge - 5 items remain

Keep this PR open: it addresses a real compaction attribution bug, but introduces two regressions that must be repaired before merging.

Priority: P2
Reviewed head: 3f6c8b8b823b5a54d35bb1397106fccb388d0d12

Before merge

  • Add real behavior proof - The changed agent-core selectors, serialization, and safeguard hook are exercised with deterministic completion responses in tests; no supplied artifact exercises the changed behavior through the shipped CLI or Gateway. Provide redacted terminal output or logs covering compaction and subsequent replay, removing IPs, API keys, phone numbers, and non-public endpoints. After adding proof, update the PR body, then request a new review with @clawsweeper re-review. The PR author or someone with repository write access can request it.
  • Preserve internal split-turn sources in deterministic fallback (P1) - When compaction splits a turn started by inter-session, internal-system, synthetic, or operator input and summary generation times out, compactWithoutSummary calls this newly filtered latestUserText on turnPrefixMessages. It now returns empty, so the fallback drops that prefix without preserving its source text, leaving the retained assistant/tool suffix without the task it belongs to. Keep a bounded, origin-labeled source projection for fallback independently of external-user request selection.
  • Scope unresolved-request selection to the admitted run (P1) - After a human task completes, an independent sessions_send or internal-system run can overflow. compaction-session-execution.ts marks overflow runs unresolved regardless of input origin, and prepareCompaction passes the complete context to this findLast. Skipping the admitted internal message selects the completed human task instead; agent-session-compaction.ts then explicitly calls that text current work and persists it as latestUnresolvedUserRequest. Use the admitted request identity and continuity facts to distinguish an update to pending human work from an independent internal run.
  • Explain or restore the original intent of Deterministic split-turn fallback - c0c6ca3: Retain the split turn's raw source request as required context when summary generation times out.
  • Explain or restore the original intent of Run-owned unresolved request - bc1dfcd: Ensure overflow recovery resumes the active request rather than an older superseded task.

Findings

  • [P1] Preserve internal split-turn sources in deterministic fallback — packages/agent-core/src/harness/compaction/compaction.ts:65-70
  • [P1] Scope unresolved-request selection to the admitted run — packages/agent-core/src/harness/compaction/utils.ts:334-338

Provenance

  • Deterministic split-turn fallback changes intended behavior without addressing why it exists (c0c6ca3: Retain the split turn's raw source request as required context when summary generation times out.)
  • Run-owned unresolved request changes intended behavior without addressing why it exists (bc1dfcd: Ensure overflow recovery resumes the active request rather than an older superseded task.)

Tests

  • Missing end-to-end proof: Provide a shipped CLI or Gateway trace showing a human request surviving internal updates through compaction and replay, including the repaired internal-only and timeout-fallback cases.
Agent review details

How this fits together

Compaction projects persisted conversation messages into bounded summarizer input and replayable checkpoints, using both agent-core preparation and the safeguard hook.

flowchart TD
 A[Persisted conversation] --> B[Compaction preparation]
 B --> C[Shared origin classification]
 C --> D[Core and safeguard summaries]
 B --> E[Deterministic timeout fallback]
 D --> F[Checkpoint and retained messages]
 E --> F
Loading

Technical review

Best possible solution:

Keep shared origin classification, preserve attributed internal split-turn sources during fallback, and bind unresolved-request selection to the admitted run.

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

Current-main source selects internal user-role messages as requests; the committed fixtures describe a concrete failing path, but no product execution was performed during this read-only review.

Is this the best way to solve the issue?

A shared origin classifier is an appropriate focused repair, but external-user selection cannot also own arbitrary split-turn source retention or infer which earlier request belongs to the active run.

Full review comments:

  • [P1] Preserve internal split-turn sources in deterministic fallback — packages/agent-core/src/harness/compaction/compaction.ts:65-70
    When compaction splits a turn started by inter-session, internal-system, synthetic, or operator input and summary generation times out, compactWithoutSummary calls this newly filtered latestUserText on turnPrefixMessages. It now returns empty, so the fallback drops that prefix without preserving its source text, leaving the retained assistant/tool suffix without the task it belongs to. Keep a bounded, origin-labeled source projection for fallback independently of external-user request selection.
    Confidence: 0.99
  • [P1] Scope unresolved-request selection to the admitted run — packages/agent-core/src/harness/compaction/utils.ts:334-338
    After a human task completes, an independent sessions_send or internal-system run can overflow. compaction-session-execution.ts marks overflow runs unresolved regardless of input origin, and prepareCompaction passes the complete context to this findLast. Skipping the admitted internal message selects the completed human task instead; agent-session-compaction.ts then explicitly calls that text current work and persists it as latestUnresolvedUserRequest. Use the admitted request identity and continuity facts to distinguish an update to pending human work from an independent internal run.
    Confidence: 0.98

Overall correctness: patch is incorrect
Overall confidence: 0.98

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Sender attribution and summary rendering keeps the original intent (8446968: Preserve stable sender attribution through ordinary, custom, split-turn, and branch summaries.)
  • Bounded summary sampling keeps the original intent (1d09a03: Bound summarizer input while prioritizing human asks, decisions, and corrections.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

Acceptance criteria:

  • pnpm test packages/agent-core/src/harness/compaction/compaction-provenance.test.ts packages/agent-core/src/harness/compaction/compaction.test.ts
  • pnpm test src/agents/agent-hooks/compaction-safeguard-provenance.test.ts src/agents/sessions/agent-session-compaction.test.ts
  • pnpm test src/agents/agent-tools.prefix-stability.test.ts

What I checked:

Likely related people:

  • computment: Raw commit 8446968 adds packages/agent-core/src/harness/compaction/utils.ts:293 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 84469689f746; files: packages/agent-core/src/harness/compaction/utils.ts)

PR surface

Source +52, Tests +215. Total +267 across 8 files. Added test files: 1.

View PR surface stats
Area Files Added Removed Net
Source 5 79 27 +52
Tests 3 217 2 +215
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 8 296 29 +267

Review metrics

Metric Value Why it matters
Production versus test changes Production +79/-27; tests +217/-2 Shared classification replaces duplicated selection loops; the tests exercise ordinary preparation, rendering, replay, and safeguard behavior.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: This is a focused conversation-continuity repair without evidence of an urgent widespread outage.
  • merge-risk: 🚨 session-state: The patch can discard an internal turn's source context or persist completed human work as the current unresolved request.
  • rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🦪 silver shellfish.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Rating scale

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

Workflow

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

Reviewed October 20, 2026, 10:47 AM ET / 14:47 UTC.

@dmitryvostryakov dmitryvostryakov changed the title fix: compaction mistakes internal updates for user requests fix: compaction loses track of the active user request Oct 21, 2026
Resolve the test import conflict after upstream removed redundant tests.
Preserve the reviewed production patch and both parent histories.

Validation: 127 focused tests, targeted types, core lint, formatting, and
line-cap pass. Three unchanged upstream UI max-lines failures remain.
Keep historical source context separate from pending human asks and fund it
through the existing compaction retention plan. Preserve it in fallback and
SQLite reload paths while keeping completed requests out of pending work.

Replace the extracted text helper assertions with actual type narrowing.
@openclaw-barnacle

Copy link
Copy Markdown

This pull request has been automatically marked as stale after 7 days without qualifying human activity.
Without new human activity, Barnacle may close it as not planned 7 days after this message was posted. This is administrative inactivity cleanup, not a claim that the problem is fixed.
A human update restarts the inactivity clock; a new PR head also restarts it. A maintainer can add no-stale for a durable hold, or bad-barnacle to suppress Barnacle. Remove the hold when work can resume.

@openclaw-barnacle

Copy link
Copy Markdown

Closing due to inactivity.
If you believe this PR should be revived, post in #clawtributors on Discord to talk to a maintainer.
That channel is the escape hatch for high-quality PRs that get auto-closed.

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

Labels

agents Agent runtime and tooling merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P2 Normal backlog priority with limited blast radius. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. size: L stale Marked as stale due to inactivity status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant