Skip to content

goals + condense: /goal Ralph loop with judge model + JSON-aware tool-output condenser - #223

Merged
FMXExpress merged 2 commits into
mainfrom
claude/goals-loop-and-json-condenser
Jun 11, 2026
Merged

FMXExpress merged 2 commits into
mainfrom
claude/goals-loop-and-json-condenser

Conversation

@FMXExpress

Copy link
Copy Markdown
Owner

Summary

Two attention-management features that pull in the same direction — get the model to make progress without burning operator tokens on overhead.

1. Goals/Ralph loop (PasClaw.Agent.Goals)

Operator declares an objective via /goal <text> (or /goal --max N <text>); the runner takes over the next N turns:

turn -> tool_loop -> judge_call (MET / CONTINUE / FAILED) -> next ...

A separate Chat() round-trip with a focused system prompt asks a judge to verdict. On MET / FAILED we stop with the judge's reason; on CONTINUE the judge's suggested next step gets fed back as the next user message and the agent keeps going until MET or the budget caps us. Default budget 5.

Implementation choices:

  • Judge gets its own Chat() call — fresh tool-less transcript, no working state, no compaction summary. Keeps the verdict honest; the assistant that just did the work would otherwise be biased toward declaring victory.
  • TGoalRunner is transport-agnostic. Caller passes a TGoalTurnFn that runs one turn (whatever full RunToolLoop config + working-state + compaction the caller wants). Cmd.Agent wires this against its existing BuildLoopConfig + session persistence. TUI hookup is a deliberate follow-up — the threaded PollLoopWorker shape is different enough to deserve its own review.
  • Judge outage doesn't kill the loop. If Chat() raises (rate-limit, network), we fall through to a generic "Continue working toward the goal." prompt so a flaky judge doesn't abort an otherwise-progressing agent. Budget still bounds the total turns.
  • ParseJudgeVerdict tolerates leading whitespace, mixed case, missing newline, decorated punctuation.

2. JSON-aware tool-output condenser (PasClaw.Condense.JSON)

Hooks into RunToolLoop's per-tool-result path before StashAndMaybeTruncate. When the body parses as JSON and is bigger than MaxBytes (4 KB default):

  • Arrays > MaxArrayItems (6 default) collapse to first N + synthetic "...K more items" + last element. An MCP search returning 300 rows becomes [ row 0, row 1, "...297 more items", row 299 ] — shape preserved at both ends.
  • Strings > MaxStringLen (120 default) ellipsize head + tail so file paths / URLs / error prefixes stay recognisable at both ends.
  • Object keys preserved verbatim — the condenser cares about structure, not key count.
  • Depth guard at MaxDepth (16).
  • Inflation guard — if condensation would produce a LARGER body (degenerate case: small array of deeply nested objects), fall back to verbatim.
  • Parse-failure tolerant — malformed or non-JSON → verbatim.

Self-contained recursive-descent walker; no fpjson / System.JSON / PasClaw.JSON dependency. Same source under both compilers.

Wiring

  • RunToolLoop runs MaybeCondenseJSON on every successful tool ResultText BEFORE the byte-budget truncate. A 200 KB JSON response that condenses to 3 KB skips the truncate entirely; OutputCache stays the fallback for bodies still over the cap.
  • pasclaw agent slash dispatcher learns /goal; /help lists it.
  • New units wired into PasClaw.dproj DCCReference list, all three sample dprojs' search paths, samples Makefile, both dcc32.cfg / dcc64.cfg, and the Windows build-fpc.bat / build-delphi.bat so all five build configurations pick up the new units identically.

Test plan

  • make test — full suite green incl. new test-condense-json (10/10) and test-goals-runner (7/7)
  • make smoke — all subcommands OK
  • Manual: pasclaw agent, /help shows /goal, run /goal write a unit test for X and verify it passes against a real provider, observe the iteration markers and the judge's verdicts
  • Manual: invoke an MCP tool that returns a big JSON array, verify in the trace that the condensed form lands in history

