Skip to content

fix(agents): deliver token-limited partial replies instead of discarding them - #123546

Merged
sallyom merged 7 commits into
openclaw:mainfrom
davenicoll:fix/length-stop-discards-visible-text
Aug 15, 2026
Merged

sallyom merged 7 commits into
openclaw:mainfrom
davenicoll:fix/length-stop-discards-visible-text

Conversation

@davenicoll

@davenicoll davenicoll commented Aug 14, 2026 •

Copy link
Copy Markdown
Contributor

Related: #94176
Related: #63188
Related: #63210
Related: #119259

What Problem This Solves

Fixes an issue where users whose reply hits the model's output token limit see
⚠️ Agent couldn't generate a response. Please try again. instead of the answer
the model already wrote. Everything the assistant produced in that turn is
thrown away, the run is recorded as abandoned, and the transcript is marked
replay-invalid — so retrying restarts the work rather than continuing it.

This is worse the more useful the answer was: long answers are exactly the ones
that hit the limit, and they are the ones that get deleted.

Why This Change Was Made

isIncompleteTerminalAssistantTurn() already accepted a hasAssistantVisibleText
parameter and callers already passed it, but the length branch never read it:

return stopReason === "toolUse" || (stopReason === "length" && !params.hasTerminalOutput);

So a length stop with visible text and no terminal tool output was classified
as an incomplete turn, and resolveIncompleteTurnPayloadText() replaced the
payloads with the failure notice.

A length stop is genuinely different from toolUse: no continuation is
pending, and whatever text the model emitted is the answer so far. The fix
respects the parameter, so a length stop is incomplete only when there is
nothing to show, and completeEmbeddedRun() appends a one-line truncation
notice to the partial payloads so a cut-off answer is not mistaken for a
complete one.

One predicate now governs all three boundaries — a length stop with no
terminal output and nothing delivered:

  • isIncompleteTerminalAssistantTurn() — classification.
  • completeEmbeddedRun() — the truncation notice.
  • resolveAttemptTrajectoryTerminal() — the durable trajectory record.

Scope is deliberately narrow. The only behavior that changes is
stopReason === "length" and visible text and no terminal tool output.
toolUse turns are untouched. Turns that already had terminal tool
media/output were already treated as complete, and they stay complete and
notice-free: the notice is gated on !hasAttemptTerminalState(attempt), so a
length stop that also produced tool media or a committed source reply does not
gain an extra text reply telling the user to ask for a continuation. The notice
additionally requires nonblank assistant text (streamed, or from the terminal
assistant message), so a cron turn whose only payload is the synthesized silent
result of a successful tool stays silent.

The classifier has four call sites. Two of them
(isEmptyResponseAssistantTurn, isNonVisibleAssistantTurnEligibleForSilentReply
in the same file) hardcode hasAssistantVisibleText: false, so they are
unaffected. The other two pass the real value and both change for that single
case, consistently: resolveIncompleteTurnPayloadText() stops replacing the
payloads, and handleAgentEnd() in embedded-agent-subscribe.handlers.lifecycle.ts
stops marking the turn replayInvalid / abandoned — which is what makes the
delivered partial answer replayable instead of a dead end.

resolveAttemptTrajectoryTerminal() is included so durable state cannot
contradict what the user received. It previously recorded
terminalError: "non_deliverable_terminal_turn" for every length turn without
terminal output, including the ones this PR now delivers. It now keys on visible
assistant text, the same fact the delivery owner keys on.

Visible text rather than payload count, deliberately: attempt finalization runs
before terminal-preparation.ts turns assistant text into payloads, so
synthesizedPayloadCount is still 0 for an ordinary text-only truncated reply
(it counts block replies, tool media, source-reply payloads, and silent-tool
payloads). Keying on it would have left the headline case still recorded as an
error while the reply was delivered. A length stop with nothing visible to show
— whitespace-only text included — stays non-deliverable.

Files changed:

  • src/agents/embedded-agent-runner/run/incomplete-turn-classification.ts —
    the classifier respects hasAssistantVisibleText.
  • src/agents/embedded-agent-runner/run/incomplete-turn-resolution.ts —
    adds TRUNCATED_REPLY_NOTICE_TEXT.
  • src/agents/embedded-agent-runner/run/terminal-resolution.ts — appends the
    notice on the success path when the turn stopped at the output limit and has
    no terminal output.
  • src/agents/embedded-agent-runner/run/attempt-trajectory-status.ts — the
    trajectory record agrees with the delivered result.

Related history: #76544 introduced the hasAssistantVisibleText parameter for
the toolUse case and left it unread by the length case; #112022 is the
precedent for emitting a notice instead of discarding output. #119259 was closed
as already-implemented on reasoning this bug invalidates.

