Skip to content

hooks: fix PR #114 review — exception out-of-band + non-destructive policy copy - #116

Merged
FMXExpress merged 2 commits into
mainfrom
claude/pr114-review-fixes
Jun 1, 2026
Merged

FMXExpress merged 2 commits into
mainfrom
claude/pr114-review-fixes

Conversation

@FMXExpress

Copy link
Copy Markdown
Owner

Summary

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

P2 #1 — Exception text leaked into Loop.Content

PR #114 stashed caught provider-exception text (e.g. "EIdSocketError: Connection refused 192.168.1.42:443") in Resp.Content so the post-walk HooksOnError could include it. But Resp.Content is also what the loop's exit-clean path copies into Loop.Content (when the provider returns no tool_calls), so Agent.Run('hi') after a TLS handshake failure surfaced internal infrastructure detail (IPs, TLS versions, parser internals) as the assistant's reply.

Fix: new local LastProviderErrText. Exception text goes there, not Resp.Content. Post-walk HooksOnError dispatch priority:

  1. LastProviderErrText (our caught exception)
  2. Resp.Content (server's deliberately-returned error JSON)
  3. status=N only

A successful fallback clears LastProviderErrText so only the last failed attempt's diagnostic surfaces. Resp.Content stays empty when we caught an exception — Loop.Content := Resp.Content returns '' cleanly.

P2 #2 — Destructive Hist drain made embedder policy unrecoverable

PR #113 introduced DrainHistorySystem to lift in-history mrSystem into SystemPrompt on first steering fold. But the drain removed the entries from Hist permanently — so when a BeforeTurn hook later cleared SystemPrompt for the documented ephemeral-steering semantics, the policy was gone from both the option slot AND from Hist. The model would silently start operating without policy.

Fix: replaced DrainHistorySystem with CopyHistorySystem (read-only). The fold copies mrSystem content only when SystemPrompt is currently empty (first fold). After that, SystemPrompt has the policy embedded and subsequent folds just append more steering — they don't re-read Hist (which would duplicate the policy).

State SystemPrompt Hist mrSystem Provider sees
Initial empty policy policy via Hist (option empty → builder includes mrSystem)
After 1st fold policy + steering policy (unchanged) policy + steering via option (builder drops Hist mrSystem)
After 2nd fold policy + steering + steering policy (unchanged) the consolidated option
BeforeTurn clears option empty policy (unchanged) policy via Hist again — recovers automatically

Verification

=== Test 1: provider exception text does NOT leak into Loop.Content ===
  PASS — Loop.Content="", OnError got the diagnostic
=== Test 2: in-history mrSystem policy preserved (non-destructive) ===
  PASS — policy in Hist + in SystemPrompt, steering folded

all PR #114 review-fix tests passed.

Test 1 raises an exception with "simulated socket reset 192.168.1.42:443". Asserts that string does not appear in Loop.Content, and that the audit hook recorded it via OnError. Test 2 asserts the policy is still in Loop.FinalMessages as an mrSystem entry (proof of non-destructive copy) after the steering fold ran.

make smoke 11/11 green.

https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon


Generated by Claude Code

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

P2 #1 — Exception text leaked into Loop.Content. PR #114 stashed
caught provider-exception text ("EIdSocketError: Connection
refused 192.168.1.42:443") in Resp.Content so the post-walk
HooksOnError could include it. But Resp.Content is ALSO what the
loop's exit-clean path copies into Loop.Content (when the provider
returns no tool_calls), so an embedder calling Agent.Run('hi')
that hit a TLS handshake failure would see internal infrastructure
detail surfaced as the assistant's reply. That's a leak of parser,
socket, IP, and TLS-version details to whatever client sits on
the other side of Loop.Content.

Fix: new local var LastProviderErrText. Exception text stashes
there, NOT in Resp.Content. The post-walk HooksOnError dispatches
in priority order:

  1. LastProviderErrText (our own caught exception, structured)
  2. Resp.Content (server's error JSON body, deliberately returned)
  3. status=N only (nothing else)

A successful fallback clears LastProviderErrText so only the LAST
failed attempt's diagnostic surfaces. Resp.Content stays empty
when we caught an exception — Loop.Content := Resp.Content keeps
returning '' (the right "nothing to say" semantic).

P2 #2 — Destructive Hist drain made embedder policy unrecoverable.
PR #113 introduced DrainHistorySystem to lift in-history mrSystem
into SystemPrompt on first steering fold (so the policy wouldn't
disappear when the option slot became non-empty). But the drain
removed the entries from Hist permanently — so if a BeforeTurn
hook later cleared SystemPrompt for ephemeral-steering semantics
(documented as supported in PR #113's comment), the policy was
gone from BOTH the option slot AND from Hist. The model would
silently start operating without policy.

Fix: replaced DrainHistorySystem with CopyHistorySystem (read-only).
The fold logic now copies mrSystem content ONLY when SystemPrompt
is currently empty (first fold). After that, SystemPrompt has the
policy embedded and subsequent folds just append more steering —
they don't re-read Hist (which would duplicate the policy text).

Net behaviour:

  Round 1, SystemPrompt empty, Hist has mrSystem:
    fold reads Hist policy into SystemPrompt → SystemPrompt = policy
    + steering. Hist mrSystem unchanged. Provider builder sees
    SystemPrompt and DROPS in-history mrSystem (avoids dup).

  Round 2, SystemPrompt = "policy + steering", Hist still has mrSystem:
    fold appends new steering only. Hist mrSystem still dropped by
    provider builder.

  BeforeTurn hook clears SystemPrompt at start of round 3:
    Provider sees empty SystemPrompt and INCLUDES in-history
    mrSystem. Policy ships via the history channel. Steering this
    round (if any) repeats the fold-from-empty path.

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

  === Test 1: provider exception text does NOT leak into Loop.Content ===
    PASS — Loop.Content="", OnError got the diagnostic
  === Test 2: in-history mrSystem policy preserved (non-destructive) ===
    PASS — policy in Hist + in SystemPrompt, steering folded

  all PR #114 review-fix tests passed.

Test 1 raises an exception with "simulated socket reset
192.168.1.42:443" in the message; asserts that string does NOT
appear in Loop.Content, AND that an audit hook recorded it via
OnError. Test 2 puts the policy as mrSystem in Hist, leaves
Cfg.Options.SystemPrompt empty, registers a steering hook, runs
the loop, then asserts: (a) the policy is STILL in
Loop.FinalMessages as an mrSystem entry (proof of non-destructive
copy), and (b) the provider's view of the system prompt on round
2 included BOTH policy and steering.

make smoke 11/11 green.

https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon

@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: 3c3acc9c5b

ℹ️ 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 403 to 407
for i := 0 to High(Hist) do
begin
if Hist[i].Role = mrSystem then
begin
if Result <> '' then Result := Result + sLineBreak + sLineBreak;
Result := Result + Hist[i].Content;

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 Avoid duplicating retained system messages for Gemini

When a Gemini-backed loop starts with an mrSystem policy and an AfterToolResult hook returns steering text, this non-destructive copy leaves the original policy in Hist while also folding it into LiveOptions.SystemPrompt. Unlike the OpenAI and Anthropic builders, the Gemini builder always appends every history mrSystem entry to Options.SystemPrompt (src/pkg/providers/PasClaw.Providers.Gemini.pas:123-132), even when that option is already populated. Every subsequent Gemini request therefore sends the retained policy twice. Please deduplicate the Gemini request construction or otherwise preserve the history policy without copying it twice for this provider.

Useful? React with 👍 / 👎.

…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
FMXExpress merged commit 7faf1a0 into main Jun 1, 2026
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