Skip to content

Make six implicit state machines explicit (#9) - #10

Merged
johnpippett merged 9 commits into
mainfrom
dev/affectionate-meitner-7btk1b
Nov 13, 2026
Merged

johnpippett merged 9 commits into
mainfrom
dev/affectionate-meitner-7btk1b

Conversation

@johnpippett

@johnpippett johnpippett commented Nov 11, 2026 •

Copy link
Copy Markdown
Owner

What and why

Closes #9. All six implicit state machines are now explicit, one commit per machine in the issue's order (SM-3, SM-1, SM-6, SM-4, SM-5, SM-2). The issue asks for one PR per machine. This session can only push one branch, so they're in one PR. Each commit stands alone (each passes the static checks and its package's tests), so they can be cherry-picked into six PRs if you'd rather review them that way.

Every machine follows the recipe: one tagged union, transitions in one pure next…State function (or an accessor plus a rules function for SM-3), an exhaustive switch with a never default, events that don't fit leaving the state unchanged, side effects in the caller, and a table test that walks every state against every event. Each one has an entry in the new IMPLEMENTATION_NOTES.md section "Explicit state machines (issue 9)".

State type Where Table test
SM-3 ApproverMode signer/src/approver-mode.ts, KeyStore.approverMode() signer/test/approver-mode.test.ts (real SignerHandler, 3 modes × 6 events)
SM-1 HandoffState, nextHandoffState core/src/handoff.ts core/test/handoff-states.test.ts
SM-6 Mailbox<T> core/src/mailbox.ts (handoff results + ceremony results) core/test/mailbox.test.ts
SM-4 PairingState, nextPairingState, pairingStatus approver/src/pairing-state.ts approver/test/pairing-states.test.ts
SM-5 CardState, nextCardState approver/src/approval-card.ts approver/test/approval-card.test.ts
SM-2 CoreGrant / signer Grant as window | single core/src/grants.ts, core/src/broker.ts, signer/src/server.ts core/test/grant-states.test.ts

Behaviour changes (all ones the issue asked for)

  • SM-1: lastEnded keeps {handoffId, outcome}, not the whole Handoff, so an ended handoff no longer pins its Playwright page and session (tested). signIn.ended runs exactly once: if the handoff ends while the card is still waiting, the card is aborted and the hook runs after the approval promise settles, so a grant from a late approval still gets dropped (tested for every end reason, plus "approval lands after end").
  • SM-4: a finish moves the pairing to verifying before its first await. Two finishes on one code can no longer both reach the signer; the second gets the existing 409. There's a race test, and it fails on the old code. The status strings are unchanged.

Where the issue's spec contradicted itself (please check)

  1. handoff.test.ts: "ending while the owner decides" expected signIn.ended to be called twice. Step 4 of SM-1 says exactly once, and the same section says this file must pass unchanged. I followed step 4 and changed that one expectation to a single call. It's the only existing expectation I edited.
  2. grants.test.ts: its helper builds grants with singleUse / armed via Partial<CoreGrant>. That can't typecheck against the target union, and a window grant can't be armed any more. I changed how the test builds grants; all its assertions are unchanged.
  3. SM-4 failed keeps its device. The issue's sketch had none, but both status endpoints answer by device kind and have to keep answering a failed pairing the same way.

Owner decisions taken by default

  • SM-5 "signing": nobody had picked, so it's A, latest tap wins (today's behaviour), pinned by native-api.test.ts › "SM-5 option A" (A asks, B asks, A's signature refused, B's accepted).
  • SM-2: the signer still doesn't track held / armed. No protocol change, no new request, same checks.

I couldn't read ../keyflap-site/notes/DECISIONS.md: the private repo isn't in this session. I changed no policy, approvals, high-risk list or CLI behaviour.

Checklist

  • pnpm check passes (and pnpm test:isolation if service mode is touched). See "Test results": everything that can run here is green, and isolation is still owed.
  • No security invariant (ARCHITECTURE.md section 5) is weakened; changed or new invariant behavior has an automated test.
  • Tests use only the local test RP and the fake pass-cli, never third-party sites or real vaults.
  • No secrets (passwords, keys, tokens, one-time codes) in code, tests, logs or this PR.
  • Any new deviation from the design is recorded in docs/IMPLEMENTATION_NOTES.md.