User Impact

A reply that runs out of output budget now arrives, followed by:

⚠️ Reply truncated at the model's output token limit. The text above is
partial — ask to continue it.

The run stays working rather than abandoned, the transcript stays
replayable, and trajectory data records the turn as a success, so "continue
that" works instead of starting over. Turns that stopped at the limit with
nothing to show still surface the existing incomplete-turn warning, unchanged.

Evidence

Runtime behavior, before and after

Observed on a live deployment running this OpenClaw version, before the fix —
gateway log, redacted:

[agent/embedded] incomplete turn detected: runId=<redacted> sessionId=<redacted>
provider=<provider>/<model> stopReason=length hasLastAssistant=yes
hasCurrentAttemptAssistant=yes payloads=1 tools=0 replaySafe=yes compactions=0
reasoningRetries=0/2 emptyRetries=0/1 missingAssistantRetries=0/1
— surfacing error to user

The user saw only:

⚠️ Agent couldn't generate a response. Note: some tool actions may have
already been executed — please verify before retrying.

hasLastAssistant=yes with payloads=1 is the defect in one line: the reply
existed and was discarded anyway. 20 occurrences in 21 hours on that deployment.

After the fix, same deployment. A length stop was forced cheaply instead of
generating a 128K reply, using a temporary provider route with
maxTokens: 400 and reasoning disabled, then prompting for a 4,000-word essay:

executionTrace.result: "success"
meta.completion.stopReason: "length"
meta.error:          null
meta.replayInvalid:  false
meta.livenessState:  "working"
payloads[0]: 1123 chars of the essay prose, isError unset
payloads[1]: the 124-char truncation notice

Two such runs, both identical in shape, and zero incomplete turn detected
lines for them — previously one per occurrence. The delivered payload shape is
byte-for-byte the same as a normal successful reply, checked against a control
run.

Disclosure on how that observation was produced: the deployment runs a published
build, so the two edits were applied to the installed bundle of the same version
rather than to a source checkout. This branch is the source-level port of those
same two edits, plus the notice gating and trajectory alignment added in review;
the tests below are what verify the port itself.

Focused tests

npx vitest run \
  src/agents/embedded-agent-runner/run/terminal-resolution.test.ts \
  src/agents/embedded-agent-runner/run/attempt-trajectory-status.test.ts \
  src/agents/embedded-agent-runner/run/attempt-result.test.ts \
  src/agents/embedded-agent-runner/run/settled-tool-evidence.test.ts \
  src/agents/embedded-agent-runner/run/incomplete-turn-resolution.test.ts \
  src/agents/embedded-agent-runner/run.incomplete-turn.delivery-resolution.test.ts \
  src/agents/embedded-agent-runner/run.incomplete-turn.classification.test.ts \
  src/agents/embedded-agent-runner/run.overflow-context-recovery.test.ts
# Test Files 13 passed (13) — Tests 266 passed (266)

New coverage:

  • terminal-resolution.test.ts — end-to-end: a length stop with visible text
    resolves to complete with the partial payload plus the notice, no
    meta.error, livenessState: "working".
  • terminal-resolution.test.ts — a length stop that already has terminal tool
    media delivers its payloads with no notice appended.
  • terminal-resolution.test.ts — a length stop with no visible text still
    yields meta.error.kind === "incomplete_turn" and livenessState: "abandoned".
  • terminal-resolution.test.ts — a length-stopped cron turn whose only payload
    is the synthesized silent tool result keeps that single NO_REPLY payload with
    no notice appended.
  • embedded-agent-subscribe.handlers.lifecycle.test.ts — a length stop whose
    visible text was never streamed (empty assistantTexts, text on the completed
    assistant message) stays working rather than abandoned, matching the
    completed-assistant fallback that payload building already applies; one with
    neither stays abandoned / replayInvalid.
  • attempt-trajectory-status.test.ts — a delivered length partial records
    status: "success" even with synthesizedPayloadCount: 0, which is the real
    finalization-time state for a text-only reply; a length stop with no visible
    text, and one with whitespace-only text, both still record
    non_deliverable_terminal_turn.
  • settled-tool-evidence.test.ts — the classifier matrix now pins both
    length outcomes.
  • run.incomplete-turn.delivery-resolution.test.ts — the existing
    token-limited-partial-answer case now asserts the answer is deliverable, and a
    new case pins the no-visible-text path.

Every new assertion was checked against pre-fix main and fails there.

Also run: pnpm tsgo:core clean; targeted oxlint --type-aware clean on all
changed files. Rebased onto current main — the earlier red CI on this PR was a
known main failure at the old base
(replyOperation.bindToolAuthorityFingerprint is not a function in
auto-reply/reply and gateway/server-methods, unrelated to these files), which
reproduces at the old base commit and passes on current main.

AI-assisted: written with Claude, from a production incident report. The full
diff and reasoning have been reviewed by hand.

@clawsweeper

clawsweeper Bot commented Aug 14, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: S labels Aug 14, 2026
@clawsweeper clawsweeper Bot added merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P1 High-priority user-facing bug, regression, or broken workflow. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Aug 14, 2026
@clawsweeper

clawsweeper Bot commented Aug 14, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed August 15, 2026, 3:31 PM ET / 19:31 UTC.

ClawSweeper review

What this changes

The PR delivers visible embedded-agent text stopped by a model output limit, adds a truncation notice, and records the partial reply as replayable success.

Regression provenance

Possible regression — probable (reviewed change; failure trace). No predecessor PR is attributed.

Merge readiness

⚠️ Ready for maintainer review - 2 items remain

Keep this PR open for normal maintainer merge handling: current main and the latest release still discard this class of reply, while the exact head resolves the delivery, replay, and trajectory disagreement with no remaining code finding.

Priority: P1
Reviewed head: 9fe47b621c275b0f6d87dd6d50eb916cbc987504

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused, behavior-backed bug fix with no remaining review finding; exact-head CI is the remaining merge gate.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (logs): The PR body includes redacted production before/after logs showing the central token-limit case changing from an incomplete-turn error to partial text plus a notice; source-port coverage verifies the remaining gates.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (logs): The PR body includes redacted production before/after logs showing the central token-limit case changing from an incomplete-turn error to partial text plus a notice; source-port coverage verifies the remaining gates.
Evidence reviewed 6 items Current-main defect: The classifier accepts visible-text input but the length branch ignores it, so a length-stopped visible reply remains incomplete.
Delivery caller: Current main passes the payload count into incomplete-turn classification, allowing the ignored visible-text fact to result in replacement error copy.
Phase-boundary repair: The PR preserves tool-use handling, delivers text-only length stops with a notice, and uses visible text before payload preparation to keep trajectory state consistent.
Findings None None.
Security None None.

How this fits together

Embedded-agent runs convert terminal model messages into reply payloads, lifecycle events, and durable trajectory state. A token-limit stop passes through classification before payload delivery, with its result later used for session replay and diagnostics.

flowchart LR
  A[Model reaches output limit] --> B[Terminal turn classification]
  B --> C[Payload preparation]
  C --> D[Partial reply and notice]
  B --> E[Lifecycle replay state]
  E --> F[Trajectory record]
Loading

Before merge

  • Resolve merge risk (P1) - The bug fix adds 54 net production lines across three ordered phases; the phase-local checks are justified because trajectory finalization precedes payload construction, but exact-head CI remains required before merge.
  • Complete next step (P2) - The latest maintainer note already owns the rebase and exact-head CI step; there is no discrete repair task to dispatch.
Agent review details

Security

None.

PR surface

Source +54, Tests +233. Total +287 across 11 files.

View PR surface stats
Area Files Added Removed Net
Source 5 64 10 +54
Tests 6 240 7 +233
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 11 304 17 +287

Review metrics

Metric Value Why it matters
Production versus test LOC production +64/-10 (net +54); tests +240/-7 (net +233) The production growth is limited to three phase-local decisions and the remainder is regression coverage for delivery, lifecycle, and durable-state agreement.

Merge-risk options

Maintainer options:

  1. Decide the mitigation before merge
    Merge the narrow phase-local repair after exact-head CI is green; keep the separate checks because a shared post-payload predicate would misclassify the earlier lifecycle and trajectory phases.
  2. Pause or close
    Do not merge this PR until maintainers decide whether the risk is worth taking.

Technical review

Best possible solution:

Merge the narrow phase-local repair after exact-head CI is green; keep the separate checks because a shared post-payload predicate would misclassify the earlier lifecycle and trajectory phases.

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

Yes in source: current main classifies a length-stopped reply as incomplete even after visible text exists, and the PR body supplies matching redacted before/after runtime logs.

Is this the best way to solve the issue?

Yes: the repair updates the owning classification, delivery, lifecycle, and trajectory boundaries rather than adding a downstream fallback; tool-use semantics remain unchanged.

AGENTS.md: found and applied where relevant.

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

Labels

Label justifications:

  • P1: This fixes visible replies being discarded and marked unreplayable when model output reaches its token limit.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (logs): The PR body includes redacted production before/after logs showing the central token-limit case changing from an incomplete-turn error to partial text plus a notice; source-port coverage verifies the remaining gates.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR body includes redacted production before/after logs showing the central token-limit case changing from an incomplete-turn error to partial text plus a notice; source-port coverage verifies the remaining gates.

Evidence

What I checked:

Likely related people:

  • amknight: Merged the related predecessor that established the incomplete tool-use contract this PR preserves. (role: feature-history owner; confidence: high; commits: a92e2b13b8b8; files: src/agents/embedded-agent-runner/run/incomplete-turn-classification.ts, src/agents/embedded-agent-subscribe.handlers.lifecycle.ts)
  • sallyom: Assigned the PR, rebased it onto current main, and requested exact-head CI preparation in the latest maintainer note. (role: recent integration contact; confidence: medium; files: src/agents/embedded-agent-runner/run/terminal-resolution.ts, src/agents/embedded-agent-subscribe.handlers.lifecycle.ts)
  • steipete: Current-main blame assigns the relocated classifier and trajectory lines to the available grafted commit, though its unrelated subject makes semantic ownership uncertain. (role: current-file provenance contact; confidence: low; commits: 939aa7dddc28; files: src/agents/embedded-agent-runner/run/incomplete-turn-classification.ts, src/agents/embedded-agent-runner/run/attempt-trajectory-status.ts)

Rank-up moves

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

  • Let exact-head CI finish on the maintainer-rebased head before merge.

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
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.

Workflow

  • 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.

History

Review history (10 earlier review cycles; latest 8 shown)
  • reviewed 2026-08-14T14:59:14.988Z sha f4fa98f170c0b6a39dc29906c9fef4029726537f :: needs changes before merge. :: [P1] Record delivered partial text as successful
  • reviewed 2026-08-14T15:28:57.706Z sha f4fa98f170c0b6a39dc29906c9fef4029726537f :: needs changes before merge. :: [P1] Record visible length partials as successful
  • reviewed 2026-08-14T15:41:42.608Z sha 8fbf2626d91e800d79b42be68822fa755c0e9679 :: needs changes before merge. :: [P1] Preserve replayability for canonical text fallbacks
  • reviewed 2026-08-14T15:53:56.379Z sha be714724a1ecc2c41b208682a651cb68079c8b9d :: needs changes before merge. :: [P1] Use fallback assistant text for lifecycle classification
  • reviewed 2026-08-14T16:30:39.192Z sha f7f6522e3c1c55d4adb974fcd72ffce368b862f6 :: needs changes before merge. :: [P2] Require visible assistant text for the truncation notice | [P2] Remove the checked-in review transcript
  • reviewed 2026-08-14T17:37:04.157Z sha ddd475b3051bf0c32821e3aa9856efd29a6537cd :: needs maintainer review before merge. :: none
  • reviewed 2026-08-14T17:51:48.073Z sha c01017f6a614816b06e20f95bd54bb33dc3dc8fd :: needs maintainer review before merge. :: none
  • reviewed 2026-08-15T19:22:29.598Z sha 9fe47b6 :: needs maintainer review before merge. :: none

@davenicoll
davenicoll force-pushed the fix/length-stop-discards-visible-text branch from 5a951b8 to 4a21c99 Compare August 14, 2026 14:35
@davenicoll

Copy link
Copy Markdown
Contributor Author

Thanks — both findings were correct and both are now fixed in 4a21c99f13d14a7e5058db5dd89f876816261752. The branch is also rebased onto current main. Point by point:

[P2] Restrict the truncation notice to partial text — agreed, this was a real overreach. The notice keyed only on stopReason, so a length stop that already had terminal output (tool media, a committed source reply, an accepted spawn) was a complete outcome before this PR and would have gained an extra reply telling the user to ask for a continuation. It is now gated on the same evidence the classifier uses, !hasAttemptTerminalState(attempt), in run/terminal-resolution.ts. New regression: "does not add a truncation notice to a length stop that already has terminal output" in run/terminal-resolution.test.ts, which asserts a length stop with toolMediaUrls delivers its payloads unchanged.

[P2] Align trajectory status with delivered length replies — agreed, and folded in rather than left out of scope. resolveAttemptTrajectoryTerminal() (run/attempt-trajectory-status.ts:132) recorded non_deliverable_terminal_turn for every length turn without terminal output, including the ones this PR now delivers, so the durable record contradicted the delivered reply.

One note on how I aligned it, in case you'd have chosen differently. Rather than keying the trajectory branch on assistant text, I keyed it on synthesizedPayloadCount === 0 — the trajectory-side analogue of the payloadCount > 0 the delivery owner passes as hasAssistantVisibleText (run/terminal-resolution.ts:250 → run/incomplete-turn-resolution.ts:57). That makes the two boundaries agree on exactly the same evidence: non-deliverable iff nothing was actually delivered. The practical difference is the existing test "marks length-limited visible text as non-deliverable without terminal output" (attempt-trajectory-status.test.ts:49), which has assistantTexts but no synthesized payload. It keeps its current non_deliverable_terminal_turn expectation, because nothing reached the user in that case. Only "does not treat streamed partial payloads as completed length-limited output" flipped, and it flipped precisely because that case — synthesizedPayloadCount: 1 — is the delivered partial this PR fixes. It is renamed to "records a delivered length-limited partial payload as success".

