Skip to content

hooks: fix PR #113 review — preserve history mrSystem + catch provider exceptions - #114

Merged
FMXExpress merged 1 commit into
mainfrom
claude/pr113-review-fixes
Jun 1, 2026
Merged

FMXExpress merged 1 commit into
mainfrom
claude/pr113-review-fixes

Conversation

@FMXExpress

Copy link
Copy Markdown
Owner

Summary

Two Codex P2 findings on the merged PR #113, both legitimate.

P2 #1 — In-history mrSystem messages silently disappear on first steering fold

A direct RunToolLoop embedder (not via TPasClawAgent) who puts their policy as mrSystem in Hist with Cfg.Options.SystemPrompt = '' saw their policy vanish the moment an AfterToolResult hook returned a non-empty SteeringMessage. PR #113 set LiveOptions.SystemPrompt to the steering text alone; the next Provider.Chat then dropped every in-history mrSystem (both OpenAI and Anthropic builders do this whenever the option slot is populated). Net: the embedder's policy was gone, replaced by just the steering note.

Fix: new DrainHistorySystem(var Hist): string helper. On every steering fold, extract all mrSystem entries from Hist (in order), concatenate their content with blank-line separators, and prepend that to whatever's about to land in LiveOptions.SystemPrompt. Hist is rewritten in place to skip the drained entries so they don't get re-folded on subsequent passes (idempotent). The next round ships:

SystemPrompt = (existing prompt) + (history mrSystem content) + (accumulated steering)

and Hist no longer carries any mrSystem the builder would drop.

P2 #2 — Provider Chat exceptions bypass HooksOnError

When Cfg.Provider.Chat or a fallback's Chat raises (Indy EIdSocketError on a wedged TLS handshake, builder parse error, OOM in CollapseSSE), execution left RunToolLoop before reaching the post-walk HooksOnError check. Audit hooks never got notified.

Fix: wrap both the primary Chat call and each fallback Chat call in try/except. On exception: log, build a synthetic Resp with StatusCode := -1 and Content := "EClass: message", continue to the next provider attempt. The existing post-walk HooksOnError (widened in PR #112 to fire on status ≤ 0) sees -1 and fires; the hook now gets the exception text in the message because the post-walk Format includes Resp.Content when populated:

- 'provider returned status=-1'
+ 'provider returned status=-1: Exception: TLS handshake refused'

No exception propagates out of RunToolLoop — embedders that prefer hard failures can still wrap their Run call.

Verification

=== Test 1: in-history mrSystem preserved on steering fold ===
  PASS — policy + steering both in SystemPrompt, no stray mrSystem
=== Test 2: raised provider exception fires OnError + no propagation ===
  PASS — OnError fired: provider returned status=-1: Exception: simulated provider raise

all PR #113 review-fix tests passed.

Test 1 asserts the in-history policy text appears in Loop.FinalSystemPrompt, the steering text also appears there, and no mrSystem entry leaks into Loop.FinalMessages (because in-history mrSystem gets dropped by provider builders, that would be a silent regression).

Test 2 uses a TRaiseProvider whose Chat always raises. Asserts that RunToolLoop returns without propagating the exception and the audit hook recorded the exception text via HooksOnError.

make clean && make smoke 11/11 green.

https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon


Generated by Claude Code

…ions

Two Codex P2 findings on PR #113, both legitimate.

P2 #1 — In-history system messages silently disappear when
steering first folds into LiveOptions.SystemPrompt. A direct
RunToolLoop embedder (not via TPasClawAgent) who puts policy as
mrSystem in Hist with Cfg.Options.SystemPrompt = '' would see
their policy vanish the moment an AfterToolResult hook returned
a non-empty SteeringMessage. PR #113 set LiveOptions.SystemPrompt
to the steering text alone; the next Provider.Chat then dropped
every in-history mrSystem (both OpenAI and Anthropic builders do
this whenever the option slot is populated). Net: the embedder's
policy was gone, replaced by just the steering note.

Fix: new DrainHistorySystem helper. On every steering fold,
extract all mrSystem entries from Hist (in order), concatenate
their content with blank-line separators, and prepend that to
whatever's about to land in LiveOptions.SystemPrompt. Hist is
rewritten in place to skip the drained entries so they don't
get re-folded on subsequent passes (idempotent). The next round
ships:

  SystemPrompt = (existing prompt) + (history mrSystem content)
                 + (accumulated steering)

and Hist no longer carries any mrSystem the builder would drop.

P2 #2 — Provider Chat exceptions bypass HooksOnError. When
Cfg.Provider.Chat or a fallback's Chat raises (Indy
EIdSocketError on a wedged TLS handshake, builder parse error,
OOM in CollapseSSE), execution leaves RunToolLoop before reaching
the post-walk HooksOnError check. Audit hooks never get notified.

Fix: wrap both the primary Chat call and each fallback Chat call
in try/except. On exception: log, build a synthetic Resp with
StatusCode := -1 and Content := "EClass: message", continue to
the next provider attempt. The existing post-walk HooksOnError
(now widened in PR #112 to fire on status <= 0) sees -1 and
fires; the hook gets the exception text in the message because
the post-walk Format now includes Resp.Content when populated:

  before: 'provider returned status=-1'
  after : 'provider returned status=-1: Exception: TLS handshake refused'

No exception propagates out of RunToolLoop — embedders that
prefer hard failures can still wrap their Run call.

Verified with a focused two-part test (built + run + removed):

  === Test 1: in-history mrSystem preserved on steering fold ===
    PASS — policy + steering both in SystemPrompt, no stray mrSystem
  === Test 2: raised provider exception fires OnError + no propagation ===
    PASS — OnError fired: provider returned status=-1: Exception: simulated provider raise

  all PR #113 review-fix tests passed.

make clean && make smoke 11/11 green.

https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon
@FMXExpress
FMXExpress merged commit 0506d5c into main Jun 1, 2026

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

Copy link
Copy Markdown

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: 9b48010e37

ℹ️ 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".

LogWarn('provider Chat raised: %s: %s', [E.ClassName, E.Message]);
Resp := Default(TLLMResponse);
Resp.StatusCode := -1;
Resp.Content := E.ClassName + ': ' + E.Message;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Keep provider exception details out of assistant content

When a provider raises after all fallbacks are exhausted, storing EClass: message in Resp.Content makes the exception flow through the normal successful-response path: the empty-tool-call branch returns True, and public consumers expose Loop.Content directly (for example, PasClaw.Gateway.Server.pas:1721-1725 returns an OpenAI-compatible HTTP 200 response and PasClaw.Channels.Discord.pas:242-243 posts it to the channel). This can leak internal parser, socket, or provider details to users while reporting the failed call as a completed assistant turn. Keep the exception text in a separate diagnostic value for HooksOnError, or return an explicit failure after the hook fires; the identical fallback assignment at line 573 needs the same treatment.

Useful? React with 👍 / 👎.

otherwise see their policy disappear the first time
steering fires. (Codex P2 on PR #113.) Idempotent — once
drained, subsequent passes find no mrSystem to fold. }
HistSystem := DrainHistorySystem(Hist);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Preserve drained policies when hooks reset steering

When a direct RunToolLoop embedder uses an in-history mrSystem policy and follows the documented ephemeral-steering behavior at lines 761-762 by resetting SystemPrompt in BeforeTurn, this destructive drain removes the only durable copy of that policy. After the first tool batch contributes steering, the policy is moved out of Hist; on the next turn the reset clears the folded prompt, so the provider receives neither the original policy nor the steering text. Keep the drained policy separate from the mutable steering portion, or restore it when rebuilding SystemPrompt.

Useful? React with 👍 / 👎.

FMXExpress pushed a commit that referenced this pull request Jun 1, 2026
…mrSystem

Codex P2 on PR #116: Gemini's BuildRequest concatenated
Options.SystemPrompt AND every in-history mrSystem into
systemInstruction. PR #114's steering fold copies in-history
mrSystem into SystemPrompt non-destructively (so the policy
stays recoverable after ephemeral-steering resets), which means
both copies reach Gemini and the policy ships twice per request.
OpenAI and Anthropic builders already drop in-history mrSystem
when SystemPrompt is set, so they're unaffected.

Fix: match the OpenAI / Anthropic precedence rule in Gemini's
BuildRequest. When Options.SystemPrompt is non-empty, that wins
and in-history mrSystem is skipped; when SystemPrompt is empty,
in-history mrSystem entries fold into Sys as before (behavior
preserved for embedders that route policy purely through Hist).

  before:
    Sys := Options.SystemPrompt;
    for i := 0 to High(Messages) do
      if (Messages[i].Role = mrSystem) ... then
        Sys := Sys + sLineBreak + Messages[i].Content;

  after:
    Sys := Options.SystemPrompt;
    if Sys = '' then               { only fold mrSystem when SystemPrompt unset }
      for i := 0 to High(Messages) do
        if (Messages[i].Role = mrSystem) ... then
          Sys := Sys + sLineBreak + Messages[i].Content;

Tiny side change: exposed BuildRequest in the interface section
so a focused unit-level test can verify the dedup without
spinning up an HTTPS round-trip. The function was already
documented and stable internally; this just makes it reachable
to test fixtures.

Verified end-to-end with a four-case probe (built + run +
removed, not committed) — counts occurrences of a sentinel
policy string in the JSON body that BuildRequest emits:

  A: SystemPrompt+mrSystem same content       expected=1 got=1
  B: empty SystemPrompt, mrSystem in Hist     expected=1 got=1
  C: SystemPrompt only, no mrSystem           expected=1 got=1
  D: SystemPrompt set, different mrSystem skipped  expected=1 got=1

Case A is the regression that PR #116's review caught. Case B
verifies the pre-existing behavior didn't regress when
SystemPrompt is empty. Case D confirms a DIFFERENT in-history
mrSystem is correctly suppressed when SystemPrompt is set —
matches OpenAI's "already added above" precedence.

make clean && make smoke 11/11 green.

https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon
FMXExpress added a commit that referenced this pull request Jun 1, 2026
hooks: fix PR #114 review — exception out-of-band + non-destructive policy copy
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants