Skip to content

Per-session profiles, plus three bugs found by running PasClaw against its own source - #551

Merged
FMXExpress merged 5 commits into
mainfrom
claude/keen-einstein-kPEMj
Aug 15, 2026
Merged

FMXExpress merged 5 commits into
mainfrom
claude/keen-einstein-kPEMj

Conversation

@FMXExpress

Copy link
Copy Markdown
Owner

One requested feature and three defects that surfaced while benchmarking the agent by pointing it at this repo through the relay provider.

Per-session config profiles (c69bd65)

A session that starts under security should stay sandboxed when you come back to it, even from a shell whose config.json names something else. The profile was resolved purely from ambient state, so resuming was a coin flip against whatever the operator's config said that day.

TSessionMeta gains a Profile field alongside the Model and Provider it already records. The resume path reads it with PeekSessionProfile, which parses just meta.profile out of the session file — the answer is needed before LoadConfig runs, and a full TSession.Create would walk every message to learn one string.

Precedence for a run:

1. --profile          typed for this invocation
2. $PASCLAW_PROFILE   ambient, set once per shell
3. the session's own recorded profile      <- new
4. workspace binding / global "profile" field

Layers 1, 2 and 4 already lived inside LoadConfig. Layer 3 is added in Cmd.Agent by passing the session's profile as the override when nothing more explicit was given — which keeps Config unaware of sessions (it sits underneath the session store, so the dependency can only point one way) and lets an empty result fall through to LoadConfig's existing chain. pasclaw resume <id> shares the path, being a thin alias for agent --session <id>.

Stamping needs to know what LoadConfig actually resolved, so TConfig gains ProfileName — runtime-derived, never read from or written to config.json, and set only once a profile's layers have applied. An unknown name falls back to defaults, and reporting it as active would make the session stamp a lie.

A session records the profile it was created under and keeps it, so an explicit --profile for one invocation does not silently rewrite the binding.

Verified by hand across the whole chain: session low-token beats global security; --profile max-build beats the session; PASCLAW_PROFILE=baseline beats the session; no --session falls back to the global field.

shell_exec reported raw wait statuses on FPC/Linux (8c3541a)

The agent ran a failing command and the tool result read exit=512. That is not an exit code — it is 2 << 8, the raw status waitpid hands back.

FPC's TProcess normalises ExitStatus only when it reaps the child itself via poWaitOnExit. Every caller here reaps through the Running poll instead, because they have to drain the output pipe as it fills; on that path ExitStatus keeps the raw status and ExitCode is the normalised one. Proven with a probe against the exact polling shape:

poWaitOnExit   ExitStatus=2     ExitCode=0
Running poll   ExitStatus=512   ExitCode=2

Three sites in the FPC branch read the wrong one — TStdioProcess.Running (which backs execute_code and the streaming TUI path), RunOneShot, and RunOneShotWithEnv. Both Delphi branches were already correct, so this only ever bit the shipping FPC/Linux build.

before:  exit 1 -> 256    exit 2 -> 512    exit 127 -> 32512
after:   exit 1 -> 1      exit 2 -> 2      exit 127 -> 127

That matters beyond cosmetics: shell_exec's own description promises reports "exit=<code>", the prompt teaches 127 as command-not-found, and any retry heuristic keyed on a real code silently missed every one. Re-verified end to end through the rebuilt binary over the relay: exit=3 and exit=127.

This commit also carries an 8-line comment fix in PasClaw.Config.Profile.pas — the task that found the exit-code bug. The unit header described stock as shipping web_fetch, vault and memory_fetch all OFF, contradicting Profile_Stock's own _description and TConfig.Create twenty lines and two hundred lines away respectively. Only vault is off.

grep_files: say on the parameter that it is a literal substring (ed64fc5)

My first tool call against this repo was grep_files with web_fetch_enabled|vault_tools_enabled|Profile_Stock. It returned "no matches", as did the second alternation in the same batch — two of three parallel slots and a whole round trip, spent on nothing.

The tool already recovers well: the handler's LooksRegexy heuristic appends "matches a LITERAL substring, not a regex". But that correction lives in the error, so the only way to learn it is to fail first. The schema had prevention backwards — every optional field (include, context_lines, max_file_bytes) carried a description, and the one required field carried none. And it is named pattern, which reads as regex to any model that has ever seen a grep flag.

One line on that parameter, mirroring the handler's wording so prevention and recovery say the same thing. Costs 162 bytes in the tool block (959 → 1121); saves a guaranteed round trip the first time a session greps.

shell_exec was on the same list and was dropped after inspection: its description already opens with "Run a shell command via /bin/sh -c" and explains the pipe/exit-code trap. Writing ${PIPESTATUS[0]} anyway was a model attention failure, not a documentation gap, and a second sentence saying the same thing would be bulk rather than a fix.

make all never rebuilt after a source change (2d781bb)

Edit a .pas, run make all, get Nothing to be done for 'all' and keep the previous binary. $(BIN) listed only the webui .res and two order-only prerequisites, so make had no reason to connect 326 Pascal units to the program compiled from them.

Worse than a slow build: verifying a change silently exercises the old binary and make reports success. It bit this work twice — an exit-code fix confirmed against a probe program while the shipped binary sat nine hours stale, and a tool-schema change declared live when nothing had compiled. make test masks it, because those targets invoke fpc on test programs directly.

vendor/Indy is deliberately excluded from the new prerequisite list: it changes only when $(INDY_DIR) fetches it, it is already an order-only prerequisite, and globbing it would add thousands of stats to every make invocation.

make build is left alone. It resolves to the build/ directory and quietly does nothing, which is how this was first hit — but it is not a documented target (no hit in README, docs/, AGENTS.md or CLAUDE.md), and $(BUILDDIR) defaults to build, so a phony alias would collide with the directory rule that 106 order-only prerequisites depend on.

Testing

New coverage:

  • session_stats_tests: TSessionMeta.Profile round-trips; PeekSessionProfile reads it back without loading the transcript, returns '' for a missing session, and refuses an unsafe id
  • config_profile_tests: TConfig.ProfileName reports an applied profile, stays empty when none is named, stays empty for an unresolvable name, and reports one named by config.json rather than the CLI

Green after rebasing onto current main: test-config-profile, test-session-stats, test-fs-grep-tier5-6, lint-studio, and a clean make all from a removed binary.

Two suites fail on this branch — test-subagent-bg and test-heartbeat — and both fail identically on unmodified main, confirmed by stashing. Untouched here.

🤖 Generated with Claude Code

https://claude.ai/code/session_01LGQKz579j1ZnDRwmr6h1V6


Generated by Claude Code

claude added 4 commits August 15, 2026 13:48
…as created with

A session that starts under `security` should stay sandboxed when you come
back to it, even from a shell whose config.json names something else. Until
now the profile was resolved purely from ambient state -- CLI flag, env var,
workspace binding, global field -- so resuming was a coin flip against
whatever the operator's config happened to say that day.

TSessionMeta gains a Profile field alongside the Model and Provider it
already records, persisted and loaded the same way. The resume path reads it
with PeekSessionProfile, which parses just meta.profile out of the session
file: the answer is needed BEFORE LoadConfig runs, and a full TSession.Create
would walk every message to learn one string.

Precedence for a run is now:

  1. --profile          typed for this invocation
  2. $PASCLAW_PROFILE   ambient, set once per shell
  3. the session's own recorded profile
  4. workspace binding / global "profile" field

Layers 1, 2 and 4 already lived inside LoadConfig. Layer 3 is added in
Cmd.Agent by passing the session's profile as the override when nothing more
explicit was given -- which keeps Config unaware of sessions (Config sits
underneath the session store, so the dependency can only point one way) and
lets an empty result fall straight through to LoadConfig's existing chain.
`pasclaw resume <id>` shares the path, since it is a thin alias for
`agent --session <id>`.