Files

  • New: src/pkg/agent/PasClaw.Agent.Goals.pas — TGoalRunner + ParseJudgeVerdict
  • New: src/pkg/condense/PasClaw.Condense.JSON.pas — MaybeCondenseJSON + recursive-descent walker
  • New: src/tests/goals_runner_tests.pas + src/tests/condense_json_tests.pas
  • src/cmd/PasClaw.Cmd.Agent.pas — /goal slash command + GoalTurnRunner nested fn
  • src/pkg/tools/PasClaw.Tools.ToolLoop.pas — pre-truncate condenser hook
  • Build wiring: main dproj, 3 sample dprojs, samples Makefile, both dcc cfgs, both Windows .bat files, top-level Makefile

https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon


Generated by Claude Code

…t condenser

Two attention-management features, deliberately shipped together because
they pull in the same direction: get the model to make progress without
burning the operator's tokens on overhead.

1) PasClaw.Agent.Goals -- the "Ralph" loop. The operator declares an
   objective via /goal <text> (optionally /goal --max N <text>); the
   runner takes over the next N turns:

     turn -> tool_loop -> judge_call (MET / CONTINUE / FAILED) -> ...

   A separate Chat() round-trip with a focused system prompt asks the
   judge to verdict. On MET / FAILED we stop with the judge's reason.
   On CONTINUE the judge's suggested next step gets fed back as the
   NEXT user message; the agent keeps going until MET or the budget
   ceiling caps us. Default budget 5; operator-overridable.

   Implementation choices:
     - Judge gets its own Chat() call -- a fresh tool-less transcript,
       no working state, no compaction summary. Keeps the verdict
       decision honest; the assistant just finished the work and
       would otherwise be biased toward declaring victory.
     - TGoalRunner is transport-agnostic. The caller passes
       TGoalTurnFn that runs ONE turn (whatever full RunToolLoop
       config + working-state + compaction the caller wants). Cmd.Agent
       wires this against its existing BuildLoopConfig + Session
       persistence; the TUI hookup is a follow-up since the threaded
       PollLoopWorker shape is different enough to deserve its own
       review.
     - Judge outage doesn't kill the loop. If Chat() raises (rate-limit,
       network), we fall through to a generic "Continue working toward
       the goal" so a flaky judge doesn't abort an otherwise-progressing
       agent. The budget ceiling still bounds the total turns.
     - ParseJudgeVerdict tolerates leading whitespace, mixed case,
       missing newline, decorated punctuation -- the LLM verdict
       grammar is "first word that looks like MET / CONTINUE / FAILED,
       case-insensitive". Tests pin all four shapes.

   7 unit tests cover: verdict parsing edge cases, MET first turn,
   CONTINUE-then-MET, CONTINUE looping to budget, FAILED, turn-fn
   abort, judge outage fallback.

2) PasClaw.Condense.JSON -- content-type-aware compression that sits
   alongside the existing per-command filters
   (PasClaw.Tools.Shell.Filters, PasClaw.Tools.OutputCache). Hooks
   into RunToolLoop's per-tool-result path BEFORE the byte-budget
   truncate stage. When the body parses as JSON and is bigger than
   MaxBytes (4 KB default):

     - Arrays longer than MaxArrayItems (6 default) collapse to
       first N elements + a synthetic "...K more items" string +
       the last element. An MCP tool returning a 300-row
       search_results array shrinks to
       `[ {...row 0...}, {...row 1...}, "...297 more items",
         {...row 299...} ]`
       -- shape preserved at both ends; the model still knows what
       it's looking at.
     - String values longer than MaxStringLen (120 default) ellipsize
       head+tail so file paths / URLs / error prefixes stay
       recognisable at the front AND tail (where the filename or
       status code usually lives).
     - Object keys preserved verbatim -- the condenser cares about
       STRUCTURE, not key count. A 50-key hash map at full fidelity
       is what we want.
     - Depth guard caps recursion at MaxDepth (16). Defensive.
     - Inflation guard: if condensation would produce something
       LARGER than the original (degenerate case), fall back to
       verbatim. We never make the situation worse.
     - Parse-failure tolerant: malformed JSON -> verbatim. Non-JSON
       -> verbatim. The condenser is a best-effort compressor, not
       a parser.

   Self-contained recursive-descent walker; no fpjson / System.JSON
   import, no PasClaw.JSON dependency. That means the unit ships the
   same source under both compilers without the wrapper indirection
   the rest of the JSON paths use.

   10 unit tests cover: small body verbatim, non-JSON verbatim,
   empty containers verbatim, big array of primitives collapsed,
   big array of objects + structural fidelity, long string head+tail
   ellipsis, nested array inside object, output remains JSON-shaped,
   MaxBytes threshold, malformed JSON verbatim.

