Skip to content

Compose nanobot-style sectioned system prompt with PasClaw identity - #50

Merged
FMXExpress merged 1 commit into
mainfrom
claude/pr46-system-prompt-builder
May 28, 2026
Merged

FMXExpress merged 1 commit into
mainfrom
claude/pr46-system-prompt-builder

Conversation

@FMXExpress

Copy link
Copy Markdown
Owner

Summary

Until now the LLM had no built-in idea what it was. pasclaw agent "hi" with no --system flag literally sent an empty system prompt — the model picked a personality from whatever the underlying provider defaulted to. Picoclaw and nanobot both compose a much richer prompt out of identity + workspace + memory + skill catalog + rules, joined by \n\n---\n\n so each section reads as a clearly delimited block. This PR brings PasClaw to feature parity, with the persona you wanted ("best 10x programmer in the world").

What the model now sees on a bare pasclaw agent "hi"

# PasClaw (v0.x.y)

You are PasClaw, the best 10x programmer in the world.

You have deep, working expertise in every programming language — Pascal,
Delphi, C, C++, Rust, Go, Python, JavaScript, TypeScript, Java, C#, Swift,
Kotlin, Ruby, Lua, Haskell, OCaml, F#, Elixir, Erlang, Clojure, Scala,
Zig, Nim, Crystal, Dart, R, Julia, Perl, PHP, shell scripting, SQL, and
every dialect and assembler in between. You write tight, correct code that
reads like it was written by someone who already knew the right answer.
You prefer each language's native idioms over generic patterns and you do
not over-engineer.

## Runtime
Free Pascal 3.2.2 on linux/x86_64

---

## Workspace
Your workspace is at: /home/user/.pasclaw
- Memory: /home/user/.pasclaw/workspace/memory/MEMORY.md
- Skills: /home/user/.pasclaw/workspace/skills/{skill-name}/SKILL.md
- Logs:   /home/user/.pasclaw/logs

---

## Memory
<verbatim MEMORY.md contents — only if the file exists>

---

## Skills
The following skills are installed in your workspace…
- `skillname` — description

---

## Rules

1. **ALWAYS use tools** when an action is needed — call the appropriate tool, do not just say you'll do it or pretend the work was done. The user will check.

2. **Be precise** — match the language's native idioms, name things clearly, do not introduce abstractions the task does not actually need. Three similar lines is fine; a premature framework is not.

3. **Verify changes** — after editing code, re-read what you wrote or run a targeted check (build, test, search). Do not assume the edit landed correctly because the tool returned success.

4. **Truncated tool calls** — if a `fs_write` call comes back with a "missing required argument: content" error, your previous response was truncated mid-tool_call (you hit max_tokens). Re-emit with the full content, or switch to `fs_edit_hashline` for incremental edits on large files.

5. **Memory** — when the user mentions something worth keeping across sessions (preferences, project facts, conventions), update <abs>/workspace/memory/MEMORY.md. Treat it as a long-lived notes file the user owns.

---

<--system text appended here, if any-->

Memory and Skills sections are only emitted when their underlying files actually exist, so a fresh pasclaw onboard install still produces clean output.

What picoclaw and nanobot actually ship (for reference)

  • Picoclaw (pkg/agent/context.go:170 getIdentity): single string # picoclaw 🦞 (<version>) You are picoclaw, a helpful AI assistant. ## Workspace … ## Important Rules 1–4. Composed via a PromptPart{Layer,Slot,Source} registry, rendered with \n\n---\n\n.
  • Nanobot HKUDS (nanobot/templates/agent/identity.md): no You are X persona in the template. Persona lives in user-editable bootstrap files (AGENTS.md / SOUL.md / USER.md). The template only provides scaffolding (runtime, workspace paths, tool contract, channel-specific format hints). build_system_prompt() joins sections with \n\n---\n\n.

PasClaw takes the picoclaw approach for the persona content but the nanobot/picoclaw approach for sectioning structure. No Python version in the runtime string — we're a Free Pascal / Delphi program.

New unit

src/pkg/agent/PasClaw.Agent.Prompt.pas exposes:

function BuildSystemPrompt(Cfg: TConfig; const UserSys: string): string;
function HasSystemMessage(const Messages: array of TMessage): Boolean;

Wiring (4 sites that previously set Options.SystemPrompt)