Stamping needs to know what LoadConfig actually resolved, so TConfig gains
ProfileName -- runtime-derived, never read from or written to config.json,
and set only once a profile's layers have applied. An unknown name falls back
to defaults, and reporting it as active would make the session stamp a lie.
The gateway comment at the resolution site already anticipated callers that
need this answer; they can now read it instead of re-walking the chain and
drifting from it.

A session records the profile it was CREATED under and keeps it, so an
explicit --profile for one invocation does not silently rewrite the binding.
The session banner and `pasclaw session show` name the profile when there is
one, and say nothing when there isn't.

Verified by hand across the whole chain: session low-token beats global
security; --profile max-build beats the session; PASCLAW_PROFILE=baseline
beats the session; no --session falls back to the global field.

test-subagent-bg and test-heartbeat fail identically on unmodified main and
are untouched by this change.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LGQKz579j1ZnDRwmr6h1V6
… 512

Found by driving PasClaw against its own source through the relay. The agent
ran a command that failed and the tool result read `exit=512`. That is not an
exit code -- it is `2 << 8`, the raw status waitpid hands back.

FPC's TProcess normalises ExitStatus only when it reaps the child itself via
poWaitOnExit. Every caller here reaps through the `Running` poll instead,
because they have to drain the output pipe as it fills; on that path
ExitStatus keeps the raw status and ExitCode is the normalised one. Proven
with a two-line probe against the exact polling shape:

    poWaitOnExit  ExitStatus=2    ExitCode=0
    Running poll  ExitStatus=512  ExitCode=2

Three sites in the FPC branch read the wrong one -- TStdioProcess.Running
(which backs execute_code and the streaming TUI path), RunOneShot, and
RunOneShotWithEnv. The Delphi branches were already correct: the POSIX one
applies WIFEXITED/WEXITSTATUS by hand and the Windows one uses
GetExitCodeProcess, so this only ever bit the shipping FPC/Linux build.

What the model saw before the fix:

    exit 1          -> 256
    exit 2          -> 512
    exit 127        -> 32512
    command missing -> 32512

and after:

    0, 1, 2, 127, 127

That matters beyond cosmetics. shell_exec's own description tells the model
"reports exit=<code>", the prompt teaches 127 as command-not-found, and any
retry heuristic keyed on a real code silently missed every one of them.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LGQKz579j1ZnDRwmr6h1V6
Driving PasClaw against its own source, my first tool call was
`grep_files` with `web_fetch_enabled|vault_tools_enabled|Profile_Stock`.
It returned "no matches", as did the second alternation in the same batch:
two of three parallel slots and a whole round trip, spent on nothing.

The tool already recovers well -- the handler's LooksRegexy heuristic
appends "matches a LITERAL substring, not a regex. Search one plain term".
But that correction lives in the ERROR, so the only way to learn it is to
fail first. The schema had the prevention backwards: every OPTIONAL field
(include, context_lines, max_file_bytes) carried a description, and the one
REQUIRED field carried none -- and it is named `pattern`, which reads as
regex to any model that has ever seen a grep flag.

One line on that parameter, mirroring the handler's own wording so the
prevention and the recovery say the same thing. Costs 162 bytes in the tool
block; saves a guaranteed round trip the first time a session greps.

Not changed: shell_exec. I had it on the same list, but on inspection its
description already opens with "Run a shell command via /bin/sh -c (or
cmd.exe on Windows)" and even explains the pipe/exit-code trap. I still
wrote ${PIPESTATUS[0]} and got "Bad substitution", which is a model
attention failure, not a documentation gap -- adding a second sentence
saying the same thing would be bulk, not a fix.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LGQKz579j1ZnDRwmr6h1V6
Edit a .pas, run `make all`, get "Nothing to be done for 'all'" and keep the
previous binary. The rule listed only the webui .res and two order-only
prerequisites, so make had no reason to believe 326 Pascal units had anything
to do with the program compiled from them.

