Skip to content

Port PicoClaw to Delphi Object Pascal (Phase 1) - #1

Merged
FMXExpress merged 11 commits into
mainfrom
claude/nice-dirac-sBwXK
May 27, 2026
Merged

FMXExpress merged 11 commits into
mainfrom
claude/nice-dirac-sBwXK

Conversation

@FMXExpress

Copy link
Copy Markdown
Owner

Summary

This is a complete port of PicoClaw — Sipeed's ultra-lightweight personal AI agent — to Delphi Object Pascal. The port targets Free Pascal 3.2+ in {$MODE DELPHI} so sources build with both FPC and Delphi RAD Studio.

Phase 1 delivers the full command-tree skeleton and core infrastructure. Subsequent phases will implement real provider, MCP, gateway, cron, skills, and channel functionality.

Key Changes

  • Complete CLI command structure: All top-level commands (agent, auth, config, cron, gateway, mcp, migrate, model, onboard, skills, status, update, version) with argument parsing and help text
  • Provider abstraction layer: Interface-based LLM provider system with Anthropic and OpenAI implementations (request building only; actual HTTP calls stubbed for Phase 2)
  • MCP (Model Context Protocol) support: Full JSON-RPC 2.0 stdio client for spawning and communicating with MCP servers; tool registration bridge into the tools registry
  • Built-in tools: Filesystem tools (fs_read, fs_write, fs_list) and shell_exec with basic safety checks
  • Tool loop infrastructure: Core agent loop that dispatches tool calls, collects results, and iterates with the LLM
  • Configuration system: TOML/JSON config loading/saving with support for providers, MCP servers, cron entries, and skills
  • CLI UI utilities: ANSI color support, banner rendering, help/error panel formatting with terminal width detection
  • Logging framework: Levelled logging (debug/info/warn/error) matching PicoClaw conventions
  • Build system: Makefile with FPC compilation, unit path management, version injection from git tags

