Skip to content

feat(cli): patchy on effect/unstable/cli with the agent contract - #89

Merged
allisonmahmood merged 3 commits into
mainfrom
feat/cli-effect
Aug 29, 2026
Merged

allisonmahmood merged 3 commits into
mainfrom
feat/cli-effect

Conversation

@allisonmahmood

Copy link
Copy Markdown
Owner

Problem

The CLI was commander with hand-rolled exit codes and its own fetch calls. Everything exited 1, so an agent could not tell its own mistake from the instance's refusal from a network that was down without parsing prose, and a worktree with a running pnpm dev still needed the environment set to publish to it.

Solution

patchy now runs on effect/unstable/cli over the client derived from @patchy/api, and promises the contract from #60 (recorded as ADR-0004):

  • Exit-code ladder. One CliError union, each tag carrying a kind (local | rejected | unreachable), one table to 1 / 2 / 3; 130 is Effect's interruption; a defect is one Unexpected error: line (stack at --log-level debug). Nothing else.
  • --json and --api-url are global flags. Success is one stdout document in the wire shape; failure is { ok: false, error, kind } on stderr with stdout empty.
  • One Instance service resolves the target: --api-url > .local/dev/env (walked up from cwd, with the token pnpm dev seeded) > PATCHY_API_URL > saved config > default. status --json reports the source and upload prints "target came from …". pnpm dev then patchy upload in the worktree publishes with nothing set.
  • Signals and the prompt. Effect's mapping; the hidden prompt is Prompt.password, so the terminal restore is a scope finalizer and the readline/raw-mode choreography and its PTY tests are gone.
  • Bundle and lint. esbuild carries Effect with the createRequire banner, commander leaves the lockfile, the language-service rules are errors for the package.
  • Tests. An in-process precedence test for Instance and a subprocess contract suite (ladder, streams, --json shapes, token never in output, fail-closed state files). The packed-CLI e2e now asserts the exact rungs and the --json documents; its signal probes stay as harness tests.

Deviations from the ticket, named: a parse error still prints usage on stdout before the one stderr line (Effect renders help inside Command.run); under --json the mint announcement is the one thing on stderr besides a failure, so the agent can still relay it; the 404-on-update hint keys on the wire's Patch not found. sentence because refusals reach the client as plain structs without a status; user-facing --draft / "Draft ID" copy is kept since the skill and e2e read it.

Stacked on #88 (feat/server-httpapi).

Closes #78

Built by Claude Fable 5 via Claude Code.

@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 Aug 29, 2026
@allisonmahmood

Copy link
Copy Markdown
Owner Author

Two-axis review of PR 89 vs merge-base feat/server-httpapi (551b732), plus the extra axes asked for: issue #78 intent, implementation method, and YAGNI.

Commits: 6dbff47 feat(cli), 6b04d43 docs(cli).


Standards

Skip: namespace imports, hoisted Schema.encodeSync/decode*, NodeRuntime.runMain only in index.ts, Git.ts as a module, nodeBuiltinImport with a reason, CLI tsconfig inheriting language-service error. Schema.TaggedError is the Effect 4 / repo API (TaggedErrorClass is not in the package). process.argv in index.ts is a justified entrypoint read (parse errors run before JsonFlag). ADR-0004 wins over splitting into many error classes: three tags plus kind stay.

Hard (documented)

packages/cli/src/Output.ts ~85 — .agents/skills/effect-service-conventions/SKILL.md, Errors and predicates: catch known tags with Effect.catchTags (or Effect.catch when the whole channel is CliError). Do not catchIf a schema predicate.

Effect.catchIf(isCliError, (error) => fail(error.message, error.kind)),

Fix: Effect.catch (handler is already Effect<A, CliError, R>).

packages/cli/src/CliError.ts ~18–36 — same skill: derive message from structured fields; do not store unstructured message as the only data. Ported services use override get message(). ADR-0004 still wants three tags and the pinned sentences; it does not require a message field. UnreachableError already has instanceUrl and still stores prose that repeats the URL.

const fields = { message: Schema.String, cause: Schema.optionalKey(Schema.Defect()) };

packages/cli/src/State.ts ~253–256 — same rule plus “catchIf only for structural predicates (e.g. platform codes)”. Recovery keys off error.message !== credentialErrors.legacy.

Effect.catchIf(
  (error) => error.message !== credentialErrors.legacy,
  () => Effect.succeed({ hosts: {} as Record<string, unknown> })

Fix: a structured reason (legacy | unreadable | invalid) on LocalError, or a distinct tagged error for the retired file; catchTags / match on that field.

packages/cli/src/commands.ts ~34 — skill Dependency acquisition: do not hide deps in module globals / imperative layer input. NodeRuntime.runMain is the entrypoint (index.ts), not here.

const local = Layer.provideMerge(Instance.layer(process.cwd()), State.layer);

Fix: resolve cwd from Path/FileSystem inside Instance.make (keep the cwd arg as the test seam).

packages/cli/src/Instance.ts ~49–50, 57–63, 79 — port shapes: Config with Redacted for secrets. PATCHY_API_TOKEN and Instance.token stay string until Redacted.make at the HTTP call. Auth redacts at the Config boundary.

Judgment (baseline smells)

  • Possible Primitive Obsession — token as string on Instance / HostCredential (same hunk as Redacted).
  • Possible Duplicated Code — configuredToken (commands.ts ~75–82) vs status’s env/dev-env/stored chain (~235–243).
  • Possible Feature Envy — mintFailure (commands.ts ~348–358) unpacks Api.classify errors and rewrites message.

Spec

Intent vs checklist. The three product intents mostly land: agents can branch 1/2/3; Instance walks .local/dev/env (seeded token) above PATCHY_API_URL, so a pnpm dev worktree publishes with nothing set; commander is gone from the tree and lockfile. HTTP is makeClient + NodeHttpClient. delete is omitted (#41 still open). Language-service CLI warning override is gone. Packed e2e asserts rungs 1/2/3, --json whoami documents, bare --version; 130/143 probes stay harness tests. Checklist is close; two behaviors break the agent-branching intent.

(a) Missing or partial

  • “mutating commands print ‘target came from …’” — only upload prints it (Output.notice). auth set does not. ADR-0004 / PR body already narrowed this to upload.
  • --json: “success … stderr empty … failure … stdout empty.” Named deviations, also in ADR-0004: parse errors still dump usage on stdout (Command.run ShowHelp); mint announcement is an extra stderr line via Output.announce. Packed e2e covers whoami --json, not upload --json (unit tests do).
  • “one-line stderr” — local validation / mint copy is still multi-line; e2e matches regex, not a single line.

(b) Scope creep

No new commands. Port carries existing product (--anonymous, --draft / “Draft ID”, mint, fail-closed state, git metadata). Extra vs spec is the mint-on-stderr --json path and process.argv.includes("--json") so parse failures can still emit the JSON document.

(c) Implemented but wrong

  • “SIGINT/SIGTERM → interrupt → 130.” promptForToken maps QuitError → LocalError (exit 1: “API token input ended…”). Effect Command.run already turns uncaught QuitError into interrupt; raw-mode Ctrl-C is typically that, not SIGINT. Cancel during Prompt.password is 1, not 130.
  • “HTTP status → kind: 4xx rejected, 5xx … unreachable.” Api.classify treats every isRefusal ("ok" in error) as RejectedError with no status. Declared 4xx {ok:false} bodies become rejected. Today @patchy/api only declares 4xx, so 5xx goes through status/DecodeError → unreachable (tested with 503 HTML). A 5xx {ok:false} body would be classified as rejected. The 404-on-update hint keys on Patch not found. for the same reason (named in the PR).

Method

Verdict: mostly right. The cut matches the contract (who acts → kind → exit), the ticket’s one Instance service, and the prototype gotchas. Failed instead of Effect’s CliError.UserError is the correct divergence: UserError is the 0/1/130 path. The rest is a faithful commander port (host-keyed state, argv --json peek), not new architecture.

  • Module cut — only Instance and State are services; Api/Git are modules; one commands.ts holds handlers. Right size. delete (feat(cli): patchy delete #41) still fits: another Command.make under run, no new service.
  • Output.contract — the ladder needs 2/3 and --json {ok,error,kind} while JsonFlag exists only in handler context, so render-then-Failed (errorExitCode / errorReported) is the honest seam.
  • argv --json peek — parse errors hit CliOutput.formatErrors before handlers. Justified; don’t thread the flag into the formatter.
  • Api.classify — HTTP→kind in one place; command copy stays in commands.ts. Per-command mapping would fork the ladder.
  • State.ts — same host-keyed verbatim merge and legacy fail-closed as the commander CLI. Don’t migrate here; that token is the only key to those pages.
  • Tests + prototype — Instance.test.ts (it.layer) for resolution; cli.test.ts subprocess vs the bundle; packed-cli-e2e for 1/2/3 on a real server. CliOutput.layer overrides and the createRequire banner are copied.

YAGNI / beauty

Mostly beautiful — services where there are two consumers, Git as a module, wire encodes at the top, extra machinery is almost all existing contract (tokens, --json streams, mint copy), not new generality.

Keep: State.ts fail-closed merge; mintFailure per-code next actions; Output.report / notice / warn / announce (they are the --json contract); --anonymous as no-op so old invocations still parse; five commands in one file.

Cut / simplify if you touch this again:

  • Git.ts Metadata is exported and unused outside the file — inline the shape.
  • File-header comments that restate ADR-0004 can shrink; keep the invariant notes (fail-closed, save-before-announce, --json streams).

Tests (contract coverage)

Pinned well: bare --version; parse error → 1 + --json {kind:"local"}; ladder 1 (script tag) / 2 (401) / 3 (503 HTML + nothing listening); token never in argv/output; mint announce on stderr under --json; fail-closed credentials; Instance precedence including empty env and .local/dev/env beating PATCHY_API_URL.

Gaps vs #78 / ADR-0004 (not a demand for more smoke tests):

  • No SIGINT on patchy itself proving 130 (harness probes 130/143 only). That matters because QuitError is currently mapped to exit 1.
  • Parse-error test never asserts stdout (usage vs empty under --json).
  • No Unexpected error: / --log-level debug stack case.
  • No packed-e2e “pnpm dev then patchy upload with nothing set” — Instance unit tests cover the walk, e2e does not.

Deleting the PTY/readline tests was correct. Prompt.password raw-mode is a scope finalizer; do not resurrect them.


Summary: Standards 5 hard + 3 judgement (worst: State.saveCredential branching on error.message). Spec 3 partial + 2 wrong, no material scope creep (worst: Ctrl-C during Prompt.password exits 1, not 130).

@allisonmahmood

allisonmahmood commented Aug 29, 2026 •

Copy link
Copy Markdown
Owner Author

Review triage — fixed in 26be75c on this branch (lint, typecheck, format, pnpm test 154/154 and the packed-CLI e2e all green):

Addressed

  • Output.contract: Effect.catchIf(isCliError) → Effect.catch (the channel is already CliError).
  • State.saveCredential: no longer branches on error.message; the retired flat file is refused by its shape (isRetired) and an unreadable/undecodable document is replaced, as documented.
  • process.cwd() module global gone: a Cwd service is provided at the entrypoint, Instance.make(cwd) keeps the test seam.
  • Tokens are Redacted from the boundary: Config.redacted for PATCHY_API_TOKEN, the dev-env token, and the stored credential are all Redacted until the bearer header; saveCredential takes a Redacted.
  • Duplicated chain: environmentToken (env → dev env) is shared by configuredToken and status.
  • Ctrl-C / EOF in Prompt.password now interrupts → exit 130, per the signal decision. Added a contract test that SIGINT on a running command exits 130.
  • Git.ts Metadata export inlined.

Dismissed, with reasons

  • 5xx {ok:false} body → rejected: the client only decodes bodies for statuses @patchy/api declares, and it declares 4xx only; a 5xx reaches classify as an HttpClientError with the response status and lands on unreachable (covered by the 503 test). If a 5xx body is ever declared, that is a wire change and the mapping is in one place.
  • mintFailure rewriting classify messages: the per-code next actions are command copy by design (ADR-0004 keeps HTTP→kind in Api.classify and the sentences with the command); the prefixing is the only thing left there.
  • "target came from" only on upload: auth set already names the instance in its success line; ADR-0004 records the narrowing.
  • Usage on stdout for a parse error / mint announcement on stderr under --json: both named deviations, recorded in ADR-0004.
  • Multi-line local/mint messages: caller-visible copy carried from the commander CLI; under --json it is one document either way.

Not adding an Unexpected error: test (nothing to trigger it deterministically from outside) or a pnpm dev e2e (the dev runner is already smoke-tested by its own ticket; the walk is unit-tested).

Ready to merge once #88 lands.

@allisonmahmood

Copy link
Copy Markdown
Owner Author

CI: lint, both test matrices, cli-smoke, dependency-review and label pass. The docker job fails on image is missing PATCHY_DB_FILE=/data/patchy-db.json — the server-image contract in scripts/verify-server-image.sh still expects the JSON driver removed by ADR-0003. It fails the same way on the base PR #88 and this branch does not touch the image; it belongs with the server PR.

The CLI was commander with hand-rolled exit codes and its own fetch calls,
so an agent could not tell its own mistake from the instance's refusal from
a network that was down.

It now runs on effect/unstable/cli over the client derived from @patchy/api.
One CliError union carries a kind (local, rejected, unreachable) and one
table maps it to exit 1, 2 or 3; 130 is Effect's interruption; a defect is
one 'Unexpected error:' line. --json and --api-url are global flags; a
failure under --json is { ok: false, error, kind } on stderr. One Instance
service resolves the target: --api-url, then the worktree's .local/dev/env
(with its seeded token), then PATCHY_API_URL, then the saved config, then
the default. The hidden prompt is Effect's, so the terminal restore is a
scope finalizer. The bundle carries Effect with the createRequire banner and
commander leaves the lockfile. The language-service rules are errors for
the package, and the packed-CLI e2e asserts the ladder and the --json shapes.
…ead it

The exit-code ladder, --json, the --api-url precedence with the dev env, and
the signal mapping as one ADR; README, skill, onboarding table and the
Publishing glossary updated to match.
Catch the whole CliError channel with Effect.catch; refuse the retired
credentials file by its shape instead of matching an error message; take
the working directory from the entrypoint as a Cwd service; carry tokens as
Redacted from the environment, the dev env and the store; share the
environment-token chain between whoami/upload and status; let Ctrl-C or EOF
in the hidden prompt interrupt (exit 130) instead of exit 1; drop the unused
Git metadata export; add the SIGINT-exits-130 contract test.
@allisonmahmood
allisonmahmood merged commit 7adc599 into main Aug 29, 2026
6 checks passed
@allisonmahmood
allisonmahmood deleted the feat/cli-effect branch August 29, 2026 23:27
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 size:l 501-1,000 changed lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(cli): patchy on effect/unstable/cli with the agent contract

1 participant