Real behavior proof — added to the PR body under Evidence, with the redacted before/after runtime output: the pre-fix incomplete turn detected gateway line showing stopReason=length hasLastAssistant=yes payloads=1 (the reply existed and was discarded), and the post-fix run shape (executionTrace.result: "success", meta.error: null, replayInvalid: false, livenessState: "working", payloads[0] real prose + payloads[1] the notice, and zero incomplete turn detected lines). The length stop was forced with a low maxTokens route rather than by generating a 128K reply.

I've disclosed the limit of that proof in the body rather than overstating it: the deployment runs a published build, so the observation came from applying the same two edits to the installed bundle of that version, not from running this branch in production. The branch is the source-level port, and the tests are what verify the port.

Acceptance criteria — pnpm tsgo:core clean and the focused suite green (13 files / 266 tests, including terminal-resolution.test.ts, attempt-trajectory-status.test.ts, attempt-result.test.ts). Every new assertion was checked against pre-fix main and fails there.

On the earlier red CI: those failures were not from this change. replyOperation.bindToolAuthorityFingerprint is not a function in auto-reply/reply and the gateway/server-methods steering failures reproduce at the old base commit 73e2489a5e and pass on current main; check-lint was cancelled by the runner (exit 143), not a lint error. The rebase should clear all of them.

On the +13 net production lines: the predicate is now centralized in the sense that matters — all three boundaries key on the same signals — but they are three separate owners (classification, terminal delivery, trajectory finalization) that receive their evidence from different params, and finalization runs before terminal resolution. Extracting a shared helper would mean threading attempt into the trajectory resolver, which currently takes only flattened signals. Happy to do that if a maintainer prefers one exported predicate; it seemed like more coupling than a bug fix should introduce.

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Aug 14, 2026
@davenicoll

Copy link
Copy Markdown
Contributor Author

CI status after the rebase, for the record: 87 checks pass, 0 test failures. The pre-rebase test failures were the stale base and are gone.

One extra commit was needed, f4fa98f170c0b6a39dc29906c9fef4029726537f: embedded-agent-subscribe.handlers.lifecycle.test.ts still pinned "marks token-limited terminal text as abandoned before runner finalization". That is the second real-value classifier call site, so it had to flip — a delivered partial reply must not be abandoned / replayInvalid, which is what makes "continue that" work. Renamed to "keeps token-limited terminal text replayable before runner finalization". Its sibling case with pending tool media is unchanged and still asserts abandoned, since that turn has terminal output.

The one remaining red check is check-lint, and I don't believe it is actionable from this branch: the oxlint:core shard hit its wall-clock limit (timed out after 1452s; terminating shard), the runner was then terminated ([oxlint] FAILED (exit 143), The runner has received a shutdown signal), and the log contains no lint diagnostic for any file. The same job died the same way on the pre-rebase run. Locally, node scripts/run-oxlint.mjs --type-aware over all six changed files is clean, and pnpm tsgo:core and pnpm tsgo:test:src both exit 0. Happy to rerun it if a maintainer retriggers the job.

@davenicoll

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review — both findings are addressed (4a21c99f13d14a7e5058db5dd89f876816261752, f4fa98f170c0b6a39dc29906c9fef4029726537f) and the branch is rebased onto current main. The two merge-risk labels should no longer apply: the truncation notice is gated on !hasAttemptTerminalState(attempt) so it cannot follow terminal media or a committed source reply, and resolveAttemptTrajectoryTerminal() now records a delivered length partial as success instead of non_deliverable_terminal_turn. Both have regression coverage.

@clawsweeper

clawsweeper Bot commented Aug 14, 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 exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. labels Aug 14, 2026
@davenicoll

Copy link
Copy Markdown
Contributor Author

You were right and my previous fix was wrong — fixed in 8fbf2626d91e800d79b42be68822fa755c0e9679.

I keyed the trajectory guard on synthesizedPayloadCount === 0 on the assumption it was the finalization-side analogue of the payloadCount > 0 the delivery owner passes as hasAssistantVisibleText. It isn't. attempt-result.ts:366 builds that count from visibleBlockReplyCount + pendingToolMediaPayloadCount + messagingToolSourceReplyPayloads.length + silentToolResultReplyPayload, and none of those is the ordinary final assistant text — that text only becomes a payload later, in terminal-preparation.ts (payloads → mergeAttemptToolMediaPayloads → payloadsWithToolMedia), which attempt-finalize.ts runs after recording the trajectory. So for a plain text-only truncated reply — the exact case this PR exists to fix — the count is 0 and my guard left the durable record as non_deliverable_terminal_turn while the reply was delivered. The contradiction you originally flagged was still there, just narrowed to the common path. My reasoning for preserving the old test expectation was built on the same wrong premise.

