Skip to content

fix(state): give the Rust CLI and the lab non-overlapping project state - #109

Merged
ElbertePlinio merged 13 commits into
mainfrom
fix/104-state-ownership
Sep 5, 2026
Merged

ElbertePlinio merged 13 commits into
mainfrom
fix/104-state-ownership

Conversation

@ElbertePlinio

@ElbertePlinio ElbertePlinio commented Sep 5, 2026 •

Copy link
Copy Markdown
Member

Closes #104
Refs #89, #93

The bug

pickforge init refused a project the lab had already used.

The two tools default to separate roots (~/.pickforge/pickforge and
~/.pickforge/lab), but a single PICKFORGE_HOME points 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 writes project.json and both
sides write runs.

Those paths never actually collided. The failure was an over-broad ownership
assertion: recoverable_state_artifacts treated every entry in the project
state 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 the
is_file() check and the whole project was refused. The documented order (init
first) hid it.

The fix

Ownership of <PICKFORGE_HOME>/projects/<projectId>/ is written down and
enforced by entry name, exhaustively and without overlap:

entry owner
layout.json shared — the layout marker
runs/ shared — one run tree, two writers
project.json pickforge — integration receipt
project.json.pickforge-backup-* pickforge — receipt backups
.pickforge-tmp-* transient, either tool
anything else nobody

runs/ is shared because both binaries write into it: the lab creates run
directories there and pickforge evidence record writes its own. Each writes
only its own runs; neither rewrites or deletes the other's, or anything unowned.

No migration, ever. The layout is versioned by a layout.json marker, and
version 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, and
the 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 than
replacing 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 path
that cannot be shown as a safe shell word is described instead of being offered
as a copyable command.

What the review of 676da66 changed

Every finding is fixed, none dismissed.

  1. Rust evidence wrote through a TypeScript-owned entry and ignored the
    marker.
    runs/ is now shared and evidence record claims and validates
    the layout before it writes. Reproduced at the old head (recorded a run under
    layoutVersion: 99), covered now by tests/evidence_layout.rs and by a
    smoke control.
  2. Marker publication could overwrite an unrelated file and publish a symlink
    marker.
    Unpredictable, exclusive, no-follow staging; identity-checked
    cleanup; symlink/hard-link/non-regular markers refused; 0700 state
    directories; descriptor-pinned lookups on Linux.
  3. TypeScript conflated temp-name collisions with publication races. Staging
    EEXIST is retried under a new random name; only publication EEXIST means
    a lost race; a pre-existing entry is never deleted; the winning marker must
    exist and validate.
  4. Marker and foreign-entry validation were not enforced by both tools.
    classifyEntry/classify_entry now back one direct-entry rule that runs in
    production before every first adoption on both sides, and neither reader
    follows a link at the marker.
  5. A failed apply could report full rollback while leaving a new marker. Now
    failed-partial with the marker as a residual.
  6. plan_init failed the complexity gate. Split into context, harness,
    workflow and receipt planners: complexity-gate check is clean for it (31 →
    under 15/4/100), with nothing suppressed.
  7. The manual mv was neither quoted nor no-clobber. Now shell-quoted,
    mv -n --, with an unused destination — or no command at all when the name
    cannot be rendered safely.
  8. Tests pinned neither the cross-language claims nor the failure cases. The
    ownership table and marker bytes are one language-neutral fixture
    (test/fixtures/state-layout.json) both suites read, and the smoke races the
    two real binaries.

Verification

scripts/state-ownership-smoke.sh drives the real Rust binary and the real lab
in isolated homes and is a genuine regression detector:

  • both orders, now including evidence record: init → lab → evidence, and
    lab → init → evidence
  • a real cross-process race between pickforge init and a lab run on a fresh
    directory, 10 rounds: both succeed, exactly one claims, the marker is always
    the complete shared bytes and singly linked
  • negative controls both tools must refuse without writing: unsupported version,
    stray marker, symlinked marker pointing at valid bytes, unowned entry, and
    evidence record under an unsupported version
  • controls for planted staging names: a symlinked one is refused with the manual
    action and its target is untouched; a stale regular one is left alone and does
    not divert the claim
  • against main (3adf3a9) it fails at order B with the original Separate Rust integration and TypeScript lab project state ownership #104
    error; against the reviewed head (676da66) it fails at the
    symlinked-marker control