This is worse than a slow build. Verifying a change silently exercises the
OLD binary, and the failure is invisible because make reports success. It bit
this session twice: an exit-code fix was confirmed against a probe program
while the shipped binary sat nine hours stale, and a tool-schema change was
declared live when nothing had compiled. `make test` masks it, because those
targets invoke fpc on test programs directly.

The fix is the prerequisite list that was missing. vendor/Indy is
deliberately excluded: it changes only when $(INDY_DIR) fetches it, it is
already an order-only prerequisite, and globbing it would add thousands of
stats to every make invocation.

Verified: touch a source -> Linking; touch nothing -> "Nothing to be done";
make clean unchanged; test-config-profile, test-session-stats,
test-fs-grep-tier5-6 and lint-studio all still pass.

Not changed: `make build`. It resolves to the build/ DIRECTORY and quietly
does nothing, which is how I first hit this -- but it is not a documented
target (no hit in README, docs/, AGENTS.md or CLAUDE.md), and $(BUILDDIR)
defaults to `build`, so a phony alias would collide with the directory rule
that 106 order-only prerequisites depend on. Using it was my error, not the
Makefile's.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LGQKz579j1ZnDRwmr6h1V6

@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: 2d781bbd62

ℹ️ 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/cmd/PasClaw.Cmd.Agent.pas Outdated
it later. Only when empty: a session records the profile it was
CREATED under and keeps it, so an explicit --profile for one
invocation doesn't silently rewrite the session's binding. }
if Session.Meta.Profile = '' then Session.Meta.Profile := Cfg.ProfileName;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Stamp the profile on every newly persisted session

This assignment only covers the session initially created by RunInteractive. A session created by pasclaw agent --profile security --session <id> -m ... is saved by RunSingleTurn without setting Meta.Profile, and a session created through interactive /new has the same omission. Resuming either session makes PeekSessionProfile return '', so LoadConfig falls back to the workspace/global profile and can silently drop the security configuration the session was created under. Stamp Cfg.ProfileName whenever these other paths create a new persisted session as well.

Useful? React with 👍 / 👎.

…k text

test-subagent-bg and test-heartbeat have both been failing on unmodified
main. One root cause: the per-turn date/time stamp lands on the outbound
copy of the history, so a scripted or fake provider legitimately receives
`body + clock` -- and both tests assert on the exact text the provider saw.

    heartbeat    want "check the build status briefly"
                 got  "check the build status briefly\n\n[current date/time: ...]"

    subagent_bg  want "ECHO[summarise rust ownership]"
                 got  "ECHO[summarise rust ownership\n\n[current date/time: ...]]"

The feature is right and the assertions were stale. A heartbeat wake-up and a
spawned subagent both benefit from knowing what time it is; nothing about
either case argues for suppressing the clock.

So the fix is on the test side, but not by hand-matching the stamp. The shape
was written inline in HistWithTurnClock, which meant any test coping with it
had to respell the format and would rot the day it moved. It now has one
owner -- TurnClockPrefix -- plus an exported StripTurnClock that both tests
go through.

StripTurnClock took two passes. The first assumed the stamp ended the string,
which holds for a message body but not for a spawn_wait status that QUOTES a
stamped prompt and continues with more text after it. It now scans to the
closing bracket and loops; the stamp carries no nested brackets, so the first
] after the marker closes it.

In subagent_bg the strip goes in the fake provider's echo rather than around
five separate assertions: those tests check WHICH TASK the job ran, not the
transport decoration around it, so one strip at the source is both smaller
and more faithful to what is being asserted.

Also in this commit, from Codex on #551: NewStampedSession.

The profile stamp started life inline in RunInteractive, which covered only
the session that path creates. `agent --session <id> -m ...` (RunSingleTurn)
and interactive /new both persist sessions too, and both were writing them
with no profile -- so resuming either fell back to the ambient profile and
silently dropped the sandbox the session was created under, which is the
exact failure this feature exists to prevent.