Wiring:
   - RunToolLoop runs MaybeCondenseJSON on every successful tool
     ResultText BEFORE deciding whether to call StashAndMaybeTruncate.
     A 200 KB JSON response that condenses to 3 KB skips the truncate
     step entirely; the OutputCache stays the fallback for bodies
     still over the cap after condensation (binary blobs etc.).
   - `pasclaw agent` slash-command dispatcher learns /goal alongside
     the existing /undo + /steer + /compact + ... set; /help lists
     the new command with the budget syntax.
   - New PasClaw.Agent.Goals + PasClaw.Condense.JSON wired into the
     main dproj DCCReference list, all three sample dprojs' search
     paths, the samples Makefile, both dcc cfgs, and the Windows
     fpc/delphi .bat files so all five build configurations pick
     up the new units identically.

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: 8fd617dc77

ℹ️ 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 Resolved
…SON ellipsis (Codex P1/P2 #223)

Two Codex findings on PR #223, both legit:

1) P1 -- Preserve the final assistant reply in goal history

   RunToolLoop returns Loop.FinalMessages BEFORE adding the final
   non-tool assistant text -- the regular CLI / TUI turn paths
   explicitly append Loop.Content afterwards. The /goal turn driver
   forgot to do this, so any iteration that ended with text (the
   common case) dropped the assistant's reply from Hist; the next
   judge-driven turn (and the persisted session) only saw the user
   message + tool transcript, not the actual answer the judge was
   asked to grade or the assistant was supposed to build on.

   Fix in GoalTurnRunner: after Hist := GLoop.FinalMessages, append
   MakeMessage(mrAssistant, GLoop.Content) when content is non-empty.
   Matches the regular CLI path's post-loop append.

   New test (TestTurnFnControlsAssistantAppend) pins the runner
   contract from the other side: TGoalRunner.Run does NOT silently
   mutate Hist beyond what TurnFn returned. The caller owns the
   shape; the runner just walks it.

