Repository navigation
Context-mode followups: memory_fetch tool + working-state snapshot + think-in-code steering - #180
Conversation
When a question needs numbers, summaries, or filtered results across many files, the model often reaches for fs_read on each one and burns tens of KB of context on raw bodies it'll never reference again. The new rule steers toward writing a short script (grep | wc -l, awk, a Python one-liner) that computes the answer and prints only the result -- the script's stdout becomes the evidence, the raw file content never enters the conversation. Concept borrowed from mksglu/context-mode's 'think in code' pattern. Pure system-prompt change, ~12 LOC in BuildRulesSection. No behavior shift for the tool loop; the model is just nudged at the prompt level. No-tools mode stays unchanged (the rule assumes tool access).
Today the model has to do three steps for a reference doc: 1. web_fetch(url) -- body lands in the conversation 2. fs_write(path, ..) -- save to workspace/memory/ 3. memory_search(q) -- query the slice later Step 1 dumps the entire body into context for what's often a manual / RFC / API doc the model will only need by search. memory_fetch collapses 1+2 into one tool call AND leaves the body out of context: only a one-line confirmation returns. The next memory_search picks up the new file via SyncDir. Concept from mksglu/context-mode. Reuses PasClaw.Providers.HTTP for the round-trip, the WebFetch SSRF guard (same public->private redirect refusal), HTMLToText for HTML pages. Files land at workspace/memory/fetched-<sanitised>.md with a 4-line YAML-ish header (source, fetched_at, content-type) so origin is traceable. Filename sanitiser is kebab-case, 60-char capped, falls back to a FNV-1a URL hash when sanitisation collapses to empty. Gated on Cfg.WebFetchEnabled at every registration site (Cmd.Agent + Cmd.TUI + Cmd.Gateway + Cmd.Serve + both TPasClawAgent/Server paths in pkg/agent) -- same shape as web_fetch, no point exposing one without the other. tcMutating category (writes to workspace). Wired into PasClaw.dproj for the Delphi build.
Tracks per-session signals the conversation transcript routinely
loses across compaction or a /quit-then-resume cycle:
- EditedFiles last 8 paths touched by fs_write / fs_edit_hashline
(deduped, newest-first move-to-front)
- LastShell most recent shell_exec command (200-char cap)
- LastError most recent tool-call ERROR: surfaced into history
- Updated unix-seconds bookkeeping
Persisted under meta.working_state in the session JSON. Helpers
in PasClaw.Session.Store:
- UpdateWorkingStateAfterTurn walks the loop's FinalMessages
and refreshes the four fields
- FormatWorkingStateBlock renders the snapshot as a
system-prompt prefix, '' when
empty so callers can prepend
unconditionally
Wired into both interactive paths:
- TUI.ApplyLoopResultTo calls UpdateWorkingStateAfterTurn
against Target.Meta before Save; TUI.StartTurn sets
Cfg.Options.SystemPrompt := FormatWorkingStateBlock(...) so
the next turn opens with structured context.
- Cmd.Agent.RunInteractive does the same: prepends the
working-state block ahead of the existing SystemPromptOverride
(compaction summary) so the model sees BOTH on every turn,
and refreshes Meta.WorkingState before each PersistSession.
Empty snapshot emits no JSON object (round-trip byte-stable for
pre-feature sessions) and renders to empty string (no prompt
pollution for fresh sessions).
Tests: working_state_tests covers fs_write extraction,
fs_edit_hashline + dedupe, shell + error capture, empty-state
formatting, populated-state formatting, Save/Load round-trip,
and the empty-not-emitted invariant.
Concept from mksglu/context-mode (session-tracking SQLite +
priority-tiered XML snapshot rebuilt after compaction). PasClaw
reuses its existing per-session JSON instead of standing up a
sidecar DB; same idea, half the moving parts.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 289dbc5557
ℹ️ 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".
| WorkingStateBlock := FormatWorkingStateBlock(Session.Meta); | ||
| if WorkingStateBlock <> '' then | ||
| LoopCfg.Options.SystemPrompt := | ||
| WorkingStateBlock + sLineBreak + LoopCfg.Options.SystemPrompt; |
There was a problem hiding this comment.
Avoid persisting the injected working-state block
When a session has any working state, this prepends the block to LoopCfg.Options.SystemPrompt, and the later SystemPromptOverride := Loop.FinalSystemPrompt persists that combined prompt for the next turn. Since the next turn reuses SystemPromptOverride and prepends the current working-state block again, interactive pasclaw agent sessions accumulate duplicate/stale "Working state from prior turns" sections on every turn after the first edit/shell/error, bloating the system prompt and keeping old snapshots around.
Useful? React with 👍 / 👎.
| if URLIsLocal(URL, SsrfWhy) then | ||
| begin | ||
| ErrMsg := 'memory_fetch: SSRF block: ' + SsrfWhy; | ||
| Exit; | ||
| end; |
There was a problem hiding this comment.
Honor disabled private-network blocking
This unconditional URLIsLocal check makes memory_fetch refuse localhost/RFC1918 URLs even when an operator has set sandbox.block_private_networks=false; web_fetch only performs the same pre-check inside if NetworkBlockingActive then, and the redirect guard in this new tool already follows that gate. In environments that intentionally allow private docs or internal services to be fetched, web_fetch works but the new memory_fetch path remains unusable.
Useful? React with 👍 / 👎.
…BlockingActive P2 #1 -- Avoid persisting the injected working-state block. Cmd.Agent.RunInteractive prepended the WorkingStateBlock to LoopCfg.Options.SystemPrompt and then captured the whole thing into SystemPromptOverride after the loop returned. On the next turn, BuildLoopConfig would overwrite Options.SystemPrompt with the (already-prefixed) override, and the new WS block would prepend AGAIN -- accumulating duplicate snapshots on every interactive turn after the first edit/shell/error. Fix: after capturing Loop.FinalSystemPrompt into SystemPromptOverride, strip the leading 'WorkingStateBlock + sLineBreak' prefix when it matches verbatim. When it doesn't match (compaction rewrote the whole prompt), keep the compacted text -- the summariser's output is what we want stored. P2 #2 -- Honor disabled private-network blocking. memory_fetch ran URLIsLocal unconditionally; web_fetch only does the check inside 'if NetworkBlockingActive then'. Operators who set sandbox.block_private_networks=false to fetch internal documentation had web_fetch working but memory_fetch refusing the same URLs. Fix: gate the pre-flight URLIsLocal call on NetworkBlockingActive, matching web_fetch. The redirect guard in this unit already honoured the gate -- only the synchronous up-front check needed the same wrapper.
Summary
Three context-mode-inspired follow-ups in one PR, kept as separate commits so the reviewer can read them independently:
memory_fetchtool — fetch a URL straight intoworkspace/memory/without the body ever entering context.meta.working_statetracks edited files / last shell / last error; re-injected as a system-prompt prefix on the next turn so a resumed session keeps its bearings after compaction.BuildRulesSectionnudging the model to answer file-aggregation questions with a small script instead of reading every file into context.Commit 1 —
memory_fetchtoolNew
PasClaw.Tools.MemoryFetchunit. The model previously had to callweb_fetch(body in context) →fs_write→memory_searchfor any reference doc.memory_fetch(url, name?)collapses 1+2 into one call AND returns only a one-line confirmation:Reuses the existing
PasClaw.Providers.HTTP.GetURL, theWebFetchredirect/SSRF guard pattern, andHTMLToTextfor HTML pages. Files land atworkspace/memory/fetched-<sanitised>.mdwith a YAML-ish header:The next
memory_searchpicks the new file up via SyncDir. Gated onCfg.WebFetchEnabledat every registration site (CLI agent + TUI + gateway + serve + bothTPasClawAgent/TPasClawServerpaths inpkg/agent) — same HTTP machinery asweb_fetch, no point exposing one without the other. Wired intoPasClaw.dprojfor the Delphi build.Commit 2 — Working-state snapshot
New
TWorkingStaterecord onTSessionMeta:Helpers in
PasClaw.Session.Store:UpdateWorkingStateAfterTurn(var Meta; const Hist)— walks the loop's final messages, captures signals, idempotent.FormatWorkingStateBlock(const Meta): string— renders as a system-prompt prefix,''when empty.Wired into both interactive paths:
ApplyLoopResultTorefreshesTarget.Meta.WorkingState;StartTurnsetsCfg.Options.SystemPrompt := FormatWorkingStateBlock(FSession.Meta)so the next turn opens with structured context.Cmd.Agent.RunInteractive: same — prepends the working-state block ahead of the existingSystemPromptOverride(compaction summary) so the model sees both, and refreshesMeta.WorkingStatebefore eachPersistSession.Persistence is via a new
working_stateJSON object insidemeta. Empty snapshot emits no JSON (byte-stable for pre-feature sessions) and renders to empty string (no prompt pollution for fresh sessions).working_state_testscovers: fs_write extraction, fs_edit_hashline + dedupe with move-to-front, shell + error capture, empty-state formatting, populated-state formatting, Save/Load round-trip, empty-not-emitted invariant.Commit 3 — "Think in code" steering
12 lines added to
BuildRulesSectioninPasClaw.Agent.Prompt:Pure system-prompt change. The no-tools path is untouched (the rule assumes tool access).
Test plan
makerebuilds cleanly (FPC, mode delphi)make test— all 12 suites green (smoke + 11 existing + newworking_state_tests)pasclaw agent, ask it to fetch and summarize a doc — confirmmemory_fetchwrites toworkspace/memory/fetched-*.md, the body never enters context, and a follow-upmemory_searchpicks the doc up./quit, resume — confirm the working-state block appears in the next system prompt and shows the edited path.proceduredefinitions are insrc/" — confirm it reaches forshell_execwith a grep + counting pipeline rather thanfs_read-ing every .pas file.Generated by Claude Code