Skip to content

Context-mode followups: memory_fetch tool + working-state snapshot + think-in-code steering - #180

Merged
FMXExpress merged 4 commits into
mainfrom
claude/context-mode-followups
Jun 8, 2026
Merged

FMXExpress merged 4 commits into
mainfrom
claude/context-mode-followups

Conversation

@FMXExpress

Copy link
Copy Markdown
Owner

Summary

Three context-mode-inspired follow-ups in one PR, kept as separate commits so the reviewer can read them independently:

  1. memory_fetch tool — fetch a URL straight into workspace/memory/ without the body ever entering context.
  2. Working-state snapshot — per-session meta.working_state tracks 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.
  3. "Think in code" steering rule — new entry in BuildRulesSection nudging the model to answer file-aggregation questions with a small script instead of reading every file into context.

Commit 1 — memory_fetch tool

New PasClaw.Tools.MemoryFetch unit. The model previously had to call web_fetch (body in context) → fs_write → memory_search for any reference doc. memory_fetch(url, name?) collapses 1+2 into one call AND returns only a one-line confirmation:

memory_fetch: 31204 chars from https://www.rfc-editor.org/rfc/rfc7230 indexed as fetched-rfc7230.md. Run memory_search to query.

Reuses the existing PasClaw.Providers.HTTP.GetURL, the WebFetch redirect/SSRF guard pattern, and HTMLToText for HTML pages. Files land at workspace/memory/fetched-<sanitised>.md with a YAML-ish header:

<!-- pasclaw memory_fetch -->
source: https://www.rfc-editor.org/rfc/rfc7230
fetched_at: 2026-06-08T22:41:33Z
content-type: text/html; charset=utf-8

<body>

The next memory_search picks the new file up via SyncDir. Gated on Cfg.WebFetchEnabled at every registration site (CLI agent + TUI + gateway + serve + both TPasClawAgent/TPasClawServer paths in pkg/agent) — same HTTP machinery as web_fetch, no point exposing one without the other. Wired into PasClaw.dproj for the Delphi build.

Commit 2 — Working-state snapshot

New TWorkingState record on TSessionMeta:

TWorkingState = record
  EditedFiles: array of string;   // last 8 fs_write / fs_edit paths, newest-first
  LastShell:   string;            // most recent shell_exec command (200 char cap)
  LastError:   string;            // most recent tool-call ERROR:
  Updated:     Int64;
end;

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:

  • TUI: ApplyLoopResultTo refreshes Target.Meta.WorkingState; StartTurn sets Cfg.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 existing SystemPromptOverride (compaction summary) so the model sees both, and refreshes Meta.WorkingState before each PersistSession.

Persistence is via a new working_state JSON object inside meta. Empty snapshot emits no JSON (byte-stable for pre-feature sessions) and renders to empty string (no prompt pollution for fresh sessions).

working_state_tests covers: 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 BuildRulesSection in PasClaw.Agent.Prompt:

6. Think in code, not in transcripts — when a question needs numbers, summaries, or filtered results across many files, prefer writing a short shell or Python script that computes the answer and prints only the result, rather than reading dozens of files into context...

Pure system-prompt change. The no-tools path is untouched (the rule assumes tool access).

Test plan

  • make rebuilds cleanly (FPC, mode delphi)
  • make test — all 12 suites green (smoke + 11 existing + new working_state_tests)
  • Manual: pasclaw agent, ask it to fetch and summarize a doc — confirm memory_fetch writes to workspace/memory/fetched-*.md, the body never enters context, and a follow-up memory_search picks the doc up.
  • Manual: edit a file via the agent, /quit, resume — confirm the working-state block appears in the next system prompt and shows the edited path.
  • Manual: ask the agent "how many procedure definitions are in src/" — confirm it reaches for shell_exec with a grep + counting pipeline rather than fs_read-ing every .pas file.

Generated by Claude Code

claude added 3 commits June 8, 2026 13:45
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.

@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: 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".

Comment on lines +645 to +648
WorkingStateBlock := FormatWorkingStateBlock(Session.Meta);
if WorkingStateBlock <> '' then
LoopCfg.Options.SystemPrompt :=
WorkingStateBlock + sLineBreak + LoopCfg.Options.SystemPrompt;

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 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 👍 / 👎.

Comment on lines +299 to +303
if URLIsLocal(URL, SsrfWhy) then
begin
ErrMsg := 'memory_fetch: SSRF block: ' + SsrfWhy;
Exit;
end;

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 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.
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