Skip to content

feat: let the agent request compaction itself (session_compact tool) - #138084

Closed
QFcattail wants to merge 1 commit into
openclaw:mainfrom
QFcattail:feat/agent-initiated-compaction
Closed

QFcattail wants to merge 1 commit into
openclaw:mainfrom
QFcattail:feat/agent-initiated-compaction

Conversation

@QFcattail

@QFcattail QFcattail commented Sep 4, 2026 •

Copy link
Copy Markdown

Closes #138083

What Problem This Solves

Long-running assistant sessions that switch between unrelated topics carry the
finished topic's history until token pressure finally triggers compaction. The
model has no way to say "this discussion is done, archive it now," so context
budget is wasted and the eventual pressure-driven summary mixes unrelated
topics.

Why This Change Was Made

Add a session_compact built-in tool that lets the model request compaction
of the current session, following the established sessions_yield pattern:
the tool records the request, the runtime owns execution.

Key design decisions:

  • The tool is only offered when the runtime provides a compaction request
    receiver, so unsupported contexts never see a dead tool. Heartbeat turns do
    not install the receiver at all (they never execute agent compaction).
  • Execution runs after the reply's delivery settlement — strictly later than
    the turn's deferred lifecycle completion, which releases the embedded
    active-run handle first (the manual pipeline rejects requests with
    active_run while the handle is still registered). Scheduling the work
    behind delivery keeps a non-streamed final reply from waiting on the whole
    summarization request. The run itself goes through the existing manual
    compaction pipeline (trigger: "manual", force, focus passed as
    customInstructions), reusing lane queueing, checkpoints, hooks, quality
    guards, and provider/model overrides unchanged.
  • A committed compaction is recorded through the same accounting owner as
    /compact (incrementCompactionCount with the committed successor entry as
    the writer fence), so finalization never persists the pre-summarization
    usage as the current context.
  • The tool is registered in CORE_TOOL_DEFINITIONS under the sessions
    section with coding/messaging profiles and the OpenClaw group, so
    profile allowlists, group:sessions, and group:openclaw agree with
    runtime eligibility.
  • No new config options, no SQLite schema changes, no new file storage: the
    summary lives in the session transcript as today, and full history stays on
    disk.

User Impact

The agent can now proactively compact on topic shifts instead of only
reacting to context pressure. Behavior is the same contract as /compact:
recent turns are preserved, the summary is stored in the session transcript,
and the operator can always inspect the full on-disk history.

Evidence

  • New focused tests (pnpm test scope):

    • src/agents/tools/session-compact-tool.test.ts (4 tests): error paths
      without session context or runtime receiver, scheduling with and without
      focus, callback payload.
    • src/auto-reply/reply/agent-runner-memory.agent-compaction.test.ts
      (7 tests): manual-pipeline invocation with focus/force, committed-entry
      writer fence plus incrementCompactionCount accounting on success,
      accounting failure logged without throwing, no-op without a request,
      heartbeat skip, skip outcome and failure both non-fatal.
    • src/auto-reply/reply/agent-runner-execution-agent-compaction.test.ts
      (2 tests): drives a full executeAgentTurn with the real
      deferred-lifecycle manager and asserts the turn surfaces the recorded
      request on the settled outcome without running compaction in-turn (the
      finalize side owns execution, after delivery settlement).
    • src/auto-reply/reply/agent-runner-maintenance.agent-compaction.test.ts
      (3 tests): the scheduled compaction runs only after ownerSettlement
      resolves, is skipped without a recorded request, and is skipped when the
      reply operation aborted before settlement.
  • Regression: agent-runner-execution-command-events.test.ts (4 tests),
    agent-tools-agent-config.test.ts (24 tests),
    agent-runner-memory.preflight-stale-tokens.test.ts (7 tests) all pass.

  • tsgo --noEmit -p tsconfig.core.json clean on this branch (core and core
    test graphs).

  • oxfmt --check clean on all touched files; docs updated in
    docs/concepts/compaction.md (Agent-initiated compaction section).

  • pnpm build and pnpm check pass locally on this branch (check includes the
    tool-display and assertion-safety ratchets that this change updates).

  • Live verification: not feasible in the author's environment — the execution
    path is the embedded auto-reply owner, which needs a full channel + provider
    setup (none available locally; the CLI-direct runtime intentionally does not
    expose the tool). The ordering and accounting guarantees are instead proven
    against the real deferred-lifecycle manager and the real settlement gate in
    the regression tests above; CI owns the full-suite run. The change touches no
    bundled plugin artifacts.

Follow-up noted during this work

  • src/system-agent/chat-turn-router.ts (untouched by this PR) has a
    pre-existing type error: resolveOperatorApprovalDecision infers T from
    both apply and denied, and the narrow literal returned by denied
    conflicts with the wide SystemAgentChatReply returned by apply. It does
    not affect the pnpm check lane (no full-project tsc there) and is unrelated
    to this feature; flagged here as a named follow-up for the owner of that
    surface.

@clawsweeper

clawsweeper Bot commented Sep 4, 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 docs Improvements or additions to documentation agents Agent runtime and tooling size: M labels Sep 4, 2026
@QFcattail
QFcattail force-pushed the feat/agent-initiated-compaction branch from 9dab3e4 to 41b750e Compare September 4, 2026 09:58
@clawsweeper clawsweeper Bot added P3 Low-priority cleanup, docs, polish, ergonomics, or speculative work. 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. labels Sep 4, 2026
@clawsweeper

clawsweeper Bot commented Sep 4, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge.

What this changes

Adds a model-facing tool that requests summarization of the current session after reply delivery, with runtime wiring, display metadata, documentation, and tests.

Review scores

Measure Result What it means
Overall readiness 🧂 unranked krab (1/6) The proposal has useful intent and focused supplemental coverage, but the unchanged assembler and maintenance defects prevent readiness.
Proof confidence 🦪 silver shellfish (2/6) Real behavior proof is necessary before merge. See Before merge.
Patch quality 🧂 unranked krab (1/6) 4 actionable review findings remain.

Merge readiness

⛔ Blocked before merge - 12 items remain

Keep open: this remains a distinct, useful proposal paired with an open issue. All four previous blockers remain at the unchanged head, and the contributor’s willingness to adopt a plugin capability gives maintainers a concrete product choice.

Priority: P2
Reviewed head: bbbf99cc9c2a459b2eb729765efa6f1f5af9c900
Owner decision: Required. See Decision needed.

Decision needed

  • Question: Should model-requested post-delivery compaction become a built-in tool or a shared runtime capability consumed by an optional plugin?
  • Recommendation: Sponsor a shared plugin capability: Retain runtime-owned scheduling and summarization while exposing a narrow request capability for an optional plugin tool.
  • Why: VISION.md favors lean core and reusable extension contracts, existing plugin APIs do not provide the complete requested seam, and the contributor explicitly offers either direction.

Before merge

  • Add real behavior proof - The changed reply owner records a model request and schedules compaction, but the supplied tests mock compaction or settlement and the captured body explicitly reports no real setup run. Add redacted logs, terminal output, or a recording showing delivered reply, committed summary and accounting, then a responsive next turn, including an existing installation with proactive compaction disabled. Redact secrets and private endpoints; update the PR body to trigger re-review, or ask a maintainer to comment @clawsweeper re-review. No stored-data format changes are introduced.
  • [P1] Restore the assembler imports and exported entry points (P1) - The introduced replacement removes every import, MEMORY_FLUSH_ALLOWED_TOOL_NAMES, the resolveToolLoopDetectionConfig re-export, and the exported internal factory’s skillReadResources parameter. attempt-tool-prepare.ts still imports both exports and passes the auxiliary parameter, while this file still references the deleted bindings and parameter. The embedded tool-preparation module cannot link correctly, and the public factory also reaches undefined bindings. Restore the canonical imports, options type, exports, and signature while retaining the new callback.
  • [P1] Honor the proactive-compaction opt-out (P1) - An installation with agents.defaults.compaction.enabled:false still receives the tool and reaches this helper, which invokes forced manual compaction. The documented setting disables proactive compaction and optional maintenance; tagging a model-requested operation as manual bypasses that existing preference. Check the setting when offering and servicing the request, while preserving operator /compact.
  • [P1] Schedule requested compaction through the preemptible owner (P1) - Calling the helper directly after settlement bypasses scheduleSessionMaintenance and its preemptible owner, fresh admission, lifecycle checks, and remaining-time budget. The helper uses trigger:"manual", so queued compaction reserves foreground priority and an active embedded handle instead of registering cancellable optional work. A new user turn cannot preempt it through the normal maintenance coordinator and can wait behind summarization. Carry the request through the established maintenance owner.
  • [P2] Require successful reply settlement before compacting (P2) - ownerSettlement resolves after owner completion even when the recorded operation result is failed. Failure freezes abort handling without necessarily aborting the signal, so this check permits compaction after failed delivery. The neighboring scheduler correctly requires replyOperation.result?.kind === "completed". Apply that successful-outcome guard here and cover failed settlement using the real operation contract.
  • Resolve merge risk - Maintainers have not selected a permanent built-in tool versus a shared runtime capability used by an optional plugin.
  • Resolve merge risk - The pinned branch conflicts with main; conflict resolution needs a refreshed review of the resulting introduced changes.
  • Complete next step - Obtain the built-in-versus-plugin capability ruling, resolve the four findings and merge conflicts, and provide redacted after-fix runtime proof before merge.
  • Improve patch quality - Restore the assembler’s canonical imports, exports, options type, and auxiliary skill-read parameter.
  • Improve patch quality - Use the existing preemptible maintenance owner with the operator opt-out and successful-delivery guard.
  • Improve patch quality - Add redacted after-fix runtime evidence covering compaction, accounting, and the next turn.
  • Resolve maintainer decision - Resolve the maintainer decision shown above before merge.