2) P2 -- Avoid splitting JSON strings inside escape sequences

   EmitCondensedString used Copy(Raw, 2, HeadLen) + Copy(Raw,
   tail-pos, TailLen) -- arbitrary byte cuts that could land
   between '\' and 'n' (inside a JSON escape) or between
   continuation bytes of a UTF-8 multi-byte rune. The resulting
   ellipsized string was technically invalid JSON
   (\" \uXX... \ unmatched) and the model received malformed
   content for tool outputs full of escaped paths / newlines.

   Fix: AdvanceCodePoint walks one logical character at a time --
   a complete JSON escape (\X or \uXXXX) or a complete UTF-8
   byte sequence (1-4 bytes). EmitCondensedString builds a list
   of safe code-point start positions, then picks HeadEnd
   (largest boundary fitting HeadTarget bytes from start) and
   TailStart (smallest boundary fitting TailTarget bytes from
   end). The split lands on safe boundaries on BOTH sides. When
   no safe split exists within the byte budget (a giant string
   of one continuous escape chain), fall back to verbatim and
   let the outer inflation check surface the original.

   New tests:
     - TestEllipsisNeverSplitsAnEscapeSequence: builds a long
       run of \n escapes, asserts the synthetic "..." never has
       an orphan backslash immediately before it (which would
       mean we split mid-escape).
     - TestEllipsisNeverSplitsUTF8Sequence: smoke test that ASCII
       payloads still ellipsize correctly under the new walker.

https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon
@FMXExpress
FMXExpress merged commit f1ba25e into main Jun 11, 2026
FMXExpress pushed a commit that referenced this pull request Jun 13, 2026
Both changelog files were stuck at the 2026-06-10 TUI / background-
subagent / session_search / tool-RPC entries. ~7 weeks of merged
PRs (#214 through #244) had landed without a corresponding entry in
either file -- the git log was the only record of features like the
knowledgebase, inbound MCP server mode, checkpoints + /undo,
heartbeat daemon, shell backends (local | docker), send_message,
promptware defense, Windows shell-output encoding fixes, fs_grep
ripgrep optimisations, OpenTelemetry traces, and `pasclaw agent
--quiet`.

Added (newest first):

  2026-06-13
    #244  agent --quiet log-level clamp

  2026-06-12
    #243  dcc64 search path + agent --quiet / -q
    #242  OpenTelemetry traces (OTLP/HTTP+JSON)
    #241  fs_grep tier 5+6 (byte walker + Boyer-Moore-Horspool)
    #240  fs_grep tier 1-4 (deferred hash + skip-dirs + binary
          sniff + size cap)

  2026-06-11
    #239  Windows shell output: auto-detect UTF-8 vs OEM
    #238  Hashline fs_read header mojibake fix (¶ vs ¶)
    #237  Windows shell output: OEM codepage decode

  2026-06-10
    #233  Shell backends (local | docker via IShellBackend)
    #232  Heartbeat daemon + reversible condensation (CCR)
    #230  send_message tool + condenser families + promptware
          defense + task-aware MEMORY.md slicing

  2026-06-09
    #223  /goal Ralph loop + judge model + JSON-aware condenser
    #222  /undo wired into agent + sample dprojs
    #221  Checkpoints (auto-snapshot + TUI /undo)
    #220  mcp catalog: lenient hub projector
    #219  mcp: SSE / Streamable HTTP / stdio hub transports
    #218  Inbound MCP server mode
    #217  onboard: offer to index docs into the knowledgebase
    #214  Knowledgebase (RAG over operator-curated docs)

Skipped from this changelog (build-system / Delphi-fix / FPC-fix
PRs visible in the git log but not user-facing features):
#215, #216, #224, #225, #226, #227, #228, #229, #231, #234, #236.

Both files (README.md and docs/changelog.md) updated with the same
entries -- intentional mirror so a reader on either surface sees
the same history. Same prose in both; same footnote refs at the
bottom.

Validated: every [#N] reference in both files has a matching [#N]:
URL footnote (no broken links).
FMXExpress pushed a commit that referenced this pull request Jun 16, 2026
Completes the profile-system plan: PR #291 shipped Stages A, B, list/
show/use and the onboarding picker (Stage E). This commit adds the
two missing subcommands.

`pasclaw profile diff <a> <b>`

  Applies each profile (with _inherits resolved) against a fresh
  TConfig in isolation, then walks a hand-curated list of comparable
  fields (loop-shaping booleans, tool_output_cap, sandbox, self-
  improving skills, prompt cache, auto-router) and prints rows where
  the two sides disagree. Suppresses rows where they agree.

  Output:

      $ pasclaw profile diff baseline max-build
      field                                         baseline   max-build
      vault_tools_enabled                           false      true
      web_fetch_enabled                             false      true
      condense_reversible                           false      true
      tool_output_cap                               0          16384
      self_improving_skills.self_manage             false      true
      ...
      (16 differing field(s))

  Why a hand-listed field set instead of a JSON walk of ToJSON output:
  ToJSON is "tidy" -- it suppresses fields matching their default,
  which would make the comparison ambiguous (no row could mean "same
  value" OR "both at default"). Walking live TConfig fields after the
  profile chain is applied is unambiguous.

`pasclaw profile bench --task "<prompt>" --profiles <a,b,c> [--runs N]`

  For each (profile, run) pair, spawns this same binary as
      pasclaw agent --profile <p> --quiet \
                    --session bench-<p>-<n>-<ts> -m "<task>"
  via PasClaw.Platform.RunOneShot. After every run, reads the
  persisted session JSON to harvest per-turn stats (TSessionStats:
  input/output tokens, cache reads, turn count, tool-call count).
  Aggregates per profile across runs, prints a comparison table:

      bench summary
        profile      runs err wall(s)  in_tok  out_tok turns t_call
        baseline        3   0    11.2    1240      380     4      7
        low-token       3   0     9.8     820      360     4      7
        max-build       3   0    12.4     910      420     5      9

  Token / turn / tool-call columns require stats_collection_enabled
  to be on in the active profile (max-build / all-on have it; the
  others don't by default). Wall time and exit codes work regardless.

  Validates every profile name BEFORE running so a typo doesn't burn
  provider calls. --runs defaults to 3; --task and --profiles are
  required. The user's existing config.json (provider keys, etc.) is
  reused; --profile is layered on top per spawn.

  Not a benchmark in the academic sense -- no statistical-significance
  testing, no variance bounds. A "show me concrete numbers on this
  task across these profiles" comparison harness for eyeballing.
  --judge for an LLM-graded quality column is a future follow-up
  (Ralph-loop pattern from PR #223).

Tests: src/tests/config_profile_tests.pas gains TestDiffMaterial,
asserting the invariant the diff command depends on (baseline vs
max-build differ on at least one tracked field; stock vs no-profile
match on the tracked subset). DoDiff's table layout is exercised by
smoke; DoBench is shell-spawn-bound so left for a manual / staging
exercise.

docs/configuration.md updated with diff + bench in the CLI block and
a short "profile diff and profile bench" subsection explaining the
mechanics and caveats.

This finishes the original 6-stage profile-system plan modulo --judge.
khongten001 pushed a commit to khongten001/PasClaw that referenced this pull request Jul 13, 2026
Completes the profile-system plan: PR FMXExpress#291 shipped Stages A, B, list/
show/use and the onboarding picker (Stage E). This commit adds the
two missing subcommands.

`pasclaw profile diff <a> <b>`

  Applies each profile (with _inherits resolved) against a fresh
  TConfig in isolation, then walks a hand-curated list of comparable
  fields (loop-shaping booleans, tool_output_cap, sandbox, self-
  improving skills, prompt cache, auto-router) and prints rows where
  the two sides disagree. Suppresses rows where they agree.

  Output:

      $ pasclaw profile diff baseline max-build
      field                                         baseline   max-build
      vault_tools_enabled                           false      true
      web_fetch_enabled                             false      true
      condense_reversible                           false      true
      tool_output_cap                               0          16384
      self_improving_skills.self_manage             false      true
      ...
      (16 differing field(s))

  Why a hand-listed field set instead of a JSON walk of ToJSON output:
  ToJSON is "tidy" -- it suppresses fields matching their default,
  which would make the comparison ambiguous (no row could mean "same
  value" OR "both at default"). Walking live TConfig fields after the
  profile chain is applied is unambiguous.

`pasclaw profile bench --task "<prompt>" --profiles <a,b,c> [--runs N]`

  For each (profile, run) pair, spawns this same binary as
      pasclaw agent --profile <p> --quiet \
                    --session bench-<p>-<n>-<ts> -m "<task>"
  via PasClaw.Platform.RunOneShot. After every run, reads the
  persisted session JSON to harvest per-turn stats (TSessionStats:
  input/output tokens, cache reads, turn count, tool-call count).
  Aggregates per profile across runs, prints a comparison table:

      bench summary
        profile      runs err wall(s)  in_tok  out_tok turns t_call
        baseline        3   0    11.2    1240      380     4      7
        low-token       3   0     9.8     820      360     4      7
        max-build       3   0    12.4     910      420     5      9

  Token / turn / tool-call columns require stats_collection_enabled
  to be on in the active profile (max-build / all-on have it; the
  others don't by default). Wall time and exit codes work regardless.

  Validates every profile name BEFORE running so a typo doesn't burn
  provider calls. --runs defaults to 3; --task and --profiles are
  required. The user's existing config.json (provider keys, etc.) is
  reused; --profile is layered on top per spawn.

  Not a benchmark in the academic sense -- no statistical-significance
  testing, no variance bounds. A "show me concrete numbers on this
  task across these profiles" comparison harness for eyeballing.
  --judge for an LLM-graded quality column is a future follow-up
  (Ralph-loop pattern from PR FMXExpress#223).

Tests: src/tests/config_profile_tests.pas gains TestDiffMaterial,
asserting the invariant the diff command depends on (baseline vs
max-build differ on at least one tracked field; stock vs no-profile
match on the tracked subset). DoDiff's table layout is exercised by
smoke; DoBench is shell-spawn-bound so left for a manual / staging
exercise.

docs/configuration.md updated with diff + bench in the CLI block and
a short "profile diff and profile bench" subsection explaining the
mechanics and caveats.

This finishes the original 6-stage profile-system plan modulo --judge.
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