Skip to content

Cmd: pasclaw learn — mine sessions for recurring tool failures (Headroom-inspired) - #190

Merged
FMXExpress merged 2 commits into
mainfrom
claude/cmd-learn
Jun 9, 2026
Merged

FMXExpress merged 2 commits into
mainfrom
claude/cmd-learn

Conversation

@FMXExpress

Copy link
Copy Markdown
Owner

Summary

New pasclaw learn subcommand. Walks $PASCLAW_HOME/workspace/sessions/*.json and surfaces tool failures the model has hit repeatedly across sessions, so the operator can promote them into MEMORY.md as durable hints. Concept borrowed from chopratejas/headroom's headroom learn.

The agent loop self-corrects within a session, but the same root cause often recurs across sessions: the model reaches for npm test in a pnpm repo, calls make build against a Makefile with no build target, fs_writes to a path the sandbox refuses. Each instance is a one-off; the pattern only becomes visible when you look across sessions.

How it works

Mining: scans every mrTool message for failure-shaped lines via a precision-tuned LooksLikeFailure predicate (error:, command not found, permission denied, no such file, non-zero exit=, etc.).

Normalisation: each candidate line normalises into a clustering signature that strips per-session variability:

Input After normalisation
digit run ≥ 2 (line numbers, pids) <n>
hex run ≥ 8 with a letter (commit shas, session ids) <hash>
absolute path (Unix /..., Windows C:\..., C:/...) <path>
whitespace runs single space

So these cluster as one pattern:

fs_write to /tmp/abc123/foo.pas line 42 failed
fs_write to /tmp/xyz789/foo.pas line 17 failed
                ↓
fs_write to <path> line <n> failed

Different commands (foo vs bar) stay distinct.

Reporting: patterns print sorted by frequency with a verbatim sample, the tool that triggered them (from the preceding assistant turn's ToolCalls), distinct session count, and a first/last-seen window. Default --min 2 drops one-offs.

Write-back: --write appends a dated ### Patterns observed (YYYY-MM-DD) block to workspace/memory/MEMORY.md so the next agent loop picks the pattern up via the system prompt. Each run gets its own dated section so re-running doesn't clobber the previous block — operators prune entries they've already addressed by hand.

Window: --since <days> limits the scan so a fix the operator has already applied doesn't keep resurfacing.

Example output

$ pasclaw learn
pasclaw learn — scanned 14 session(s), found 6 unique pattern(s)

[1] 8 occurrence(s) across 3 session(s)
    tool:   shell_exec
    sample: bash: foo: command not found
    seen:   first 4d ago, last 12h ago

[2] 4 occurrence(s) across 2 session(s)
    tool:   fs_write
    sample: fs_write: permission denied
    seen:   first 2d ago, last 3h ago

Tests

learn_tests (7 cases):

  • Normalisation: digit runs, hex hashes (including the tricky "starts with digits" case that bit me during dev — caught by the test, swap the check order so hex wins first), Unix + Windows paths, whitespace collapse, the clustering contract end-to-end
  • LooksLikeFailure positives + negatives (precision matters more than recall here)

End-to-end session walk covered by the smoke target (pasclaw learn runs against an empty PASCLAW_HOME).

Out of scope

LLM-generated explanations of each pattern. Headroom does that; the operator knows their project better than the model does on a cold read of someone else's session JSON. The bare report + the operator's edit-down-to-the-actual-lesson is the v1 contract.

Test plan

  • make rebuilds cleanly
  • make test — all 15 suites green (smoke + 13 existing + new learn_tests)
  • pasclaw learn --help shows usage
  • pasclaw learn against empty PASCLAW_HOME prints "no saved sessions to mine"
  • Manual: against a real workspace with a dozen+ sessions — confirm the report surfaces a recognisable recurring failure, that --write appends a sensible block to MEMORY.md, and that re-running with --since 7 shrinks the window

Generated by Claude Code

Borrowed from chopratejas/headroom's `headroom learn`. The agent
loop self-corrects within a session, but the same root-cause
mistake often recurs across sessions: the model reaches for
`npm test` in a pnpm repo, calls `make build` against a Makefile
with no `build` target, fs_writes to a path the sandbox refuses.
Each instance is a one-off; the pattern only becomes visible
across sessions.

Mining: walks $PASCLAW_HOME/workspace/sessions/*.json and scans
every mrTool message for failure-shaped lines via a precision-
tuned LooksLikeFailure predicate (`error:`, `command not found`,
`permission denied`, `no such file`, non-zero `exit=`, etc.).
Each candidate normalises into a clustering signature that
strips per-session variability:

  - digit runs >= 2 collapse to <n>      (line numbers, pids)
  - hex runs >= 8 with a letter -> <hash> (commit shas,
                                            session ids, UUIDs)
  - absolute paths -> <path>             (temp dirs, workspace
                                            roots)
  - whitespace runs collapse to a single space

So "fs_write to /tmp/abc123/foo.pas line 42 failed" and
"fs_write to /tmp/xyz789/foo.pas line 17 failed" cluster as one
pattern. Different commands (foo vs bar) stay distinct.

Reporting: patterns sorted by frequency, each with a verbatim
sample, the tool that triggered them (from the preceding
assistant turn's ToolCalls), distinct session count, and a
first/last-seen window. Default --min 2 drops one-offs.

Write-back: opt-in via --write. Appends a dated
"### Patterns observed (YYYY-MM-DD)" block to
workspace/memory/MEMORY.md so the next agent loop picks the
pattern up via the system prompt. Each run gets its own section
(operators prune by hand) so re-running doesn't clobber an
earlier entry.

--since <days> limits the scan window so a fix the operator has
already applied doesn't keep resurfacing.

Tests: learn_tests pins the normaliser (digit runs, hex hashes,
paths, whitespace collapse, the clustering contract) and
LooksLikeFailure (positive + negative cases). The end-to-end
session-walk is covered by the smoke target (`pasclaw learn`
runs against an empty PASCLAW_HOME).

Out of scope for this PR: LLM-generated explanations of each
pattern (Headroom does that; the operator knows their project
better than the model does on a cold read of someone else's
session JSON).

@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: dd4371c743

ℹ️ 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.Learn.pas Outdated
Now_ := DateTimeToUnix(Now, False);
for i := 0 to High(Patterns) do
begin
if Patterns[i].Count < MinCount then Continue;

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 Require recurrence across sessions before reporting

When a single session repeats the same failure line twice, it passes the default --min 2 check because this predicate uses total occurrence count rather than distinct session count. That contradicts the command's stated purpose of mining failures recurring across sessions and can cause --write to persist one-session noise into MEMORY.md; gate the default report/write path on Sessions.Count (or add a separate occurrence threshold) if the pattern must be cross-session.

Useful? React with 👍 / 👎.

Comment thread src/cmd/PasClaw.Cmd.Learn.pas Outdated
Comment on lines +359 to +361
if Length(Sess.Messages[i].ToolCalls) > 0 then
PrevAssistantTool :=
Sess.Messages[i].ToolCalls[0].Func.Name;

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 Match tool results to their actual tool call

For assistant turns with multiple tool calls, every following mrTool failure is labeled with ToolCalls[0] here. The tool loop appends one assistant message containing all calls and then one tool-result message per call, so a failure from the second or later call is reported and written under the wrong tool: context; use the tool result's ToolCallId to look up the matching call instead of carrying only the first call name.

Useful? React with 👍 / 👎.

P2 #1 -- Require recurrence across sessions before reporting.
The threshold check was MinCount against TOTAL occurrence count,
not distinct session count. So a single noisy session that hit
the same failure line twice would pass the default --min 2 and
get reported / written to MEMORY.md -- contradicting the
command's stated purpose of mining patterns RECURRING ACROSS
sessions.

Renamed --min -> --min-sessions (the old --min stays as a
deprecated alias for soft migration). Internally MinCount ->
MinSessions, and the gate now reads Sessions.Count >= MinSessions
via a new PassesThreshold helper. Single-session noise no longer
slips past the default 2.

P2 #2 -- Match tool results to their actual tool call.
ScanSession was caching PrevAssistantTool := ToolCalls[0].Func.Name
from the last assistant turn -- but assistant turns with PARALLEL
tool calls emit one assistant message with all calls and then
one mrTool message per call. So a failure from the 2nd, 3rd, ...
call was being attributed to whichever name happened to sit at
ToolCalls[0] in the most recent assistant message. Wrong tool
in the report; wrong tool persisted to MEMORY.md.

Built a per-session ToolCallId -> Func.Name map (TStringList with
Sorted + IndexOfName), populated across every assistant turn's
ToolCalls. Each mrTool message looks up its OWN call by its
ToolCallId field. Empty when the result has no id (older session
JSON, etc.) -- safer to drop the tool annotation than mis-attribute.

Same-signature later hits backfill the Context if the first
occurrence happened to land without an id; either way the
operator's report shows the correct tool name.
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