Skip to content

[feat]: thread currentTokenCount into ContextEngine.assemble#81079

Closed
DatPham-6996 wants to merge 2 commits into
openclaw:mainfrom
DatPham-6996:feat/context-engine-current-token-count
Closed

[feat]: thread currentTokenCount into ContextEngine.assemble#81079
DatPham-6996 wants to merge 2 commits into
openclaw:mainfrom
DatPham-6996:feat/context-engine-current-token-count

Conversation

@DatPham-6996

@DatPham-6996 DatPham-6996 commented May 12, 2026

Copy link
Copy Markdown

Summary

  • Problem: ContextEngine.assemble receives only tokenBudget (the full model context window) and has no signal for how many of those tokens are already consumed by messages + systemPrompt + prompt. Engines that prepend a systemPromptAddition have no way to size it against actual remaining headroom.
  • Why it matters: On long sessions an engine's injection can push the prompt past the model's context limit. The runtime's preemptive-compaction (which has full visibility) runs before assemble, so it does not catch overflow caused by the engine's injection — the next LLM call simply fails with a context-limit error.
  • What changed: Added an optional currentTokenCount?: number field to ContextEngine.assemble params, plumbed it through assembleHarnessContextEngine, and wired computation at every production caller: the PI runner main assemble (runEmbeddedAttempt), the PI runner tool-loop hook (installContextEngineLoopHook via the getRuntimeContext callback), and the Codex harness (extensions/codex/src/app-server/run-attempt.ts). estimatePrePromptTokens is re-exported from openclaw/plugin-sdk/agent-harness-runtime so extension harnesses use the same estimator the PI runner uses — defining the semantics once. Docs updated.
  • What did NOT change (scope boundary): Behavior of engines that don't read the new field (it's optional). Semantics or value of tokenBudget. preemptive-compaction logic. No public type was renamed or removed. No new dependency was added.

Change Type (select all)

  • Bug fix
  • Feature
  • Refactor required for the fix
  • Docs
  • Security hardening
  • Chore/infra

Scope (select all touched areas)

  • Gateway / orchestration
  • Skills / tool execution
  • Auth / tokens
  • Memory / storage
  • Integrations
  • API / contracts
  • UI / DX
  • CI/CD / infra

Linked Issue/PR

  • Closes #
  • Related #
  • This PR fixes a bug or regression

No upstream OpenClaw issue. Motivation comes from a downstream context-engine plugin (@byterover/byterover) that hit a real overflow on long sessions and could not implement a precise guard without this field.

Real behavior proof (required for external PRs)

  • Behavior or issue addressed: Context-engine plugins cannot precisely guard their systemPromptAddition against the model's remaining headroom because assemble receives only tokenBudget, not currentTokenCount. After this change, engines can compute remaining = tokenBudget - currentTokenCount - <reserve> and skip injection when the curated content would not fit.
  • Real environment tested: macOS (Darwin 25.2.0), local pnpm workspace, pnpm exec vitest run on the touched test files. Not yet tested against a live model on a long session — verification so far is at the unit/integration-test layer. A follow-up real-session repro on a Gemini 1M-context channel where pre-this-PR overflow was observed is planned before merge.
  • Exact steps or command run after this patch:
cd ~/dpmemories/openclawdp/openclaw
pnpm install
pnpm exec vitest run \
  src/agents/harness/context-engine-lifecycle.test.ts \
  src/agents/pi-embedded-runner/tool-result-context-guard.test.ts \
  src/agents/pi-embedded-runner/run/attempt.spawn-workspace.context-injection.test.ts \
  src/agents/pi-embedded-runner/run/attempt.spawn-workspace.context-engine.test.ts \
  extensions/codex/src/app-server/run-attempt.context-engine.test.ts
  • Evidence after fix:
RUN  v4.1.6 /Users/datpham/dpmemories/openclawdp/openclaw