Implementation Details

  • All units follow the PasClaw.* namespace hierarchy mirroring the Go package structure
  • JSON handling uses fpjson/jsonparser from FPC's standard library
  • Process spawning and pipe I/O for MCP via TProcess (FPC's process unit)
  • HTTP client stubs in place for provider implementations (full integration in Phase 2)
  • Tool registry uses a slot-based handler dispatch system to work around Pascal's lack of closures
  • Config paths respect PASCLAW_HOME and PASCLAW_CONFIG environment variables, with fallback to ~/.pasclaw
  • All command handlers follow a consistent pattern: parse args → load config → execute → save if needed

This foundation is ready for Phase 2 (real HTTP provider calls), Phase 3 (streaming), Phase 4 (gateway), and beyond.

https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon

claude added 11 commits May 26, 2026 19:16
Brings up the full command tree from cmd/picoclaw/main.go in FPC mode Delphi:
config, onboard, agent, auth, gateway, status, cron, mcp, migrate, skills,
model, update, version. Each command parses argv, reads/writes a JSON config
at $PASCLAW_HOME/config.json (default ~/.pasclaw), and is wired into the root
dispatcher in src/cmd/PasClaw.Cmd.Root.pas.

Core units mirror picoclaw layout:
  src/pkg/cliui   ANSI colour, NO_COLOR detection, banner, panel rendering
  src/pkg/utils   path/string/file helpers (HomeDir, JoinPath, ReadFileText…)
  src/pkg/logger  levelled logger (debug/info/warn/error)
  src/pkg/config  build-time version, TConfig record, fpjson load/save

Build: `make` (FPC 3.2+) → build/pasclaw; `make smoke` exercises every command.

Provider HTTP, MCP transport, gateway, scheduler, and skills loader come in
subsequent phases per the README roadmap.
Ports pkg/providers (subset) and pkg/tokenizer from picoclaw so
`pasclaw agent -m "..."` actually talks to a real LLM endpoint:

  src/pkg/providers/PasClaw.Providers.Types.pas   protocol records (TMessage,
                                                  TToolCall, TLLMResponse, …)
  src/pkg/providers/PasClaw.Providers.Intf.pas    ILLMProvider interface
  src/pkg/providers/PasClaw.Providers.HTTP.pas    fphttpclient + openssl POST
                                                  helper (PostJSON)
  src/pkg/providers/PasClaw.Providers.Anthropic.pas
      Anthropic Messages API: builds tool_use / tool_result blocks, parses
      content[*].text and content[*].tool_use, threads usage and stop_reason.
  src/pkg/providers/PasClaw.Providers.OpenAI.pas
      Chat Completions: handles tool_calls in both request and response,
      works with OpenAI-compatible endpoints (Groq, Together, Ollama, …)
  src/pkg/providers/PasClaw.Providers.Factory.pas
      Resolves provider by name from TConfig; surfaces clear errors for
      missing entry / missing API key.
  src/pkg/tokenizer/PasClaw.Tokenizer.pas         ~4-chars/token estimator

The agent command now parses --model / --provider / --system / --thinking
/ --max-tokens, holds turn history in interactive mode, and falls back to
an offline preview when no provider is configured. Verified end-to-end
against a fake OpenAI endpoint.
Ports pkg/tools (subset) from picoclaw and wires the agent into a real
iterative tool-use loop:

  src/pkg/tools/PasClaw.Tools.Types.pas      TTool record + handler signature
  src/pkg/tools/PasClaw.Tools.Registry.pas   register/find/dispatch + provider def builder
  src/pkg/tools/PasClaw.Tools.FS.pas         fs_read, fs_write, fs_list
  src/pkg/tools/PasClaw.Tools.Shell.pas      shell_exec (denylist: rm -rf /, mkfs, dd if=, fork bomb, shutdown)
  src/pkg/tools/PasClaw.Tools.ToolLoop.pas   core loop: call → if tool_calls, dispatch, append tool messages, repeat

`pasclaw agent` now wires the built-in registry by default, accepts
--no-tools and --max-iterations, and prints tool calls/results inline.
Verified against a two-turn fake LLM: model requests fs_read, dispatcher
runs it, result feeds back, model produces final answer.

Also: declared TToolDefinitionArray / TMessageArray aliases so function
return types compile under FPC's stricter return-type parsing.
Ports pkg/mcp (subset) so PasClaw can spawn and talk to Model Context
Protocol servers over stdio:

  src/pkg/mcp/PasClaw.MCP.Types.pas         protocol constants + TMCPTool
  src/pkg/mcp/PasClaw.MCP.StdioClient.pas   JSON-RPC 2.0 stdio client:
      spawns `cmd args` via TProcess, frames newline-delimited messages,
      implements initialize / tools/list / tools/call, parses content[*]
      blocks and surfaces server-reported errors.
  src/pkg/mcp/PasClaw.MCP.Bridge.pas        registers each MCP tool into
      the existing tools registry under "<server>__<tool>". Uses a small
      slot table + per-slot wrapper handlers because TToolHandler is a
      plain procedural type (no closures in mode Delphi).

`pasclaw mcp test <name>` now actually spawns the configured command,
runs the initialize/tools/list handshake, and reports server info +
available tools. `pasclaw agent` auto-connects every enabled MCP server
at startup (override with --no-mcp). Verified end-to-end against a
Python stdio MCP server: agent calls fakemcp__greet, gets back text,
produces final answer.
Migrates HTTP I/O to Indy so the same sources build on both FPC (vendored
via `make get-indy`) and Delphi/RAD Studio (uses RAD Studio's bundled Indy).

  src/pkg/providers/PasClaw.Providers.HTTP.pas  rewritten on TIdHTTP +
      IdSSLOpenSSL; same THTTPResult/PostJSON/GetJSONURL surface as before
      so providers (Anthropic, OpenAI) and the MCP bridge keep working.

  src/pkg/gateway/PasClaw.Gateway.Server.pas    new. TIdHTTPServer with five
      routes: /v1/health, /v1/version, /v1/status, /v1/tools, /v1/chat.
      /v1/chat drives the same RunToolLoop as the CLI so MCP-bridged tools
      and built-ins are usable over HTTP.

  src/pkg/channels/PasClaw.Channels.Telegram.pas  long-polling Telegram bot
      adapter: getUpdates / sendMessage via Indy, dispatches each incoming
      text message through the agent loop. Token comes from --token or
      PASCLAW_TELEGRAM_TOKEN.

  src/cmd/PasClaw.Cmd.Gateway.pas               rewritten to start the server,
      optionally also start the Telegram channel, block until Ctrl-C.

`pasclaw gateway` listens on the address/port from config (override with
--addr/--port). `pasclaw gateway --telegram --token <TOK>` runs both at
once. Verified end-to-end against a fake LLM: curl POST /v1/chat returns
{"content","iterations","input_tokens","output_tokens"}.

Build notes:
* FPC build picks up Indy from vendor/Indy; `make get-indy` clones it
  (one-shot). Adds iconvenc unit path for IdGlobal on Linux.
* main program now uses cthreads + cmem under {$IFDEF UNIX} so Indy's
  worker threads work under FPC. Delphi build ignores both.
Adds a thin JSON wrapper so the rest of the codebase doesn't bind to a
specific library. Under FPC the backend is fpjson/jsonparser; under
Delphi/RAD Studio the IFDEF branch can be filled in with System.JSON
(stubbed in the source so the port is a one-file change).

  src/pkg/json/PasClaw.JSON.pas         TJsonObject / TJsonArray with
      Get*/Put* helpers, Parse class methods, ToJSON, plus JsonEscape and
      one-shot JsonReadStr/Int/Bool. Memory model: parent owns nested
      children; PutObject/PutArray transfer ownership and nil the var.

  src/pkg/channels/PasClaw.Channels.Discord.pas   TDiscordWebhook for
      outbound posting; TDiscordBot polls /channels/:id/messages every
      3s, ignores bot authors, dispatches text through the agent loop.

  src/pkg/channels/PasClaw.Channels.Slack.pas     TSlackWebhook for
      outbound; SlackChallengeResponse for Events API URL verification
      so the gateway can register an endpoint when Phase 8 wires the
      inbound receiver.

  src/cmd/PasClaw.Cmd.Post.pas          new `pasclaw post discord|slack
      <webhook-url> "<content>"` for one-shot notifications. Useful from
      cron and skills.

Verified end-to-end: `pasclaw post discord <url> "..."` posts valid
{"content":"..."} JSON; `pasclaw post slack <url> "..."` posts valid
{"text":"..."} JSON. Both checked against a local Python webhook server.
Three new packages ported from picoclaw's pkg/cron, pkg/skills, pkg/memory:

  src/pkg/cron/PasClaw.Cron.Expr.pas        5-field cron parser with
      *, N, N,M, N-M, N-M/S, */S syntax across minute/hour/day/month/dow.
      NextFireAfter() walks forward minute-by-minute (≤13 months) to find
      the next match. Sunday = 0 or 7, both accepted.

  src/pkg/cron/PasClaw.Cron.Scheduler.pas   background TThread that ticks
      every ~30s, fires due jobs, sleeps on an event so stop is instant.
      Each job invokes a registered skill via the tool registry.

  src/pkg/skills/PasClaw.Skills.Loader.pas  loads JSON manifests from
      $PASCLAW_HOME/workspace/skills/*.json and registers them as tools
      named "skill_<name>". Two skill kinds: "shell" (run a templated
      command via /bin/sh or cmd.exe) and "prompt" (render a template
      string for the LLM). Mustache-style {{arg}} substitution.

  src/pkg/memory/PasClaw.Memory.pas         append-only NDJSON conversation
      log per session, with LoadHistory() to seed a chat turn.

`pasclaw skills list` now reads actual manifests from disk. `pasclaw
gateway` auto-loads skills + starts a TCronScheduler if the config has
any enabled cron entries; agent picks up skills as tools too.

Verified: cron parser handles "*/5 * * * *" (5min) and "0 9 * * 1-5"
(weekday 9am) and produces correct next-fire times; skills list reads
a sample manifest end-to-end.
  src/pkg/mcp/PasClaw.MCP.HttpClient.pas  Streamable HTTP transport for MCP
      servers exposed over HTTPS. Uses TIdHTTP for the JSON-RPC envelope,
      parses single-object responses and collapses text/event-stream "data:"
      lines into one body. Same Connect/ListTools/CallTool surface as the
      stdio client so PasClaw.MCP.Bridge can drop it in next.

  src/pkg/providers/PasClaw.Providers.Stream.pas  PostStreaming() helper
      that POSTs to an SSE endpoint and walks the response line-by-line,
      firing an OnLine(event, data) callback for each event. Used by the
      Anthropic/OpenAI streaming refactor in a follow-up.

  src/pkg/gateway/webui.html              Real HTML file. Vanilla CSS+JS,
      no framework, no CDN. Two fetches: GET /v1/status (header) and
      POST /v1/chat (message). Self-contained dark-theme single-page UI.

  src/pkg/gateway/webui.rc                Resource definition declaring
      PASCLAW_WEBUI_HTML as RCDATA pointing at webui.html. Same .rc file
      compiles via fpcres (FPC) and brcc32 (Delphi).

  src/pkg/gateway/PasClaw.Gateway.WebUI.pas  {$R webui.res} embeds it;
      WebUIStream returns a TMemoryStream of the raw bytes loaded via
      TResourceStream. No string encoding ever touches the body, which
      sidesteps an Indy ContentText/UTF-8 issue under FPC.

  src/pkg/gateway/PasClaw.Gateway.Server.pas  GET / now hands Indy the
      resource stream directly via ContentStream/FreeContentStream and
      sets ContentLength from the stream Size. WriteBodyStream helper
      added for JSON routes (avoids the same ContentText pitfall).

  Makefile gains a webui-res target that runs fpcres against webui.rc;
  all builds now depend on src/pkg/gateway/webui.res. webui.res is
  gitignored so a fresh checkout rebuilds it via `make webui-res`.

Build verified: the resource is compiled, the binary links it in, and
PasClaw.Gateway.Server.pas now references it via TResourceStream. Live
HTTP serving could not be exercised in this remote env (the harness
reaps backgrounded long-running processes), so request/response
round-trip will be validated on the user's machine.
Three new packages + three new top-level commands close out the picoclaw
port roadmap.

  src/pkg/updater/PasClaw.Updater.pas      GitHub releases self-update:
      FetchLatestRelease queries /repos/<owner>/<repo>/releases/latest with
      the X-GitHub-Api-Version header, picks the asset matching
      HostPlatformSuffix (linux_amd64, darwin_arm64, windows_amd64.exe, …),
      compares versions numerically with NormalizeVersion+CompareVersions,
      downloads to <binary>.new, and on POSIX renames over the running
      binary (legal under Linux/macOS). Windows leaves the .new in place
      for a launcher swap.

  src/cmd/PasClaw.Cmd.Update.pas           --check / --repo o/n flags;
      gracefully reports when api.github.com is unreachable so the command
      stays useful in sandboxed environments.

  src/pkg/membench/PasClaw.Membench.Runner.pas + src/cmd/PasClaw.Cmd.Membench.pas
      Throughput benchmark for the memory NDJSON log. `pasclaw membench
      --records 500 --content 256` measures rec/s and MiB/s for both
      write and load passes. Verified locally: ~125K rec/s write, 71K
      rec/s load, 44 MiB/s on this VM.

  src/pkg/tui/PasClaw.TUI.pas + src/cmd/PasClaw.Cmd.TUI.pas
      Line-based ANSI TUI with header (logo + provider/model + tools count),
      separator, prompt loop, and /help, /tools, /clear, /quit slash
      commands. TermWidth detected via ioctl(TIOCGWINSZ) on UNIX (falls
      back to 80). Stays line-based so it works in vt100/xterm/Windows
      Terminal/tmux without alt-screen weirdness. A future phase can
      swap in dmvc-tui's full-screen renderer.

Root dispatcher exposes tui, membench, update; smoke test covers all 11
commands. README roadmap marks phases 6-9 done.
Anthropic SSE streaming

Two integration loose ends from Phases 8/9 closed so the new code
actually flows through the existing dispatchers:

  src/pkg/mcp/PasClaw.MCP.Types.pas          new TMCPBaseClient abstract
      base — Connect/ListTools/CallTool as virtual methods, ServerInfo
      property pulled up. Stdio + HTTP clients now both descend from it.

  src/pkg/mcp/PasClaw.MCP.Bridge.pas         carries TMCPBaseClient
      instead of TMCPStdioClient. ConnectMCPServers picks transport from
      the server entry's Cmd field: http(s):// URLs go to TMCPHttpClient,
      everything else to TMCPStdioClient. Args field doubles as the
      Authorization header for HTTP transport ("Bearer ..." etc.).

  src/cmd/PasClaw.Cmd.MCP.pas                `pasclaw mcp test <name>`
      same dispatch — uses HTTP client for URL entries, stdio for the
      rest.

  src/pkg/providers/PasClaw.Providers.Anthropic.pas  ChatStream now does
      real Server-Sent Events. Forces stream:true on the request body,
      routes through PostStreaming with an SSE-aware callback that:
        * handles message_start / message_delta / message_stop events,
        * accumulates content_block_delta text_delta chunks,
        * extracts input_tokens / output_tokens from message usage,
        * threads stop_reason into FinishReason.
      Verified end-to-end against a fake SSE endpoint: three deltas
      concatenated correctly, token counts and stop reason round-tripped.

      SupportsStreaming now returns True so the agent loop can opt in.

The state shared between PostStreaming's plain-function callback and the
provider lives in three module-level vars (GStreamCB/Acc/Last); single-
threaded use only, which matches the single-agent CLI surface. Future
multi-channel gateway threading would need to pin these per-request.
@FMXExpress
FMXExpress merged commit c66346d into main May 27, 2026
FMXExpress pushed a commit that referenced this pull request May 28, 2026
Three related changes around the Phase 4 scripts/ runtime:

1. Sample greet.sh is now executable (PR #60 P2 review)
   git update-index --chmod=+x on samples/skills/hello/scripts/
   greet.sh — committed mode flips from 100644 to 100755. The
   reviewer's point was correct: a model copying the sample and
   invoking the advertised absolute path through shell_exec
   would otherwise hit "permission denied" because the canonical
   sample on disk was non-executable.

2. Install-time chmod for the GitHub + ClawHub paths
   Both installers' CopyTree uses TFileStream which preserves
   bytes but not Unix mode bits. Even a source repo that
   committed scripts as mode 100755 (per fix #1) would land on
   the user's POSIX disk as 0644. Added ChmodPlusXScriptsTree
   to both PasClaw.Skills.GitHub and PasClaw.Skills.ClawHub,
   called immediately after CopyTree. Walks <skill>/scripts/
   non-recursively and chmods every file to 0755. Best-effort
   (ignores errors; the file was just created so we own it).
   FPC UNIX uses BaseUnix.FpChmod(Path, &755); Delphi POSIX uses
   Posix.SysStat.chmod(p, $1ED). No-op on Windows where NTFS
   has no execute bit. Mirrors the existing pattern in
   PasClaw.Updater for the self-update binary chmod.

3. Windows-aware invocation hints in the system prompt
   cmd.exe (what PasClaw.Platform.RunOneShot wraps on Windows)
   cannot execute a .sh file natively — the file has no
   default Win32 association and shebang lines are ignored.
   Even with git-bash installed, the model needs to type
   `bash /path/to/script.sh` for shell_exec to find a working
   interpreter.

   New ScriptInvocation helper in PasClaw.Agent.Prompt renders
   each script's path with the OS-appropriate invocation:

     {$IFDEF MSWINDOWS}
       .sh   ->  `bash <path>`
                 (resolves through git-bash, WSL, or MSYS if any
                 is on PATH; fails clearly otherwise so the model
                 can pivot)
       .ps1  ->  `powershell -ExecutionPolicy Bypass -File <path>`
       other ->  bare path
     {$ELSE}
       always bare path (shebang + executable bit handle it)
     {$ENDIF}

   The scripts: header line in BuildSkillsSection also picks up
   an OS-aware hint string mentioning the bash / powershell
   requirement on Windows.

samples/skills/hello/SKILL.md updated to describe the chmod
behaviour and the Windows .sh -> bash dance.

README's "Skill bundle layout" subsection grows a
"Cross-platform scripts" paragraph documenting the chmod and
the per-OS invocation rendering.

https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon
FMXExpress pushed a commit that referenced this pull request May 29, 2026
Two P2s on PR #79, both material:

P2 #1: SetLastFired(DateTimeToUnix(Now_)) after firing the earliest
       missed slot means the next tick's NextFireAfter starts from
       "now" and walks forward to a FUTURE slot, silently dropping
       every intervening missed slot. Stamp the SLOT we just handled
       (Next) instead — now subsequent ticks find the next missed
       slot and fire it, one per tick, until caught up. This is the
       behaviour the PR description claimed in the first place.

P2 #2: Save sequence was
         WriteFileText(Tmp); DeleteFile(FPath); RenameFile(Tmp,FPath);
       which opens a window where a crash (or rename failure) leaves
       neither FPath nor a recoverable copy — exactly the failure
       mode the state file was supposed to survive. Fix with a
       backup-file dance that keeps a known-good copy at every
       point:
         1. WriteFileText(Tmp)
         2. Clear stale .bak from a prior aborted save
         3. RenameFile(FPath -> .bak)  (skip if no current state)
         4. RenameFile(Tmp -> FPath)
         5. DeleteFile(.bak)
       If step 4 fails, restore .bak so the previous state survives.
       Load checks for .bak when FPath is missing and recovers from
       it, then promotes it back to the primary path so a future
       clean Save doesn't have to handle the .bak existing. No
       IFDEFs needed; works the same on POSIX rename (atomic) and
       Windows RenameFile (which fails on existing destination —
       the .bak clear in step 2 avoids that).

Standalone recovery smoke covers the new paths:
  - normal save leaves no .bak (success path cleanup)
  - second save still no .bak (dance idempotent)
  - state.json absent + .bak present → Load recovers AND promotes
  - stale .bak from aborted save → cleared on next Save
  - round-trip survives the dance with the latest value
11 assertions, all pass.

https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon
FMXExpress pushed a commit that referenced this pull request Jun 6, 2026
Codex P2: the original RenderInline ran inline-code wrapping FIRST
(\`code\` -> Ansi.Dim + reverse + body + reset) and then ran bold,
italic, strikethrough, and link transforms on the same string. The
later passes still saw the body characters inside the wrapped span
and ate any markdown markers that happened to appear there:

  Input:  use \`**kwargs**\` to splat
  Buggy:  the ** inside the code span gets transformed to bold,
          so "kwargs" comes out bold and the literal ** is lost.

  Input:  the \`*.pas\` files
  Buggy:  the * starts an italic span that never closes, eating
          everything after.

  Input:  see \`[x](y)\` syntax
  Buggy:  [x](y) inside the code becomes a styled link.

That contradicts the renderer's stated contract that inline
transforms are suppressed inside code spans.

Fix: standard placeholder pattern.

  Pass 1 — extract every \`code\` span into a parallel array of
    already-styled ANSI bodies. Leave a #1<index>#1 placeholder
    in the string. SOH (#1) is the delimiter — models virtually
    never emit it and it has no markdown meaning.

  Pass 2 — bold (**), italic (*), strikethrough (~~), and link
    transforms run on the placeholder-laden string. The
    placeholders contain no markdown markers, so nothing scans
    into them.

  Pass 3 — substitute each placeholder back with its stored
    code body. Final styled output drops in untouched.

5 assertions added to TestInlineCodeProtectsMarkdownMarkers:
  - \`**kwargs**\` -> ** literals survive
  - \`*.pas\` -> the * doesn't start an italic
  - \`[x](y)\` -> the link syntax stays verbatim
  - two adjacent code spans both stay intact
  - a code span followed by genuine bold: code body protected,
    real bold OUTSIDE still rendered.

  make test-markdown-render -> all 12 cases OK (was 11)
  make smoke                -> all 11 commands OK
FMXExpress pushed a commit that referenced this pull request Jun 7, 2026
Two distinct findings from Codex on PR #171, both real:

P2 #1 — Normalize provider kind before lookup.
  ResolveSpecForName in PasClaw.Cmd.Model passed the raw
  Cfg.Providers[Idx].Kind to LookupProvider. But NewProviderFromConfig
  in PasClaw.Providers.Factory routes through NormalizeProviderKind
  (lowercase + trim + collapse "openai-compat" → "openai") and falls
  back to Cfg.Providers[Idx].Name when Kind is blank. Configs that
  the runtime factory resolves cleanly were rejected here as "unknown
  kind", so `pasclaw model refresh openai-compat-thing` couldn't
  populate the cache for providers that chat normally.

  Fix part 1: export NormalizeProviderKind from PasClaw.Providers.Factory
  (it was internal — IsGenuineOpenAI is already exported alongside).
  Fix part 2: mirror the factory's pattern verbatim in
  ResolveSpecForName — normalise the Kind, fall back to the normalised
  Name when Kind is empty, then look up.

P2 #2 — Key model caches by Provider Name, not Spec.Kind.
  PR #171's cache file path was $PASCLAW_HOME/cache/models/<Kind>.json.
  But NewProviderFromConfig resolves Cfg.Providers[] entries by Name,
  and two named entries (e.g. "openai-primary", "openai-backup") may
  legitimately share a Kind while pointing at different APIBase/keys.
  With the old key, refreshing "openai-primary" would silently
  overwrite "openai-backup"'s roster (and vice versa), making
  `model list` / `model show` surface models from the wrong backend.

  Fix: cache keyed on the operator-facing Provider Name throughout
  the refresh / list / show paths:
    - RefreshOne          → SaveCachedModels(Name, R)
    - DoList              → LoadCachedModels(Argv[1], R)
    - DoShow              → LoadCachedModels(Cfg.DefaultProvider, R)
                            (Cfg.DefaultProvider is a Name reference,
                            not a Kind)
  Onboarding's PickModelInteractive keeps SaveCachedModels(Spec.Kind, R)
  because UpsertProvider sets Name := Spec.Kind for both the upsert
  and insert paths in that file — the invariant holds at onboarding
  time, just documented now so the next reader doesn't undo it.

  Header doc in PasClaw.Providers.Models updated to spell out the
  cache-key contract.

Test coverage (model_discovery_tests):
  - TestCacheKeysDontCollideAcrossNames pins the P2 #2 fix: writing
    different rosters to two Names that share a Kind preserves both.
  - TestKindNormalisationMatchesFactory pins the P2 #1 contract:
    'openai-compat' → 'openai', case + whitespace normalisation,
    empty stays empty so the caller can fall back to Name.

All 11 test suites green: smoke + hashline + toolview +
anthropic-server-tools + openai-server-tools + println-helper +
utf8-codepage-tag + gemini-schema-strip + markdown-render +
json-utf8-roundtrip + model-discovery (now 6 cases).
FMXExpress pushed a commit that referenced this pull request Jun 8, 2026
…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.
FMXExpress pushed a commit that referenced this pull request Jun 9, 2026
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.
FMXExpress pushed a commit that referenced this pull request Jun 13, 2026
…openclaw env alias

Two Codex P2 findings + one openclaw-compat ask, fixed together
since they touch the same code path.

P2 #1 -- env-only secret leaking into the persisted config:
  LoadConfig used to do Result.Gateway.Token := <env value>, so
  any later SaveConfig (auth login, model set, skills install,
  ...) round-tripped the env-only secret into config.json. A
  user who only wanted the token in $PASCLAW_GATEWAY_TOKEN ended
  up with it baked into ~/.pasclaw/config.json on the next CLI
  command and probably committed to git on the next dotfile sync.
  Fix: keep the env value in a SEPARATE module-level
  GEnvGatewayToken in PasClaw.Config and expose a public
  GetEffectiveGatewayToken(C) that returns env-or-config. ToJSON
  still serialises only C.Gateway.Token (the in-file value); the
  env override never persists. The middleware uses the effective
  getter at the auth check and at all three identity-stamp sites.

P2 #2 -- /v1/config returning the raw bearer token:
  HandleConfig already masks providers[].api_key and
  mcp_servers[].env to "•••" but not the new gateway.token field.
  An authenticated /v1/config caller (or anyone hitting the
  endpoint when gateway.token is empty) would see the shared
  secret in cleartext. Fix: mirror the existing mask block on
  the gateway sub-object.

openclaw-compat:
  Operators porting an existing openclaw .env file shouldn't have
  to rename the env var. LoadConfig now also honours
  $OPENCLAW_GATEWAY_TOKEN; PASCLAW_GATEWAY_TOKEN wins when both
  are set (we're not openclaw, after all). Adds 2 lines to the
  env-pickup block.

Test additions (now 13 cases across 3 binary runs):

  TestEffectiveTokenContract (first pass):
    - no token anywhere: getter returns ""
    - config-only: getter returns Cfg.Gateway.Token
    - ToJSON / FromJSON round-trip of a config-set token
    - ToJSON does NOT emit "token" field when empty (guards
      against a future SaveConfig dropping a "":"" row)

  TestEnvModePrecedence (--env-mode pass):
    - LoadConfig leaves Cfg.Gateway.Token empty when only env is set
    - GetEffectiveGatewayToken returns the env value
    - ToJSON of an env-only-token config does NOT include the
      "token" field -- THIS is the literal assertion that catches
      the original Codex P2 bug
    - FromJSON round-trip produces empty Cfg.Gateway.Token

  Makefile runs the binary three times:
    1. clean env (10 base cases + TestEffectiveTokenContract)
    2. PASCLAW_GATEWAY_TOKEN set (TestEnvModePrecedence)
    3. OPENCLAW_GATEWAY_TOKEN set (TestEnvModePrecedence again --
       same assertion, different env var path)

`make test` aggregate: 23 PASS markers (was 21).

Docs updated:
  docs/gateway.md      adds OPENCLAW_GATEWAY_TOKEN alias note,
                       persistence-isolation contract, and the
                       /v1/config masking note.
  docs/configuration.md adds the alias row + persistence note to
                        the env-var table.
FMXExpress pushed a commit that referenced this pull request Jun 16, 2026
…self-shadow inherit

Three Codex P2 findings, all legit.

P2 #1 -- the profile-selection block sat under `if FileExists(Path)`
so `pasclaw agent --profile low-token` and `PASCLAW_PROFILE=low-token`
silently used plain defaults on a fresh deploy that hadn't created
config.json yet. Moved profile resolution OUT of the FileExists
guard so it runs unconditionally; config.json is then layered on top
when it exists. The third-tier "profile field in config.json"
fallback is still gated on HasConfigFile (only meaningful when the
file exists).

P2 #2 -- `pasclaw profile use <name>` wrote the "profile" key by
hand-crafting JSON, so any subsequent SaveConfig() (auth login,
model set, /v1/config PUT, the TUI's settings tab, ...) would drop
the key because TConfig didn't know about it. Added Profile: string
field to TConfig that round-trips through FromJSON / ToJSON. DoUse
now goes through LoadConfig + SetField + SaveConfig like every
other config-mutating command.

P2 #3 -- the documented "fork a built-in" pattern --
$PASCLAW_HOME/profiles/low-token.json containing
`{"_inherits":["low-token"], "tool_output_cap":4096}` -- false-cycled.
LookupProfile returned the user file for both the child AND its
inherited parent (because both lookups asked for "low-token"), and
the resolver then saw the same name twice in Visited and reported a
cycle. Added a LookupProfileInternal overload with a
`BypassUserShadow` switch + threaded NameToBypass through
ResolveInto. When a user-shadow's _inherits contains its own name,
the recursive parent lookup bypasses the user file and reaches the
built-in directly. Visited is briefly popped + re-added across the
recursive call so the cycle guard doesn't false-fire.

Tests:
  TestProfileWithoutConfigFile      P2 #1
  TestSaveConfigPreservesProfile    P2 #2 (round-trip + SaveConfig
                                          preserves through a second
                                          mutation)
  TestSelfShadowInherit             P2 #3 (verifies two-layer
                                          resolution: built-in first,
                                          user override second)

All existing test-config-profile, test-config-secret-merge, test-
config-env-subst, test-plan-build-mode, test-loop-shaping-defaults
remain green. Live-verified each fix end-to-end via the CLI.
FMXExpress pushed a commit that referenced this pull request Jun 16, 2026
PR #295 review feedback, two legit fixes + one deferred.

* P2 #1 (generation-number): ExtractTextAndMetadata's primary path
  looked content streams up via Format('%d 0 obj', [ObjID]),
  hardcoding generation 0.  An incrementally-updated PDF whose page
  /Contents references "12 1 R" would silently fall through to the
  empty-text branch.  Switched to ObjIndex.TryGetValue, which the
  parser already builds via BuildObjectIndex and which records the
  position of every <id> <gen> obj regardless of gen.  Stream-bounds
  check now uses 'endobj' (mirroring GetObjectStreamData) instead of
  the next 'obj' keyword.

* P2 #3 (positioned-Tj spacing): "BT (Hello) Tj 50 0 Td (World) Tj
  ET" used to extract "HelloWorld".  ParseTextOperators now detects
  Td/TD/Tm/T*/'/" position operators and flips a NeedSpaceBeforeNext
  flag; the next paren-close or hex-close emits via a local
  EmitWithSpacing helper that prepends a single space.  The existing
  TJ-array negative-number spacing (>120 units = word boundary) is
  unchanged and still handles intra-TJ glyph runs.

* P2 #2 (per-page font resource map): BuildResourceFontMap is still
  document-wide -- proper per-page maps would restructure
  GetPageContentStreamIDs to thread a TDictionary per content stream
  through ParseTextOperators, which is a bigger refactor than this
  PR warrants.  Added a header comment explaining the known
  limitation: single-font and same-font-across-pages docs work, and
  the CP1252 fallback keeps ASCII readable when /ToUnicode misses on
  per-page-subset fonts (LaTeX output).

New regression tests in src/tests/kb_pdf_extract_tests.pas:
* TestPositionedTjSpacing  -- "Foo Bar" via Td between Tj operands.
* TestNonZeroGenerationContent -- "4 1 obj" content stream resolves.

End-to-end smoke: `kb add` + `kb search "cross reference"` on a PDF
with three position-separated Tj operands now returns
"Cross reference Document" (was "CrossreferenceDocument").
FMXExpress pushed a commit that referenced this pull request Jun 16, 2026
Three Delphi-correctness fixes flagged by Codex.

* P2 #1 (UTF-8 decode in ReadHead): Move(Buf[0], Result[1], N) on
  a UnicodeString reinterprets UTF-8 bytes as UTF-16 code units and
  leaves the second half of the allocation as garbage.  Now goes
  through TEncoding.UTF8.GetString -- same path ReadFileText uses
  in PasClaw.Utils.

* P2 #2 (UTF-8 write of AGENTS.md): TFileStream.WriteBuffer(Body[1],
  Length(Body)) under Delphi writes Length-in-chars (UTF-16 units)
  bytes of UTF-16 memory, producing a half-size NUL-laced file.
  Replaced with WriteFileText, which encodes properly under both
  compilers.

* P2 #3 (/init unwired in positioned TUI): SubmitInput's slash
  dispatcher now recognises /init.  To keep the framebuffer clean
  (Provider.Chat status output would corrupt the rendered display),
  the action goes through a new stdio-free RunInit worker that
  returns a TInitOutcome record; the positioned TUI reports the
  result via Flash, the CLI's Cmd_Init_Run wraps the same worker
  with PrintLn/PrintErr.

Public surface change: PasClaw.Cmd.Init now exports RunInit +
TInitOutcome so the TUI (and any future programmatic caller, e.g.
a /v1/init gateway endpoint) can drive the bootstrap without
screen-scraping CLI output.

New tests:
* TestDigestUtf8 -- writes a README with a multibyte UTF-8 codepoint
  (`é` as C3 A9) and asserts it survives the ReadHead/digest path.
  Pins the regression.
* TestRunInitArgFailures -- exercises the no-network arg-validation
  paths of RunInit (missing dir, existing AGENTS.md without --force)
  and asserts Status / ErrorMsg shape.
FMXExpress pushed a commit that referenced this pull request Jun 21, 2026
…mpty model, P2 tool calls)

Codex review on PR #318 surfaced four real issues. All four addressed.

P1 #1 -- Cancel queued requests before freeing
==============================================

Reviewer:
  > When Chat times out (for example, no worker is connected or no
  > worker matches the model), the request is still stored in
  > FPending or FInflight because the timeout path never removes it
  > from TRelayQueue. The finally then frees the object while the
  > queue still holds its pointer, so a later worker dequeue/respond
  > or queue destruction can dereference or free a stale request.
  > Please remove/cancel the request under the queue lock before
  > freeing it, or make queue ownership explicit.

Fix
---

New TRelayQueue.Cancel(id): Boolean -- removes the request from
FPending or FInflight under FLock. Idempotent; returns False when
the request was already consumed (Respond raced WaitFor's wake).

TRelayProvider.Chat()'s finally block now does:

    Q.Cancel(ReqId);
    Req.Free;

Cancel guarantees the queue no longer holds a pointer regardless of
which path Chat exited on (success, timeout, abort, wait failure).
The provider always Frees -- whether Cancel pulled it from a list or
not, the request object is no longer reachable from any queue state
after Cancel returns, so the provider owns the memory and frees it.

New tests cover Cancel-from-pending, Cancel-from-inflight, and
Cancel-of-unknown-id-returns-False.

P1 #2 -- Broadcast work notifications to matching workers
==========================================================

Reviewer:
  > With capability filtering, this auto-reset event wakes only one
  > arbitrary blocked worker per enqueue. If workers have disjoint
  > capabilities and the woken worker cannot serve the new request,
  > it goes back to sleep while the matching worker remains blocked
  > until another enqueue/register event or its poll timeout, so
  > runnable work can sit pending and eventually make the caller
  > time out. The wakeup needs to broadcast/re-signal enough waiters
  > or be per-capability/per-worker.

Fix
---

FNewWork switched from auto-reset to MANUAL-reset. SetEvent now
unblocks ALL blocked DequeueForWorker waiters; each one re-checks
under the lock and either takes a matching request or finds none.

Reset-when-empty semantics keep the event correctly Cleared:

  - Enqueue (under lock): adds request, calls SetEvent.
  - DequeueForWorker (under lock): if no match for THIS worker and
    FPending.Count = 0 after the check, calls ResetEvent before
    releasing the lock and WaitFor-ing.

The Reset + SetEvent ordering serialises on FLock, so there is no
lost-wakeup race: any Enqueue that ran after our ResetEvent must
hold the same lock we'll re-acquire on the next loop iteration --
the Enqueue's SetEvent and our next FLock.Acquire are ordered.

Considered per-worker events; rejected because of TEvent lifetime
race with UnregisterWorker (the freed event would be deref'd by an
in-progress WaitFor on the dequeuer side). Manual-reset shared
event is simpler and provably correct.

P2 #3 -- Empty relay model treated as wildcard
==============================================

Reviewer:
  > When the relay provider is configured without a model (the
  > catalog default), EffMod remains empty and the queue matches
  > that literal empty string against worker capabilities. Since
  > CanServe only treats an empty capability list as wildcard,
  > workers that advertise explicit models never receive these
  > requests, so the documented/default "whatever connected workers
  > advertise" mode hangs until timeout unless the worker omits
  > capabilities. Empty model should be matched as wildcard or
  > resolved to an advertised capability before enqueue.

Status
------

Already addressed in the second commit on this PR (PR #318 head
before this review):

    function TRelayWorker.CanServe(const Model: string): Boolean;
    ...
      if (Target = '') or (Length(FCapabilities) = 0) then Exit(True);

The truth table:

  request='', worker=any caps     -> match (caller said "any worker")
  request=X,  worker=[] caps      -> match (worker said "anything")
  request=X,  worker=['X']        -> match (exact)
  request=X,  worker=['Y']        -> miss  (operator pinned a model
                                            no connected worker serves)

Covered by TestEmptyRequestModelMatchesAnyWorker (added in that
same commit). Flagging here so the reviewer sees the resolution.

P2 #4 -- Populate tool calls from relay responses
==================================================

Reviewer:
  > DecodeResponse zeroes the response and copies only content/usage/
  > status, leaving TLLMResponse.ToolCalls empty for every successful
  > worker reply. RunToolLoop dispatches tools only from
  > Resp.ToolCalls, so a relay-backed agent will stop after a worker
  > emits a textual tool call instead of executing it, despite the V1
  > relay contract saying worker replies are text-parsed for tool
  > calls. Parse the content here or add structured tool calls to the
  > relay response before returning success.

Fix
---

Accept structured tool_calls in the worker response JSON envelope
(OpenAI shape: id / type / function.name / function.arguments), in
preference to text-parsing. Workers using inference libraries that
emit structured tool calls (WebLLM, mlc-llm, llama.cpp grammar mode,
Transformers.js) populate the array; PasClaw forwards verbatim.

  - TRelayResponse gains ToolCalls: array of TToolCall.
  - HandleRelayRespond parses tool_calls[] from the POST body into
    Resp.ToolCalls.
  - TRelayProvider.DecodeResponse copies ToolCalls into
    TLLMResponse.ToolCalls.
  - RunToolLoop's existing dispatch handles them like any other
    structured tool call.

Text-extraction is NOT implemented -- the V1 doc claim about "text-
parsed" was overoptimistic. Workers that only emit text get text-only
chat through the relay, same limitation V1 doc warned about for
"smaller local models without strong tool support." Most modern small-
model runtimes (WebLLM, mlc-llm, llama.cpp grammar mode) DO emit
structured tool calls, so this floor is right for V1.

Doc updates
===========

  - docs/providers-relay.md updated: response envelope shows the
    tool_calls array; the V1-scope bullet explains the
    structured-vs-text-only distinction; the WebLLM worker example
    forwards tool_calls from completion.choices[0].message.tool_calls.

Tests
=====

make clean && make passes. make test-relay-queue passes all 14
cases (was 11; added TestCancelPullsFromPending,
TestCancelPullsFromInflight, TestCancelOfUnknownIsFalse).
FMXExpress pushed a commit that referenced this pull request Jun 22, 2026
Codex P2 review on PR #334. The Connect-time guard
  if (!_relayScopedToken && gwToken()) await refreshRelayScopedToken();
only re-fetched when the cache was EMPTY. TGatewayServer.Create
regenerates FRelayToken on every startup, so if the gateway
restarted (or its config reloaded) while the Relay tab stayed open,
the stale cached token kept getting handed to the Worker -> the
worker 401'd against the fresh server-side token -> the in-browser
worker spun forever on the auto-retry loop until the operator
reloaded the whole page.

Fix: always call refreshRelayScopedToken() on Connect when a main
token is set. The fetch is one tiny JSON GET; freshness matters
more than the cache hit. Also re-runs syncRelayTokenInput +
renderRelaySnippets so the visible token / displayed snippet
bodies reflect the just-refreshed value (covers the case where
the operator had "show" on with a stale token visible).

Live smoke (gateway with main token MAINTOKEN, port 18911):
  boot #1 token: KYNB-G50W  -> /v1/relay/status 200
  restart
  boot #2 token: 76QZ-GGCD  -> /v1/relay/status 200
  stale KYNB-G50W against fresh #2  -> 401 (the failure mode)
  fresh 76QZ-GGCD against fresh #2  -> 200 (the fix path)

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon
khongten001 pushed a commit to khongten001/PasClaw that referenced this pull request Jul 13, 2026
…press#324 review)

Three review fixes against PR FMXExpress#324.

P2 FMXExpress#1: temporal-dead-zone on /#relay deep link. Page loaded with the
hash already set ran showTab("relay") in the boot block before the
relay tab's `let` / `const` state bindings (relayTimer,
relaySetupDone, relayShowToken, RELAY_TOKEN_PLACEHOLDER) had
initialised. setupRelayTab() / renderRelaySnippets() then hit
ReferenceError on each, and bookmarked Relay URLs landed on a blank
tab. Moved all four bindings above the boot block.

P2 FMXExpress#2: nonexistent CLI command -- resolved on its own. PR FMXExpress#323
landed `pasclaw relay` into main; the snippet's command is real now.
No code change needed.

P2 FMXExpress#3: browser snippet relied on EventSource constructor headers,
which native browser EventSource silently ignores. Without
Authorization the gateway returns 401 on token-protected setups,
and even untokened setups returned 400 ("X-Relay-Worker-Id is
required"). Two changes:

  - Gateway (HandleRelayPoll): accept ?worker_id= and ?caps= as
    fallbacks for the equivalent headers. Mirrors the existing
    ?token= fallback the bearer-auth gate already uses on /v1/*
    routes. Header still wins when both are present.

  - Webui browser snippet: rewritten to use URLSearchParams +
    URL-only EventSource. Auth + worker identity + capabilities all
    ride as query params. fetch() for the response POST keeps the
    Authorization header.

  - docs/providers-relay.md: the same broken EventSource-headers
    pattern was in the docs reference implementation. Rewritten to
    match. Added a "Query-string fallback for browser EventSource
    workers" note to the wire-protocol section so non-browser
    workers know they can keep the header path (no extra URL noise,
    no token-in-server-logs concern).

webui.res regenerated.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon
FMXExpress pushed a commit that referenced this pull request Aug 15, 2026
…ectories. 191 rows, 176 sourced

The retry rule produced all three outcomes it can produce, in one pass.

The pass-5 lead "RL from agent trajectories" sourced richly under sharper
terms: SkyRL trains multi-turn tool-use agents online at SWE-Bench scale,
Skywork-SWE turns successful trajectories into rejection-sampling SFT,
SWE-RM scores agent work execution-free, and SA-SWE-32B reached 39.4%
Pass@1 trained by RL alone. Out of scope for a harness to DO -- but the
trajectories PasClaw already persists are exactly the data these methods
consume.

"Prompt management as a harness category" failed a THIRD differently-worded
search and is demoted: the products exist, but nothing in this corpus
treats them as an agent-harness feature. Recording the demotion is the
finding -- the alternative was tabling recalled marketing.

And one source corrected the survey's own flagship section. Since pass 2,
"Where PasClaw leads" claimed skill distillation had no field counterpart.
Socratic-SWE -- self-evolving coding agents via trace-derived skills -- is
that counterpart, sourced. The claim is demoted in place; the SCARS
failure-mining claim survives. A survey that cannot demote its own flagship
claims is advertising.

The most actionable row of any pass so far: Serena. The survey's standing
#1 gap -- symbol/AST navigation instead of whole-file reads -- has an
off-the-shelf answer: an MCP server exposing LSP-backed symbol tools
(find_symbol, find_referencing_symbols, insert_after_symbol) across 40+
languages, and the supported-language list includes Pascal. PasClaw is an
MCP client. Closing the #1 gap is configuration, not code.

Also new: tmux as the agent runtime (detachable persistent terminals,
driving TUIs by keystroke and pane read, supervisor-over-panes patterns),
and simulated-user evaluation (tau2-bench's dual-control agent+user+policy
scoring) together with its sourced caution -- LLM-simulated users are
unreliable proxies for humans.

learn scans six research sessions, zero recurring failures across six
clean runs.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LGQKz579j1ZnDRwmr6h1V6
FMXExpress pushed a commit that referenced this pull request Aug 22, 2026
Codex P2 x2 on PR #586. Both findings are the same class of bug the
original fix claimed to eliminate, surviving in places that fix did not
reach.

1. by_provider kept the identical defect. Keying buckets on
   (endpoint, model) left Meta.Provider scalar and overwritten: two
   providers serving one model string share a bucket, so the first
   provider's tokens get credited to the second. That happens when
   /v1/config switches the primary provider while clients keep sending
   the same model, and whenever a direct vendor key and an aggregator
   both answer to one name.

   Reproduced against the old key: 50 requests on one provider then one
   on another reported 15,003 tokens for the provider that used 3.

   Worth recording why this shipped: the original test varied model and
   provider TOGETHER (model-EXPENSIVE/anthropic, model-CHEAP/openai), so
   its "bucket provider = anthropic" assertion passed for the wrong
   reason and could never have caught a model-only key.
   TestAttributionByProvider now holds the model constant and varies
   only the provider.

2. The readable id is lossy, so it cannot carry identity alone.
   Sanitising maps everything outside [A-Za-z0-9_-] to '-', flattening
   "openai/gpt-5" and "openai:gpt-5" into one bucket; trailing
   separators are stripped, so "gpt-5/" and "gpt-5:" merge; and
   truncation collides any two long names sharing a prefix, which is
   entirely plausible for dated or versioned model ids. Every collision
   merges counters and reinstates the misattribution.

   The id now ends in a 32-bit FNV-1a of the RAW provider and model,
   joined by #1 -- a byte that cannot appear in either, so provider "a"
   + model "bc" cannot hash the same as "ab" + "c". FNV-1a because it
   must be deterministic across processes and restarts; a non-stable
   hash would orphan yesterday's bucket on every boot. The readable
   prefix stays for humans reading the session list; the suffix is what
   makes the identity sound.

All six accumulate call sites now pass the provider name they already
had to hand.

The test grew from 16 assertions to 24 and was negative-tested: reverted
to the old model-only lossy key, exactly the expected six fail --
provider attribution (15,003 vs 3), slash-vs-colon, and trailing
separators. The two remaining collision cases guard the new scheme's own
risks (hash field boundary, 64-char truncation) rather than the old bug,
so they correctly stay green either way.
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