Repository navigation
fix(state): give the Rust CLI and the lab non-overlapping project state - #109
Merged
Merged
Conversation
`pickforge init` refused a project the lab had already used. When one `PICKFORGE_HOME` is shared by both tools — the normal setup for CI, automation, and the #93 Android pass — a lab run creates `projects/<id>/runs/`, and init's ownership check treated every entry in the project state directory as something it had to recognise. `runs/` is a directory, so it failed the `is_file()` check and the whole project was refused. The documented order (init first) hid it. Ownership of `<PICKFORGE_HOME>/projects/<projectId>/` is now written down and enforced by entry name, exhaustively and without overlap: the receipt and its backups belong to the Rust CLI, `runs/` to the lab, `.pickforge-tmp-*` is a transient of either, `layout.json` is shared, and anything else is owned by nobody and refused with the exact `mv` to run. The layout is versioned by a `layout.json` marker. Version 1 describes the layout alpha.1 and alpha.2 already wrote rather than replacing it, so nothing is migrated: an existing directory is adopted in place, the marker appearing beside what is already there. First use is atomic. The marker is staged in a temp entry and published with `link(2)`, so it carries complete content the moment it exists. An `O_EXCL` create plus write was the first attempt and the concurrency test caught it: the loser of the race read the file after creation but before the winner's bytes landed. Concurrent first use now yields exactly one claim and cannot leave partial ownership. Both tools fail closed on a layout they do not understand, writing nothing and naming the manual action. `scripts/state-ownership-smoke.sh` proves both orders against one canonical project in isolated homes with the real binary and the real lab; it fails on the unfixed CLI with the original error. Closes #104 Refs #89, #93
Review of #109 found the ownership statement was not true of the code and the claim itself was not safe. `pickforge evidence record` writes `runs/<run id>` into the shared project state directory, but v1 declared `runs/` the lab's and recording neither read nor claimed the marker: it recorded happily under `layoutVersion: 99`. `runs/` is now shared — both tools write into it, each only under its own run directory — and recording goes through the same claim as `init`, so an unknown version, a marker that is not ours, and an unowned entry all fail closed on one path before anything is written. The claim is now safe against the directory it writes into. It stages the marker in an exclusively created, unpredictably named, no-follow file with its bytes already complete, publishes it with `link(2)`, and removes the staging entry only when that name still resolves to the file it created. A crash remnant, or an entry planted under the name the old pid/thread scheme would have reused, is inert: at the reviewed head such a symlink was opened with `create(true).truncate(true)`, so init replaced an external file's bytes and left `layout.json` a symlink. Both tools now refuse a marker that is a symlink, a hard link, or not a regular file, read back and validate whichever marker won a race, and — on Linux — resolve every lookup through the state directory's own descriptor. Rust state directories are created `0700` again. TypeScript separated the two errors it used to conflate. `EEXIST` from creating the staging entry is a name collision to retry, not a lost publication race; the old single catch made a crash remnant plus pid reuse delete the pre-existing entry, skip claiming, and continue into `runs/` with no marker at all. One direct-entry rule now runs before every first adoption, in production in both languages: a directory nobody has claimed may hold only entries the table assigns to an owner. A claimed directory is not re-judged. An init that fails after publishing a new marker reports `failed-partial`, `changed: true`, and the marker as a residual instead of a clean rollback it did not perform. Refusals carry a shell-quoted `mv -n -- <path> <unused>`; a path that cannot be a safe shell word is described, not offered. `plan_init` is split into context, harness, workflow, and receipt planners and is under the complexity gate for the first time. The ownership table and marker bytes live in one language-neutral fixture both suites check, so the two implementations cannot silently diverge. New tests cover evidence recording against unknown, stray, symlinked, and markerless directories, stale staging names and pid reuse, hard links, cleanup identity, winner validation, and apply failure after a claim. The smoke now races the two real binaries on a fresh directory, records evidence in both orders, and requires both tools to fail closed on four planted layouts. It fails at the reviewed head on the symlinked-marker control and at `main` on the original #104 order. Closes #104 Refs #89, #93
A no-follow open answers ELOOP or ENOTDIR depending on what the entry is, so the marker is lstat'd once on the failure path — as the lab's directory handles already do — instead of reporting every such failure as a symlink. File identity also gets a portable fallback beside the Unix and Windows implementations, matching the evidence module.
The manual-action test hardcoded POSIX separators, so it failed on the Windows CI job where `with_file_name` rebuilds the path with a backslash; it now derives both paths from a temp directory. The two tests that plant symlinks are gated on Unix, as the evidence suite's already are.
The link-count check read a Unix-only field and silently reported one link elsewhere, so a hard-linked marker would have been accepted on Windows. It now reads the count from the open descriptor on both platforms, with the same `GetFileInformationByHandle` call the evidence reader uses, and the non-Unix open refuses a non-regular marker before reading it.
Windows CI caught it: staging identity was captured from the file's metadata before its bytes were written, and the Windows implementation used creation time and size, so the identity never matched afterwards. Cleanup was skipped, the staging name kept a second link on the published marker, and `init` then refused its own marker as hard-linked. Identity and link count now come from one `FileFacts` read from an open descriptor — device and inode on Unix, volume serial and file index on Windows — and cleanup compares the file it opens, not the name.
Windows resolves the temp root to a different path than the one the test environment is built from, so comparing the residual to a locally derived path failed there. The assertion now uses the directory the plan reports, which is the physical path the report names.
Closure review of #109 found eight fixed findings and ten residuals. Six of them are real gaps in the ownership rule this PR introduced, and they are fixed here in both languages, on the one claim path both tools already share. - A `layout.json` that is a FIFO, a socket, or a device node hung both tools instead of being refused: the marker was opened for reading before its type was checked, and a blocking `open(2)` on a pipe never returns. The marker is now opened non-blocking and no-follow, nothing is read before the descriptor's own type says it is a regular file, and a refusal names what the entry actually is. The bounded tests fail as a block, not as a hang (R1). - `init --dry-run` reported a clean plan for a directory with a receipt, no marker, and an unowned entry, which the real run then refused. The preview now runs the same direct-entry rule the claim runs, and still writes nothing (R2). - Both tools now refuse a symlinked `projects/<projectId>`. The lab always did; the CLI followed one, because the transaction layer and `evidence record` canonicalised the path first. The check is on the logical path and leaves a real existing directory alone (R3). - The lab creates the state root, `projects/`, the project directory, and `runs/` owner-only (`0700`), as the CLI does. Creation modes only: no chmod, no migration of directories that already exist (R4). - The lab no longer prints an `mv -n --` for an entry whose name is not valid UTF-8 on disk. It described the entry with replacement characters, so the command could not have addressed the real file; it now describes it, as the CLI already did (R5). - First adoption checks the shape of every owned entry, not just its name. A symlinked `runs/` no longer gets a marker stamped beside it certifying a layout both tools would then refuse to write through. Real receipts, real backups, a real run tree, and inert transients are adopted exactly as before (R7). The hard-link window is judged rather than merely waited out: a marker that is multiply linked is refused at once unless the second name is visibly the publication in flight — a `.pickforge-tmp-` entry in the same directory naming the same file — in which case it is waited out for a full second. A publisher descheduled longer than the old fixed 200 ms no longer makes a reader refuse a good marker, and a planted hard link is still refused, faster than before (R6). Tests: 11 new Rust tests and 10 new lab tests fail on the old head `a31411f`; the smoke gains bounded invocations (a tool that blocks now fails it instead of hanging it), controls for a FIFO marker, a socket marker, a symlinked run tree, a symlinked state directory, a non-UTF-8 name, and dry-run parity, plus two more real cross-process races. Refs #104, #89, #93.
`EntryKind` named three entry types Windows has no directory entry for, so `cargo clippy -D warnings` failed there on `dead_code` — the variants could never be constructed. They are now compiled where they can occur, together with the test helpers whose only callers are the unix cases. Verified with `cargo clippy -p pickforge-cli --all-targets --locked --target x86_64-pc-windows-msvc -- -D warnings`, which is the check that would have caught this before the push.
…m can see The reader refuses a planted hard link immediately where a directory listing exposes file identity, and after the settle budget on Windows, which has no such listing. The test asserted the fast path everywhere and failed on `rust (windows-latest)`. It now asserts the refusal on both, and the promptness only where it is a guarantee.
ElbertePlinio
added a commit
that referenced
this pull request
Sep 5, 2026
This was referenced Sep 5, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Closes #104
Refs #89, #93
The bug
pickforge initrefused a project the lab had already used.The two tools default to separate roots (
~/.pickforge/pickforgeand~/.pickforge/lab), but a singlePICKFORGE_HOMEpoints both at one root —the normal setup for CI, automation, and the #93 Android pass. Inside it they
share
projects/<projectId>/, where the Rust CLI writesproject.jsonand bothsides write runs.
Those paths never actually collided. The failure was an over-broad ownership
assertion:
recoverable_state_artifactstreated every entry in the projectstate directory as something it had to recognise and rejected anything that was
not a regular file it owned.
runs/is a directory, so it failed theis_file()check and the whole project was refused. The documented order (initfirst) hid it.
The fix
Ownership of
<PICKFORGE_HOME>/projects/<projectId>/is written down andenforced by entry name, exhaustively and without overlap:
layout.jsonruns/project.jsonpickforge— integration receiptproject.json.pickforge-backup-*pickforge— receipt backups.pickforge-tmp-*runs/is shared because both binaries write into it: the lab creates rundirectories there and
pickforge evidence recordwrites its own. Each writesonly its own runs; neither rewrites or deletes the other's, or anything unowned.
No migration, ever. The layout is versioned by a
layout.jsonmarker, andversion 1 describes the layout alpha.1 and alpha.2 already write. An existing
directory is adopted in place: the marker appears beside what is already there
and nothing else is read, rewritten, moved, or deleted.
One claim, every writer.
pickforge init,pickforge evidence record, andthe lab's run storage all go through the same claim, so the layout version, the
marker's shape, and the direct-entry rule are enforced on exactly one path per
language.
First adoption validates the directory. Before either tool stamps the marker
on an unclaimed directory, every direct entry must be one the table assigns to
an owner; one unowned entry stops the adoption and nothing is written. A
directory that already carries a marker is not re-judged — re-policing it would
let an entry added later break a tool that never reads it.
First use is atomic and cannot be diverted. The marker is staged in an
exclusively created, unpredictably named, no-follow file whose bytes are
complete and flushed, then published with
link(2), which fails rather thanreplacing anything. The staging entry is removed only when that name still
resolves to the file this run created. Both tools refuse a marker that is a
symlink, a hard link, or not a regular file, and both read back and validate
whichever marker won a race. On Linux every lookup resolves through the state
directory's own descriptor.
Failures are reported honestly. An init that fails after publishing a new
marker reports
failed-partial,changed: true, and the marker as a residual.Refusals carry a shell-quoted, no-clobber
mv -n -- <path> <unused>.bak; a paththat cannot be shown as a safe shell word is described instead of being offered
as a copyable command.
What the review of
676da66changedEvery finding is fixed, none dismissed.
marker.
runs/is now shared andevidence recordclaims and validatesthe layout before it writes. Reproduced at the old head (recorded a run under
layoutVersion: 99), covered now bytests/evidence_layout.rsand by asmoke control.
marker. Unpredictable, exclusive, no-follow staging; identity-checked
cleanup; symlink/hard-link/non-regular markers refused;
0700statedirectories; descriptor-pinned lookups on Linux.
EEXISTis retried under a new random name; only publicationEEXISTmeansa lost race; a pre-existing entry is never deleted; the winning marker must
exist and validate.
classifyEntry/classify_entrynow back one direct-entry rule that runs inproduction before every first adoption on both sides, and neither reader
follows a link at the marker.
failed-partialwith the marker as a residual.plan_initfailed the complexity gate. Split into context, harness,workflow and receipt planners:
complexity-gate checkis clean for it (31 →under 15/4/100), with nothing suppressed.
mvwas neither quoted nor no-clobber. Now shell-quoted,mv -n --, with an unused destination — or no command at all when the namecannot be rendered safely.
ownership table and marker bytes are one language-neutral fixture
(
test/fixtures/state-layout.json) both suites read, and the smoke races thetwo real binaries.
Verification
scripts/state-ownership-smoke.shdrives the real Rust binary and the real labin isolated homes and is a genuine regression detector:
evidence record: init → lab → evidence, andlab → init → evidence
pickforge initand a lab run on a freshdirectory, 10 rounds: both succeed, exactly one claims, the marker is always
the complete shared bytes and singly linked
stray marker, symlinked marker pointing at valid bytes, unowned entry, and
evidence recordunder an unsupported versionaction and its target is untouched; a stale regular one is left alone and does
not divert the claim
main(3adf3a9) it fails at order B with the original Separate Rust integration and TypeScript lab project state ownership #104error; against the reviewed head (
676da66) it fails at thesymlinked-marker control
Gates on the exact head
73509db, withmain3adf3a9merged in:cargo fmt,cargo clippy --workspace --all-targets --locked -D warnings,cargo test --workspace --locked --all-targets(116),bun run typecheck,bun run lint,bun run testandbun run test:coverage(112 files, 1,432 passed, 4 skipped,thresholds pass,
PICKFORGE_REQUIRE_BROWSER=1),test/security(32),bun run build, andcomplexity-gate check --changed— all pass. GitHub CI(
33953089617) and candidate smokes (33953089776) are attempt 1 on this exactSHA and green on every job, including the Windows Rust job.
11 of the new TypeScript tests fail against the reviewed head, and the smoke
fails there too, so they detect what they claim to.
Notes for review
libc(unix targets only), for theO_DIRECTORY/O_NOFOLLOWflags andELOOPthat pin the claim to a verifieddirectory. It was already in
Cargo.locktransitively;bun.lockandpackage.jsonare untouched.because a publisher holds a second link for the moment between
link(2)andremoving its staging entry. A genuine hard link survives the wait and is
refused.
runs/shared is the honest description of what both binaries alreadywrite, and it keeps "no migration" true for every existing alpha.1/alpha.2
directory.
bun run testruns hit the known load-sensitive Android port-allocationand Xvfb desktop flakes, which do not execute the state path; both files pass
in isolation, the coverage run was clean, and CI is green.
from a Unix-only field, and the staging entry's identity was captured before
its bytes were written and compared by size on Windows, so cleanup was skipped
and
initrefused its own marker. Both are fixed on the descriptor-readFileFactspath the marker and cleanup now share.Closure-review hardening (head
0ff1a2d)The closure review of
a31411fconfirmed all eight findings (H1–L8) fixed andlisted ten residuals. Six were real gaps in the ownership rule this PR
introduces and are fixed here, in both languages, on the one claim path both
tools already share.
O_NOFOLLOW|O_NONBLOCK, nothing is read before the descriptor's own type says "regular file", and refusals name the type ("a named pipe (FIFO)", "a socket", "a device node", "a directory", "a symbolic link"). Tests race every such call against a timeout, so a regression fails as a block instead of hanging the suiteinit --dry-runmissed one refusalprojects/<id>asymmetrymv -n --projects/,projects/<id>/, andruns/0700, as the CLI does. Creation modes only — nochmod, no migration; a test pins that an existing0755directory keeps its moderuns/must be a real directory, receipts real regular files. A symlinkedrunsis refused rather than certified. Real receipts, real backups, a real run tree, and inert transients are still adoptedR6 (the publication window) is improved rather than merely widened. A
multiply linked marker is refused immediately unless the second name is
visibly the publication in flight — a
.pickforge-tmp-entry in the samedirectory naming the same file — in which case it is waited out for up to a
second. A publisher stalled 400 ms (twice the old fixed window) is now
tolerated, and a planted hard link is refused faster than before. On Windows,
where a listing exposes no file identity, the settle budget still applies.
R8 (concurrent
inits contending on~/.claude.json) is the transactionlayer's drift check and predates this PR. R10 (edge-version wording) would mean
parsing invalid versions just to name them; both tools fail closed today.
Tests
tests/state_layout.rs, 8 intests/evidence_layout.rs, 51lab tests in
state-layout.test.ts. 21 of them fail on the previous heada31411f(9 + 2 Rust, 10 lab).timeout, so a tool that blocks failsit instead of hanging it, and gains controls for a FIFO marker, a socket
marker, a symlinked run tree, a symlinked state directory, a non-UTF-8 name,
and dry-run/apply parity — plus two more real cross-process races (
evidence recordagainst a lab run in a claimed directory, and all three writers on onefresh directory). Run with this head's smoke,
a31411ffails at the FIFOcontrol:
pickforge init blocked instead of refusing.Behaviour changes worth a second look
runs/or a symlinkedprojects/<id>is now refused where itwas previously followed or silently certified. Failing closed with an exact
command is the policy this layout already applies elsewhere, but it is a
change for anyone who linked those deliberately.
Pickforge layout marker must be one (it is a named pipe (FIFO))".
Gates at
0ff1a2dcargo fmt,cargo clippy --workspace --all-targets --locked -D warnings,the same clippy for
x86_64-pc-windows-msvc,cargo test --workspace --locked --all-targets(133),bun run typecheck,lint,build,test/security(32),
bun run test(113 files, 1,471 passed, 4 skipped),bun run test:coverage(2 runs, both green),complexity-gate checkon every changedfile (only the pre-existing
evidence.rs::same_fileFAIL from #70), andscripts/state-ownership-smoke.shwithPICKFORGE_RACES=10.CI
33959352362and candidate smokes33959352448are attempt 1 on thisexact SHA and green on every job, including both Rust jobs and
bun run test:coverage— the step that was red ata31411fbecause of #107'sguest-readinesstest. That test is not fixed here and cannot be: it isinherited from
main, its fix is PR #113, and its flake is latent rather thangone. Two intermediate heads of mine were red and are fixed in this branch's
history:
b73ca05brokerust (windows-latest)ondead_codefor entry-typevariants Windows cannot have, and
3e7a88bhad a test of mine assert aunix-only timing guarantee there.