Test Files  9 passed (9)
     Tests  194 passed (194)
  Duration  19.96s
  • Observed result after fix: New field is plumbed end-to-end across every production assemble path.
    • PI runner main assemble: runEmbeddedAttempt computes preassemblyCurrentTokenCount via estimatePrePromptTokens from { activeSession.messages, systemPromptText, params.prompt } and passes it through assembleAttemptContextEngine.
    • PI runner tool-loop hook: installContextEngineLoopHook reads currentTokenCount from the existing getRuntimeContext() callback. The production install site at attempt.ts:1996 now computes the estimate from the loop messages and systemPromptText (with empty prompt — the continuation is driven by tool results already in messages), so engines see a real value on this path too.
    • Codex harness: extensions/codex/src/app-server/run-attempt.ts:624 computes the same estimate from { historyMessages, developerInstructions, params.prompt } and passes it through assembleHarnessContextEngine.
  • What was not tested: A live overflow scenario with a real LLM provider. The downstream plugin's consumption of this field (which is where the real-world payoff happens) is tracked in a separate plugin PR.
  • Before evidence (optional but encouraged): N/A — this PR adds new capability rather than fixing a behavior already present in OpenClaw.

Root Cause (if applicable)

N/A — this is a capability addition, not a bug fix in OpenClaw. The existing behavior (passing only tokenBudget) is by design.

  • Root cause: N/A
  • Missing detection / guardrail: N/A
  • Contributing context (if known): Plugin authors building context engines that inject systemPromptAddition discovered they had no way to size injection safely. The ContextEngineRuntimeContext type already defined currentTokenCount for other lifecycle hooks (afterTurn, maintain, compact) — assemble was the only one that didn't receive it.

Regression Test Plan (if applicable)

  • Coverage level that should have caught this:
    • Unit test
    • Seam / integration test
    • End-to-end test
    • Existing coverage already sufficient
  • Target test or file:
    • src/agents/harness/context-engine-lifecycle.test.ts — wrapper pass-through (present + absent)
    • src/agents/pi-embedded-runner/tool-result-context-guard.test.ts — tool-loop hook propagation (from runtimeContext, missing-from-context, no-callback)
    • src/agents/pi-embedded-runner/run/attempt.spawn-workspace.context-injection.test.ts — attempt-level alias plumbs the field
    • src/agents/pi-embedded-runner/run/attempt.spawn-workspace.context-engine.test.ts — captures loop-hook params and asserts getRuntimeContext() returns a positive currentTokenCount in production
    • extensions/codex/src/app-server/run-attempt.context-engine.test.ts — Codex harness path now asserts a positive currentTokenCount reaches the engine
  • Scenario the test should lock in: currentTokenCount reaches engine.assemble from every production harness path; field is omitted (not undefined-valued) when no estimate is available, so engines can detect older runtimes.
  • Why this is the smallest reliable guardrail: Each wiring layer (wrapper, PI main computation site, PI loop-hook computation site, Codex computation site, attempt-level re-export) has its own test. Refactoring any one of them without preserving pass-through will fail an existing test.
  • Existing test that already covers this (if any): preemptive-compaction.test.ts already covers the underlying estimatePrePromptTokens helper that produces the value.
  • If no new test is added, why not: N/A (9 new tests / assertions added across 5 test files).

User-visible / Behavior Changes

None for OpenClaw end users. Plugin authors implementing ContextEngine get a new optional currentTokenCount?: number param on assemble. Plugins that do not read it see unchanged behavior. Extension authors gain a new re-export estimatePrePromptTokens on openclaw/plugin-sdk/agent-harness-runtime for use when wiring custom harnesses.

Diagram (if applicable)

Before:
runEmbeddedAttempt          (PI harness — main + loop-hook)
  └─ contextEngine.assemble({ tokenBudget, messages, prompt, ... })

extensions/codex run-attempt (Codex harness)
  └─ contextEngine.assemble({ tokenBudget, messages, prompt, ... })

  (engines have no view of pre-assembly consumed tokens)

After:
runEmbeddedAttempt          (PI harness)
  ├─ main assemble
  │   ├─ estimatePrePromptTokens(messages + systemPrompt + prompt) → N
  │   └─ contextEngine.assemble({ tokenBudget, currentTokenCount: N, ... })
  └─ tool-loop hook (getRuntimeContext callback at install site)
      ├─ estimatePrePromptTokens(loopMessages + systemPrompt + "") → N
      └─ contextEngine.assemble({ tokenBudget, currentTokenCount: N, ... })

extensions/codex run-attempt (Codex harness)
  ├─ estimatePrePromptTokens(historyMessages + developerInstructions + prompt) → N
  └─ contextEngine.assemble({ tokenBudget, currentTokenCount: N, ... })

  (engines can compute remaining = tokenBudget - currentTokenCount - reserve)

Security Impact (required)

  • New permissions/capabilities? No
  • Secrets/tokens handling changed? No
  • New/changed network calls? No
  • Command/tool execution surface changed? No
  • Data access scope changed? No
  • If any Yes, explain risk + mitigation: N/A.

Repro + Verification

Environment

  • OS: macOS Darwin 25.2.0
  • Runtime/container: pnpm 11.x workspace, Node 22, vitest 4.1.6
  • Model/provider: N/A (tests use mocked ContextEngine)
  • Integration/channel (if any): N/A
  • Relevant config (redacted): default tsconfig.json + workspace pnpm-workspace.yaml

Steps

  1. git checkout feat/context-engine-current-token-count
  2. pnpm install
  3. pnpm exec vitest run src/agents/harness/context-engine-lifecycle.test.ts src/agents/pi-embedded-runner/tool-result-context-guard.test.ts src/agents/pi-embedded-runner/run/attempt.spawn-workspace.context-injection.test.ts src/agents/pi-embedded-runner/run/attempt.spawn-workspace.context-engine.test.ts extensions/codex/src/app-server/run-attempt.context-engine.test.ts

Expected

  • All 194 tests across the 9 affected test files pass.
  • git diff --stat origin/main..HEAD shows only the touched source, test, and docs files.

Actual

  • 194/194 tests pass (see Evidence above).

Evidence

  • Failing test/log before + passing after — not applicable; this is a feature addition, no prior failing test existed.
  • Trace/log snippets — vitest summary above.
  • Screenshot/recording
  • Perf numbers (if relevant) — estimatePrePromptTokens is now invoked at each main assemble call site (PI main, Codex) and once per tool-loop iteration (PI loop hook). The helper already runs at the preemptive-compaction precheck on the same turn (PI main path), so the marginal cost there is one extra encode of messages + systemPrompt + prompt. Loop-hook iterations add one encode per iteration. Not measured separately.

Human Verification (required)

  • Verified scenarios:
    • assembleHarnessContextEngine passes currentTokenCount to the engine when supplied.
    • assembleHarnessContextEngine omits the field when caller does not supply it (so engines can detect older runtimes via params.currentTokenCount === undefined).
    • installContextEngineLoopHook reads currentTokenCount from getRuntimeContext() when the callback returns it; omits otherwise; omits when no callback is wired.
    • The production loop-hook install site at attempt.ts:1996 computes currentTokenCount and feeds it into the getRuntimeContext runtime context (asserted by capturing the callback in attempt.spawn-workspace.context-engine.test.ts).
    • The attempt-level assembleAttemptContextEngine re-export still plumbs the field.
    • The Codex harness call at extensions/codex/src/app-server/run-attempt.ts:624 computes a positive currentTokenCount and passes it through (asserted in run-attempt.context-engine.test.ts).
  • Edge cases checked:
    • Missing getRuntimeContext callback in the loop hook → field omitted.
    • getRuntimeContext returns an object without currentTokenCount → field omitted.
    • Older callers that don't supply currentTokenCount → unchanged behavior.
  • What you did NOT verify:
    • End-to-end run against a real LLM provider where pre-this-PR overflow would have occurred. This is the most important real-world signal and will be performed before merge.
    • Performance impact of the additional estimatePrePromptTokens calls under stress (large transcripts, fast tool loops).

Review Conversations

  • I replied to or resolved every bot review conversation I addressed in this PR.
  • I left unresolved only the conversations that still need reviewer or maintainer judgment.

Compatibility / Migration

  • Backward compatible? Yes
  • Config/env changes? No
  • Migration needed? No
  • If yes, exact upgrade steps: N/A. The new field is optional. Existing context engines compile and run unchanged. Engines that want to opt in simply read params.currentTokenCount and gate behavior on whether it is present.