Fixed structurally rather than by repeating the assignment at three call
sites -- the same shape Codex rightly rejected on #547. Session creation now
has one stamped entry point and `grep "TSession.Create("` in Cmd.Agent
returns only the line inside it, so a fourth path cannot forget the stamp.

`make -k test` is now fully clean.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LGQKz579j1ZnDRwmr6h1V6
@FMXExpress
FMXExpress merged commit d17d8d8 into main Aug 15, 2026
FMXExpress pushed a commit that referenced this pull request Aug 15, 2026
…rn/scars cover them

`pasclaw learn` mines saved sessions, `--write-scars` turns recurring
failures into SCARS.md, and SCARS.md feeds the prompt (wired on #551). That
chain worked for the CLI and for the web UI -- which posts its transcript
back through /v1/sessions -- and stopped dead for anything driving PasClaw
through the chat endpoints.

The gateway kept only stats buckets. AccumulateGatewayStats loads
_gateway_v1_chat, adds token counters, saves. No transcript, ever, even
when the request carried X-PasClaw-Session: the id was used for steering and
checkpoint selection and then dropped. A full multi-turn run left this:

    sessions/_gateway_v1_chat.json  ->  messages: 0
    meta.stats: input_tokens 13000, output_tokens 9300

22k tokens flowed and nothing was kept, so `pasclaw learn` answered "(no
saved sessions to mine)". The desktop app, any HTTP integration, and the
relay all sit behind those endpoints, and none of them could ever produce a
scar. The agent kept relearning mistakes it had already made there.

PersistGatewaySession writes Loop.FinalMessages to a session named by the
request, alongside the existing bucket accounting rather than instead of it.
Wired into /v1/chat and both /v1/chat/completions paths (streaming and
buffered).

Opt-in by construction: no session id, no transcript. Stateless passthrough
-- where the conversation belongs to the caller, not to PasClaw -- is
byte-identical to before, which is why the buckets stay exactly as they
were. IsSafeSessionId gates the filename, and a transcript that cannot be
written logs a warning instead of failing the request the caller actually
asked for.

Verified end to end. One /v1/chat request with X-PasClaw-Session: gwlearn1:

    before   sessions/ -> only _gateway_v1_chat.json (383 B, messages: 0)
             learn     -> "(no saved sessions to mine)"

    after    sessions/gwlearn1.json -> 7892 B, messages: 3, provider relay
             learn     -> "scanned 2 session(s)"

Zero patterns found is the correct answer there, not a gap: a pattern has to
recur across at least two sessions before learn will name it.

Found by benchmarking PasClaw against itself and then trying to close the
loop with `learn`, per the standing method -- the run produced nothing to
learn from, and the reason was that the harness drove the HTTP API rather
than the CLI. That was a harness mistake, but it uncovered a real one: every
non-CLI surface had the same blind spot, and unlike the harness it could not
be fixed by calling something else.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LGQKz579j1ZnDRwmr6h1V6
FMXExpress pushed a commit that referenced this pull request Aug 15, 2026
…rn/scars cover them

`pasclaw learn` mines saved sessions, `--write-scars` turns recurring
failures into SCARS.md, and SCARS.md feeds the prompt (wired on #551). That
chain worked for the CLI and for the web UI -- which posts its transcript
back through /v1/sessions -- and stopped dead for anything driving PasClaw
through the chat endpoints.

The gateway kept only stats buckets. AccumulateGatewayStats loads
_gateway_v1_chat, adds token counters, saves. No transcript, ever, even
when the request carried X-PasClaw-Session: the id was used for steering and
checkpoint selection and then dropped. A full multi-turn run left this:

    sessions/_gateway_v1_chat.json  ->  messages: 0
    meta.stats: input_tokens 13000, output_tokens 9300

22k tokens flowed and nothing was kept, so `pasclaw learn` answered "(no
saved sessions to mine)". The desktop app, any HTTP integration, and the
relay all sit behind those endpoints, and none of them could ever produce a
scar. The agent kept relearning mistakes it had already made there.

