Repository navigation
build: pasclaw build cmd + cog-build/ predictor with workspace.zip handshake - #300
Conversation
Multi-iteration unattended agent runs with a workspace.zip
handshake so $PASCLAW_HOME (memory, KB, sessions, checkpoints,
skills, project files) survives between ephemeral-compute calls.
Designed for the "build on temp GPUs, ship state between hosts"
pattern.
CLI: `pasclaw build` (src/cmd/PasClaw.Cmd.Build.pas)
* Thin orchestration over Cmd_Agent_Run with build-friendly
defaults: --max-iters 50 (vs agent's 8), `-q` quiet stdout,
and two zip handshakes.
* Flags: -d/--describe (required), --max-iters, --workspace-in,
--workspace-out, --cwd, --home, --keep-home. Everything else
forwards verbatim to `pasclaw agent` (provider/model/profile/
session/mode/system/...).
* 4 GiB input cap (PASCLAW_WORKSPACE_ZIP_CAP), enforced before
extraction so a runaway input fails fast.
* Handshake protocol:
1. workspace-in -> ExtractZipToDir($home)
2. cwd -> SetCurrentDir(--cwd or $home/workspace)
3. agent -> Cmd_Agent_Run with forwarded argv
4. workspace-out-> PackDirToZip($home, denylist)
* Cross-platform SetEnv (cdecl setenv on POSIX, Windows API on
MSWindows) so the temp PASCLAW_HOME is visible to agent's
GetHome lookup.
* Output: model's final reply on stdout (cog-capturable via
subprocess.run), progress + zip size on stderr.
Zip helper: PackDirToZip added to PasClaw.Skills.Zip
* Cross-toolchain: TZipper (FPC fcl-base) + TZipFile (Delphi).
* Case-insensitive ExcludeNames denylist for basenames at any
depth -- build uses ['.git', '.DS_Store', 'Thumbs.db',
'kb.db-journal'] to keep zip-build noise out.
* Forward-slash entry names so archives are portable.
cog-build/ (sibling to /cog/):
* cog.yaml -- pulls FPC, vendors OpenSSL 1.0.2 for Indy's TLS
path, compiles pasclaw, installs `pget` from Replicate for
fast multi-connection downloads of large workspace URLs.
* predict.py -- new Predictor with Output BaseModel:
- inputs: message, max_iters, timeout_seconds (default 3600),
workspace_in (Path: handles upload + URL via cog), and
workspace_in_url (str: explicit URL via pget; precedence
over workspace_in).
- 4 GiB cap mirrored from Pascal side, plus
zipfile.is_zipfile validation before extraction.
- returns Output(workspace=Path(out_zip), text=stdout) so
the caller knows BOTH the new workspace AND the model's
reply, and can decide whether to feed back for another
round.
- checkpoints_enabled=True in seeded config.json so the
zpaq-backed /undo + /redo journal travels in the zip.
* requirements.txt -- cog>=0.13 for the Output BaseModel +
Path interop.
* README.md -- input table, control-loop example, what travels
in the zip (including which files are denylisted and why),
why pget for URL inputs.
Tests: src/tests/build_workspace_roundtrip_tests.pas
* Round-trip a workspace through PackDirToZip + ExtractZipToDir.
* Binary payload (0..255 byte values) round-trips intact --
critical for kb.db / archive.zpaq / kb-files/*.bin.
* Nested directories preserved.
* Exclusion denylist honoured case-insensitively at any depth.
* Empty-source-dir pack succeeds (extraction of zero-entry zip
isn't asserted -- corner case the underlying lib differs on
between versions).
* Missing-source-dir pack fails cleanly with 'not found'.
* Makefile: test-build-roundtrip target + aggregate `make test`
entry + .PHONY.
Docs:
* docs/commands.md -- new `## build` section comparing it to
`pasclaw agent`, listing all the new flags, naming the
denylist, pointing at cog-build/README.md.
* cog-build/README.md -- inputs/outputs table + a control-loop
example for sequential builds chained by workspace_in_url.
Root dispatch:
* src/cmd/PasClaw.Cmd.Root.pas -- `build` registered in the
subcommand list (position 26, between runbook and
heartbeat) and routed in DispatchCommand.
Smoke verified end-to-end:
- `pasclaw build -d "..." --workspace-in in.zip --workspace-out
out.zip --max-iters 1` unpacks the input, runs the agent (it
failed on the no-provider test fixture, as expected), and
packs the output zip containing memory + config from input.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 2cb8189303
ℹ️ 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".
| end; | ||
| LogInfo('build: unpacking %s (%d bytes) -> %s', | ||
| [A.WorkspaceIn, Bytes, Home]); | ||
| if not ExtractZipToDir(A.WorkspaceIn, Home, ErrMsg) then |
There was a problem hiding this comment.
Reject unsafe workspace zip paths
For workspace zips supplied through the new CLI/Cog flow, this extracts every archive member directly into PASCLAW_HOME after only size/signature checks. ExtractZipToDir does not validate member names, so a zip containing ../... or absolute-path entries can write outside the build home before the agent runs, potentially overwriting sibling scratch files or container files when the Cog is exposed to untrusted inputs. Validate canonical member paths or use a safe extractor before accepting --workspace-in.
Useful? React with 👍 / 👎.
| with open(config_path, "w") as f: | ||
| _json.dump(config_data, f, indent=2) |
There was a problem hiding this comment.
Redact API keys before zipping the workspace
When a Cog caller supplies provider credentials, config_data contains the raw providers[].api_key values and this writes them under PASCLAW_HOME; the later pasclaw build --workspace-out zips the entire home and returns it as the prediction output. That makes the returned workspace.zip contain the caller's API keys, so anyone who receives or can access the workspace artifact gets reusable credentials. Keep the runtime config outside the zipped home, or scrub/replace secrets before producing workspace_out.zip.
Useful? React with 👍 / 👎.
Bug: predict.py wrote config.json (with API keys) inside the
home_dir that pasclaw build zips up as workspace_out. Two
consequences:
1. Output workspace.zip carried the keys back to the Replicate
caller. Anywhere the caller stored the zip (logs, buckets,
downstream tools) became a key-leak surface.
2. workspace_in extraction unpacked over home_dir, clobbering
the fresh API keys this predict() call was given with the
stale config.json from the prior run. A caller rotating
keys (or switching providers between calls) silently kept
using the old creds.
Fix: write config.json to scratch/ (sibling of home_dir, not
inside it) and set PASCLAW_CONFIG so PasClaw finds it there.
PasClaw.Config.GetConfigPath already honoured that env var; the
fallback to $PASCLAW_HOME/config.json kicks in only when
PASCLAW_CONFIG is unset, so every other caller (CLI, TUI,
gateway, the existing /cog/ predictor) is unchanged.
Two-line diff in predict.py + an explanatory comment block.
README.md "Workspace contents" section reworded:
* config.json removed from the on-disk shape diagram.
* New "What does NOT ship" section explaining the env-var
override + the backward-compatibility guarantee.
No Pascal-side changes; pasclaw build's zip defaults stay as-is
so a CLI operator running `pasclaw build` directly (without
setting PASCLAW_CONFIG) still gets their config.json in the
workspace.zip exactly like today.
Codex P1 on PR #300: ExtractZipToDir handed every archive member straight to Zipper.UnZipAllFiles (FPC) / TZipFile.ExtractZipFile (Delphi), neither of which validates member names. A malicious zip with `../../etc/passwd` or absolute-path entries could write outside the destination dir before the agent ran -- material when `pasclaw build`'s --workspace-in accepts arbitrary cog/CLI input. The skills-install path uses the same helper but only against the api.github.com/codeload/* URLs the catalog publishes, which we already trust. Fixing this in the shared helper rather than in PasClaw.Cmd.Build means every caller gets the protection for free without each site re-implementing the check. The validator (IsUnsafeMemberName + ValidateZipEntries) rejects: 1. Empty entry names. 2. Absolute POSIX paths (leading /). 3. Windows drive prefixes (C:, D:, ...). 4. UNC paths (//, \\). 5. Any segment that is exactly "..". 6. Resolved paths that fall outside an ExpandFileName-canonicalised DestDir. This is the load-bearing check -- it catches sneaky compositions like "workspace/../../etc/passwd" by collapsing them at resolution time. Forward and backslash are normalised before the segment scan so a Windows-produced archive with backslash separators can't slip a "..\..\foo" past the check by exploiting the separator difference. Containment compares via StartsText against a slash-terminated absolute destination so prefix collisions ("/dest/" vs "/dest-evil/") can't fool the check either. Validation runs in a single pass before extraction begins; on rejection the archive is left untouched (no partial-extraction state for operators to clean up). Tests in src/tests/build_workspace_roundtrip_tests.pas: TestRejectsParentTraversal ../escaped.txt TestRejectsDeepParentTraversal workspace/../../escaped.txt TestRejectsAbsolutePath /tmp/__pasclaw_owned__ TestRejectsBackslashTraversal ..\..\escaped.txt TestAcceptsLegitimateNested workspace/sessions/foo/session.json (positive case: containment check must not over-fire on legitimate deep paths) Each malicious-case test additionally verifies that no file was written outside Dest, not just that ExtractZipToDir returned False. Skills-install tests (test-skills-install, test-self-improving- skills) still pass -- legitimate codeload archives don't trip any of the rejection criteria.
User reported on PR #300: [dcc64 Error] PasClaw.Cmd.Build.pas(281): E2003 Undeclared identifier: 'GetTempDir' [dcc64 Error] PasClaw.Cmd.Build.pas(282): E2035 Not enough actual parameters [dcc64 Error] PasClaw.Cmd.Build.pas(297): E2010 Incompatible types: 'PWideChar' and 'string' [dcc64 Error] PasClaw.Cmd.Build.pas(308): E2010 Incompatible types: 'PWideChar' and 'string' [dcc64 Error] PasClaw.Cmd.Build.pas(311): E2010 Incompatible types: 'UInt64' and 'TSearchRec' [dcc64 Error] PasClaw.Cmd.Build.pas(324): E2010 Incompatible types: 'UInt64' and 'TSearchRec' Two root causes. ROOT CAUSE 1: SysUtils.GetTempDir is FPC-only. The signature `GetTempDir(Global: Boolean): string` exists in FPC's SysUtils but Delphi's RTL has no such function. Delphi exposes TPath.GetTempPath in System.IOUtils instead. Fix: wrap once at the unit top: function PlatformTempRoot: string; begin {$IFDEF FPC} Result := GetTempDir(False); {$ELSE} Result := TPath.GetTempPath; {$ENDIF} end; ROOT CAUSE 2: the Windows unit (in scope for SetEnvironmentVariable under {$IFDEF MSWINDOWS}) shadows several SysUtils file-system helpers with PWideChar/THandle overloads, which then collide with TSearchRec parameters. Specifically: Windows.DeleteFile(lpFileName: PWideChar) shadows SysUtils.DeleteFile(const FileName: string) Windows.FindClose(hFindFile: THandle) shadows SysUtils.FindClose(var F: TSearchRec) Windows.FindFirst* / FindNext* shadow SysUtils.FindFirst / FindNext for TSearchRec The dcc64 errors were: PWideChar mismatch -> we passed `string` to DeleteFile. UInt64 mismatch -> we passed a TSearchRec to FindClose. Fix: explicit SysUtils. qualification on every file-system call in the Windows-uses scope -- DeleteFile, FileExists, DirectoryExists, FindFirst, FindNext, FindClose, RemoveDir, TSearchRec. Comment block on RemoveTree documents the why so a future contributor doesn't "clean up the redundant prefix" and break dcc64. Bonus: dropped GetProcessID from the tempdir name. It's SysUtils-FPC-only with no portable Delphi equivalent (Delphi requires Windows.GetCurrentProcessId on Windows or Posix.Unistd.getpid on Linux). Two Random calls give 2^62 entropy which is ample for per-invocation tempdir uniqueness on a single host. FPC build (linux/x86_64) still clean. test-build-roundtrip still passes 10/10 (5 zip round-trip + 5 zip-slip regression). End-to-end smoke unchanged: `pasclaw build -d "smoke" --max-iters 1 --workspace-out /tmp/out.zip` produces the expected tempdir + zip output.
User reported in production: pasclaw error: unknown command: build The cog-build image's binary has no `build` subcommand even though main has had it since PR #300 (commit 2cb8189, merged 2026-06-17 00:30 UTC). Root cause: Docker / Cog image-build layer cache. Each RUN step is keyed by its command text, NOT its runtime output. The `git clone https://github.com/FMXExpress/PasClaw.git /src` line is byte- identical on every build, so the layer hits the cache and replays the working tree from whenever the cache was first populated -- i.e. before PR #300 merged. Two-layer defense: 1. CACHE BUST. Before the clone, fetch the current main commit SHA via the GitHub API into a tmp file: curl -fsSL https://api.github.com/repos/FMXExpress/PasClaw/commits/main | head -c 200 > /tmp/pasclaw_main_sha The response body changes whenever main moves, so the RUN string reflects a different output and Docker re-executes from this point. `head -c 200` keeps it under a kilobyte and contains the `"sha"` field of the latest commit -- enough for the cache key to differ. 2. EXPLICIT HARD RESET. Right after the clone: cd /src && git fetch origin main && git reset --hard origin/main This is belt-and-braces -- if some future caching surface I haven't anticipated still keeps a stale clone, the reset guarantees the working tree matches origin/main. 3. POST-BUILD VERIFICATION. After cp'ing the binary into /opt/pasclaw, run `pasclaw build --help` and fail the image build (exit 1) if it doesn't return cleanly. Loud failure at image-build time is much better than letting the cog go live and 500 every prediction with the "unknown command: build" error the user actually saw. The error message names PR #300 explicitly and suggests `cog build --no-cache` as the operator-facing remediation. The user can now `cog push` and the image build will either succeed with a working binary or fail with a clear diagnostic.
User reported on PR FMXExpress#300: [dcc64 Error] PasClaw.Cmd.Build.pas(281): E2003 Undeclared identifier: 'GetTempDir' [dcc64 Error] PasClaw.Cmd.Build.pas(282): E2035 Not enough actual parameters [dcc64 Error] PasClaw.Cmd.Build.pas(297): E2010 Incompatible types: 'PWideChar' and 'string' [dcc64 Error] PasClaw.Cmd.Build.pas(308): E2010 Incompatible types: 'PWideChar' and 'string' [dcc64 Error] PasClaw.Cmd.Build.pas(311): E2010 Incompatible types: 'UInt64' and 'TSearchRec' [dcc64 Error] PasClaw.Cmd.Build.pas(324): E2010 Incompatible types: 'UInt64' and 'TSearchRec' Two root causes. ROOT CAUSE 1: SysUtils.GetTempDir is FPC-only. The signature `GetTempDir(Global: Boolean): string` exists in FPC's SysUtils but Delphi's RTL has no such function. Delphi exposes TPath.GetTempPath in System.IOUtils instead. Fix: wrap once at the unit top: function PlatformTempRoot: string; begin {$IFDEF FPC} Result := GetTempDir(False); {$ELSE} Result := TPath.GetTempPath; {$ENDIF} end; ROOT CAUSE 2: the Windows unit (in scope for SetEnvironmentVariable under {$IFDEF MSWINDOWS}) shadows several SysUtils file-system helpers with PWideChar/THandle overloads, which then collide with TSearchRec parameters. Specifically: Windows.DeleteFile(lpFileName: PWideChar) shadows SysUtils.DeleteFile(const FileName: string) Windows.FindClose(hFindFile: THandle) shadows SysUtils.FindClose(var F: TSearchRec) Windows.FindFirst* / FindNext* shadow SysUtils.FindFirst / FindNext for TSearchRec The dcc64 errors were: PWideChar mismatch -> we passed `string` to DeleteFile. UInt64 mismatch -> we passed a TSearchRec to FindClose. Fix: explicit SysUtils. qualification on every file-system call in the Windows-uses scope -- DeleteFile, FileExists, DirectoryExists, FindFirst, FindNext, FindClose, RemoveDir, TSearchRec. Comment block on RemoveTree documents the why so a future contributor doesn't "clean up the redundant prefix" and break dcc64. Bonus: dropped GetProcessID from the tempdir name. It's SysUtils-FPC-only with no portable Delphi equivalent (Delphi requires Windows.GetCurrentProcessId on Windows or Posix.Unistd.getpid on Linux). Two Random calls give 2^62 entropy which is ample for per-invocation tempdir uniqueness on a single host. FPC build (linux/x86_64) still clean. test-build-roundtrip still passes 10/10 (5 zip round-trip + 5 zip-slip regression). End-to-end smoke unchanged: `pasclaw build -d "smoke" --max-iters 1 --workspace-out /tmp/out.zip` produces the expected tempdir + zip output.
The README + docs/changelog.md last entry was 2026-06-13 (FMXExpress#244). Five substantial PRs (FMXExpress#314 FMXExpress#315 FMXExpress#316 FMXExpress#317 FMXExpress#318) and ten more feature PRs between them and that entry shipped without changelog entries. This brings both files current through today. Twenty new entries (newest first, matching the existing style): 2026-06-21 FMXExpress#318 Relay pull-worker provider (queue + provider + /v1/relay/* HTTP) 2026-06-20 FMXExpress#317 pasclaw plan + build PLAN.md pickup + build --goal + cog mode FMXExpress#316 Cloudflare AI Gateway provider catalog rows FMXExpress#315 MCP progressive disclosure + tool_search FMXExpress#314 Stock defaults adopt lean-edit shape; fs_grep split-gate 2026-06-18 FMXExpress#312 Web UI workspace.zip export + import FMXExpress#310 Model-callable cron tool FMXExpress#309 FTS5 snippet window widened 24 -> 60 FMXExpress#307 Windows cmd.exe quoting fix 2026-06-17 FMXExpress#306 cog-build honours profile=security sandbox FMXExpress#304 cog-build default profile = max-build FMXExpress#303 cog-build list[Path] outputs + Secret inputs + -q 2026-06-16 FMXExpress#302 cog-build optional workspace_in FMXExpress#300 pasclaw build cmd + cog-build/ predictor (parent feature) FMXExpress#299 Checkpoints zpaq backend + /redo FMXExpress#298 AGENTS.md + pasclaw init + /init FMXExpress#297 tool_choice force-a-specific-tool form FMXExpress#296 Delphi ExtraEnv injection fix FMXExpress#295 KB native PDF ingest 2026-06-15 FMXExpress#292 pasclaw profile diff + bench Skipped per the changelog's stated convention ("Bug fixes and review follow-ups are in the full git log"): FMXExpress#293 cmd/profile dcc64 fix FMXExpress#294 skills_manage gemini empty-enum fix FMXExpress#301 cmd.build dcc64 fix FMXExpress#311 cron dcc64 fix Files updated identically (the docs/changelog.md note at the top says "This file mirrors the changelog section at the top of the root README.md"): M README.md 20 entries + 20 link refs added M docs/changelog.md same The link-ref block at the bottom of each file gained 20 [#NNN] entries keeping the existing one-per-line / sorted-numerically format.
Summary
Adds
pasclaw build+ a siblingcog-build/Replicate predictor for the "ship state between ephemeral compute" pattern: feed inworkspace.zipfrom a previous run, getworkspace.zip(full$PASCLAW_HOME) back together with the model's reply text.CLI —
pasclaw buildpasclaw build -d "implement the X feature" \ --max-iters 30 \ --workspace-in /tmp/prev.zip \ --workspace-out /tmp/next.zip \ --provider openai --model gpt-4oThin orchestration over
Cmd_Agent_Runwith unattended-friendly defaults (--max-iterations 50,-q). All agent flags forward verbatim.pasclaw agentpasclaw build--workspace-in/--workspace-outPASCLAW_HOME~/.pasclaw--home, or fresh tempdirInput zip capped at 4 GiB, matched on both sides. Output zip's only exclusions are noise:
.git,.DS_Store,Thumbs.db,kb.db-journal. Logs,tmp/,kb-files/*.binall ship back — the point is to preserve the entire brain, including kb upload binaries and execution logs.cog-build/— Replicate predictorcog.yaml— builds the image with FPC + PasClaw + OpenSSL 1.0.2 (Indy TLS) and installspgetfor parallel multi-connection downloads of large workspace URLs.predict.py— returns an Output BaseModel with two fields the caller wants:workspace: Path— the newworkspace.zip(cog handles persistence past temp-dir cleanup).text: str— model's final reply, so the caller can decide whether to feed the workspace back for another round.message,max_iters(1–500),timeout_seconds(30s–24h), the API keys, plus two workspace inputs:workspace_in: Path— cog handles upload + URL via Path.workspace_in_url: str— explicit URL → downloaded via pget (parallel) for big files. Wins overworkspace_inwhen set.Sample control loop in
cog-build/README.md— chain builds sequentially by feeding the previous call'sworkspaceURL back asworkspace_in_url.Zip helper
PackDirToZipadded toPasClaw.Skills.Zip(next to existingExtractZipToDir). Cross-toolchain:TZipperunder FPC,TZipFileunder Delphi. Honors a case-insensitiveExcludeNamesdenylist at any depth.Files
Test plan
make test-build-roundtrip— 5 tests: text/binary/nested round-trip, exclusion denylist (case-insensitive at depth), empty-dir pack, missing-source-dir failure mode.make— full binary compiles clean under FPC 3.2.2.pasclaw build -d "..." --workspace-in in.zip --workspace-out out.zip --max-iters 1unpacks input, runs agent, packs output. Verified the workspace round-trip carriesworkspace/memory/MEMORY.mdandconfig.jsonfrom input through to output.test-delphi-build(PackDirToZipusesTZipFile.Addwhich is RTL since XE2).pgetfrom GitHub releases and pin OpenSSL 1.0.2 the same way/cog/does.Why two workspace inputs (
Pathandstr)Cog's
Pathtype handles both file-upload and URL-input transparently, but the URL fetch is single-stream. For multi-hundred-MB workspaces (typical oncekb.db+kb-files/+ checkpoint archives accumulate), pget's parallel multi-connection download is 3–5× faster. Letting callers explicitly pick the fast path is cheap; falling back to cog's default is fine for smaller workspaces.Generated by Claude Code