Gates on the exact head 73509db, with main 3adf3a9 merged 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 test and bun run test:coverage (112 files, 1,432 passed, 4 skipped,
thresholds pass, PICKFORGE_REQUIRE_BROWSER=1), test/security (32),
bun run build, and complexity-gate check --changed — all pass. GitHub CI
(33953089617) and candidate smokes (33953089776) are attempt 1 on this exact
SHA 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

  • One dependency edge is added: libc (unix targets only), for the
    O_DIRECTORY/O_NOFOLLOW flags and ELOOP that pin the claim to a verified
    directory. It was already in Cargo.lock transitively; bun.lock and
    package.json are untouched.
  • Marker readers wait out a short window when the marker is multiply linked,
    because a publisher holds a second link for the moment between link(2) and
    removing its staging entry. A genuine hard link survives the wait and is
    refused.
  • Making runs/ shared is the honest description of what both binaries already
    write, and it keeps "no migration" true for every existing alpha.1/alpha.2
    directory.
  • Two bun run test runs hit the known load-sensitive Android port-allocation
    and Xvfb desktop flakes, which do not execute the state path; both files pass
    in isolation, the coverage run was clean, and CI is green.
  • Windows CI caught two things worth naming: the marker's link count was read
    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 init refused its own marker. Both are fixed on the descriptor-read
    FileFacts path the marker and cleanup now share.

Closure-review hardening (head 0ff1a2d)

The closure review of a31411f confirmed all eight findings (H1–L8) fixed and
listed 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.

residual fix
R1 a FIFO/socket/device marker hung both tools the marker is opened 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 suite
R2 init --dry-run missed one refusal the direct-entry rule runs whenever there is no marker and the directory exists, receipt or no receipt. Preview and apply refuse the same directory; the preview still writes nothing
R3 symlinked projects/<id> asymmetry both tools refuse it, checked on the logical path before the transaction layer canonicalises it away. A real existing directory is untouched, and the refusal carries the exact mv -n --
R4 lab directory modes the lab creates the state root, projects/, projects/<id>/, and runs/ 0700, as the CLI does. Creation modes only — no chmod, no migration; a test pins that an existing 0755 directory keeps its mode
R5 non-UTF-8 names in the lab's action the adoption check reads the listing as bytes and refuses a name that does not round-trip through UTF-8, with the Rust wording; U+FFFD is also in the unsafe-shell-word set, so no path can render one into a copyable command
R7 name-only first adoption owned entries are shape-checked before the marker is stamped: runs/ must be a real directory, receipts real regular files. A symlinked runs is refused rather than certified. Real receipts, real backups, a real run tree, and inert transients are still adopted

R6 (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 same
directory 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 transaction
layer'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

  • 34 Rust tests in tests/state_layout.rs, 8 in tests/evidence_layout.rs, 51
    lab tests in state-layout.test.ts. 21 of them fail on the previous head
    a31411f
    (9 + 2 Rust, 10 lab).
  • The smoke bounds every invocation with timeout, so a tool that blocks fails
    it 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 record against a lab run in a claimed directory, and all three writers on one
    fresh directory). Run with this head's smoke, a31411f fails at the FIFO
    control: pickforge init blocked instead of refusing.

Behaviour changes worth a second look

  • A symlinked runs/ or a symlinked projects/<id> is now refused where it
    was 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.
  • Refusal text now names what an entry is, e.g. "is not a regular file where the
    Pickforge layout marker must be one (it is a named pipe (FIFO))".

Gates at 0ff1a2d

cargo 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 check on every changed
file (only the pre-existing evidence.rs::same_file FAIL from #70), and
scripts/state-ownership-smoke.sh with PICKFORGE_RACES=10.

CI 33959352362 and candidate smokes 33959352448 are attempt 1 on this
exact SHA and green on every job
, including both Rust jobs and bun run test:coverage — the step that was red at a31411f because of #107's
guest-readiness test. That test is not fixed here and cannot be: it is
inherited from main, its fix is PR #113, and its flake is latent rather than
gone. Two intermediate heads of mine were red and are fixed in this branch's
history: b73ca05 broke rust (windows-latest) on dead_code for entry-type
variants Windows cannot have, and 3e7a88b had a test of mine assert a
unix-only timing guarantee there.

`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
@ElbertePlinio
ElbertePlinio merged commit 47e3b76 into main Sep 5, 2026
10 checks passed
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.

Separate Rust integration and TypeScript lab project state ownership

1 participant