Findings

  • [P1] [P1] Restore the assembler imports and exported entry points — src/agents/agent-tools.ts:241
  • [P1] [P1] Honor the proactive-compaction opt-out — src/auto-reply/reply/agent-runner-memory.ts:1240-1244
  • [P1] [P1] Schedule requested compaction through the preemptible owner — src/auto-reply/reply/agent-runner-maintenance.ts:96-106
Agent review details

How this fits together

OpenClaw’s reply runtime turns model tool calls into recorded requests and delivered responses. Session compaction then summarizes older conversation history and updates the context accounting used by subsequent turns.

flowchart TD
  A[Model tool call] --> B[Record compaction request]
  B --> C[Finish agent turn]
  C --> D[Reply delivery settlement]
  D --> E[Compaction scheduling]
  E --> F[Existing summarization pipeline]
  F --> G[Transcript and context accounting]
Loading

Technical review

Best possible solution:

Keep compaction execution with the existing preemptible maintenance owner, preserve operator settings, and expose topic-shift policy through a maintainer-approved capability surface.

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

Yes for the patch defects: source establishes missing assembler exports and bindings, an unchecked opt-out, and incomplete scheduling guards. Runtime scenarios were not executed in this read-only review.

Is this the best way to solve the issue?

No as submitted: reuse of the existing summarizer is appropriate, but scheduling must use the established maintenance owner and the capability surface needs maintainer direction.

Full review comments:

  • [P1] [P1] Restore the assembler imports and exported entry points — src/agents/agent-tools.ts:241
    The introduced replacement removes every import, MEMORY_FLUSH_ALLOWED_TOOL_NAMES, the resolveToolLoopDetectionConfig re-export, and the exported internal factory’s skillReadResources parameter. attempt-tool-prepare.ts still imports both exports and passes the auxiliary parameter, while this file still references the deleted bindings and parameter. The embedded tool-preparation module cannot link correctly, and the public factory also reaches undefined bindings. Restore the canonical imports, options type, exports, and signature while retaining the new callback.
    Confidence: 1
  • [P1] [P1] Honor the proactive-compaction opt-out — src/auto-reply/reply/agent-runner-memory.ts:1240-1244
    An installation with agents.defaults.compaction.enabled:false still receives the tool and reaches this helper, which invokes forced manual compaction. The documented setting disables proactive compaction and optional maintenance; tagging a model-requested operation as manual bypasses that existing preference. Check the setting when offering and servicing the request, while preserving operator /compact.
    Confidence: 0.98
  • [P1] [P1] Schedule requested compaction through the preemptible owner — src/auto-reply/reply/agent-runner-maintenance.ts:96-106
    Calling the helper directly after settlement bypasses scheduleSessionMaintenance and its preemptible owner, fresh admission, lifecycle checks, and remaining-time budget. The helper uses trigger:"manual", so queued compaction reserves foreground priority and an active embedded handle instead of registering cancellable optional work. A new user turn cannot preempt it through the normal maintenance coordinator and can wait behind summarization. Carry the request through the established maintenance owner.
    Confidence: 0.98
  • [P2] [P2] Require successful reply settlement before compacting — src/auto-reply/reply/agent-runner-maintenance.ts:91-96
    ownerSettlement resolves after owner completion even when the recorded operation result is failed. Failure freezes abort handling without necessarily aborting the signal, so this check permits compaction after failed delivery. The neighboring scheduler correctly requires replyOperation.result?.kind === "completed". Apply that successful-outcome guard here and cover failed settlement using the real operation contract.
    Confidence: 0.99

