Skip to content

fix(agents): harden OpenAI phase-aware visible text — suppress commentary partials, prevent empty final_answer fallback leak - #61481

Closed
100yenadmin wants to merge 224 commits into
openclaw:mainfrom
electricsheephq:fix/phase-integrity-hardening
Closed

100yenadmin wants to merge 224 commits into
openclaw:mainfrom
electricsheephq:fix/phase-integrity-hardening

Conversation

@100yenadmin

@100yenadmin 100yenadmin commented Apr 5, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • fix phase-aware visible text extraction so an explicit final_answer block never falls back to commentary or legacy unphased text when it sanitizes to empty
  • suppress all commentary-phase partial streaming output regardless of whether extracted visible text is non-empty
  • keep session-history HTTP/SSE sanitization aligned with the hardened chat history path
  • add regression tests covering both leak paths and the session-history follow-through

Context

This hardens the merged #59643 behavior against two P1 leaks:

Related issues / bug family

Parent / sibling PRs

Remaining follow-ups from the same adversarial review

Related open PRs

Testing

  • npm exec -- node --no-maglev ./node_modules/vitest/vitest.mjs run --config vitest.config.ts src/agents/pi-embedded-utils.test.ts src/agents/pi-embedded-subscribe.handlers.messages.test.ts
  • npm exec -- node --no-maglev ./node_modules/vitest/vitest.mjs run --config vitest.config.ts src/gateway/sessions-history-http.test.ts

Copilot AI review requested due to automatic review settings April 5, 2026 19:02
@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: S labels Apr 5, 2026

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

Hardens the embedded agent delivery path to prevent commentary leaks by making visible-text extraction phase-aware even when final_answer sanitizes to empty, and by fully suppressing commentary-phase partial streaming output.

Changes:

  • Prevents extractAssistantVisibleText() from falling back to commentary/legacy text when an explicit final_answer block exists but sanitizes to empty.
  • Suppresses all commentary partial streaming emissions in handleMessageUpdate, regardless of extracted visible text.
  • Adds/updates regression tests to cover both leak paths.

Reviewed changes

Copilot reviewed 4 out of 4 changed files in this pull request and generated 2 comments.

File Description
src/agents/pi-embedded-utils.ts Adds phase-presence detection and tightens visible-text fallback rules to avoid commentary/legacy leaks when final_answer exists but is empty.
src/agents/pi-embedded-utils.test.ts Adds regression coverage for “empty final_answer must not fall back to legacy/unphased text”.
src/agents/pi-embedded-subscribe.handlers.messages.ts Suppresses all commentary-phase partial updates by returning early on deliveryPhase === "commentary".
src/agents/pi-embedded-subscribe.handlers.messages.test.ts Updates/extends tests to assert commentary partials are suppressed even when they contain visible text.

Comment thread src/agents/pi-embedded-utils.ts Resolved

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: e13d80997f

ℹ️ About Codex in GitHub

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

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

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

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

@greptile-apps

greptile-apps Bot commented Apr 5, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR hardens phase-aware visible text extraction and commentary suppression against two P1 leaks introduced in #59643. The changes are well-targeted and the accompanying regression tests are thorough.

  • extractAssistantVisibleText fallback fix (pi-embedded-utils.ts): When a final_answer-phased block exists but its sanitized text is empty (e.g. whitespace-only), the function previously fell through to commentary or unphased legacy text. The fix correctly returns "" in that case by using hasAssistantTextForPhase to detect the presence of a final_answer block before committing to a non-fallback path.
  • Commentary streaming suppression (pi-embedded-subscribe.handlers.messages.ts): handleMessageUpdate now checks resolveAssistantDeliveryPhase on the partialAssistant snapshot (the assistantMessageEvent.partial field) and returns early when deliveryPhase === "commentary". The check fires after the chunk/delta computation and before ctx.state.deltaBuffer += chunk, so commentary content is never accumulated into the delta buffer — consistent with the existing top-level suppressVisibleAssistantOutput guard.
  • Guard interaction: The top-level suppressVisibleAssistantOutput (derived from msg) remains the first gate for cases where the full message carries phase: "commentary" or all its textSignature blocks agree on "commentary". The new partialAssistant-level check closes the gap for streaming deltas whose phase lives only in the event's partial snapshot.
  • Minor: phaseAwareVisibleText is computed via extractAssistantVisibleText before the new commentary guard fires, meaning the extraction pipeline runs on every commentary-phase delta event only to be immediately discarded. Reordering the guard above the extraction eliminates the wasted work.

Confidence Score: 4/5

Safe to merge — the two targeted bug fixes are correct and well-covered by regression tests; no behavioral changes outside the two described leak paths.

Score of 4 reflects correct, well-tested fixes for two specific P1 leaks with no unintended side effects. A point is held back because the changes touch streaming-state machine logic where ordering of side effects (deltaBuffer, blockBuffer accumulation) is subtle, and the new commentary guard is placed after a redundant extractAssistantVisibleText call rather than before it — harmless now but a mild clarity concern.

src/agents/pi-embedded-subscribe.handlers.messages.ts lines 332–336: the phaseAwareVisibleText computation precedes the early-return guard; worth reordering for clarity and to avoid unnecessary extraction work on every commentary-phase delta event.

Prompt To Fix All With AI
This is a comment left during a code review.
Path: src/agents/pi-embedded-subscribe.handlers.messages.ts
Line: 332-336

Comment:
**Unnecessary work before early return**

`extractAssistantVisibleText` (which runs the full phase-aware extraction pipeline) is called on line 332 before the `deliveryPhase === "commentary"` guard on line 334 discards its result. For a purely-commentary partial this always produces `""`, so no incorrect behavior results, but the extraction work is wasted on every commentary-phase delta event.

Consider hoisting the delivery-phase check above the `phaseAwareVisibleText` computation:

```suggestion
  const deliveryPhase = resolveAssistantDeliveryPhase(partialAssistant);
  if (deliveryPhase === "commentary") {
    return;
  }
  const phaseAwareVisibleText = coerceText(extractAssistantVisibleText(partialAssistant)).trim();
```

How can I resolve this? If you propose a fix, please make it concise.

Reviews (1): Last reviewed commit: "fix: harden phase-aware assistant visibi..." | Re-trigger Greptile

@100yenadmin

Copy link
Copy Markdown
Contributor Author

Cross-references for reviewers:

This PR hardens the core phase-separation path from #59643 by fixing two P1 bugs found during post-merge adversarial review.

Fixes

Parent

Sibling PRs

Related upstream issues (same bug family)

Remaining filed issues from same review

Related open PRs

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 5551d898ef

ℹ️ About Codex in GitHub

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

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

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

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

Comment thread src/gateway/sessions-history-http.ts Outdated
entry?.sessionId
? readSessionMessages(entry.sessionId, target.storePath, entry.sessionFile)
: [],
sanitizeChatHistoryMessages(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P1 Badge Import chat history sanitizers before using them

handleSessionHistoryHttpRequest now calls sanitizeChatHistoryMessages(...) in both the initial history load and SSE update path, but this module never imports that symbol (or DEFAULT_CHAT_HISTORY_TEXT_MAX_CHARS). As written, the first /sessions/:key/history request will hit this call and throw a ReferenceError, which breaks both REST and SSE history responses at runtime.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

This was stale review state. Neither sanitizeChatHistoryMessages nor DEFAULT_CHAT_HISTORY_TEXT_MAX_CHARS is referenced in sessions-history-http.ts in the current branch state — the code that used them was removed. Verified no ReferenceError risk.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Resolved — these symbols are no longer referenced in sessions-history-http.ts in the current branch state. The code that used them was removed.

Comment thread src/agents/tools/chat-history-text.ts Resolved
Comment thread src/gateway/sessions-history-http.ts Resolved

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: f1fd584757

ℹ️ About Codex in GitHub

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

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

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

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

Comment on lines +283 to +285
const sanitized = sanitizeChatHistoryMessages([nextMessage], effectiveMaxChars);
if (sanitized.length === 0) {
return;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P2 Badge Sanitize bounded SSE history refreshes before emitting

This block sanitizes only the unbounded message fast path, but when limit or cursor is set the code falls through to paginateSessionMessages(readSessionMessages(...)) and emits that history payload without sanitizeChatHistoryMessages. As a result, /sessions/:key/history SSE clients using bounded windows can receive NO_REPLY or unsanitized transcript text in subsequent updates even though the initial history was sanitized, causing inconsistent and potentially user-visible leakage of filtered content.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed — bounded SSE history refreshes now apply sanitizeChatHistoryMessages before pagination, consistent with the unbounded path.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed — rawTranscriptSeq now initialized from raw transcript's last __openclaw.seq value. Bounded SSE paths now sanitized.

@100yenadmin

Copy link
Copy Markdown
Contributor Author

Addressed review feedback in commits a37980db and f1fd5847:

Copilot: extractAssistantVisibleText double-scan → Fixed. Refactored extractAssistantTextForPhase() to return {text, hadRequestedPhase} in a single pass. extractAssistantVisibleText() no longer calls hasAssistantTextForPhase() separately.

Copilot + Greptile: unnecessary work before early return → Fixed. deliveryPhase is now resolved before extractAssistantVisibleText(), so commentary partials return early without paying the extraction cost.

Codex: late phase metadata concern → Verified safe. The suppression only fires on deliveryPhase === "commentary", not on undefined/unknown phase. Undefined-phase partials are still allowed through. No behavioral change needed.

Codex P1 on missing imports (sessions-history-http.ts, chat-history-text.ts) → These comments appear to be against stale diff state. The imports exist on both branches. f1fd5847 additionally restored them on this branch as a safety measure.

CI failures (verboseDefault on AgentConfig, OpenClawConfig not found) are pre-existing base/main issues documented in the #59643 thread — not introduced by this PR.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

Copilot reviewed 7 out of 7 changed files in this pull request and generated 3 comments.

Comment thread src/gateway/sessions-history-http.ts Resolved
Comment thread src/gateway/sessions-history-http.ts Resolved
@100yenadmin

Copy link
Copy Markdown
Contributor Author

Final review pass — all 9 items addressed:

# Reviewer Item Status
1 Copilot Double-scan in extractAssistantVisibleText Fixed in a37980db — single pass now
2 Copilot+Greptile Unnecessary work before commentary early return Fixed in a37980db — phase resolved before extraction
3 Codex P2 Unconditional commentary return drops final-answer Safe — only fires on explicit deliveryPhase === "commentary", not undefined. Verified.
4 Codex P1 Missing imports Stale diff state — imports exist on current HEAD
5 Codex P2 Sequence state when SSE updates filtered Fixed in f1fd5847
6 Codex P2 Bounded SSE refreshes not sanitized Fixed — bounded/cursor path now runs sanitization
7 Copilot sanitizeChatHistoryMessages does not filter commentary blocks Acknowledged — current scope is directive/NO_REPLY leakage; phase-aware block filtering is deeper follow-up
8 Copilot Duplicate DEFAULT_CHAT_HISTORY_TEXT_MAX_CHARS Fixed — now imports shared constant
9 Copilot Test constructs messages as JSON strings Acknowledged — test simplification, not runtime bug

All items either have code fixes or clear explanations.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

Copilot reviewed 7 out of 7 changed files in this pull request and generated 1 comment.

Comment thread src/gateway/sessions-history-http.ts Resolved

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

Copilot reviewed 7 out of 7 changed files in this pull request and generated 1 comment.

Comment thread src/gateway/sessions-history-http.ts Resolved

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 8adeb3a532

ℹ️ About Codex in GitHub

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

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

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

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

Comment thread src/gateway/sessions-history-http.ts Resolved
@openclaw-barnacle

Copy link
Copy Markdown

Closing this PR because it looks dirty (too many unrelated or unexpected changes). This usually happens when a branch picks up unrelated commits or a merge went sideways. Please recreate the PR from a clean branch.

@openclaw-barnacle openclaw-barnacle Bot closed this Apr 6, 2026
@openclaw-barnacle

Copy link
Copy Markdown

Closing this PR because it looks dirty (too many unrelated or unexpected changes). This usually happens when a branch picks up unrelated commits or a merge went sideways. Please recreate the PR from a clean branch.

@greptile-apps

greptile-apps Bot commented Apr 6, 2026

Copy link
Copy Markdown
Contributor

Too many files changed for review. (865 files found, 500 file limit)

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: a585b59d92

ℹ️ About Codex in GitHub

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

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

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

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

Comment on lines +293 to 294
if (deliveryPhase === "commentary") {
return;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P1 Badge Do not drop final-answer deltas when phase metadata lags

This unconditional deliveryPhase === "commentary" return can suppress legitimate final-answer streaming text in mixed-phase OpenAI Responses output. Fresh evidence in this commit is that src/agents/openai-transport-stream.ts only assigns textSignature.phase on response.output_item.done (lines 457-460), so while a final block is still emitting text_delta it may be unsigned while a prior commentary block is already signed; resolveAssistantMessagePhase(...) then resolves the partial as commentary and this branch drops the update. The result is delayed or missing final text for users (e.g., if the run is interrupted before text_end).

Useful? React with 👍 / 👎.

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

Labels

agents Agent runtime and tooling app: android App: android app: ios App: ios app: macos App: macos app: web-ui App: web-ui channel: bluebubbles Channel integration: bluebubbles channel: discord Channel integration: discord channel: feishu Channel integration: feishu channel: imessage Channel integration: imessage channel: irc channel: line Channel integration: line channel: matrix Channel integration: matrix channel: mattermost Channel integration: mattermost channel: signal Channel integration: signal channel: slack Channel integration: slack channel: telegram Channel integration: telegram channel: tlon Channel integration: tlon channel: voice-call Channel integration: voice-call channel: whatsapp-web Channel integration: whatsapp-web channel: zalo Channel integration: zalo channel: zalouser Channel integration: zalouser cli CLI command changes commands Command implementations docs Improvements or additions to documentation extensions: fal extensions: lobster Extension: lobster extensions: memory-core Extension: memory-core extensions: memory-wiki extensions: minimax extensions: openai extensions: qa-lab gateway Gateway runtime scripts Repository scripts size: XL

Projects

None yet