Skip to content

Mid-loop steering — push follow-ups into a running agent's tool loop - #120

Merged
FMXExpress merged 2 commits into
mainfrom
claude/steering
Jun 1, 2026
Merged

FMXExpress merged 2 commits into
mainfrom
claude/steering

Conversation

@FMXExpress

Copy link
Copy Markdown
Owner

Summary

Ports picoclaw's pkg/agent/steering.go and nanobot's _inject_pending pattern: while an agent is mid-tool-loop, a follow-up message can be queued and folded into history as a [user steering] ... system note at the top of the NEXT iteration. The next LLM round-trip sees the course-correction without aborting the loop or discarding tool results so far. ~280 LOC.

The audit's #1 Tier 1 gap from yesterday's survey.

What's new

  • src/pkg/agent/PasClaw.Agent.Steering.pas — file-backed FIFO queue at $PASCLAW_HOME/workspace/steering/<key>.jsonl. Pushes are atomic per-line POSIX appends; drains rename to .draining then read+delete, so concurrent push during drain lands in a fresh file the next drain picks up — no message lost, none returned twice. Key validation reuses IsSafeSessionId from PR Persistent session management — durable conversations across restarts #117 (no path traversal). Empty / whitespace text refused.
  • TToolLoopConfig.SteeringKey field. RunToolLoop drains it at iteration top with MaxSteeringPerTurn=4 (matches nanobot's _MAX_INJECTIONS_PER_TURN); extras are dropped with a warn log so a runaway pusher can't grow Hist unbounded.
  • src/cmd/PasClaw.Cmd.Steer.pas — pasclaw steer <id> "..." pushes from another terminal, --list shows pending count, --clear drops the queue. Wired into Cmd.Root + PrintRootHelp.
  • Cmd.Agent sets LoopCfg.SteeringKey := Session.Meta.Id (PR Persistent session management — durable conversations across restarts #117 auto-allocates session ids, so this is always populated for interactive runs). New /steer <msg> slash command for same-terminal testing. /help lists it. /status shows pending count. /reset, /new, and pasclaw session delete clear the queue alongside their existing cleanup.
  • dproj + uses chain entries for the new units.

Usage

# Terminal A
pasclaw agent --session daily-2026-06-01
> Research the latest FPC release notes and tell me about everything that changed since 3.2.4.

# Terminal B, while the tool loop is running
pasclaw steer daily-2026-06-01 "actually skip ARM-specific changes, focus on the language features"
# ✓ queued: "actually skip ARM-specific changes, focus on the language features"
#   the running agent will pick it up at the top of its next iteration

# Terminal A's next loop iteration sees:
# [user steering] actually skip ARM-specific changes, focus on the language features

Out of scope

Channels (Telegram, Discord, etc.) don't yet wire SteeringKey — their inbound message handlers run RunToolLoop synchronously, so there's no "while a loop is running" window for steering to interrupt. That restructure (non-blocking polling per chat) is a per-channel follow-up; the queue + drain mechanism is in place for when each channel opts in.

Test plan

  • make clean && make clean (442688 lines)
  • make smoke 11/11 OK
  • Focused steering queue test (built, ran, removed): 8 assertion groups — unsafe-key rejection at every entry point, push+drain roundtrip with PostedAt, FIFO ordering, MaxMessages cap drops rest (not requeues), drain consumes, PendingSteeringCount inspects without consuming, ClearSteering, empty/whitespace text refused, multiline + quotes + backslashes survive JSON encoding
  • CLI ergonomics spot-checked: push, --list, --clear, unsafe-id rejection
  • Manual: live pasclaw agent --session X + parallel pasclaw steer X "..." against Anthropic — confirm the steering note appears in the next iteration and the model adjusts behaviour

Generated by Claude Code

Ports picoclaw's pkg/agent/steering.go and nanobot's _inject_pending
pattern: while an agent is mid-tool-loop, a follow-up message can be
queued and folded into history as a "[user steering] ..." system note
at the top of the NEXT iteration. The next LLM round-trip sees the
course-correction without aborting the loop or discarding tool
results so far. ~280 LOC.

  - New src/pkg/agent/PasClaw.Agent.Steering.pas: file-backed FIFO
    queue at $PASCLAW_HOME/workspace/steering/<key>.jsonl. Pushes
    are atomic per-line POSIX appends; drains rename to .draining
    then read+delete, so concurrent push during drain lands in a
    fresh file and the next drain picks it up — no message lost,
    none returned twice. Validation: key must pass IsSafeSessionId
    (no path traversal). Empty / whitespace-only text refused.
  - TToolLoopConfig.SteeringKey field. RunToolLoop drains it at
    iteration top with MaxSteeringPerTurn=4 cap (matches nanobot's
    _MAX_INJECTIONS_PER_TURN); extras are dropped with a warn log
    so a runaway pusher can't grow Hist unbounded.
  - New src/cmd/PasClaw.Cmd.Steer.pas CLI: `pasclaw steer <id>
    "..."` pushes from another terminal, `--list` shows pending
    count, `--clear` drops the queue. Wired into Cmd.Root +
    PrintRootHelp.
  - Cmd.Agent sets LoopCfg.SteeringKey := Session.Meta.Id (PR #117
    auto-allocates session ids, so this is always populated for
    interactive runs). Added `/steer <msg>` slash command for
    same-terminal testing; `/help` lists it; `/status` shows
    pending count. /reset, /new, and pasclaw session delete clear
    the queue alongside their existing cleanup.
  - dproj + uses-chain entries for the new units.

Channels currently inherit empty SteeringKey — they don't yet do
concurrent polling and the inbound message handler runs RunToolLoop
synchronously, so there's no "while a loop is running" window for
steering to interrupt. That restructure is a per-channel follow-up
(documented in README); the queue + drain mechanism is in place for
when each channel wires it.

Verified with a focused test (created, built, ran, removed) covering
8 assertion groups: unsafe-key rejection across every entry point,
push+drain roundtrip with PostedAt, FIFO ordering, MaxMessages cap
drops the rest (not requeues), drain consumes, PendingSteeringCount
inspects without consuming, ClearSteering, empty/whitespace text
refused, multiline text + quotes + backslashes survive JSON encoding.
CLI ergonomics spot-checked: push prints queued message, --list
shows count, --clear succeeds, unsafe id rejected with a clear
error.

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: a0c791e4a9

ℹ️ 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 +570 to +572
SetLength(Hist, Length(Hist) + 1);
Hist[High(Hist)] := MakeMessage(mrSystem,
'[user steering] ' + Steers[sti].Text);

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 Fold queued steering into the transmitted prompt

For the CLI path, BuildLoopConfig always supplies the composed Options.SystemPrompt, so appending the queued correction as an mrSystem history item does not send it to the model. The OpenAI builder skips history system messages whenever Sys <> '' (PasClaw.Providers.OpenAI.pas:154-168), Anthropic selects Options.SystemPrompt and then skips every mrSystem item (PasClaw.Providers.Anthropic.pas:131-172), and Gemini follows the same precedence (PasClaw.Providers.Gemini.pas:136-173). As a result, pasclaw steer <id> ... drains and permanently consumes the queue but the next LLM call never sees the correction. Fold these messages into LiveOptions.SystemPrompt, or use a message role that the provider builders actually transmit.

Useful? React with 👍 / 👎.

Comment on lines +153 to +155
Stream.Seek(0, soEnd);
Line := UTF8String(EncodeLine(NowUnix, TrimmedText) + #10);
Stream.WriteBuffer(Pointer(Line)^, Length(Line));

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 Make queue appends atomic with concurrent drains and pushes

When two pasclaw steer processes push concurrently, or a push overlaps the tool loop's rename-based drain, this open/seek/write sequence is not the atomic POSIX append described by the new unit. The stream is not opened with O_APPEND, so two writers can seek to the same EOF and overwrite each other. A drain can also rename the file after a writer opens it, causing that writer to append to the old .draining inode after it has been read or deleted. In both cases a successfully reported steering message can be lost or leave malformed JSONL. Use an actual append-mode descriptor and coordinate it with the rename operation.

Useful? React with 👍 / 👎.

Comment on lines +147 to +151
EnsureSteeringDir;
if FileExists(Path) then
Stream := TFileStream.Create(Path, fmOpenWrite or fmShareDenyNone)
else
Stream := TFileStream.Create(Path, fmCreate);

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 Return false when opening the steering queue fails

When $PASCLAW_HOME is read-only, the steering directory cannot be created, or the queue file cannot be opened, ForceDirectories or TFileStream.Create can fail before the function reaches its try block. The exception escapes PushSteering, so pasclaw steer terminates instead of taking its documented False path and printing the intended error. Wrap directory creation, file creation, and writes so filesystem failures consistently return False.

Useful? React with 👍 / 👎.

…sh, fs failures return False

Three Codex findings on the steering PR — two P1 critical, one P2.
All legit, all fixed in place on PR #120.

  P1 — Steering messages never reached the model. The original
  implementation appended drained steering as mrSystem to Hist, but
  every provider builder (OpenAI :148-151, Anthropic :170-172,
  Gemini :136-173) skips in-history mrSystem entries whenever
  Options.SystemPrompt is set — which BuildLoopConfig always does
  on the CLI path. The queue was being drained (and permanently
  consumed) but the next LLM call never saw the correction. The
  whole feature was a no-op.
  Fix: fold steering into LiveOptions.SystemPrompt instead of
  Hist. The next provider call's `system` field carries the
  addendum as a "[user steering received mid-turn]" block beneath
  the original system prompt. Same channel compaction already
  uses for the same provider-precedence reason. Cache breakpoint
  invalidates for the steering turn — acceptable, the steering is
  short and infrequent.

  P1 — Atomic concurrent push. The original PushSteering opened
  TFileStream + Seek(soEnd) + Write — NOT atomic on POSIX. Two
  concurrent writers can both seek to the same EOF and clobber
  each other's writes, and a writer who opened the file before
  the drain's rename will append to the renamed (about-to-be-
  deleted) inode after the drain has finished reading.
  Fix: directory-based mutex via mkdir (atomic on both POSIX and
  Windows; CreateDirectory / O_EXCL semantics). Every push AND
  drain AND clear acquires <key>.jsonl.lock first; stale locks
  older than 30s are reclaimed so a crashed CLI doesn't wedge
  the queue forever. Lock wait is 25ms spin with a 2s timeout.
  Verified with a focused test: 8 worker threads each push 25
  messages concurrently; all 200 must drain back, none torn.

  P2 — Filesystem failures must return False, not raise. The
  original ForceDirectories / TFileStream.Create could throw on
  read-only $PASCLAW_HOME, permissions denial, or a vanished
  disk — the exception escaped PushSteering and reached the CLI.
  Fix: wrap directory creation, lock acquisition, stream
  creation, and the write itself in try/except blocks that log
  + return False, matching the documented contract.

Also tightened the docstring's concurrency claim — it previously
claimed "atomic per-line POSIX appends" but the implementation
didn't actually deliver O_APPEND. Now describes the directory-
mutex model accurately.

Verified with a focused test (created, built, ran, removed)
covering all three: BuildRequest output contains the steering
text inside the Anthropic `system` array; 8 concurrent push
threads × 25 messages each produces 200 drainable entries (no
torn writes); a regular file blocking the steering dir path
causes Push to return False rather than throw.

https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon
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