Skip to content

feat(cli): sign machines in with login and logout - #157

Merged
allisonmahmood merged 2 commits into
mainfrom
auth/142-cli-login-logout
Sep 6, 2026
Merged

allisonmahmood merged 2 commits into
mainfrom
auth/142-cli-login-logout

Conversation

@allisonmahmood

Copy link
Copy Markdown
Owner

Publishing required a machine token you already held. Agents had no way to hand sign-in to a person, and logging out needed to work even when the instance was unreachable.

Adds patchy login with a URL/code handoff, resumable completion, and waiting for people at real terminals. Stored logins outrank the dev seed. patchy logout forgets the local key first, then revokes it as a courtesy. The CLI docs and publishing skill teach the new flow.

Stacked on auth/141-device-login-server, which provides the server-side device-login routes. This PR targets that branch and contains only the CLI follow-through for #142.

Verification:

  • pnpm test: 317 tests passed across 37 files.
  • pnpm typecheck, pnpm lint, and pnpm test:packed-cli-e2e passed.
  • Browser confirmation, human-terminal waiting, and logout restoring the seeded machine verified locally with offline Clerk signing.
  • Standards and spec reviews have no remaining findings; skill lock hash matches.

Closes #142.

Model: GPT-6 Astra. Harness: Oh My Pi.

@github-actions github-actions Bot added area:ci CI, shared testing infrastructure, development scripts and tooling area:cli Touches the cli area area:docs Touches the docs area size:l 501-1,000 changed lines labels Sep 5, 2026
@allisonmahmood

Copy link
Copy Markdown
Owner Author

Astra review

Reviewed e09358b against origin/auth/141-device-login-server (802a884) using git diff origin/auth/141-device-login-server...HEAD, against issue #142 and its referenced auth spec §10. One pass, no subagents; merge-blocking findings only.

Standards

No merge-blocking method or YAGNI findings.

Spec

Intent — [P2] Make --wait bound an in-flight poll

packages/cli/src/Login.ts:70–76, with the deadline checked only at lines 123–129.

Issue #142 requires “pending after --wait (default 60) at exit 0”; the agent handoff promises to wait up to a minute. The deadline currently bounds sleeps between polls, but not pollDeviceLogin itself. A slow HTTP response prevents the loop from observing the deadline, so the agent's command can run beyond its requested wait.

Reproduced: with an isolated loopback endpoint that returns { ok: true, status: "pending" } after four seconds, the actual source CLI's login --complete --wait 1 --json exited 0 with status: "pending" after 4.50 seconds, rather than respecting the one-second wait. The new TestClock case uses immediate responses and does not cover this boundary.

Bound in-flight polling by the remaining wait budget, preserving pending state on timeout and retaining --wait 0's single-poll behavior. Keep transport timeouts distinguishable from an actual server pending answer under the existing exit-code contract.

Verification: pnpm exec vitest run packages/cli/src/Login.test.ts packages/cli/src/cli.test.ts — 44 passed; delayed-response CLI probe reproduced the finding; public skill SHA-256 matches skills-lock.json. Full suite and packed e2e were not rerun. No source changes.

Summary: Standards: 0 blockers. Spec: 1 blocker — the completion wait budget does not cover an in-flight HTTP poll.

@allisonmahmood allisonmahmood linked an issue Sep 5, 2026 that may be closed by this pull request
3 tasks
@allisonmahmood

Copy link
Copy Markdown
Owner Author

Code review — PR 157 vs issue #142

Reviewed auth/142-cli-login-logout (e09358b) against its stacked base auth/141-device-login-server (802a884), not against main. Originating spec is #142 (auth spec §10). Axes below are separate on purpose: a change can match the issue and still miss a standard, or the reverse.

Intent, in one paragraph. #142 asked for the agent-native CLI follow-through of device login: patchy login returns a URL/code/next document, the agent never opens a browser and finishes with --complete; a person at a real TTY waits in one command; logout forgets locally first and revokes as a courtesy; a stored login outranks the worktree seed; the mint announcement is replaced everywhere an agent reads. That is what this PR is. Surfaces the issue named are present (README, ADR-0004, skill + lock hash, onboarding, DEVELOPMENT.md, CONTEXT.md, product.md, packed e2e, logout as the reverse of login). The divergences are in how resume and completion report, not in whether the commands exist.


Standards

No Effect service findings. Login.ts stays a module (one consumer). State keeps the canonical file order. Effect.catch on the login/logout HTTP channel is the right tool: DeviceLoginGone is a plain wire struct, not a tagged failure. Layers, runPromise/ManagedRuntime, namespace imports, and test seams (FileSystem.layerNoop, HttpClient) match the spec. Surfaces are covered: README, ADR-0004, skills/patchy + matching skills-lock.json hash (ddb42195…0cc7), docs/DEVELOPMENT.md, patchy-dev-loop, CONTEXT.md, docs/product.md, and logout as the reverse of login.

(a) Documented standard

packages/cli/src/commands.ts ~234–236 — hard. New --help copy:

Command.withDescription(
  "Sign in this machine; relay the URL and code, then use --complete [code]."
)

packages/cli/CONTEXT.md Sign-in is the browser session; Login handoff is patchy login. Same PR: README “Log this machine in…”, skill/onboarding “Say sign in for the person’s browser session and log this machine in for publishing.” CLAUDE.md: use CONTEXT words. Expected: “Log this machine in; relay the URL and code, then use --complete [code].”

(auth’s pre-existing “authentication” description is untouched; out of scope.)

(b) Baseline smell (judgement)

Primitive Obsession — packages/cli/src/Login.ts ~80–88

if ("code" in error) {
  yield* state.forgetPendingLogin(apiUrl);
  const message =
    error.code === "denied"
      ? "The login was denied in the browser. Nothing was saved. Run: patchy login"
      : error.code === "expired"
        ? "The login expired before it was confirmed (codes last ten minutes). Run: patchy login"
        : `No login is pending for code ${login.userCode} on ${apiUrl}; it may already have been reported. Run: patchy login`;

@patchy/api already names this DeviceLoginGone (expired | denied | unknown). Duck-typing "code" matches the existing isRefusal ("ok" in error) pattern, so this is not a hard breach; a Schema.is(DeviceLoginGone) branch would still be the honest type. Mapping all three onto RejectedError is required by ADR-0004 (one CliError union, exit 2) and overrides splitting them into extra tags.


Spec

(a) Missing or partial

Agent login rerun does not reprint the handoff. Spec §10: “Otherwise it prints the handoff as lines, one line saying why it did not wait, and Then run: patchy login --complete XXXX-XXXX, exit 0. A rerun with a live login pending resumes it.” Resume is implemented (no second start). A non---complete agent rerun (reason !== null) does not reprint that handoff (no URL, no “why it did not wait”).

(b) Not asked for

That rerun polls. Polling is specified only for --complete. Login.login does poll(current, 0) on an agent rerun, ignoring --wait. Packed e2e asserts this as the resume contract.

login --api-url writes config.json. Spec §10 does not ask login to save the instance; only auth set does. The skill/README then depend on it.

(c) Looks implemented, wrong

Rerun success shape is --complete pending, not the login handoff. Spec §10 handoff JSON: { ok, status: "awaiting_confirmation", verificationUrl, verificationUrlBare, userCode, expiresAt, interval, next, agentNextSteps, notWaitingBecause }. The rerun returns { status: "pending", userCode, expiresAt, next, agentNextSteps } — no URLs, no notWaitingBecause. An agent that reruns patchy login --json cannot recover the URL the spec assigned to that command.

Complete reports failure after the key is saved. Spec §10: “On complete it saves the token with source: "login" and the machine, forgets the pending record, and prints Logged in to <instance> as <company>. This machine is "<name>".” After persist, me() is fatal (exit 3). A one-time mint can look like a failed login; a retry starts a new code because pending is already gone. The suite locks this in (“keeps a completed key when the subsequent identity request is unreachable”). ADR-0004’s new courtesy-call rule is the same idea for logout; login’s local act is the save.


Method

This is the method I would ship. It is the prototype’s Stripe-shaped handoff with the throwaway knobs (PATCHY_LOGIN_SHAPE, --block, two-step) stripped, which is what #142 meant by “copy the shape, not the files.”

  • Seam. Login.ts as a module (one consumer: commands.ts) and pending login on the existing State service is the smallest correct split. Putting the poll/gate back into commands.ts would be the prototype mistake.
  • Agent gate. Env-list + TTY + --json is the specified heuristic, and the only one that works when agents have PTYs. Treating empty values as set is stricter than the prototype and is the right call for leftover harness vars. The list will rot as new agents appear; that is the spec’s cost.
  • Poll. Client loop is RFC 8628. slow_down +5 persisted onto the pending record is better than an in-memory bump. --wait 0 = one poll; remaining ≤ interval sleeps it off and reports pending without another poll — conservative, TestClock-honest. Human path passes null and lets the instance own expiry.
  • Save-before-me(). The completing poll is one-shot and does not carry company name. Persisting the token before the identity request is the correct storage order. The wrong report is the spec finding above: a failed me() should not look like login failed once the key is on disk.
  • Logout. Delete first, then revoke with the deleted token; 401 = success; unreachable = warning, exit 0. Reverse order would strand a dead stored key when the instance is down. No pending-revoke file; the warning points at Your machines.
  • Credential chain. Env → stored (login or auth-set) → seed. A login therefore outranks the worktree seed without a special case. PATCHY_API_TOKEN still wins; logout warns, login does not.

The --complete code is a boolean flag plus an optional positional, so patchy login --complete BCDF-GHJK (what next emits) works, and --complete=BCDF-GHJK does not. ADR writes [--complete [code]]. Agents follow next; this is a docs/help mismatch, not a broken handoff.


YAGNI

Mostly the right size. JSON shapes, --complete / --wait, next, agentNextSteps are ADR-0004, not creep. HostCredential as a two-arm union (so source: "login" requires machine) is types, not ceremony.

The one piece of machinery I would still question:

// packages/cli/src/index.ts
ConfigProvider.layer(ConfigProvider.fromEnv({ preserveEmptyStrings: true }))

The catalog of agent variables is specified. Presence is name in process.env. This provider changes every env read so empty CLAUDECODE= still counts, then Instance.optionalEnv filters "" back out. Keep the list; drop the global provider if a narrower read can test presence.

The gate truth table in Login.test.ts (~84 cells) only checks result === null, not the reason copy, and never runs login(). Three cases would pin it (TTY waits, --json doesn’t, empty CLAUDECODE doesn’t). Packed e2e past the four required scenarios (live confirm, PTY gate, handoff keys, logout restores seed) starts repeating cli.test.ts.

readHostKeyed(deviceLoginPath, "deviceCode", …) invents a “legacy” path for a file that never had a flat format. Reuse is still cheaper than a third persistence shape.


Summary

  • Standards: 2 findings (1 hard, 1 judgement). Worst: --help says “Sign in this machine,” which is the browser session in this glossary.
  • Spec: 4 findings (1 partial, 2 unasked, 2 look-wrong of which one overlaps the partial). Worst: a completed mint can exit 3 after the publishing key is already saved, so a retry starts a new machine.

The method is the one to keep. The two changes worth making before merge are the success path after me() fails (treat the save as the local act, like logout’s courtesy call) and reprinting the handoff — or documenting the poll-on-rerun shape in ADR-0004 if that is the intended agent contract.

@github-actions github-actions Bot added the area:server Touches the server area label Sep 5, 2026
@allisonmahmood

Copy link
Copy Markdown
Owner Author

Resolved both reviews on this PR; dispositions below.

Fixed

  • In-flight polls could exceed --wait (Astra P2): the remaining budget now covers the HTTP response and body decoding, not just sleeps. An unanswered request is exit 3 unreachable with an unknown outcome and the local login record retained; it is not misreported as server pending. A real pending answer followed by budget exhaustion remains exit 0. --wait 0 still waits for one real poll. Once a complete response is received, saving its one-time key is outside the polling timeout.
  • A saved login could fail on the subsequent /api/me request: removed that request. The mint transaction now returns the confirming user's email and company handle/name with the key, so the CLI prints the existing promised receipt after saving, without inventing identity details or adding a second network failure point. Wire schema, auth implementation/tests, CLI tests and generated API docs are updated together.
  • Help vocabulary: changed “Sign in this machine” to “Log this machine in”; browser sign-in remains a separate concept.
  • Terminal-error predicate (judgement finding): replaced "code" in error with the existing DeviceLoginGone schema predicate. All three protocol refusals still use the required exit-2 RejectedError contract.
  • Resume documentation ambiguity: README, ADR-0004, skill and development guidance explicitly distinguish a fresh handoff from a one-poll rerun. Documented the timeout distinction and refreshed the public skill hash.

Kept as is, with reasons

  • Poll-on-rerun and its pending/logged_in result, rather than a second handoff: intentional resume behavior from #131's prototype decision, referenced by feat(cli): patchy login and patchy logout #142. It consumes completed/terminal answers without orphaning or minting a new code. The original URL/code remains usable while pending; the explicit command is --complete. Chose the review's suggested ADR clarification instead of changing that behavior.
  • Saving an explicit --api-url: without it, a subsequent upload outside a worktree can resolve a different instance than the newly stored credential. This matches existing auth set behavior. The explicit flag remains in next because environment/worktree selection outranks saved config; ADR now states the reason.
  • Environment-presence ConfigProvider: keeps reads inside Effect's injectable configuration boundary rather than reaching into process.env from the login module. Empty agent markers must count as present. The other CLI environment consumers already filter empty values (instance URL/token and state directory), so their behavior stays unchanged.
  • Gate truth table: feat(cli): patchy login and patchy logout #142 explicitly requests it and names all ten markers. A three-case reduction would stop defending several required agent gates. Actual CLI invocation under a PTY is also covered by packed e2e.
  • Packed e2e beyond the minimum four examples: it exercises the installed artifact against the real auth server, including token replacement/revocation and seed restoration; stub-HTTP CLI tests cannot establish those server-side effects. No duplicate-only tests were added for this revision.
  • Shared host-keyed reader: reused the existing owner-only atomic persistence mechanism. Its unused flat-file compatibility branch is not a new login compatibility layer; splitting it would add another persistence path with no behavioral benefit.
  • --complete CODE parser shape: retained the explicitly emitted, tested command rather than adding another argument syntax. README and ADR now state that the code is space-separated; --complete=CODE is not supported.

Verification and merge readiness

Committed and pushed as 612021aafd28281c156a376382062184401c38cd (fix(cli): honor login deadlines and report saved keys).

  • Focused CLI/auth regression run: 70 passed across 4 files.
  • Full local run: 321 tests passed across 37 files; pnpm typecheck, pnpm lint, pnpm format:check, and pnpm test:packed-cli-e2e all passed, run serially.
  • Actual bundled CLI against isolated loopback endpoints: stalled headers and stalled body with --wait 1 returned exit 3 in 1.148 s / 1.142 s, with pending state retained. --wait 0 awaited one delayed answer and returned pending/exit 0; complete saved its key and printed the receipt with exactly one request, no /api/me, and no key in output.
  • TestClock coverage includes a delayed second poll using only the remaining budget and successful key persistence running past the deadline.
  • Actual login --help checked; public skill SHA-256 matches skills-lock.json (68c6dc1b…1602bc2).
  • Latest-commit GitHub CI is green: test (22), test (24), lint (including typecheck/format), cli-smoke, dependency-review, plus label.
  • GitHub reports no required checks configured for this target; all six reported checks pass. PR is MERGEABLE / CLEAN, still stacked on auth/141-device-login-server. Checkout is clean, and no newer review findings appeared after the push.

No unresolved blockers. Ready to merge into the specified stacked base; not merged.

@vsrikar08

Copy link
Copy Markdown
Collaborator

jgood to merge

@allisonmahmood
allisonmahmood force-pushed the auth/141-device-login-server branch from 802a884 to 5ee3700 Compare September 6, 2026 13:01
Base automatically changed from auth/141-device-login-server to main September 6, 2026 13:05
@allisonmahmood
allisonmahmood force-pushed the auth/142-cli-login-logout branch from 612021a to 7185d4f Compare September 6, 2026 13:06
@allisonmahmood
allisonmahmood merged commit 75b992a into main Sep 6, 2026
6 checks passed
@allisonmahmood
allisonmahmood deleted the auth/142-cli-login-logout branch September 6, 2026 13:09
allisonmahmood added a commit that referenced this pull request Sep 6, 2026
Offline auth tests cannot prove that real Clerk sessions verify through
JWKS or that Clerk accepts invitation delivery requests. This adds a
separate live tier while keeping `pnpm test` offline.

`pnpm test:clerk` loads the developer's keys, exercises `/company`
through real `RequireSession`, and creates, lists, revokes and re-sends
invitations. Fixtures are run-scoped and swept after testing, with an
additional `always()` sweep in CI. The job runs on same-repository PRs
except Dependabot and on `main`; missing secrets fail immediately.
Credentials stay out of the shared Vitest context.

Verification also exposed an embedded Postgres exit-hook bug that turned
failed suites into exit 0. A pinned dependency patch and regression test
preserve the failure status.

**Stacked on #157 (`auth/142-cli-login-logout`).** This PR targets that
branch and contains only the live-tier changes.

### Verification
- Local live tier: 2 tests passed; repeated cleanup confirmed zero run
users.
- Offline suite: 322 tests passed, fetch guard silent.
- Lint, typechecking, formatting and packed CLI e2e passed.
- Missing-secret failures and the workflow gate's
main/same-repo/fork/Dependabot cases checked locally.
- Standards and Spec reviews completed; the secret-handling finding was
fixed and rechecked.

Marking `clerk-live` required is a maintainer step. Branch protection
was not changed; the CI application's repository secrets already exist.

Closes #143.

Built with OpenAI GPT-6 Astra in the Oh My Pi harness.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:ci CI, shared testing infrastructure, development scripts and tooling area:cli Touches the cli area area:docs Touches the docs area area:server Touches the server area size:l 501-1,000 changed lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(cli): patchy login and patchy logout

2 participants