PersistGatewaySession writes Loop.FinalMessages to a session named by the
request, alongside the existing bucket accounting rather than instead of it.
Wired into /v1/chat and both /v1/chat/completions paths (streaming and
buffered).

Opt-in by construction: no session id, no transcript. Stateless passthrough
-- where the conversation belongs to the caller, not to PasClaw -- is
byte-identical to before, which is why the buckets stay exactly as they
were. IsSafeSessionId gates the filename, and a transcript that cannot be
written logs a warning instead of failing the request the caller actually
asked for.

Verified end to end. One /v1/chat request with X-PasClaw-Session: gwlearn1:

    before   sessions/ -> only _gateway_v1_chat.json (383 B, messages: 0)
             learn     -> "(no saved sessions to mine)"

    after    sessions/gwlearn1.json -> 7892 B, messages: 3, provider relay
             learn     -> "scanned 2 session(s)"

Zero patterns found is the correct answer there, not a gap: a pattern has to
recur across at least two sessions before learn will name it.

Found by benchmarking PasClaw against itself and then trying to close the
loop with `learn`, per the standing method -- the run produced nothing to
learn from, and the reason was that the harness drove the HTTP API rather
than the CLI. That was a harness mistake, but it uncovered a real one: every
non-CLI surface had the same blind spot, and unlike the harness it could not
be fixed by calling something else.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LGQKz579j1ZnDRwmr6h1V6
FMXExpress pushed a commit that referenced this pull request Aug 15, 2026
…k walk

The "a dead provider is not a model turn" guard closed a real bug but took
something with it: a 429 or a 503 with no fallbacks configured used to fall
into the no-tool-call nudge path and get retried BY ACCIDENT. Wrong
mechanism, occasionally right outcome. Removing it without a replacement
turns a rate limit into a failed turn.

So: retry the same provider, bounded, before the fallback walk. A 429 means
"you are going too fast", not "this provider is broken" -- switching
providers on it wastes a healthy primary. Defaults are 2 attempts with a
750 ms backoff that doubles, matching StreamReliability.EmptyRetryAttempts
rather than inventing a second convention. provider_retry_attempts = 0
disables.

The important half is what is NOT retried. IsRetryableStatus accepts
status <= 0, because a socket reset looks like that -- but so does every
permanent local misconfiguration: a relay with no gateway, a missing
OpenSSL handler, an unresolvable host. Retrying those buys latency and the
identical failure, and it would partly undo the guard this sits next to. A
new, narrower IsTransientHttpStatus covers 408 / 429 / 5xx only, i.e. the
cases where the SERVER said to try again. "This provider is down" remains
the fallback walk's job.

An exception during a retry breaks out rather than continuing: an
exception is not the transient the server promised.

New test-provider-retry pins all four behaviours with a counting fake
provider, since call count is the only honest assertion here:

    429 once then 200        -> 2 calls, caller sees the recovered answer
    503 forever, attempts=2  -> 3 calls (initial + 2), then stops
    status -1 forever        -> 1 call, never retried
    attempts=0               -> 1 call, disabled

Config threaded through every loop construction site: Cmd.Agent, all three
gateway handlers, the TUI, and PasClaw.Agent.

Full sweep passes except test-subagent-bg and test-heartbeat, which fail
identically on unmodified main and are fixed on #551.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LGQKz579j1ZnDRwmr6h1V6
FMXExpress pushed a commit that referenced this pull request Aug 15, 2026
…k walk

The "a dead provider is not a model turn" guard closed a real bug but took
something with it: a 429 or a 503 with no fallbacks configured used to fall
into the no-tool-call nudge path and get retried BY ACCIDENT. Wrong
mechanism, occasionally right outcome. Removing it without a replacement
turns a rate limit into a failed turn.