Site Before After
Cmd.Agent.pas:155 Result.Options.SystemPrompt := A.SystemPrompt := BuildSystemPrompt(Cfg, A.SystemPrompt) — --system "..." is now additive (appended as USER section), so bare invocations get the full identity for free
Gateway.Server.pas:360 (/v1/chat) unset := BuildSystemPrompt(FCfg, '') always
Gateway.Server.pas:810 (/v1/chat/completions) unset := BuildSystemPrompt(FCfg, '') only when not HasSystemMessage(Msgs) — third-party clients that supply their own persona via the messages array win
Component.pas:294 (TPasClawAgent) if FSystemPrompt <> '' then ... (override semantics) := BuildSystemPrompt(FConfig, FSystemPrompt) — additive, like the CLI

BuildLoopConfig in Cmd.Agent grows a Cfg: TConfig parameter (both call sites updated).

Build wiring

  • Makefile: src/pkg/agent added to UNIT_DIRS.
  • PasClaw.dproj: ..\pkg\agent added to DCC_UnitSearchPath; the new unit added to the DCCReference list between skills and memory.

Failure modes

  • Missing MEMORY.md → MEMORY section skipped, no error.
  • Misconfigured skill manifest → SKILLS section skipped (the loader's exception is caught), no error.
  • FConfig = nil on the component path → Cfg parameter currently unused inside BuildSystemPrompt (signature is forward-compatible for future config-driven knobs).

Test plan

  • pasclaw agent "hi" — confirm the assembled system prompt appears (use --debug to see the body bytes growing to ~3–4 KB just from the preamble).
  • pasclaw agent --system "Use British English." "hi" — confirm identity is present AND the British-English line shows up at the bottom (appended, not replaced).
  • Drop a MEMORY.md into ~/.pasclaw/workspace/memory/ — confirm contents appear under the MEMORY section.
  • Install a skill — confirm it shows up in the SKILLS section.
  • curl /v1/chat -d '{"message":"hi"}' — composed prompt is in effect.
  • curl /v1/chat/completions -d '{"messages":[{"role":"system","content":"You are a parrot."},{"role":"user","content":"hi"}]}' — model behaves as a parrot, NOT as PasClaw. (Client wins.)
  • curl /v1/chat/completions -d '{"messages":[{"role":"user","content":"hi"}]}' — model uses composed PasClaw prompt (no client system message → we inject).
  • FPC build (make) + Delphi .dproj build cleanly.
  • make smoke — every top-level command still runs.

https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon


Generated by Claude Code

Until now the LLM had no built-in idea what it was. PasClaw forwarded
whatever single string the caller put into Options.SystemPrompt and
nothing else — `pasclaw agent "hi"` with no --system flag literally
sent an empty system prompt. Picoclaw and nanobot both compose a much
richer prompt out of identity / workspace / memory / skill catalog /
rules, joined by "\n\n---\n\n" so each section reads as a clearly
delimited block. This change brings PasClaw to feature parity, with
the persona content the user actually wants.

New unit src/pkg/agent/PasClaw.Agent.Prompt.pas exposes one helper:

  BuildSystemPrompt(Cfg: TConfig; const UserSys: string): string

Sections emitted in order, skipping any that are empty:

  IDENTITY   "You are PasClaw, the best 10x programmer in the world."
             + the language list + version + runtime string. The
             runtime string is OS + arch + compiler (Free Pascal or
             Delphi) — no Python version, since we are not a Python
             program.
  WORKSPACE  Resolved absolute paths inside ~/.pasclaw so the model
             can rely on them: memory dir, skills dir, logs dir.
  MEMORY     Verbatim contents of <home>/workspace/memory/MEMORY.md
             if the file exists. Lets the user pin facts that
             persist across sessions (same convention picoclaw and
             nanobot already use).
  SKILLS     One line per registered skill, pulled from
             PasClaw.Skills.Loader. Only emitted when at least one
             skill is actually installed.
  RULES     Five behavioral rules:
              1. ALWAYS use tools when an action is needed.
              2. Be precise; match the language's native idioms.
              3. Verify changes after editing code.
              4. Truncated tool calls — if fs_write returns
                 "missing required argument: content" (see PR #41),
                 re-emit or switch to fs_edit_hashline.
              5. Memory — when something seems memorable update
                 <abs>/workspace/memory/MEMORY.md.
  USER      Whatever the caller passed via --system / the component
             property / the request body. Appended last so the user
             can override or extend by recency in the prompt.

Sections are joined by "\n\n---\n\n" so the model sees them as
horizontal-rule-separated blocks — matches picoclaw's
renderPromptPartsLegacy and HKUDS/nanobot's build_system_prompt
joiner exactly.

Also exposes:

  HasSystemMessage(const Messages: array of TMessage): Boolean

Used by the /v1/chat/completions gateway path to decide whether to
inject the composed prompt or honor a client-supplied system message.

Wired into all four sites that previously set Options.SystemPrompt:

  src/cmd/PasClaw.Cmd.Agent.pas
    BuildLoopConfig grows a Cfg parameter and passes it through.
    --system "..." text is now appended as the USER section, not
    used as the entire system prompt — bare-bones invocations
    (`pasclaw agent "hi"`) get the full identity + memory + rules
    for free.

  src/pkg/gateway/PasClaw.Gateway.Server.pas
    /v1/chat — the legacy single-message endpoint — always uses the
    composed prompt.
    /v1/chat/completions — the OpenAI-compatible endpoint — uses
    HasSystemMessage(Msgs) to gate: bare-bones clients get the
    composed prompt, but third-party tooling that supplies its own
    persona via the messages array wins (we don't want to silently
    override an integrating app's character).

  src/pkg/component/PasClaw.Component.pas
    TPasClawAgent.SystemPrompt is now treated as additive — the
    composed identity is always there, the property text is appended.

Memory and skill catalog reads swallow their errors (missing
MEMORY.md or a misconfigured skill manifest just means that section
is skipped, not a hard failure).

Build wiring: src/pkg/agent added to Makefile UNIT_DIRS and
PasClaw.dproj DCC_UnitSearchPath; the new unit added to the
DCCReference list between skills and memory.

On nanobot vs picoclaw: I checked both before writing this. Picoclaw
ships a "You are picoclaw, a helpful AI assistant" persona baked into
the identity preamble. Nanobot HKUDS does NOT — its identity.md
template is pure scaffolding (runtime, workspace paths, tool
contract); the persona lives in user-editable workspace files
(AGENTS.md, SOUL.md, USER.md). PasClaw takes the picoclaw approach
for the persona but the nanobot approach for sectioning structure.

https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon
@FMXExpress
FMXExpress merged commit f037286 into main May 28, 2026

@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: 645d45797f

ℹ️ 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 +167 to +170
if Desc = '' then
Lines.Add('- `' + Skills[i].Name + '`')
else
Lines.Add('- `' + Skills[i].Name + '` — ' + Desc);

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 Use the actual registered skill tool names

When any installed skill is present, this section tells the model to call the skill by Skills[i].Name, but RegisterSkills registers the provider tool as skill_ + name (PasClaw.Skills.Loader.pas). For a manifest named weather, the prompt advertises weather even though the callable tool is skill_weather, so models following the new system prompt will try a nonexistent tool or avoid the available one.

Useful? React with 👍 / 👎.

Result.MaxIterations := A.MaxIterations;
Result.Options := DefaultChatOptions;
Result.Options.SystemPrompt := A.SystemPrompt;
Result.Options.SystemPrompt := BuildSystemPrompt(Cfg, A.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 Do not advertise tools in no-tools sessions

When the CLI is run with pasclaw agent --no-tools, Reg remains nil, so RunToolLoop sends an empty tool list, but this call still builds a prompt that can include installed skills and a rule to always use tools. In that context the model is explicitly instructed to use capabilities that are disabled for the request, which can produce unusable responses instead of respecting --no-tools.

Useful? React with 👍 / 👎.

FMXExpress pushed a commit that referenced this pull request May 28, 2026
Windows commands, regex allow-lists, stale-registry no-tools prompt,
sample build instructions

Five legitimate issues raised in review of the prior commit.

1. Case-sensitive path comparison on POSIX
   PathInsideDirectory used SameText, which treats
   /tmp/workspace and /tmp/Workspace as the same prefix on
   case-sensitive filesystems. If both happen to exist, a
   restricted fs_read for /tmp/Workspace/secret would pass the
   prefix check, then the actual ReadFileText opens the
   differently-cased path — sandbox bypass. New PathsEqual
   helper does the right thing per OS:
     {$IFDEF MSWINDOWS}  SameText (Windows is case-insensitive)
     {$ELSE}             A = B    (case-sensitive)

2. Relative-path bypass in shell sandbox
   HasOutsideAbsolutePath only fired on '/'-prefixed tokens, so
   `cd .. && cat secret` slipped through silently with
   restrict_to_workspace=true: no absolute path appeared, and
   RunOneShot inherited the parent's cwd so the relative paths
   resolved wherever pasclaw was launched.

   Three defenses, layered:
     a) cd / chdir / pushd / popd added to ForbiddenTokens so
        the model cannot change cwd inside the shell.
     b) New HasTraversalToken refuses any whitespace-separated
        token containing '..'. Catches `cat ../secret`,
        `(cd ..)`, `bash -c '...cd..'`, etc.
     c) RunOneShot grows a WorkingDir parameter, plumbed through
        all four platform impls (FPC POSIX/Windows via
        TProcess.CurrentDirectory; Delphi Windows + Delphi POSIX
        via ChDir/restore around TStdioProcess.Spawn). Tool_Shell
        passes CurrentWorkspace when RestrictionActive, so even
        a token the denylist missed runs from the workspace and
        cannot reach files above it via relative paths.

3. Windows command coverage
   The denylist was POSIX-shaped: rm, mkfs, dd, etc. cmd.exe and
   PowerShell users had no equivalent. Added 9 Windows tokens
   (del, erase, rd, rmdir, format, attrib, takeown, icacls,
   runas) and 17 PowerShell substrings (del /f|q|s, rd /s,
   rmdir /s, format /q, powershell -e/-en/-enc/-ec,
   -encodedcommand, iex (, invoke-expression,
   [convert]::frombase64, [text.encoding],
   .getstring([byte[], set-executionpolicy). Picoclaw's
   windowsDenyPatterns set is the reference. Patterns are
   checked unconditionally — running shell_exec on Linux today
   does not mean a portable policy should let `format c:`
   through if the same config is deployed on Windows tomorrow.

4. Regex allow-lists (FPC + Delphi)
   New unit src/pkg/tools/PasClaw.Tools.Regex.pas wraps the two
   regex engines behind one call:
     {$IFDEF FPC}   uses RegExpr.TRegExpr
     {$ELSE}        uses System.RegularExpressions.TRegEx

   Both are bundled with their respective compilers (no extra
   package install needed; FPC ships RegExpr in fcl-regexpr,
   Delphi has System.RegularExpressions since XE). Invalid
   patterns return False rather than raising so a malformed
   regex in config.json does not crash the agent — the sandbox
   layer treats False the same as "no allowlist match" and
   falls through to the workspace check.

   AllowReadPaths / AllowWritePaths now match via the regex
   wrapper instead of the in-unit glob matcher. PCRE syntax —
   ^/tmp/.*, ^/usr/(include|share)/.*, etc. README updated.
   Existing glob users migrate: '/tmp/*' becomes '^/tmp/.*'
   (anchor the prefix, replace * with .*).

5. Stale FRegistry leaks tools into "no tools" prompt
   TPasClawAgent.EnsureRegistry caches FRegistry and only
   honours FUseTools when the registry is nil. A component used
   with UseTools=True, then flipped to False, would build a
   "No tools in this session" prompt while still sending the
   cached registry to RunToolLoop — contradictory instructions
   plus actual tool access. Single source of truth is the
   registry handed to RunToolLoop. Every BuildSystemPrompt call
   site now derives the third arg from `<scope>.Registry <> nil`:
     Cmd.Agent   - Reg parameter
     Component   - Cfg.Registry
     Gateway     - LoopCfg.Registry

   PR #51's content (skill_ tool name prefix + no-tools rules +
   ToolsEnabled parameter) was also reapplied here. The PR was
   merged but the squash collapsed only PR #50's commits into
   main, so the actual changes were lost.

Sample (samples/component-console/SampleConsole.dpr):
  The header comment shipped a literal
  `fpc -Fu../../src/cmd -Fu../../src/pkg/...` instruction. The
  '...' isn't an FPC wildcard — it tried to use '...' as a
  directory name and failed. Also the sample needs ~25 unit
  search paths plus three Indy paths, not just two. Replaced
  the broken instruction with a real Makefile at
  samples/component-console/Makefile that re-uses the top-level
  UNIT_DIRS list re-rooted at the repo root. Comment now points
  at it.

https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon
FMXExpress pushed a commit that referenced this pull request May 28, 2026
Windows commands, regex allow-lists, stale-registry no-tools prompt,
sample build instructions

Five legitimate issues raised in review of the prior commit.

1. Case-sensitive path comparison on POSIX
   PathInsideDirectory used SameText, which treats
   /tmp/workspace and /tmp/Workspace as the same prefix on
   case-sensitive filesystems. If both happen to exist, a
   restricted fs_read for /tmp/Workspace/secret would pass the
   prefix check, then the actual ReadFileText opens the
   differently-cased path — sandbox bypass. New PathsEqual
   helper does the right thing per OS:
     {$IFDEF MSWINDOWS}  SameText (Windows is case-insensitive)
     {$ELSE}             A = B    (case-sensitive)

2. Relative-path bypass in shell sandbox
   HasOutsideAbsolutePath only fired on '/'-prefixed tokens, so
   `cd .. && cat secret` slipped through silently with
   restrict_to_workspace=true: no absolute path appeared, and
   RunOneShot inherited the parent's cwd so the relative paths
   resolved wherever pasclaw was launched.

   Three defenses, layered:
     a) cd / chdir / pushd / popd added to ForbiddenTokens so
        the model cannot change cwd inside the shell.
     b) New HasTraversalToken refuses any whitespace-separated
        token containing '..'. Catches `cat ../secret`,
        `(cd ..)`, `bash -c '...cd..'`, etc.
     c) RunOneShot grows a WorkingDir parameter, plumbed through
        all four platform impls (FPC POSIX/Windows via
        TProcess.CurrentDirectory; Delphi Windows + Delphi POSIX
        via ChDir/restore around TStdioProcess.Spawn). Tool_Shell
        passes CurrentWorkspace when RestrictionActive, so even
        a token the denylist missed runs from the workspace and
        cannot reach files above it via relative paths.