Overall correctness: patch is incorrect
Overall confidence: 0.99

AGENTS.md: found and applied where relevant.

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

Merge-risk options

Maintainer options:

  1. Preserve existing settings and foreground priority (recommended)
    Restore the assembler contract and route requests through the established maintenance owner with opt-out and successful-delivery checks.
  2. Pause pending product sponsorship
    Hold implementation work until maintainers choose the built-in or plugin capability direction.

Security

None.

Evidence

What I checked:

  • Pinned introduction and review continuity: The introduced delta is 066a93f..bbbf99c. The checkout matches the previously reviewed head, and comparison against that head produces no changes in the three files containing the prior blockers. No pinned test merge is available, so no claim is made that base-only work would be removed. (bbbf99cc9c2a)
  • Assembler regression is introduced by this branch: The patch removes the assembler’s imports, memory-flush constant, loop-detection re-export, exported internal factory, and auxiliary skill-read parameter. Existing callers still import the removed exports and pass that parameter; the remaining body still references the deleted bindings. (src/agents/agent-tools.ts:241, bbbf99cc9c2a)
  • Existing maintenance owner supplies the missing lifecycle: scheduleSessionMaintenance creates a preemptible owner, waits for successful foreground settlement, obtains fresh session admission, checks session identity and lifecycle revision, and uses the remaining turn budget. The introduced scheduler instead invokes the manual compaction helper directly. (src/agents/session-maintenance/run.ts:117, bbbf99cc9c2a)
  • Operator opt-out remains an established contract: The documentation says compaction.enabled:false disables proactive compaction and optional maintenance while preserving operator /compact. The neighboring maintenance scheduler checks this setting, but the new receiver and forced manual-compaction helper do not. Public docs: docs/concepts/compaction.md. (docs/concepts/compaction.md:51, bbbf99cc9c2a)
  • Settlement does not establish successful delivery: ownerSettlement is Promise<void>; complete() settles it even when a previously recorded failure remains. fail() freezes abort handling without aborting the controller. The established scheduler additionally requires result.kind === completed; the new scheduler checks only abortSignal. (src/auto-reply/reply/reply-run-registry.operation.ts:492, bbbf99cc9c2a)
  • Current main and release still lack this core tool: Current-main searches distinguish session_compact lifecycle events from a model-callable tool. The session tool sections inspected on current main and v2026.9.7 contain sessions_yield, subagents, and session_status, without the proposed tool. Searches found earlier same-tool proposals closed unmerged, not a verified merged fixing PR. (src/agents/tool-catalog.ts:266, aad3deb6d88e)

PR surface

Source +467, Tests +466, Docs +12. Total +945 across 29 files.

View PR surface stats
Area Files Added Removed Net
Source 18 566 99 +467
Tests 10 466 0 +466
Docs 1 12 0 +12
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 29 1044 99 +945

Review metrics

Metric Value Why it matters
Production versus test growth src production +565/-99, net +466; tests and support +466/-0 The runtime wiring has a stated purpose, but part of the production growth duplicates the canonical assembler options while removing required imports and exports.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: This is a substantive session-management improvement with concrete runtime defects, rather than an urgent failure already affecting released users.
  • merge-risk: 🚨 compatibility: The introduced path bypasses the existing proactive-compaction opt-out, changing behavior for configured installations.
  • merge-risk: 🚨 availability: Removed assembler exports and bindings break tool preparation, while direct manual compaction bypasses foreground-preemptible maintenance.
  • rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🦪 silver shellfish and patch quality is 🧂 unranked krab.
  • 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.

History

