Skip to content

refactor(cli): remove duplicate refusal and repo-write handling - #283

Merged
allisonmahmood merged 3 commits into
mainfrom
portal/cleanup-cli-refusals
Sep 16, 2026
Merged

allisonmahmood merged 3 commits into
mainfrom
portal/cleanup-cli-refusals

Conversation

@allisonmahmood

@allisonmahmood allisonmahmood commented Sep 16, 2026 •

Copy link
Copy Markdown
Owner

The CLI converted wire refusals into seven separate error classes and then reconstructed the same fields for output. Repo writes and definition comparisons duplicated logic too.

Use one RejectedError carrying the decoded refusal, share the atomic patchy.json writer, and compare canonical definition defaults. CLI messages, JSON failure documents, kinds and exit codes remain unchanged. Direct output and the child-CLI relay share the documented field allowlist, and an existing lifecycle test now asserts the complete failure document. This diff is confined to packages/patchy.

Stacked on #282, with base branch portal/cleanup-portal-router.

Verification

  • pnpm lint and pnpm typecheck passed after the review fixes.
  • All 209 CLI, login and reminder tests passed after the review fixes.
  • Before the review followup, the full suite passed all 938 tests with two workers and pnpm test:packed-cli-e2e passed. The initial default-worker run hit two Postgres timeouts and an unexpected worker exit.
  • A temporary before/after probe confirmed 28 refusal documents and exit codes were byte-identical. A separate future-field probe failed before the allowlist fix and passed afterward.
  • See the review-disposition comment for the decisions and latest-commit CI results.

Implemented with openai-codex/gpt-6-astra in Oh My Pi.

@github-actions github-actions Bot added area:cli Touches the cli area size:m 100-500 changed lines labels Sep 16, 2026
@allisonmahmood

Copy link
Copy Markdown
Owner Author

Astra review

Reviewed 6233c290 against origin/portal/cleanup-portal-router at 4daed9fa, using the PR cleanup brief and ADR-0004. One pass, no subagents.

Standards

No merge-blocking method or YAGNI findings. The single refusal model, shared atomic writer, and canonical definition comparison match the requested simplification. No unrequested abstraction or future-facing machinery found.

Spec

No merge-blocking intent findings. The changed paths retain the CLI failure kinds, exit-code ladder, refusal details and repair messages. The shared writer preserves the existing repo identity checks and description stamps; definition comparison still treats omitted boolean defaults as false.

Verification: rebuilt the worktree CLI with node scripts/build-patchy-package.mjs --bundle-only. All 52 selected CLI contract tests passed, covering lifecycle refusals, discovery state hints, publish recovery, repo description writes and reminders. The 150 unselected CLI cases were skipped. All 7 tests in primitiveReminders.test.ts and Login.test.ts passed. Full-suite lint, typecheck and tests were not rerun.

Summary: Standards 0 blockers, worst issue none. Spec 0 blockers, worst issue none.

@allisonmahmood

Copy link
Copy Markdown
Owner Author

Opus review

Second reviewer, standing in for grok build. Fixed point origin/portal/cleanup-portal-router (4daed9fa), three-dot against 6233c290. One commit, 8 files, +172/−260, all under packages/patchy/src. Two axes in parallel sub-agents, plus my own verification of the checks the brief named.

Verification

Tests. git diff <base>...HEAD -- '*test*' is empty — no test file is touched. On this commit CI has test (22), test (24), lint, postgres-concurrency and clerk-live green; cli-smoke was still pending when I wrote this. packages/patchy typechecks clean locally (tsc -p ... --noEmit, exit 0), so @effect/language-service raises nothing. My own vitest --dir packages/patchy runs were not usable as evidence: the harness's globalSetup (test/postgres.ts:44) rebuilds the 13 MB CLI bundle that cli.test.ts:49 executes, and a subset run races it. The spec sub-agent hit the same race independently. CI's full pnpm test is the signal, and it passes.

Byte-identity of the --json failure documents. This is the one thing the tests do not cover — they assert with toMatchObject/toEqual on parsed JSON (cli.test.ts:2471, :3456), so key order is invisible to them, and swapping hand-written literals for Struct.omit(refusal, ["ok","error"]) (CliError.ts:101) is exactly where order could move. I probed it against the real schemas. Struct.omit builds its result from Reflect.ownKeys (effect/src/Struct.ts:1460), preserving source order; Effect's struct decode re-emits keys in schema declaration order regardless of input order. failure() (packages/api/src/schemas.ts:67) declares { ok, error, ...fields }, so every decoded refusal yields the old literal verbatim: {code,owner}, {code}, {code,purgeAt}, {code,dependants}, {code,sources}, {code,state}. The hand-built refusals at Login.ts:109, Project.ts:223/369/631/650, commands.ts:117/418/789 and Api.ts:159 either order ok, error first or carry a single detail key. Excess wire keys (status injected by the publish transport at Api.ts:79, errors, a relayed child CLI's kind/warnings) are stripped by the decode. Byte-identity holds, and Output.contract's { ok, error, kind, ...details, warnings? } (Output.ts:85) is untouched.