It now keys on visible assistant text, which is the canonical fact and is already resolved at that boundary via resolveTerminalAssistantTexts() in attempt-finalize.ts:84:

const hasVisibleAssistantOutput =
  hasNonEmptyAssistantText(params.assistantTexts) || params.synthesizedPayloadCount > 0;

synthesizedPayloadCount is kept as an additional positive signal, not as the test for absence, so media-only and source-reply-only length stops still read as success. The same value now also feeds hasDeliverableOrProgress, so there is one visible-output fact in the function instead of two spellings.

Test changes, all in attempt-trajectory-status.test.ts:

  • "records length-limited visible text as success with no synthesized payload" — explicitly pins synthesizedPayloadCount: 0 with assistant text, i.e. the real finalization-time state for a text-only reply. This is the finalization-to-delivery regression you asked for; it fails against the previous commit.
  • "keeps a length-limited turn with nothing to show non-deliverable" — no text, no payload, no terminal output stays non_deliverable_terminal_turn.
  • "keeps whitespace-only length-limited text non-deliverable" — guards the trim boundary, since hasNonEmptyAssistantText trims.

The old "marks length-limited visible text as non-deliverable without terminal output" expectation is replaced by the first of those, which is what you asked for in the original finding.

Verified: 12 files / 352 tests pass across attempt-trajectory-status, terminal-resolution, attempt-result, settled-tool-evidence, run.incomplete-turn.delivery-resolution, embedded-agent-subscribe.handlers.lifecycle, and both trajectory consumers (src/trajectory/export.test.ts, src/trajectory/runtime.test.ts). pnpm tsgo:core and targeted oxlint --type-aware clean. PR body updated with the reasoning.

@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. labels Aug 14, 2026
@davenicoll

Copy link
Copy Markdown
Contributor Author

Addressed the remaining finding in f7f6522e3c.

You were right that the two boundaries disagreed. buildEmbeddedRunPayloads derives the reply from the completed assistant message when the streamed texts are empty (src/agents/embedded-agent-runner/run/payloads.ts:265 and :338-358, fed from terminal-preparation.ts:173-179), so a non-streamed length stop is delivered — while handleAgentEnd computed visibility only from ctx.state.assistantTexts, and so still marked that same turn abandoned / replayInvalid. incomplete-turn-resolution.ts:61 was already safe because it keys on payloadCount, i.e. after payload building.

src/agents/embedded-agent-subscribe.handlers.lifecycle.ts now falls back to resolveFinalAssistantVisibleText(lastAssistant) when no streamed text is present, and keeps the streamed-only view for error and aborted stop reasons — the same exclusion resolveTerminalAssistantTexts makes, since raw text on those messages can describe an interrupted generation rather than a reply. Two tests cover it: a length stop with visible content and empty assistantTexts stays working, and a length stop with neither stays abandoned / replayInvalid.

Tool-use behaviour is unchanged: isIncompleteTerminalAssistantTurn returns true for toolUse regardless of visible text, so the widened value cannot flip that branch.

Verified locally: all 59 embedded-agent-subscribe* test files (1269 tests) plus the classification, terminal-resolution, trajectory-status, finalization and before_agent_finalize hook suites; pnpm tsgo:core, pnpm tsgo:test:src and type-aware oxlint on the changed files are clean.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Aug 14, 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 exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@clawsweeper clawsweeper Bot added merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Aug 14, 2026
@davenicoll
davenicoll force-pushed the fix/length-stop-discards-visible-text branch from ddd475b to c01017f Compare August 14, 2026 17:45
@davenicoll

Copy link
Copy Markdown
Contributor Author

Rebased onto current main (0cd18e1fb9); head is now c01017f6a6 — same diff, no content changes. That should also give the review checkout a fresh tree to fetch after the DNS failure, and re-runs check-lint, which failed on the previous head as infrastructure rather than lint: the log ends with The runner has received a shutdown signal / [oxlint] FAILED (exit 143) after [oxlint:core] still running after 150s, with zero diagnostics reported for any file. The same job passed on the immediately preceding head with the same lint surface, and type-aware oxlint over the changed files is clean locally.

Agreed on the net-line reading: the phase-local checks are deliberate, because a shared helper would have to couple the pre-payload lifecycle and trajectory decisions to post-payload delivery facts — which is what caused the original contradiction.