Risks and Mitigations

  • Risk: The additional estimatePrePromptTokens call at each main assemble call site adds one extra token-estimation pass per turn, plus one per tool-loop iteration on the PI loop-hook path.
    • Mitigation: Uses the same helper the runtime already invokes at the preemptive-compaction precheck on the same turn (PI main path), so the marginal cost there is small and amortized. Loop-hook iterations add one encode per iteration; if this proves measurably costly under sustained tool loops, the result can be cached or computed lazily.
  • Risk: Engines that misread the new field (e.g. treat absent as zero) could over-restrict their injection on older runtimes that don't pass the field.
    • Mitigation: Field is explicitly omitted rather than set to undefined or 0 when not supplied (see the ...(typeof x === "number" ? { x } : {}) spread idiom in the wrappers). Engines that follow the documented contract (params.currentTokenCount === undefined ⇒ no headroom info available) behave correctly.
  • Risk: Re-exporting estimatePrePromptTokens from openclaw/plugin-sdk/agent-harness-runtime widens the public extension API by one function and commits us to maintaining its signature.
    • Mitigation: The function is small, pure, and stable — it already exists at its source location and is used internally. Re-exporting just makes the same shape available to extension harnesses. If the internal signature ever needs to change, the barrel re-export can be wrapped at that point.

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: S proof: supplied External PR includes structured after-fix real behavior proof. labels May 12, 2026
@clawsweeper

clawsweeper Bot commented May 12, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge. Reviewed July 8, 2026, 8:21 AM ET / 12:21 UTC.

Summary
The PR adds an optional currentTokenCount parameter to ContextEngine.assemble, threads token-budget estimates through embedded and Codex harness assemble paths, re-exports token-budget helpers, and updates docs/tests.

PR surface: Source +85, Tests +180, Docs +37. Total +302 across 13 files.

Reproducibility: not applicable. this is a new optional context-engine/plugin SDK capability rather than a reported current-main bug reproduction.

Review metrics: 1 noteworthy metric.

  • Public Plugin API Surface: 1 assemble parameter added, 2 SDK runtime exports added. Third-party context-engine/plugin authors may depend on these contracts, so API approval and baseline updates matter before merge.

Merge readiness
Overall: 🦪 silver shellfish
Proof: 🦪 silver shellfish
Patch quality: 🦐 gold shrimp
Result: blocked until real behavior proof from a real setup is added.

Overall follows the weaker of proof and patch quality, so missing proof can cap an otherwise strong patch.

Rank-up moves:

  • [P1] Post redacted live output, logs, or an artifact showing a real long-session/downstream context-engine run using currentTokenCount after the fix.
  • [P1] Align currentTokenCount with the exact stripped message set passed to assemble and add focused regression coverage for hidden runtime-context custom messages.
  • Regenerate and commit the plugin SDK API baseline for the new exports.

Proof guidance:

  • [P1] Needs real behavior proof before merge: The PR body supplies unit/integration test output only and explicitly says the live long-session/provider scenario has not been tested; add redacted live output, logs, recording, or an artifact before merge. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.

Risk before merge

  • [P1] This PR changes the public context-engine/plugin SDK contract, so merging without maintainer API approval can lock third-party engines into this narrower headroom shape while the broader assemble metadata RFC remains open.
  • [P1] The PR body still provides only unit/integration test output and explicitly says the live long-session/downstream context-engine scenario has not been tested.
  • [P1] The branch is behind current main, so the final merge review should refresh after the patch findings and proof gap are addressed.

Maintainer options:

  1. Approve API After Repair And Proof (recommended)
    Accept the narrow public contract only after the count alignment, SDK baseline, and redacted live long-session proof are all present.
  2. Fold Into Broader Metadata
    Pause or close this branch if maintainers want token counts to ship with the broader provenance/internal-event assemble metadata design.
  3. Accept Contract Risk Explicitly
    Merge the API shape as-is only if maintainers explicitly accept the baseline/proof debt and possible third-party contract drift as follow-up work.

Next step before merge

  • [P1] Human review remains because the public plugin API direction and contributor live proof cannot be supplied by an automated repair, even though the two code blockers are mechanically clear.

Maintainer decision needed

  • Question: Should OpenClaw accept currentTokenCount plus the new SDK token-budget helpers as a stable public ContextEngine/plugin SDK contract now, or fold this signal into the broader assemble metadata design tracked at RFC: Expose existing InputProvenance / AgentInternalEvent signals to ContextEngine.assemble() #82137?
  • Rationale: The patch changes a public plugin API that third-party context engines may compile against, while the broader assemble metadata shape is still unresolved and the current patch still needs mechanical fixes and real proof.
  • Likely owner: jalehman — They are assigned and have the strongest recent merged history on the context-engine budget path affected by this decision.
  • Options:
    • Accept Narrow Contract After Fixes (recommended): Approve currentTokenCount as a separate backward-compatible API after the two patch blockers are fixed and redacted live behavior proof is added.
    • Fold Into RFC: Pause this PR and land token counts together with the broader provenance/internal-event assemble metadata contract.
    • Keep Helpers Private For Now: Remove the SDK helper exports and defer public helper exposure until maintainers settle the permanent plugin API shape.

Security
Cleared: The diff changes TypeScript API plumbing, docs, and tests without workflows, dependency sources, lockfiles, secrets handling, package resolution, or downloaded code.

Review findings

  • [P2] Count the same messages assemble receives — src/agents/harness/context-engine-lifecycle.ts:165-167
  • [P2] Regenerate the SDK API baseline — src/plugin-sdk/agent-harness-runtime.ts:360-362
Review details

Best possible solution:

Land a maintainer-approved assemble headroom contract only after the count is derived from the exact messages visible to assemble, the SDK baseline is regenerated, and redacted live long-session plugin proof is posted.

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

Not applicable: this is a new optional context-engine/plugin SDK capability rather than a reported current-main bug reproduction.

Is this the best way to solve the issue?

No: the narrow API is plausible, but this patch still misaligns currentTokenCount with the message set visible to assemble and needs maintainer API approval, SDK baseline regeneration, and live proof.

Full review comments:

  • [P2] Count the same messages assemble receives — src/agents/harness/context-engine-lifecycle.ts:165-167
    assembleHarnessContextEngine strips hidden runtime-context custom messages before calling the engine, but the new currentTokenCount is computed by callers from the unstripped array and then forwarded unchanged here. On turns with runtime-context carriers, engines using tokenBudget - currentTokenCount can see less headroom than the delivered messages actually consume, so derive the estimate from the stripped messages or have the wrapper own both values together.
    Confidence: 0.87
  • [P2] Regenerate the SDK API baseline — src/plugin-sdk/agent-harness-runtime.ts:360-362
    This PR adds public exports on openclaw/plugin-sdk/agent-harness-runtime, but the generated plugin SDK API baseline/hash is not updated and check-docs is failing. Regenerate and commit the SDK API baseline so the public surface change is intentional and the API check does not drift.
    Confidence: 0.88

Overall correctness: patch is incorrect
Overall confidence: 0.88

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 4bf70be01a21.

Label changes

Label justifications:

  • P2: This is a bounded context-engine/plugin SDK feature with limited blast radius but merge-relevant API, proof, and correctness requirements.
  • merge-risk: 🚨 compatibility: The PR changes the public context-engine/plugin SDK contract by adding an assemble parameter and SDK runtime exports.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish and patch quality is 🦐 gold shrimp.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask. Needs real behavior proof before merge: The PR body supplies unit/integration test output only and explicitly says the live long-session/provider scenario has not been tested; add redacted live output, logs, recording, or an artifact before merge. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
Evidence reviewed

PR surface:

Source +85, Tests +180, Docs +37. Total +302 across 13 files.

View PR surface stats
Area Files Added Removed Net
Source 7 104 19 +85
Tests 5 181 1 +180
Docs 1 40 3 +37
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 13 325 23 +302

What I checked:

  • Repository policy read: Root AGENTS.md and scoped docs/extensions/agents/plugin-sdk guides were read; the plugin SDK compatibility and Codex-source inspection rules apply because this PR changes src/plugin-sdk/* and extensions/codex/*. (AGENTS.md:29, 4bf70be01a21)
  • Current main assemble contract: Current main exposes currentTokenCount on other context-engine lifecycle surfaces, but ContextEngine.assemble still accepts only messages, tokenBudget, tools, citations, model, prompt, and runtimeSettings. (src/context-engine/types.ts:426, 4bf70be01a21)
  • PR head strips messages but forwards caller count unchanged: PR head strips hidden runtime-context custom messages before calling contextEngine.assemble, then forwards params.currentTokenCount unchanged, so the count can describe a larger message set than the engine receives. (src/agents/harness/context-engine-lifecycle.ts:158, 65deda82e458)
  • PR head computes count before the wrapper strip: The embedded main assemble path computes preassemblyCurrentTokenCount from activeSession.messages before passing those same raw messages to the wrapper that strips hidden runtime-context messages. (src/agents/embedded-agent-runner/run/attempt.ts:3390, 65deda82e458)
  • Estimator includes fallback content: estimateTranscriptTokenPressure sums estimateMessageTokenPressure, whose fallback counts record.content; hidden custom runtime-context carriers are therefore included unless callers strip them first. (src/agents/embedded-agent-runner/run/preemptive-compaction.ts:296, 65deda82e458)
  • API baseline not updated: PR head adds public exports on openclaw/plugin-sdk/agent-harness-runtime, but the tracked generated API-baseline hash is not changed and live PR status shows check-docs failing. (src/plugin-sdk/agent-harness-runtime.ts:360, 65deda82e458)

Likely related people:

  • jalehman: Assigned to the PR, authored the branch rebase commits, and authored merged context-engine token-budget/runtime-context PRs on the same surface. (role: recent area contributor and likely follow-up owner; confidence: high; commits: 75e7fc97f804, d5e9b4d1a32f; files: src/context-engine/types.ts, src/agents/embedded-agent-runner/run/attempt.ts, extensions/codex/src/app-server/run-attempt.ts)
  • vincentkoc: Authored the runtime-context filtering change that makes context-engine hooks receive stripped messages, which is central to the current count-alignment blocker. (role: recent adjacent harness contributor; confidence: medium; commits: b3ab3cde96e7, cc083e5f4fe0; files: src/agents/harness/context-engine-lifecycle.ts, src/agents/harness/context-engine-lifecycle.test.ts)
  • danhdoan: Authored the prior additive prompt?: string parameter on ContextEngine.assemble, the closest merged API-shape precedent for this PR. (role: adjacent assemble-contract contributor; confidence: medium; commits: e78129a4d93e; files: src/context-engine/types.ts)
What the crustacean ranks mean
  • 🦀 challenger crab: rare, exceptional readiness with strong proof, clean implementation, and convincing validation.
  • 🦞 diamond lobster: very strong readiness with only minor maintainer review expected.
  • 🐚 platinum hermit: good normal PR, likely mergeable with ordinary maintainer review.
  • 🦐 gold shrimp: useful signal, but proof or patch confidence is still limited.
  • 🦪 silver shellfish: thin signal; proof, validation, or implementation needs work.
  • 🧂 unranked krab: not merge-ready because proof is missing/unusable or there are serious correctness or safety concerns.
  • 🌊 off-meta tidepool: rating does not apply to this item.

Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

How this review workflow works
  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.
Review history (3 earlier review cycles)
  • reviewed 2026-07-04T03:47:10.751Z sha b7aa56b :: needs real behavior proof before merge. :: [P2] Regenerate the SDK API baseline
  • reviewed 2026-07-06T23:49:11.290Z sha 65deda8 :: needs real behavior proof before merge. :: [P2] Regenerate the SDK API baseline
  • reviewed 2026-07-08T03:07:05.032Z sha 65deda8 :: needs real behavior proof before merge. :: [P2] Count the same messages assemble receives | [P2] Regenerate the SDK API baseline

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation extensions: codex labels May 12, 2026
@DatPham-6996

Copy link
Copy Markdown
Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented May 12, 2026

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

@DatPham-6996

Copy link
Copy Markdown
Author

Hi @jalehman could you please help me review this PR ?

@DatPham-6996

Copy link
Copy Markdown
Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented May 12, 2026

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

Re-review progress:

@DatPham-6996

Copy link
Copy Markdown
Author

Addressed [P2] in 14d6dca26d.

The production loop-hook install site at src/agents/pi-embedded-runner/run/attempt.ts:1996 now computes currentTokenCount via estimatePrePromptTokens({ messages, systemPrompt: systemPromptText, prompt: "" }) and passes it through buildAfterTurnRuntimeContext, so the loop-hook pass-through added in the previous commit now receives a real estimate in production rather than undefined.

prompt: "" mid-loop because the continuation is driven by tool results that are already appended to messages — there's no new user prompt for those iterations.

Test: new test in src/agents/pi-embedded-runner/run/attempt.spawn-workspace.context-engine.test.ts ("populates currentTokenCount in the loop-hook getRuntimeContext callback") captures the loop-hook params, invokes the captured getRuntimeContext with synthetic loop messages, and asserts the returned runtime context contains currentTokenCount as a positive number. This locks in the wiring at the install site so a regression there fails the test.

Tally: 194/194 tests pass on the touched files. PR description updated to reflect the new bullet, target test file, and counts.

Real behavior proof from a live long-session run is still pending and will be posted before merge.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented May 12, 2026

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

Re-review progress:

@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 May 27, 2026
@clawsweeper clawsweeper Bot added the rating: 🌊 off-meta tidepool PR readiness rating does not apply to this item. label May 27, 2026
@clawsweeper

clawsweeper Bot commented May 27, 2026

Copy link
Copy Markdown
Contributor

ClawSweeper PR egg: 🎁 locked until real behavior proof passes.

Details
  • No creature or rarity is rolled until proof passes.
  • Eggs are collectible flavor only; they do not affect labels, ratings, merge decisions, or automation.

@openclaw-barnacle openclaw-barnacle Bot removed the stale Marked as stale due to inactivity label May 28, 2026
@clawsweeper clawsweeper Bot added 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. P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. and removed rating: 🌊 off-meta tidepool PR readiness rating does not apply to this item. labels May 28, 2026
@jalehman jalehman self-assigned this Jul 6, 2026
jalehman added 2 commits July 6, 2026 16:03
tokenBudget passed to ContextEngine.assemble now means the same thing on
every harness path: the budget available for assembled messages, computed
by the shared computeContextEngineMessageBudget helper (context window
minus compaction reserve minus rendered system/user prompt pressure).
currentTokenCount is now a messages-only estimate
(estimateTranscriptTokenPressure), so engines size systemPromptAddition
as tokenBudget - currentTokenCount with no double-counting.

- PI main assemble: budget block now uses the shared helper; count is
  messages-only
- PI tool loop: new assembleTokenBudget hook param carries the loop
  budget; afterTurn keeps the raw window per its contract; the hook
  resolves getRuntimeContext once per iteration instead of twice
- Codex harness: derives the budget with reserve 0 (native compaction
  owns the reserve concept there)
- plugin SDK re-exports both helpers instead of the removed
  estimatePrePromptTokens alias; docs and interface comments updated
@jalehman
jalehman force-pushed the feat/context-engine-current-token-count branch from b7aa56b to 65deda8 Compare July 6, 2026 23:23
@openclaw-barnacle

Copy link
Copy Markdown

This assigned pull request has been automatically marked as stale after being open for 27 days.
Please add updates or it will be closed.

@openclaw-barnacle openclaw-barnacle Bot added the stale Marked as stale due to inactivity label Jul 7, 2026
@clawsweeper clawsweeper Bot added 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 Jul 8, 2026
@openclaw-barnacle openclaw-barnacle Bot removed the stale Marked as stale due to inactivity label Jul 8, 2026
@openclaw-barnacle

Copy link
Copy Markdown

This assigned pull request has been automatically marked as stale after being open for 27 days.
Please add updates or it will be closed.

@openclaw-barnacle openclaw-barnacle Bot added the stale Marked as stale due to inactivity label Jul 8, 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 extensions: codex merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. proof: supplied External PR includes structured after-fix real behavior proof. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. size: M 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.

2 participants