Spot checks from the brief. not_owner, has_dependants, wrong_state from discovery ("Patch is retired; pass --state retired.") and a generic 4xx with a code all reproduce their old text and details. ADR-0004:47–53 (the documented field list, "Discovery's wrong_state refusal includes the actual patch state", the owner/dependants/sources/purgeAt retention), ADR-0004:388–396 and packages/patchy/README.md:186–189 all still describe what the code emits. Nothing in the docs named the deleted classes, so no doc surface was owed an update.

The remaining checks. catchTags: Output.ts:104 was the only site naming a deleted tag and it is updated; no other catchTags/catchTag in packages/patchy or apps referenced them, and no dangling reference to the seven classes or the Rejected union survives anywhere in the tree. hint: written only at Api.ts:114 and Discovery.ts:39, read only at CliError.ts:97 — the other grep hits are unrelated wire fields. writeRepo (Project.ts:163) keeps makeTempFileScoped → writeFileString → rename under Effect.scoped, with the safePath resolve still outside the mapped error exactly as before, and both callers keep their exact messages; nothing references the retired .patchy-description-/.patchy-publish- prefixes. canonical (primitiveReminders.ts:17) treats omitted and false alike for both shared/optional and unique, and index columns stays an array compared by isDeepStrictEqual, so column order is still significant.

Standards

1. The collapse contradicts this repo's own review spec. .agents/skills/effect-service-conventions/SKILL.md is unusually direct here:

  • :57 — "Do not introduce a large switch or lookup table in an error's message getter to model failures that deserve separate error classes."
  • :54 — "Split semantically distinct failures into separate error classes when a reason, kind, phase, or similar discriminator is used to choose the user-facing message."
  • :53 — "Existing distinct caller-visible messages are evidence that the failures should normally remain distinct error tags … rather than being collapsed into a generic operation error."

CliError.ts:62–87 is a six-arm switch on code inside RejectedError's message getter, chosen over seven classes with distinct caller-visible messages. To be fair to the author: the brief commissioned precisely this, and :53's primary demand — preserve the messages — is met exactly. So this is not an execution defect; it is a conflict between the brief and a documented standard, and someone should decide it consciously rather than let it land by silence. The skill's scope line ("Apply them when a change creates, moves, refactors, or consumes an Effect service") makes applicability a judgement call, since this is an error module rather than a service — but the Errors and predicates section is plainly written for these constructs and names the CLI.

2. Struct.omit turns a checked mirror into an automatic one. refusalDetails (CliError.ts:101) now passes the decoded refusal through. If WrongState in packages/api gains a field, the --json failure document silently grows a key that ADR-0004:47 does not document, with no compile error — where the old literal would simply have kept emitting {code, state}. Removing a field is the mirror case: the old switch failed to compile, the new one silently drops it. Worse, the two mirrors now diverge: the relay path still hardcodes the field list in refusalFields (CliError.ts:40, consumed by Project.ts:80), so a new wire field would appear on the direct path and vanish on the child-CLI path. CLAUDE.md's "Hit every surface" makes packages/api the source and the rest mirrors; an automatic mirror is fine, but it needs the other mirror to be automatic too, or a test pinning the document. Judgement call, but the cheapest fix is real: assert one full document with toEqual including key order.

3. Discovery.ts:38 is the one site that stores an undecoded wire object in refusal. Every other construction either decodes (Api.ts:110) or writes a literal. isWrongState is Schema.is, a type guard that tolerates excess properties, so anything extra on that object flows straight into the failure document. Latent today — the HttpApi client decodes discovery errors and nothing injects status on that path — but it is the asymmetry that makes finding 2 exploitable. Judgement call; Api.fromRefusal-style decoding here would close it.

4. Two unrelated things named hint, and two named refusalMessage. Api.refusalMessage (Api.ts:98, wire text plus the errors list) and the module-private CliError.refusalMessage (:62, lifecycle prose) are different functions with the same name, and Project.ts:370 calls the first while the getter calls the second. Separately, RejectedError.hint means "message override", while commands.ts:108's doc comment uses "hint" for the host suffix appended to a message. Mysterious Name; judgement calls.

5. Small ones. Api.ts:110–114 sets refusal.error = message and hint = message on the None branch, where the generic union member's fallthrough (CliError.ts:86) would already return error — the hint there is redundant. CliError.ts:68 is the one arm with no "…" in value guard, so a reader cannot tell whether the guards are load-bearing (they are, for malformed bodies) or defensive. ok: false as const at Project.ts:650 is a wart from hoisting the literal. The diff also removes six private Schema.is constants from Api.ts, which the same skill asks for at :56 — credit where due.

Spec

Clean on all three items. The seven classes and the Rejected union are gone with no dangling reference; one message function keyed on code; details equal the refusal body minus ok/error, byte-identical as shown above; one writeRepo behind both callers with the atomic write intact; canonicalize-then-isDeepStrictEqual behaviourally equivalent — TableDefinition has only description|columns|indexes|shared and Manifest parses with onExcessProperty: "error", so no field escapes the old comparison that the new one now sees, and description is equal by the caller's guard at primitiveReminders.ts:72.