3. Windows command coverage
   The denylist was POSIX-shaped: rm, mkfs, dd, etc. cmd.exe and
   PowerShell users had no equivalent. Added 9 Windows tokens
   (del, erase, rd, rmdir, format, attrib, takeown, icacls,
   runas) and 17 PowerShell substrings (del /f|q|s, rd /s,
   rmdir /s, format /q, powershell -e/-en/-enc/-ec,
   -encodedcommand, iex (, invoke-expression,
   [convert]::frombase64, [text.encoding],
   .getstring([byte[], set-executionpolicy). Picoclaw's
   windowsDenyPatterns set is the reference. Patterns are
   checked unconditionally — running shell_exec on Linux today
   does not mean a portable policy should let `format c:`
   through if the same config is deployed on Windows tomorrow.

4. Regex allow-lists (FPC + Delphi)
   New unit src/pkg/tools/PasClaw.Tools.Regex.pas wraps the two
   regex engines behind one call:
     {$IFDEF FPC}   uses RegExpr.TRegExpr
     {$ELSE}        uses System.RegularExpressions.TRegEx

   Both are bundled with their respective compilers (no extra
   package install needed; FPC ships RegExpr in fcl-regexpr,
   Delphi has System.RegularExpressions since XE). Invalid
   patterns return False rather than raising so a malformed
   regex in config.json does not crash the agent — the sandbox
   layer treats False the same as "no allowlist match" and
   falls through to the workspace check.

   AllowReadPaths / AllowWritePaths now match via the regex
   wrapper instead of the in-unit glob matcher. PCRE syntax —
   ^/tmp/.*, ^/usr/(include|share)/.*, etc. README updated.
   Existing glob users migrate: '/tmp/*' becomes '^/tmp/.*'
   (anchor the prefix, replace * with .*).

5. Stale FRegistry leaks tools into "no tools" prompt
   TPasClawAgent.EnsureRegistry caches FRegistry and only
   honours FUseTools when the registry is nil. A component used
   with UseTools=True, then flipped to False, would build a
   "No tools in this session" prompt while still sending the
   cached registry to RunToolLoop — contradictory instructions
   plus actual tool access. Single source of truth is the
   registry handed to RunToolLoop. Every BuildSystemPrompt call
   site now derives the third arg from `<scope>.Registry <> nil`:
     Cmd.Agent   - Reg parameter
     Component   - Cfg.Registry
     Gateway     - LoopCfg.Registry

   PR #51's content (skill_ tool name prefix + no-tools rules +
   ToolsEnabled parameter) was also reapplied here. The PR was
   merged but the squash collapsed only PR #50's commits into
   main, so the actual changes were lost.

Sample (samples/component-console/SampleConsole.dpr):
  The header comment shipped a literal
  `fpc -Fu../../src/cmd -Fu../../src/pkg/...` instruction. The
  '...' isn't an FPC wildcard — it tried to use '...' as a
  directory name and failed. Also the sample needs ~25 unit
  search paths plus three Indy paths, not just two. Replaced
  the broken instruction with a real Makefile at
  samples/component-console/Makefile that re-uses the top-level
  UNIT_DIRS list re-rooted at the repo root. Comment now points
  at it.

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