Review history (7 earlier review cycles)
  • reviewed 2026-09-04T10:12:14.414Z sha 41b750ec1f607d1ccc7380bd025f7c7fcd47a725 :: needs real behavior proof before merge. :: [P1] Release the deferred run before starting manual compaction
  • reviewed 2026-09-08T08:19:21.236Z sha 95eb1a04ba9204b74de7da3d6f57fe2330777d21 :: needs real behavior proof before merge. :: [P2] Preserve successful compaction accounting | [P2] Deliver the completed reply before optional summarization | [P2] Register the tool in the canonical tool catalog | [P2] Withhold the request receiver from heartbeat turns
  • reviewed 2026-09-10T07:44:08.056Z sha 738ac9c6a9069093e46c347a56eeab1d29fd84fc :: needs real behavior proof before merge. :: [P2] Preserve successful compaction accounting | [P2] Deliver the completed reply before optional summarization | [P2] Register the tool in the canonical tool catalog | [P2] Withhold the request receiver from heartbeat turns
  • reviewed 2026-09-12T13:42:25.749Z sha 4495c3db6f4317bf5c336b1fe5e3962413cdb63c :: needs real behavior proof before merge. :: [P1] Honor the existing proactive-compaction opt-out | [P1] Schedule requested compaction through the preemptible owner | [P2] Require successful reply settlement before compacting
  • reviewed 2026-09-12T14:47:14.242Z sha 2cf2586b0a09ea6ae1a3589d09bf95cf6bad6b03 :: needs real behavior proof before merge. :: [P1] Honor the existing proactive-compaction opt-out | [P1] Schedule requested compaction through the preemptible owner | [P2] Require successful reply settlement before compacting
  • reviewed 2026-09-20T04:14:55.130Z sha bbbf99c :: needs real behavior proof before merge. :: [P1] [P1] Restore the tool assembler’s imports and exported entry points | [P1] [P1] Honor the existing proactive-compaction opt-out | [P1] [P1] Schedule requested compaction through the preemptible owner | [P2] [P2] Require successful reply settlement before compacting
  • reviewed 2026-09-25T18:45:45.510Z sha bbbf99c :: needs real behavior proof before merge. :: [P1] [P1] Restore the tool assembler’s imports and exported entry points | [P1] [P1] Honor the proactive-compaction opt-out | [P1] [P1] Schedule requested compaction through the preemptible owner | [P2] [P2] Require successful reply settlement before compacting

Reviewed October 2, 2026, 4:30 PM ET / 20:30 UTC (Revision 8).

@QFcattail
QFcattail force-pushed the feat/agent-initiated-compaction branch from 41b750e to 95eb1a0 Compare September 8, 2026 08:09
@clawsweeper clawsweeper Bot added 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. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. labels Sep 8, 2026
@QFcattail
QFcattail force-pushed the feat/agent-initiated-compaction branch 2 times, most recently from 738ac9c to 4495c3d Compare September 12, 2026 13:35
@clawsweeper clawsweeper Bot added merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. and removed merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. labels Sep 12, 2026
@QFcattail
QFcattail force-pushed the feat/agent-initiated-compaction branch from 4495c3d to 2cf2586 Compare September 12, 2026 14:39
Let the model request compaction of the current session when it judges
the conversation ready - for example when a topic concludes and a new
one starts - instead of waiting for context pressure.

- Add the session_compact built-in tool following the sessions_yield
  pattern: the tool records the request, the runtime owns execution.
- The tool is only offered when the runtime provides a compaction
  request receiver; heartbeat turns and native-compaction runtimes
  ignore requests, and failures never fail the recorded reply.
- Execution reuses the manual compaction pipeline (trigger manual,
  force, focus passed as customInstructions) after the turn completes,
  so checkpoints, hooks, and quality guards apply unchanged.
- Document the behavior in docs/concepts/compaction.md.
@QFcattail
QFcattail force-pushed the feat/agent-initiated-compaction branch from 2cf2586 to bbbf99c Compare September 20, 2026 04:07
@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. labels Sep 20, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. and removed P3 Low-priority cleanup, docs, polish, ergonomics, or speculative work. labels Oct 2, 2026
@openclaw-barnacle

Copy link
Copy Markdown

This pull request has been automatically marked as stale due to inactivity.
Please add updates or it will be closed.

@openclaw-barnacle openclaw-barnacle Bot added the stale Marked as stale due to inactivity label Oct 15, 2026
@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 docs Improvements or additions to documentation merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. size: XL 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.

Feature request: let the agent request compaction itself (topic-shift aware context archiving)

1 participant