One item outside the brief: Project.ts:370 now attaches cause: error where the old construction dropped it. Invisible in output, arguably a fix, not asked for.

Is it a net simplification?

Yes, with one qualification. writeRepo and canonical are unambiguous wins — two near-identical 25-line blocks become one, and a 22-line hand-rolled structural comparison becomes a normalizer plus one library call, which is both shorter and easier to be sure about. The refusal collapse is a genuine reduction in concepts (seven error classes, a union, six Schema.is constants and an eight-arm refusalDetails switch become one class, one union and one switch) and it is the reason the diff is net −88 lines. What it trades away is compiler-checked exhaustiveness at the --json boundary: the old refusalDetails could not drift from the wire schemas without failing to build, and the new one can. That is a real cost on a documented agent contract, and it is not paid for by a test. I would take the change and buy the safety back with one toEqual on a full failure document.

Summary

Standards: 5 findings, none an execution defect — the worst is the documented conflict with effect-service-conventions :53/:54/:57, which is the brief's call to make, not the author's. Spec: 0 findings. I found nothing merge-blocking in the code itself.

@allisonmahmood

allisonmahmood commented Sep 16, 2026 •

Copy link
Copy Markdown
Owner Author

Addressed the review in 224cbfd.

Fixed

  • Opus 1: kept the single RejectedError and added the rationale above refusalMessage. This CLI adapter relays the wire's code; it is not a service modelling its own failures. Separate tags duplicated the @patchy/api refusal union.
  • Opus 2: direct output now encodes the same refusalFields allowlist used by the child-CLI relay, instead of forwarding every decoded wire field. New wire fields therefore cannot widen the ADR-0004 envelope on just one path. Strengthened the existing has_dependants lifecycle test to toEqual the complete failure document, including the exact error message, structured dependants and warnings.

Kept as is

  • Opus 3: no additional discovery decoder. Although Schema.is tolerates excess properties, constructing RejectedError already decodes its nested refusal and strips them. Confirmed with a source-level probe. The new output allowlist also prevents future decoded fields from escaping.
  • Opus 4: retained the module-local names and hint. Api.refusalMessage formats generic wire text and validation errors; CliError.refusalMessage selects lifecycle prose. Renaming them or the host-hint helper would not change behavior or address the contract risk.
  • Opus 5: retained the fallback hint; it is not redundant for a malformed { ok: false, code: "patch_retired" } without error. It preserves the generic fallback rather than selecting the retirement repair message. The payload guards remain necessary for generic refusals sharing recognized codes; patch_retired has no extra payload to guard. The hoisted ok: false as const keeps its literal type without another abstraction.
  • Retained cause: error in Project.refusal: preserving the original failure follows the error-translation convention and does not affect output. Astra reported no actionable findings.

Verification

  • pnpm lint and pnpm typecheck passed.
  • All 209 tests passed in cli.test.ts, Login.test.ts and primitiveReminders.test.ts with two workers.
  • A probe simulating a future decoded wire field failed before the fix and passed afterward. Separate probes confirmed discovery's existing excess-field stripping and the malformed-retirement fallback.
  • CI on 224cbfd passed: test (22), test (24), lint, postgres-concurrency, cli-smoke, clerk-live, and dependency-review. The separate label check also passed.
  • GitHub reports no checks configured as required for this stacked base; all eight reported checks are green. Head remains 224cbfdc77c0e1e5dc6b00cd04d2d85a019545fb, with MERGEABLE / CLEAN against portal/cleanup-portal-router. Rechecked conversation comments, the Reviews tab and inline comments after CI; no new findings or unresolved blockers. Ready to merge into the stated stacked base; not merged.
  • Follow-up d7a6274: documented the wire-refusal adapter exception beside the message-switch rule in .agents/skills/effect-service-conventions/SKILL.md; formatting and all eight latest-head checks passed.

@github-actions github-actions Bot added the area:docs Touches the docs area label Sep 16, 2026
@allisonmahmood
allisonmahmood force-pushed the portal/cleanup-portal-router branch from 4daed9f to ada4f7f Compare September 16, 2026 16:00
@allisonmahmood
allisonmahmood force-pushed the portal/cleanup-cli-refusals branch from d7a6274 to 15e38e4 Compare September 16, 2026 16:00
@allisonmahmood
allisonmahmood force-pushed the portal/cleanup-portal-router branch from ada4f7f to 82c40d5 Compare September 16, 2026 18:34
Base automatically changed from portal/cleanup-portal-router to main September 16, 2026 18:42
@allisonmahmood
allisonmahmood changed the base branch from portal/cleanup-portal-router to main September 16, 2026 18:42
@allisonmahmood
allisonmahmood force-pushed the portal/cleanup-cli-refusals branch from 15e38e4 to 4aca63a Compare September 16, 2026 18:43
@allisonmahmood
allisonmahmood merged commit 9ce778c into main Sep 16, 2026
8 checks passed
@allisonmahmood
allisonmahmood deleted the portal/cleanup-cli-refusals branch September 16, 2026 18:51
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:cli Touches the cli area area:docs Touches the docs area size:m 100-500 changed lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant