Skip to content

feat(sdk): initialize and refresh patch projects - #220

Merged
allisonmahmood merged 3 commits into
mainfrom
sdk/204-sdk-commands
Sep 12, 2026
Merged

allisonmahmood merged 3 commits into
mainfrom
sdk/204-sdk-commands

Conversation

@allisonmahmood

Copy link
Copy Markdown
Owner

Starting a patch repo still required manual setup, and refreshing its release could leave the installed CLI, generated clients and project skills out of sync.

Add authenticated init, refresh, catalog, add and remove commands, backed by instance-served generation and five canonical project skills. Refresh installs and re-executes the pinned release, then activates the managed files together or rolls back. Declaration edits preserve user code and fixtures; initialization preserves the caller's working directory.

Stacked on sdk/203-patchy-package (#219), which is this PR's base rather than main. Local patchy dev runtime execution remains in the next dev-runtime ticket.

Closes #204.

Validation:

  • pnpm lint and pnpm typecheck pass.
  • pnpm test: 70 files, 613 tests pass.
  • Real CLI smoke covers default init, generated-project typechecking, unusual connection handles, pin-only refresh and fixture preservation. Regression tests cover the caller directory and concurrent package edits.

Implemented with GPT-6 Astra in the Oh My Pi harness.

@github-actions github-actions Bot added area:server Touches the server area 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 11, 2026
@allisonmahmood

Copy link
Copy Markdown
Owner Author

Astra review

Reviewed 0c20d01 against origin/sdk/203-patchy-package (a4b5ad5), using #204 and its referenced §7 decisions. One pass, no subagents; merge blockers only.

Standards

No independent merge-blocking method or YAGNI findings.

Spec

P1 — Intent: failed refresh can erase author-owned edits

ManagedProject.ts:225–237, with the unconditional config snapshot at lines 85–91.

#204 limits managed writes to “the pin” and “the one uses edit for add and remove.” But begin() snapshots the entire patchy.config.ts even for plain refresh, and finish(false) deletes and restores every snapshot regardless of whether the transaction wrote it.

If an author saves a config change while generation is running and generation subsequently fails, rollback silently replaces that save with the earlier config. During a release upgrade, the same whole-file rollback of package.json erases unrelated package edits saved after the pin write.

Evidence: two isolated filesystem probes against the production ManagedProject implementation reproduced both losses: a newly saved config reverted to its original contents; a newly added package script disappeared while the old pin was restored. These exercised the transaction directly, not the full CLI.

Required fix: do not enroll config in plain-refresh rollback. Stage and conflict-check source edits, and restrict rollback of author-owned files to the pin/uses changes the command actually owns rather than restoring whole-file snapshots over later saves.

Summary: Standards: 0 blockers. Spec: 1 blocker; worst issue is silent loss of author-owned source/package edits on refresh failure.

@allisonmahmood allisonmahmood 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.

Code review — PR 220 vs #204

Two-axis review of a4b5ad5...0c20d01 (three-dot vs sdk/203-patchy-package), plus method and YAGNI as requested. Seven parallel reviews: Standards, Spec, Effect conventions, surfaces, tests vs Done-when, implementation method, YAGNI.

Intent vs #204

#204 asked for the SDK door: catalog + generate on the instance, five project skills served from packages/sdk, and init / refresh / catalog / add / remove that leave a typechecking tree whose managed files stay coherent with one release.

That intent landed. Server generates finished files; the CLI executes config, writes manifest.json, and activates a managed set. Core skills come from init; postgres/shared-table skills are sticky. remove is the reverse of add and leaves fixtures. patchy dev runtime is correctly left to #207.

The gaps are not a different product. They are: leftover CLI copy that still says refresh does not exist, init resolving instance as a repo command, thin automated coverage of the Done-when list, and error mapping that collapses busy into source_unavailable.


Standards

Hard

packages/patchy/src/commands.ts (init via runProject) — ADR-0004 instance order. init is wired with runProject → Instance.layer(cwd, true), so a cwd patchy.json outranks saved config. The ADR lists that extra link only for refresh, catalog, add, remove, and private generation: “init and file-oriented commands keep the order above.” patchy init ./other from inside an existing repo therefore targets that repo’s instance. Use run / Instance.layer(cwd).

packages/sdk/src/Generation.ts (make) — effect-service-conventions: catch known tags with Effect.catchTags; map failures where the context is known. connections.list / snapshot, patches.find / sharedTables / sharedTable, and skill reads all mapError into GenerationUnavailable (cause only). That folds Busy (PatchesApi → code: "busy") and SqlError into HTTP source_unavailable. Shared-table handling then uses Schema.is(PatchNotOpenable) in mapError to keep the converted tag — the catchIf-with-predicate shape the spec forbids. Catch PatchNotOpenable / Busy / company-database tags explicitly; die on SqlError; put stage/resource on remaining unavailability.

Generation as a Context.Service — “a capability with one consumer stays a module.” In-process consumer is SdkApi only (CLI talks HTTP). Unlike Artifact, nothing is cached at construction. Keep the file in packages/sdk; export catalog / generate as Effect.fn that yield* ConnectionStore / Patches / FileSystem, called from the handlers.

Judgement (smells)

Duplicated Code — Project.ts refresh vs init. Same installed-CLI spawn (__generate, --json, PATCHY_API_TOKEN), installedFailure, decodeChild, then ManagedProject.activate. Two copies of the re-exec contract.

Possible Divergent Change — Project.ts. Catalog text, pin AST, subprocess generate, add resolution, and init orchestration share one 665-line module. Repo YAGNI can keep it; it will change for unrelated repo-command reasons.

Possible Divergent Change — Generation.ts sharedClient / columnType vs generateClient.ts. Shared-table client strings live in the service; the owned-client template is a sibling module. Postgres already delegates to Postgres.postgres.generate.

No eslint-level import / in-body Schema.* compile / runPromise issues in the new Effect modules.


Spec

Quoted against #204 “What to build” / “Done when” and spec §7.

(a) Missing or partial

Done-when is implemented more than it is proven. Spec §7 lists --json for init/refresh/catalog/add/remove. packages/patchy/src/cli.test.ts was not in the diff and never runs those five commands (no-key Run: patchy login still only covers whoami/publish/delete/share). Shapes are assembled in Project.ts (Output.report) but not checked as a bundled CLI.

Init “pnpm typecheck passes with nothing added” is not exercised. Starter tsconfig.json + generated client exist (initProject.ts, generateClient.ts); the only init test is cwd preservation (initProject.test.ts). Add-on-spread “fails with the exact line” lives in editUses.ts with no test.

Otherwise the ticket’s tree, generation, catalog/generate routes, sticky skills, managed-write set, and surfaces (ADR-0004, docs/API.md, docs/product.md § Building a patch, docs/SKILL_DISTRIBUTION.md, global skill + matching skills-lock.json hash, vocabulary, README layout) are present. client.ts does import type config from "../../patchy.config.js" and import manifest from "./manifest.json". Skills are read from packages/sdk/skills/, not hand-copied.

(b) Not asked for

Nothing user-facing. Unlisted patchy __generate is the re-exec the spec required, not a new command. Catalog offered on ?all is spec §7 / §11.

(c) Implemented but wrong

Leftover copy. Spec surface: CLI README. packages/patchy/README.md:374 still says “patchy refresh is not implemented yet. This CLI currently publishes files only,” contradicting the new command table and ADR-0004 (“refresh is available now”). Command-flags list (README.md:451-459) also omits --tier, --purpose, --as, --all.

Catalog “openable” is company liveness, not per-member. Done-when: “a member who cannot open a source patch does not see its shared table.” Generation.catalog calls Patches.sharedTables(companyId) only. sharedSources drops deleted/disabled/expired same-company patches; there is no viewer filter. Matches today’s company-wide open rule, and SdkApi.test.ts only hides a disabled_at source. Connection filtering (all || entry.status === "connected") is correct; generate refuses connection_not_connected / patch_not_openable.

packages/patches/CONTEXT.md still calls a patch repo a “future working copy.”


Method

Verdict: sound-but-heavy.

Server-generates / CLI-writes is the right cut. executeConfig must run locally; snapshots, openability, skill bytes, and revision stamps are company-live. The honest split is the generated README line: manifest.json is written locally by the CLI, never by the server.

The refresh transaction is the smallest model that actually rolls back. Load-bearing: .patchy/refresh-lock, pre-images, isManagedOutputPath on both sides, fixture COPYFILE_EXCL, symlink refusal, and “rolling back a pin without its executable is not rollback” (node_modules rename). activateStarter hard links plus inode/mtime checks are load-bearing for init . (you cannot rename onto cwd).

__generate is the honest re-exec, and a trap. The parent already holds the lock and the old node_modules, so it cannot re-enter refresh. Unlisted command + stdout childSchema + stderr failureSchema + PATCHY_API_TOKEN is the IPC that cut forces. Trap: the old parent decodes the new child’s Generated and activates it — an unversioned compatibility surface. A second: the child writes patchy.config.ts with raw FS, not transaction.write, counting on begin()’s snapshot.

editUses is justified (exact line on spread; no import rewrite). editPackagePin is the same surgical idea applied where JSON.parse+stringify would have been enough. Routing add/remove through full pin-install-re-exec is one path, but a declaration edit can upgrade the world.


YAGNI

Verdict: Spec-required (re-exec, atomic refresh, AST line, symlink, cwd). Author extras are a nested init transaction, duplicated __generate, and a concurrent-author CAS §7 never named.

Init already stages under .patchy-init-* and rm -rfs it on failure, then opens a second ManagedProject only to write files and count diffs. write() is typed for "package.json" | "patchy.config.ts" but only called with package.json. The double-read CAS defends a race the spec does not mention; ManagedProject.test.ts is two tests of that invented invariant.

editUses, generateClient (~20-line template), catalog as filter+map, and packaged skill files are the small model. Project.ts at 665 is a command module padded by copy-paste, not a grab-bag — extract one runInstalledGenerate helper, not more files.


Tests vs Done-when

SdkApi.test.ts covers catalog/generate wire, disconnected filtering, disabled shared sources, refusals, sticky skills, and path validation. Focused, not slop.

Not in CI, only claimed as smoke: init typecheck; second init refuses; refresh pin+re-exec; mid-fail leaves _generated/ byte-identical; add AST insert; spread exact-line; remove leaves fixture. No editUses tests. cli.test.ts unchanged.

CLAUDE.md would want the five-command --json/exit ladder in cli.test.ts, the spread refusal, and ManagedProject.finish(false) restoring _generated/ bytes.


Standards: 3 hard, 3 judgement. Worst: init uses repo instance order; Generation collapses Busy into source_unavailable.
Spec: 3 findings. Worst: CLI README still says patchy refresh is not implemented.

@allisonmahmood

Copy link
Copy Markdown
Owner Author

Reviewed Grok’s review and Astra’s comment. Fixes are in 4576918.

Fixed

  • Astra P1: rollback erases author edits. Plain refresh never snapshots or writes the config. Add/remove execute staged source and activate the config last, only while its source still matches. Package rollback reverses only the command-written pin in the latest package text; later scripts, metadata, formatting, a changed pin, or malformed author text are not replaced by an old whole-file snapshot. Managed outputs are backed up only when the command is about to mutate them.
  • Init instance precedence. Init uses ordinary instance resolution, as ADR-0004 specifies. The bundled test starts inside another repo and proves saved configuration wins over its patchy.json.
  • Error mapping. Busy survives to HTTP 503/code busy. PatchNotOpenable and the company-database tags are handled explicitly; SQL and identity-mismatch failures remain defects. Lower-level unavailability retains its immediate cause and bounded stage/resource diagnostics without leaking provider details.
  • Single-consumer Generation service. Removed its tag, construction and layer, including server wiring. Catalog and generate are ordinary Effect.fn exports; the SDK HTTP boundary supplies their request dependencies.
  • Duplicated private re-exec. Init and refresh now share runInstalledGenerate, including spawn, token propagation and decoding.
  • Nested init transaction and extra CAS. Init writes directly into its staging tree. Removed the second ManagedProject transaction and recursive parent/mtime checks; retained exclusive creation and minimal inode ownership for safe cleanup without replacing the caller’s cwd.
  • Missing bundled CLI proof. cli.test.ts now exercises all five commands’ JSON success and local-failure contracts, representative API/transport exit codes, real pin/install/re-exec, add/remove and fixture retention, exact-line spread refusal, and concurrent author saves during refused refresh with unchanged _generated bytes. Init performs a real isolated pnpm install, then pnpm typecheck with no edits; repeated init is refused. ManagedProject tests also prove byte-for-byte rollback after activation has actually replaced generated files.
  • Stale surfaces. Removed “refresh is not implemented,” documented --tier/--purpose/--as/--all, and made the patch-repo glossary current rather than “future.”
  • Existing CI timeout. Split unrelated delete target-selection cases out of the long scenario and removed its duplicated no-key case. TypeScript editing machinery now initializes only on editing/pin paths, not every CLI command; no blanket test-timeout increase.

Kept as-is, with reasons

  • Company-wide catalog visibility. Current source access is company membership plus liveness; there is no additional per-member source ACL to enforce. Disabled/unopenable sources remain excluded/refused. Inventing a new permission model here would change the product.
  • Project command module and shared-table template. Kept these boundaries rather than splitting by line count. The duplicated re-exec was extracted; the pin editor is separate so its TypeScript dependency can load lazily. Owned-client assembly and discovered shared-table row generation have different inputs, so no speculative common generator was added.
  • Surgical pin edits and source conflict checks. These are now load-bearing for Astra’s author-edit invariant, not whole-file CAS for its own sake. JSON parse/stringify or restoring old config/package bytes would destroy unrelated author bytes. The old tests of whole-file CAS were replaced with observable rollback cases.
  • Private __generate and add/remove through refresh. Installed-release execution and one coherent release are required by §7. The IPC now has one implementation; no speculative cross-version protocol framework was added for future releases.

Verification

  • Local: pnpm typecheck, pnpm lint, and pnpm test — 649 tests passed across 70 files.
  • The CLI proof runs the bundled program against loopback SDK/registry fixtures; SDK route/error tests exercise the actual handlers and dependency implementations with alternate fault layers.

Surfaces: CLI README and patches glossary updated. Existing wire schemas, API docs, ADR-0004 and public skills already describe the intended contract and remain unchanged. No dev-runner, migration, new company-database caller, served-page or package-layout change. Add/remove reverse behavior is exercised.

Latest-commit CI: run 34553617501 completed successfully on 4576918326616b454b62d66d48eae734a5a423f2. All seven checks passed: test (22), test (24), lint, cli-smoke, clerk-live, dependency-review and label. GitHub reports no separately required checks for this stacked branch; every reported check was verified, not just that empty required subset. PR state is CLEAN / MERGEABLE, base sdk/203-patchy-package; no new review findings after the push. No merge performed.

Changes and verification: GPT-6 Astra via Oh My Pi.

@allisonmahmood
allisonmahmood merged commit 81bc04e into main Sep 12, 2026
7 of 14 checks passed
@allisonmahmood
allisonmahmood deleted the sdk/204-sdk-commands branch September 12, 2026 12:17
allisonmahmood added a commit that referenced this pull request Sep 12, 2026
Tier 1 patches need to run browser code without inheriting the reader's
login or gaining direct access to company resources.

This adds the sandboxed frame and document-bound broker, admits raw tier
1 bundles, and handles routes, files, session changes and stale
versions. It includes a1c3b77's reader-facing polish for the notices and
needs-rebuild door.

**Stacked on #220 (`sdk/204-sdk-commands`)**, which remains this PR's
base branch.

Review corrections in 741b990 expose the real client route/download
APIs, transfer upload buffers, preserve Auth door policies, force inert
shell downloads, retain public routing, serve UTF-8 content, share
runtime limits, and correct the README/SDK guidance.

**Approved framing policy, applied in 7d8ba8f:** Static and scripted
`/~content` responses use `frame-ancestors 'self'`, including content
error responses. Outer shells and first-party pages retain
`frame-ancestors 'none'`. Both Chromium and Firefox verify that normal
shell framing works, foreign parents cannot embed content, and shells
cannot themselves be embedded. The earlier policy decision is resolved.

### Verification
- `pnpm lint` and `pnpm typecheck` passed.
- `pnpm test --maxWorkers=1`: 661 tests passed across 70 files; no tests
skipped or timeouts changed.
- Chromium and Firefox: all 8 serial acceptance scenarios passed,
including real-client route/history/download calls, actual upload
detachment, ignored-download-hint containment, public routing for both
identities, Auth sign-out submission, Unicode rendering, outer-shell
anti-framing, and native 2,000-row printing.
- Auth uses isolated fake development sessions. Browser sign-out
submission is intercepted before contacting Clerk; offline Auth socket
tests cover the logout response.

Closes #205.

Implementation and PR prepared with GPT-6 Astra in Oh My Pi. Notice
polish by Claude Fable 5.1.

---------

Co-authored-by: Claude Fable 5.1 <[email protected]>
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(sdk): catalog, generate and project skills; patchy init, refresh, add and remove

1 participant