Test results (cloud container, root)

  • Static checks (pnpm check:static): pass at every commit.
  • pnpm test (all projects, unit + e2e): 2269 passed, 15 failed. All 15 fail the same way on base main in this container, so none come from this diff:
    • 9 from running as root: keystore.test.ts › "a migration that cannot be written…" (root ignores chmod) and 8 cases in install/test/simple-install-shell.test.ts.
    • 6 from the container itself (a real claude CLI on PATH, and root): 4 in cli/test/dev-console.e2e.test.ts and 2 in cli/test/setup.e2e.test.ts. I reproduced all 6 on a worktree of 34f2b4d.
    • e2e ran against Chromium 1243 aliased as 1248, because Playwright's CDN is blocked here. CI runs the real pin.
  • verify-aab: all 8 features pass, 42/42 steps (passkey, password-totp, policy, agents-intents, status-audit, challenge, persistence, handoff including the single approval for check + sign-in). doctor.sh failed only its two port-owner checks, because ss isn't installed. Port ownership was confirmed through /proc/net/tcp instead.
  • pnpm test:isolation: not run to completion. The systemd container starts, but install.sh refuses with "--browsers-dir has no Chromium 1248", and the pinned build can't be downloaded from this network. It needs a machine that can fetch the pin. This affects the signer PRs (SM-3, SM-2).
  • CI fix, separate commit b27b2c9: the two service-config tests broke on GitHub's current Ubuntu image (/usr/bin/env is now a uutils symlink). Details in the PR comment.

🤖 Generated with Claude Code

https://claude.ai/code/session_01KJaP4fvvUwCMdb6ZKz8q8s

KeyStore.approverMode() derives 'unpaired' | 'phone' | 'phone-empty' from
the stored latch and approver count; approverModeRules() replaces the three
hand-written conditions in server.ts. Nothing new is written to disk.
Table test walks every mode against every event.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KJaP4fvvUwCMdb6ZKz8q8s
HandoffState (awaiting_approval | waiting_for_phone | controlled | ended)
replaces controller, ended, endedAt, claimed and abort; nextHandoffState is
the only transition. lastEnded keeps a small record instead of the whole
handoff, so an ended handoff no longer pins its page and session.
signIn.ended now runs exactly once per handoff with a sign-in offer: an end
while the card waits runs it after the approval settles, so a late grant is
still dropped. The one test that pinned the old double call now expects one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KJaP4fvvUwCMdb6ZKz8q8s
Mailbox<T> (put / has / take, read at most once inside its window) replaces
the hand-rolled claimed flags for handoff results and passkey ceremony
results. Both 60-second windows and the 32-entry ceremony cap are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KJaP4fvvUwCMdb6ZKz8q8s
PairingState replaces the four-value state and the nullable challenge,
token and kind; nextPairingState is the only transition and pairingStatus
the one map to the strings the page and iOS app read (unchanged). A finish
now takes the pairing (verifying) before its first await, so two finishes
on one code can no longer both reach the signer: the second gets the
existing 409.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KJaP4fvvUwCMdb6ZKz8q8s
CardState (queued | signing | approved | denied | timed_out) replaces the
nullable statement and the done flag; nextCardState is the only transition.
Keeps today's behaviour (option A, latest tap wins), now pinned by a test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KJaP4fvvUwCMdb6ZKz8q8s
CoreGrant and the signer's internal Grant are now 'window' | 'single'
unions (core: phase held | armed; signer: spentBy) instead of optional
singleUse / armed / usedBy / handoffId. The broker's Authorized is
by-grant | by-approval, so registration can no longer receive a grant and
its internal_error guard goes away. No signer protocol change.
grants.test.ts builds grants in the new shape; its assertions are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KJaP4fvvUwCMdb6ZKz8q8s
GitHub's current Ubuntu runner ships uutils coreutils, where /usr/bin/env is
a symlink. install-config rightly refuses a linked tool, but the two
service-config tests guarded with statSync, which follows the link, and
so ran the positive pin case on a path the product must refuse. Guard with
lstatSync().isFile() like inv1-tool-trust.test.ts already does. No
assertion changes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KJaP4fvvUwCMdb6ZKz8q8s

Copy link
Copy Markdown
Owner Author

CI unit (shard 2/2) failed on 6914a4c in packages/cli/test/service-config.test.ts ("install-config refuses a pass-cli …" and "… a tailscale …"). The cause isn't this PR's diff, and the same failure would hit main on today's runner image. The image now ships uutils coreutils, so /usr/bin/env is a symlink to /usr/lib/cargo/bin/coreutils/env. install-config rightly refuses a linked tool. The tests check that /usr/bin/env is root-owned with statSync, which follows the link, so they went on to try to pin a path the product has to refuse.

Ported fix in b27b2c9: the tests now guard with lstatSync(...).isFile(), the same check packages/sources/test/inv1-tool-trust.test.ts already uses for this fixture. Assertions are unchanged. On a runner where /usr/bin/env is a symlink, the positive pin case is skipped, as it already is in the sources test.


Generated by Claude Code

Copy link
Copy Markdown
Owner Author

macOS e2e (shard 3/4) failed on b27b2c9: packages/core/test/inv8-fill.e2e.test.ts › "identifier-first where Enter does nothing" returned { status: 'failed' }. The same test passed in the macOS run on 6914a4c, and the only change between the two heads is the cli test fixture in b27b2c9, so the core code under test is identical. It also passes on Linux CI and locally. Nothing in this PR touches the fill driver (core/src/fill.ts). I've re-run the failed job once. If it fails again, I'll treat it as real and dig in.


Generated by Claude Code