@clawsweeper clawsweeper Bot removed merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. labels Aug 14, 2026
@davenicoll

Copy link
Copy Markdown
Contributor Author

CI on c01017f6a6: 85 pass, 1 fail. check-lint passed this time, confirming the earlier failure was the runner shutdown, not lint.

The one red check, checks-node-compact-small-14, is unrelated to this PR and looks like a sub-millisecond mtime flake in tooling coverage introduced by #123649:

FAIL test/scripts/prepare-extension-package-boundary-artifacts.test.ts
  > keeps mtime-stale artifacts fresh when the hash stamp matches the input digest
AssertionError: expected 1786730265261 to be greater than or equal to 1786730265261.0984

test/scripts/prepare-extension-package-boundary-artifacts.test.ts:595 compares mtimeMs with toBeGreaterThanOrEqual, and the repaired output mtime lands 0.0984 ms below the input on a filesystem with coarser timestamp granularity. No file in this PR is involved. The same file passes locally (19/19). Happy to leave it to a re-run, or to open a separate PR rounding that comparison if a maintainer would like.

@sallyom

sallyom commented Aug 15, 2026 •

Copy link
Copy Markdown
Contributor

Maintainer note: all review findings have been addressed. I am updating this PR from c01017f6a614816b06e20f95bd54bb33dc3dc8fd onto current origin/main (8668aeb) to pick up the latest base fixes and prepare exact-head CI for merge. No other action is needed for now.

@sallyom sallyom self-assigned this Aug 15, 2026
@sallyom
sallyom force-pushed the fix/length-stop-discards-visible-text branch from c01017f to 21902fd Compare August 15, 2026 19:15
…ing them

`isIncompleteTerminalAssistantTurn` accepted `hasAssistantVisibleText` but the
`length` branch never read it, so a turn that stopped at the output token limit
after emitting visible text was classified incomplete. The whole reply was then
replaced with "Agent couldn't generate a response" and the run was marked
abandoned.

Respect the flag: a `length` stop is incomplete only when there is no visible
text and no terminal tool output. A length stop that did produce text now
delivers that text with a truncation notice appended, so a cut-off answer is
not mistaken for a complete one.
Review follow-up on the token-limited partial reply fix.

The truncation notice keyed only on stopReason, so a length stop that also
produced terminal output (tool media, a committed source reply) gained an extra
text reply telling the user to ask for a continuation. Those turns were already
complete before this fix, so the notice now uses the same predicate as the
classifier: a length stop with no terminal output.

resolveAttemptTrajectoryTerminal() also still recorded a delivered partial
reply as non_deliverable_terminal_turn, so durable trajectory state contradicted
what the user received. It now uses the same payload-count evidence the terminal
owner uses, so a length stop is only non-deliverable when nothing was delivered.
A length stop with visible text but no synthesized payload stays an error.
…tials

handleAgentEnd() no longer marks a length stop with visible text as abandoned
and replay-invalid, because that turn is now delivered as a partial reply. The
lifecycle test still pinned the old outcome. The sibling case that has pending
tool media is unchanged: it still has terminal output, so it stays abandoned.
…d count

The previous guard used synthesizedPayloadCount, which does not include ordinary
final assistant text: attempt-result.ts computes it from block replies, tool
media, source-reply payloads, and silent-tool payloads, and finalization runs
before terminal-preparation.ts turns assistant text into payloads. So an ordinary
text-only truncated reply — the case this PR exists to fix — still recorded
non_deliverable_terminal_turn while the reply was delivered.

Key on visible assistant text instead, which is the fact the delivery owner also
keys on and is already resolved at finalization. A length stop with nothing
visible to show stays non-deliverable, whitespace-only text included.
…gth partials

The attempt-finalize table row for a length stop expected finalStatus "error".
Its fixture assistant carries visible text, which resolveTerminalAssistantTexts()
promotes to terminal assistant text for a length stop, so that row is a delivered
partial reply and must now record success. Renamed to say so.
…lity

The lifecycle handler derived assistant-visible text only from streamed
assistant texts, while terminal payload building falls back to the completed
assistant message's visible text when the streamed texts are empty. A
non-streamed length stop was therefore delivered to the user and, at the same
time, recorded as an abandoned, replay-invalid turn.

Give the classifier call site the same canonical fact, keeping the
streamed-only view for error and abort stop reasons whose raw text can describe
an interrupted generation rather than a reply.
A cron turn can end with a length stop whose only payload is the synthesized
silent result of a successful tool. Gating the notice on terminal-state absence
alone appended a visible truncation message to that intentionally silent result.
Require nonblank assistant text — streamed or from the terminal assistant
message — so the notice only labels prose the user actually received.