So: retry the same provider, bounded, before the fallback walk. A 429 means
"you are going too fast", not "this provider is broken" -- switching
providers on it wastes a healthy primary. Defaults are 2 attempts with a
750 ms backoff that doubles, matching StreamReliability.EmptyRetryAttempts
rather than inventing a second convention. provider_retry_attempts = 0
disables.

The important half is what is NOT retried. IsRetryableStatus accepts
status <= 0, because a socket reset looks like that -- but so does every
permanent local misconfiguration: a relay with no gateway, a missing
OpenSSL handler, an unresolvable host. Retrying those buys latency and the
identical failure, and it would partly undo the guard this sits next to. A
new, narrower IsTransientHttpStatus covers 408 / 429 / 5xx only, i.e. the
cases where the SERVER said to try again. "This provider is down" remains
the fallback walk's job.

An exception during a retry breaks out rather than continuing: an
exception is not the transient the server promised.

New test-provider-retry pins all four behaviours with a counting fake
provider, since call count is the only honest assertion here:

    429 once then 200        -> 2 calls, caller sees the recovered answer
    503 forever, attempts=2  -> 3 calls (initial + 2), then stops
    status -1 forever        -> 1 call, never retried
    attempts=0               -> 1 call, disabled

Config threaded through every loop construction site: Cmd.Agent, all three
gateway handlers, the TUI, and PasClaw.Agent.

Full sweep passes except test-subagent-bg and test-heartbeat, which fail
identically on unmodified main and are fixed on #551.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LGQKz579j1ZnDRwmr6h1V6
khongten001 pushed a commit to khongten001/PasClaw that referenced this pull request Nov 10, 2026
…rn/scars cover them

`pasclaw learn` mines saved sessions, `--write-scars` turns recurring
failures into SCARS.md, and SCARS.md feeds the prompt (wired on FMXExpress#551). That
chain worked for the CLI and for the web UI -- which posts its transcript
back through /v1/sessions -- and stopped dead for anything driving PasClaw
through the chat endpoints.

The gateway kept only stats buckets. AccumulateGatewayStats loads
_gateway_v1_chat, adds token counters, saves. No transcript, ever, even
when the request carried X-PasClaw-Session: the id was used for steering and
checkpoint selection and then dropped. A full multi-turn run left this:

    sessions/_gateway_v1_chat.json  ->  messages: 0
    meta.stats: input_tokens 13000, output_tokens 9300

22k tokens flowed and nothing was kept, so `pasclaw learn` answered "(no
saved sessions to mine)". The desktop app, any HTTP integration, and the
relay all sit behind those endpoints, and none of them could ever produce a
scar. The agent kept relearning mistakes it had already made there.

PersistGatewaySession writes Loop.FinalMessages to a session named by the
request, alongside the existing bucket accounting rather than instead of it.
Wired into /v1/chat and both /v1/chat/completions paths (streaming and
buffered).

Opt-in by construction: no session id, no transcript. Stateless passthrough
-- where the conversation belongs to the caller, not to PasClaw -- is
byte-identical to before, which is why the buckets stay exactly as they
were. IsSafeSessionId gates the filename, and a transcript that cannot be
written logs a warning instead of failing the request the caller actually
asked for.

Verified end to end. One /v1/chat request with X-PasClaw-Session: gwlearn1:

    before   sessions/ -> only _gateway_v1_chat.json (383 B, messages: 0)
             learn     -> "(no saved sessions to mine)"

    after    sessions/gwlearn1.json -> 7892 B, messages: 3, provider relay
             learn     -> "scanned 2 session(s)"

Zero patterns found is the correct answer there, not a gap: a pattern has to
recur across at least two sessions before learn will name it.

Found by benchmarking PasClaw against itself and then trying to close the
loop with `learn`, per the standing method -- the run produced nothing to
learn from, and the reason was that the harness drove the HTTP API rather
than the CLI. That was a harness mistake, but it uncovered a real one: every
non-CLI surface had the same blind spot, and unlike the harness it could not
be fixed by calling something else.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LGQKz579j1ZnDRwmr6h1V6
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