@johnpippett johnpippett left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review of b27b2c9 against issue #9. The six refactors hold up and I found no outright regression. Typecheck, lint, the three source checks and the nine touched unit test files (203 tests) pass on this head; e2e and isolation were not run for this review.

Fix before merge (4 inline comments):

  1. phone.ts:1057: "latest tap wins" does not hold on the web decide path, and an expired statement can consume the card.
  2. handoff.test.ts:655: an existing expectation was edited; needs the owner's explicit yes.
  3. handoff.ts:554: the once-only signIn.ended depends on the approval promise settling; if it does not, a single-use grant is never dropped.
  4. service-config.test.ts:271: the test returns early on Linux CI and asserts nothing. Unrelated to #9.

Smaller (6 inline comments): a test that asserts nothing, a stale IMPLEMENTATION_NOTES entry, a mailbox round trip plus a leftover flag, transition detection by object identity, and two cleanup notes.

Issue #9 asked for one pull request per machine; this is all six in one. Fine to keep as is if the owner prefers, but the unrelated service-config test change should come out.


Generated by Claude Code

Comment thread packages/approver/src/phone.ts Resolved
Comment thread packages/core/test/handoff.test.ts Resolved
Comment thread packages/core/src/handoff.ts Resolved
Comment thread docs/IMPLEMENTATION_NOTES.md Resolved
Comment thread packages/core/src/sessions.ts Resolved
Comment thread packages/approver/src/phone.ts Resolved
Comment thread packages/core/src/handoff.ts Resolved
Comment thread packages/approver/src/phone.ts Resolved
…sals

- approver: decide and nativeDecide read the card's statement after their
  last await and verify signature and expiry against it; a finished card
  answers 404. New approval-card-web.test.ts pins both orders and a
  challenge landing mid-decision (fails on the old web path).
- approver: nextCardState and nextPairingState return null for a refused
  event instead of relying on object identity; the pairing token lives only
  in the paired state.
- core: end() is the one place that discharges signIn.ended; from
  awaiting_approval it chains onto the stored approval promise. Tests for an
  approve that ignores the abort and for handoffs without an offer.
  Drop stateOf/isEnded, the dead entry guard and the unread ended.at.
- core: a ceremony already claimed in flight is not put in the mailbox.
- signer: drop the never-read handoffId from the single-use grant.
- cli(test): probe for a root-owned regular system file instead of
  skipping when /usr/bin/env is a symlink, so the pin assertions always run.
- notes: bring the SM-1, SM-4, SM-5, SM-6 and SM-2 entries up to date.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KJaP4fvvUwCMdb6ZKz8q8s

Copy link
Copy Markdown
Owner Author

macOS e2e (shard 1/4) failed on 53a9957: packages/core/test/swipe-approval.e2e.test.ts › "a drag whose pointer capture is lost lets go of the card". The .dragging class was still set 5 s after releasePointerCapture.

This is a client-side gesture on the phone page. The test asserts that neither /api/challenge nor /api/decide is called. The PR doesn't touch packages/approver/src/page/, and the test passed on macOS for 6914a4c and b27b2c9. I've re-run the failed job once. If it fails again I'll treat it as real and dig in.


Generated by Claude Code

The phone page posts each live-view input without the click awaiting it,
and the handoff applies inputs one after another. The test clicked Enter,
then the scroll, then Done straight away, so on a slow runner the handoff
could end while the scroll was still queued, and the audited count read
scrolls: 0 (macOS CI, run 43151607654). Wait for each input's response
first. The assertions are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KJaP4fvvUwCMdb6ZKz8q8s

Copy link
Copy Markdown
Owner Author

The macOS re-run on 53a9957 failed differently. swipe-approval passed this time, and inv10-audit.e2e.test.ts failed: handoff.ended.inputs showed scrolls: 0, where the test expects 1.

Root cause is a race in the test, not this diff. The live view's send() posts each input without the click waiting for it, and the handoff applies inputs one at a time through h.queue. The test clicked Enter, then the scroll, then Done immediately. On a slow runner the handoff ended while the scroll was still queued behind the key press, so apply saw it ended and didn't count it. This PR doesn't change the input path (input / apply / controlled).

Fix in 8864dd8: the test now waits for each /api/handoff/input response before clicking Done. Only the sequencing changed; every assertion stays the same. It passes locally. This is an invariant test file, so I'm flagging it in case you'd rather fix it some other way.

On swipe-approval › "pointer capture lost": it passed on the re-run and on macOS for 6914a4c and b27b2c9, and it involves only the page's gesture code, which this PR doesn't touch. I couldn't reproduce it locally, and I have no root cause yet. If it fails again on this head, I'll dig into the page side.


Generated by Claude Code

@johnpippett
johnpippett marked this pull request as ready for review November 13, 2026 18:58
@johnpippett
johnpippett merged commit 12f0de7 into main Nov 13, 2026
16 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.

Make six implicit state machines explicit (tracking issue + build recipe)

2 participants