Also drops .rev3.md, a review transcript committed by accident.
@sallyom
sallyom force-pushed the fix/length-stop-discards-visible-text branch from 21902fd to 9fe47b6 Compare August 15, 2026 19:16
@sallyom

sallyom commented Aug 15, 2026 •

Copy link
Copy Markdown
Contributor

Merge-ready at source HEAD 9fe47b621c275b0f6d87dd6d50eb916cbc987504.

Best-fix verdict: this repair sits at the correct classification, delivery, lifecycle, and trajectory owner boundaries. All ClawSweeper findings are addressed; current-head ClawSweeper and local autoreview are clean; the required exact-head CI gate is green after the transient lint-runner shutdown cleared on rerun.

Compatibility: no public API, config, environment, plugin SDK, protocol, schema, persistence, dependency, or migration changes. The only intentional behavior change is that token-limited replies containing visible text are delivered with a truncation notice and remain replayable instead of being discarded as an error.

Merged as db0d133ec9521edffe9f722551762dce3d1d5783.

@sallyom
sallyom merged commit db0d133 into openclaw:main Aug 15, 2026
207 of 209 checks passed
@sallyom

sallyom commented Aug 15, 2026

Copy link
Copy Markdown
Contributor

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Aug 16, 2026
…ing them (openclaw#123546)

* fix(agents): deliver token-limited partial replies instead of discarding them

`isIncompleteTerminalAssistantTurn` accepted `hasAssistantVisibleText` but the
`length` branch never read it, so a turn that stopped at the output token limit
after emitting visible text was classified incomplete. The whole reply was then
replaced with "Agent couldn't generate a response" and the run was marked
abandoned.

Respect the flag: a `length` stop is incomplete only when there is no visible
text and no terminal tool output. A length stop that did produce text now
delivers that text with a truncation notice appended, so a cut-off answer is
not mistaken for a complete one.

* fix(agents): scope the truncation notice and align trajectory status

Review follow-up on the token-limited partial reply fix.

The truncation notice keyed only on stopReason, so a length stop that also
produced terminal output (tool media, a committed source reply) gained an extra
text reply telling the user to ask for a continuation. Those turns were already
complete before this fix, so the notice now uses the same predicate as the
classifier: a length stop with no terminal output.

resolveAttemptTrajectoryTerminal() also still recorded a delivered partial
reply as non_deliverable_terminal_turn, so durable trajectory state contradicted
what the user received. It now uses the same payload-count evidence the terminal
owner uses, so a length stop is only non-deliverable when nothing was delivered.
A length stop with visible text but no synthesized payload stays an error.

* test(agents): flip the lifecycle expectation for delivered length partials

handleAgentEnd() no longer marks a length stop with visible text as abandoned
and replay-invalid, because that turn is now delivered as a partial reply. The
lifecycle test still pinned the old outcome. The sibling case that has pending
tool media is unchanged: it still has terminal output, so it stays abandoned.

* fix(agents): key length trajectory status on visible text, not payload count

The previous guard used synthesizedPayloadCount, which does not include ordinary
final assistant text: attempt-result.ts computes it from block replies, tool
media, source-reply payloads, and silent-tool payloads, and finalization runs
before terminal-preparation.ts turns assistant text into payloads. So an ordinary
text-only truncated reply — the case this PR exists to fix — still recorded
non_deliverable_terminal_turn while the reply was delivered.

Key on visible assistant text instead, which is the fact the delivery owner also
keys on and is already resolved at finalization. A length stop with nothing
visible to show stays non-deliverable, whitespace-only text included.

* test(agents): flip the finalization trajectory case for delivered length partials

The attempt-finalize table row for a length stop expected finalStatus "error".
Its fixture assistant carries visible text, which resolveTerminalAssistantTexts()
promotes to terminal assistant text for a length stop, so that row is a delivered
partial reply and must now record success. Renamed to say so.

* fix(agents): use the completed assistant message for lifecycle visibility

The lifecycle handler derived assistant-visible text only from streamed
assistant texts, while terminal payload building falls back to the completed
assistant message's visible text when the streamed texts are empty. A
non-streamed length stop was therefore delivered to the user and, at the same
time, recorded as an abandoned, replay-invalid turn.

Give the classifier call site the same canonical fact, keeping the
streamed-only view for error and abort stop reasons whose raw text can describe
an interrupted generation rather than a reply.

* fix(agents): require partial text before appending the truncation notice

A cron turn can end with a length stop whose only payload is the synthesized
silent result of a successful tool. Gating the notice on terminal-state absence
alone appended a visible truncation message to that intentionally silent result.
Require nonblank assistant text — streamed or from the terminal assistant
message — so the notice only labels prose the user actually received.

Also drops .rev3.md, a review transcript committed by accident.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: M status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants