Skip to content

feat(patchy): publish patches directly from repos - #222

Merged
allisonmahmood merged 7 commits into
mainfrom
sdk/206-repo-publish
Sep 12, 2026
Merged

allisonmahmood merged 7 commits into
mainfrom
sdk/206-repo-publish

Conversation

@allisonmahmood

@allisonmahmood allisonmahmood commented Sep 11, 2026 •

Copy link
Copy Markdown
Owner

Patch repos can be initialized and refreshed, but cannot yet be published without switching to a standalone HTML file.

Add repo publishing for tiers 0 and 1, with release and declaration checks, typechecking, single-file bundling, and recoverable publication. Creates save the returned patch ID; share and delete use that repo identity. Update the CLI contracts and skills, and cover interrupted publication and bundle refusal paths.

Stacked on sdk/205-tier1-shell (#221). This PR targets that branch and contains the #206 changes, not the preceding stack.

Closes #206.

Verification

  • pnpm test: 672 tests passed across 70 files.
  • pnpm format:check, pnpm lint, and pnpm typecheck passed.
  • pnpm test:packed-cli-e2e passed against a real disposable server.
  • Real-server/browser smoke verified provisioning, additive updates, refusal paths, and starter saves through the broker.
  • Standards and spec reviews completed; all findings fixed and confirmed resolved.

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

Merge preparation: three multi-process CLI scenarios exceeded Vitest's five-second default on Node 22. Backported #223's existing 30-second budgets for the credential-precedence sequence and two repo-build scenarios. Assertions and product code are unchanged. All 113 CLI tests passed locally on Node 22 with two CPUs; all four focused cases passed with one CPU. Formatting and lint passed.

CI correction and merge preparation: GPT-6 in Codex.

@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 5cc33ed5 against origin/sdk/205-tier1-shell (7d8ba8f4), using #206 and its referenced §8. Single pass, no subagents; merge blockers only.

Standards

No independent merge-blocking standards or YAGNI findings. The method concern below has an observable spec failure, rather than being a style preference.

Spec

  1. Intent / method: the CSS dependency check both admits external assets and rejects ordinary text. repoBuild.ts:30–50

    feat(patchy): patchy publish from a repo #206 requires the single-file build to “fail loudly when anything is left outside the HTML.” A tier-1 repo containing background-image: image-set("https://example.invalid/missing.png" 1x) exits 0 and sends that external reference unchanged in the published HTML. The hosted CSP will block the image. Conversely, self-contained CSS body::before { content: "@import" } exits 1 as an external dependency. Scanning decoded CSS with regexes cannot distinguish syntax from string contents and misses valid resource-bearing syntax. Use syntax-aware CSS dependency inspection (including string-valued image-set candidates), rather than extending this regex policy. Keep refusal before attempt persistence/POST.

  2. Intent: recovery applies the result to an obsolete absolute repo path. commands.ts:408–424

    feat(patchy): patchy publish from a repo #206 requires that “the stored response carries the id the CLI writes to patchy.json” and that a lost create reply is recoverable from .patchy/publish/. After an interrupted create, rename/move the repo with its saved attempt and rerun publish: the CLI finds and resends the attempt, receives the successful create response, then exits 1 saying to run inside a patch repo. It tries to write through attempt.repo at the old path; the actual repo remains without patch, and its attempt cannot clear. Resolve local application and clearing against the repo containing the recovered attempt, passed from the current invocation; preserve the saved request/key unchanged.

Verification: exercised the source CLI with real TypeScript/Vite tools and a disposable local HTTP stub. A baseline repo published successfully; both CSS cases and moved-repo recovery reproduced as described. No live instance/database or full-suite run.

Summary: Standards: 0 blockers. Spec: 2 blockers; worst is stranded create recovery after moving the repo.

@allisonmahmood

Copy link
Copy Markdown
Owner Author

Sol review

Standards

  1. High — recovered updates do not re-apply the repo identity (packages/patchy/src/commands.ts:408-424). packages/patchy/CONTEXT.md says the original repo identity remains the recovery target, but Project.recordPublish runs only for creates. If patchy.json.patch is removed or changed while an update outcome is uncertain, replay updates the original patch and clears the attempt while leaving the repo unbound or bound to another patch; the next publish can create or update the wrong patch. Call recordPublish for every repo response; it already no-ops for the same ID and refuses a conflicting ID while retaining the attempt.

  2. Medium — repo-local attempts still require the unrelated global state dir (packages/patchy/src/State.ts:352-365). ADR-0004 puts repo attempts under .patchy/publish/, but lockPublish unconditionally creates State.dir first. With an environment publishing key and a writable repo, an unavailable PATCHY_STATE_DIR blocks publishing. Remove the first makeDirectory; recursively creating path.dirname(file) covers both file and repo modes.

  3. Low — use the repository's tagged-error convention (packages/patchy/src/repoBuild.ts:275-279). .agents/skills/effect-service-conventions/SKILL.md requires Effect.catchTags({ PlatformError: ... }) for known tagged failures and explicitly disallows catchTag. This is a mechanical replacement.

Spec

  1. High — create can persist an instance/patch pair that never existed (packages/patchy/src/Project.ts:111-140, packages/patchy/src/commands.ts:409-411). The spec says patchy.json records { instance, patch? } so a clone publishes the same patch. Repo target precedence permits --api-url, dev-env, or PATCHY_API_URL to override the stored instance, but recordPublish adds the returned ID while preserving the old instance. The next ordinary publish sends a foreign ID to the old instance. Record the resolved instance with the create result, or refuse a mismatched target before sending.

  2. Medium — stale release-bound generated output can publish (packages/patchy/src/executeConfig.ts:81-93,175-194). Issue feat(patchy): patchy publish from a repo #206 requires: “A stale generated directory is refused before the build.” index.json stamps release and manifestVersion, but the decoder ignores both; current package/runtime bytes beside an older committed generated set pass. A focused reproducer with release: "old-release" and manifestVersion: 0 was accepted and returned the current manifest. Decode and compare both stamps before accepting declaration metadata.

  3. Medium — the hand-written CSS scan rejects valid self-contained bundles (packages/patchy/src/repoBuild.ts:31-50). The requirement is to reject dependencies left outside the HTML. The regex also matches CSS strings: .note::before { content: "@import" } and content: "url(foo)" are not dependencies but are refused. Use a quote-aware CSS tokenizer/parser rather than adding policy through substring matching.

Verification

Additional verified defects:

  1. High — publishing follows a symlink when updating the generated manifest (packages/patchy/src/repoBuild.ts:201-215). writeFileString("patchy/_generated/manifest.json", ...) bypasses the existing safePath guard, so a symlinked managed file truncates its external target before typecheck/build. Resolve this write through the same no-symlink path guard as other managed-file writes.

  2. High — a moved repo cannot settle a recovered attempt (packages/patchy/src/State.ts:65-72, packages/patchy/src/commands.ts:409-424). The attempt persists the original absolute cwd. Because .patchy moves with the repo, replay is found at the new root, but create application reads the old path and update clearing looks under the old path. Store a repo-mode discriminator, not an absolute cwd; apply and clear against the current root that contained the attempt.

  3. Medium — tier-zero <noscript> dependencies bypass inspection (packages/patchy/src/repoBuild.ts:112-116). parse5.parse defaults scriptingEnabled to true, so nested tags are text; the tier-zero sandbox disables scripts, making that content active. <noscript><img src="https://example.test/leak.png"></noscript> passes this walk and loads externally. Parse tier-zero HTML with scriptingEnabled: false (or inspect both active trees). Chromium confirmed <noscript> content is active in sandbox="".

  4. Medium — HTTP 413 leaves repo publishing permanently replaying an unfixable attempt (packages/patchy/src/commands.ts:362-385). The definitive-refusal list covers selected 422/409/404 responses but omits the publish route's declared 413. A bundle within 10 MiB can still exceed the 3× JSON cap through an unbounded manifest; the attempt then survives and every retry resends it before rebuilding. Treat a proven first-send 413 as definitive, or make replay/body-cap handling preserve recovery while allowing a corrected request.

  5. High — stale response clearing is a read/check/remove race (packages/patchy/src/State.ts:449-461). The helper reads key K1 and later removes the path. Another sender can remove K1 and wx-create K2 between those operations; the stale K1 response then deletes K2, violating ADR-0004’s “A stale response cannot clear a newer attempt.” The algorithm predates this branch, but this PR newly puts repo attempts through it. Serialize create/check/delete with an inter-process lock or use a key-addressed atomic state model.

Focused verification passed: 13 repo-publish/config tests, 3 server interruption/replay tests, and the tier-specific body-cap test. skills-lock.json matches the SHA-256 of skills/patchy/SKILL.md. Separate focused reproducers confirmed the global-state coupling, stale generated-index acceptance, and stale-clear race.

Summary: Standards: 3 findings; worst is recovered updates losing repo identity. Spec: 3 findings; worst is persisting a foreign instance/patch pair. Verification added 5 concrete edge defects; the managed-file symlink write and recovery-state races are the highest risk.

@allisonmahmood

allisonmahmood commented Sep 11, 2026 •

Copy link
Copy Markdown
Owner Author

Addressed the Astra review and Opus review in e9e7564. Opus replaces Sol as the cross-family pass. This disposition supersedes the earlier instance-rebinding advice.

Opus disposition

  • Authoritative repo target — fixed. Repo commands read the stored instance before selecting an effective flag, dev-env or environment override. A different target returns local instance_mismatch, names both instances safely, and sends no HTTP request. Matching overrides retain existing source/token precedence. recordPublish checks the instance again before applying a result and writes only the patch id, preserving the stored instance spelling and author fields. A mismatch during recovery or during the request retains the attempt. File-mode and init targeting remain unchanged.
  • Tier-zero size classification — fixed. Tier 0 uses 512 KiB; tier 1 uses 10 MiB. Oversize bundles return local too_large with the largest contributors before static-HTML validation. The validator receives the same cap; the default tier-zero cap is shared with core and server configuration.
  • Anchor acceptance — fixed. Relative/in-app, external and fragment anchors accepted by core also publish at tier 1. Hyperlinks are navigation, not missing bundle resources. Runtime sandbox/navigation policy is unchanged.
  • CLI contract — fixed. ADR-0004, README and the public skill document all six local repo codes: instance_mismatch, release_mismatch, stale_generated, invalid_manifest, too_large and tier_mismatch. The definitive-refusal clearing list is complete. README again documents has_primitives, repo publishing as its remedy, and browser-only connection secrets. Target/recovery guidance, the glossary, dev-loop docs/skill and the public skill hash are updated.
  • HTML-policy boundary — kept separate intentionally, narrowed and covered by shared fixtures. Core validates safe static HTML for file mode and the API; repo inspection checks that a built artifact contains its resources, including tier-one browser code. Applying repo completeness to core would reject supported remote images in file mode; applying static safety to every repo would reject tier-one scripts. Removed unrelated tag/attribute and navigation restrictions from bundle inspection. It still inventories nested resources, requires embedded dependencies and inline scripts/styles, and refuses CSS imports. Core fixtures now exercise navigation in both repo tiers and demonstrate that a remote image is valid static HTML but an incomplete repo bundle. This is a build-artifact invariant, not another security policy.
  • Errno guard note — added. The state guard explains its dependency on Effect's wrapped Node errno and that unfamiliar wrappers fail closed.

Earlier fixes retained

Moved-repo replay uses the current root and the exact saved request/key; owner checks precede replay. CSS-tree handles escaped syntax and string-valued image candidates without rejecting harmless strings. Generated release/manifest stamps, safe managed-manifest paths, tier-zero noscript inspection, recovered-update binding checks, decoded definitive 413 handling, key-addressed atomic selection/clearing, repo/global-state independence and catchTags remain covered. The atomic state model needs no separate stale-lock recovery; unknown outcomes and authentication/admission refusals remain recoverable.

Evidence and merge readiness

  • pnpm test: 710 tests passed across 71 files, including real CLI/tsc/Vite regressions for all three target overrides, refresh before-network refusal, moved recovery and an in-flight binding edit, both tier caps, shared navigation fixtures and nested resource dependencies.
  • pnpm lint, pnpm format:check and pnpm typecheck: passed.
  • pnpm test:packed-cli-e2e: passed — offline install with an empty npm cache and the real-server CLI contract.
  • All seven checks passed on e9e7564: test (22), test (24), lint, clerk-live, cli-smoke, dependency-review and label. CI run.
  • GitHub reports no separately required checks and MERGEABLE / CLEAN. No newer review findings or inline review comments were outstanding when checked.
  • Affected surfaces: CLI contract, public/internal skills, dev-loop guidance, glossary and shared HTML fixtures. No wire contract, migration, package-layout or company-database behavior changed; server-side feat(patchy): patchy publish from a repo #206 behavior remains inherited from the stack base.

Unresolved blockers: none. Ready to merge into sdk/205-tier1-shell; not merged.

@allisonmahmood

Copy link
Copy Markdown
Owner Author

Opus review

Reviewed ebd5038 against origin/sdk/205-tier1-shell. I read the Astra and Sol reviews and the reply first: those fixes land as described (moved-repo recovery, CSS-tree inspection, generated stamps, safePath on the managed manifest, noscript, key-addressed slot, catchTags) and I am not re-raising them. The server-side half of #206 — replay-first, lazy company database, bytes before the platform transaction, the 60 s deadline, inventory-only company transaction, rollback under one row lock, the orphan sweep's age-plus-absence, the 3× body cap — is all present on the base branch, so this PR correctly adds only regression coverage there.

Everything below was reproduced by running the real CLI through this package's own test harness (a scratch copy of packages/patchy/src/cli.test.ts, deleted afterwards; real tsc, real Vite, stub instance), not by reading alone.

Standards

  1. The documented CLI contract no longer describes what repo publish emits. Repo mode introduces four local refusal codes — stale_generated (executeConfig.ts:103), invalid_manifest (repoBuild.ts:223), too_large (repoBuild.ts:307) and tier_mismatch (repoBuild.ts:325, :332) — but ADR-0004:57-60 still defines the envelope's code as "<wire refusal code>" plus "A release mismatch detected before publishing is local with code: release_mismatch", and packages/patchy/README.md:506 repeats it. tier_mismatch, invalid_manifest and too_large appear nowhere in either document. ADR-0004:346 tells agents that branching on refusal prose is the anti-pattern and that code is the machine-actionable field, so an agent cannot learn these codes exist. CLAUDE.md names this ADR as the thing to keep current when touching packages/cli. The prose at ADR-0004:219-223 and README.md:381-385 already describes these failures; it just needs to name the codes, and the code sentence in both files needs to stop claiming local failures only carry release_mismatch.

    Same file, smaller: ADR-0004:241-244's definitive-refusal list omits 422 release_mismatch/invalid_manifest/tier_mismatch, any 422 carrying errors, 409 publish_key_conflict, and the new 404-with-patchId clear at commands.ts:382-385 — the deleted-patch path the ADR itself introduces at :209-210. That the attempt is cleared there is exactly the fact an agent needs to not retry for recovery.

  2. The README rewrite deleted a live refusal rather than updating it. The removed paragraph (base packages/patchy/README.md:427) documented has_primitives: file publishing onto a patch with cumulative inventory, "which is not available in this CLI yet". Repo publishing now is available, so the trailing clause was stale — but the refusal is still live (packages/patches/src/Patches.ts:192, PatchesApi.ts:292) and still documented in ADR-0004:240 and skills/patchy/SKILL.md:200-202. has_primitives now appears nowhere in the README, along with the definitive-payload-refusal list and the "connection secrets only in the admin's browser" sentence that went with it. Reverse of the intended edit: keep the paragraph, drop the clause.

  3. (judgement call) A second HTML acceptance policy, with no fixtures. CLAUDE.md's surface list says "what HTML is accepted or rejected lands as fixtures under packages/core/fixtures, which the policy tests and pnpm seed:dev both read". inspectBundle (repoBuild.ts:33-160) is a second, independent acceptance policy living in the CLI with its assertions only in cli.test.ts, and the two policies now disagree on the same markup: an external <img src> is accepted by @patchy/core's policy (and by file-mode publish) and refused by repoBuild.ts:110-112; <a href> is accepted by core at every tier and refused by repoBuild.ts:115-124 at tier 1 only. Self-containment being stricter than the served-page policy is defensible, but it should be one policy with fixtures in the documented place, not two that drift.

Spec

  1. patchy.json's instance is neither honoured nor preserved — the repo's identity can be silently moved to another instance. feat(patchy): patchy publish from a repo #206 and README.md:372 both make patchy.json the repo's identity ("patchy.json supplies its instance and optional patch id"), and Sol's Spec 1 asked for "the resolved instance recorded with the create result, or refuse a mismatched target before sending". Only the first half landed. Instance.make ranks patchy.json fourth (Instance.ts:126-152: flag, dev-env, PATCHY_API_URL, then project), commands.ts:498-505 sends project.patch to whatever that resolved to, and Project.ts:129 then writes instance: apiUrl over the file. Reproduced, both halves:

    • Repo with patchy.json = {"instance":"https://production.example.invalid"} (no patch), PATCHY_API_URL pointing elsewhere: patchy publish --json exits 0 and rewrites patchy.json to {"instance":"http://127.0.0.1:34957","patch":"abcdefghijkl"}. Under --json the "target came from PATCHY_API_URL" notice is suppressed, so an agent gets no signal at all that the declared instance was overridden and then overwritten.
    • Same repo with patch already set: the foreign id is sent to the other instance (request body carries patchId: "abcdefghijkl"), the 404 comes back as exit 2 with "Patch is unavailable for update. Remove patch from patchy.json to create a new patch." (commands.ts:402) — advice that, if followed, destroys the original binding and creates a duplicate patch on the wrong instance.

    This is reachable in the ordinary dev loop, not a contrived setup: a worktree with .local/dev/env outbids patchy.json for every repo underneath it. The pin check stops the first attempt with release_mismatch → "run patchy refresh", and refresh rewrites the pin but not patchy.json (Project.ts:322-327), so the second attempt goes through. Smallest fix: when patchy.json names an instance and the resolved target differs, refuse before sending, naming both URLs; and never rewrite instance on a result — the only field a create has authority over is patch.

  2. Tier 1 refuses every hyperlink, including in-app ones; tier 0 accepts the same markup. repoBuild.ts:115-124 flags any <a>/<area> href that does not start with # when tier > 0. Reproduced on the starter tree: <a href="https://crm.example.com/leads"> and <a href="/reports"> both exit 1 with "The HTML bundle is not self-contained or uses unsupported external dependencies: - <a> href is unsupported"; <a href="#top"> publishes; and at tier 0 both of the refused links publish fine. feat(patchy): patchy publish from a repo #206 asks the build to "fail loudly when anything is left outside the HTML" — a hyperlink is not a resource left outside the HTML, and nothing in the ticket asks for a navigation policy, so this reads as scope creep that lands on the product's core case (an internal tool linking to the CRM it wraps). If the intent is that no link can navigate out of the sandbox (shell.ts:46 grants only allow-scripts allow-modals, and routing goes through route.set, broker.ts:448-452), then the same rule has to apply at tier 0, where the identical link is just as dead, and the message should say links cannot navigate inside a patch rather than blaming external dependencies. Either way the tiers must not disagree.

  3. A tier 0 bundle over 512 KiB fails as tier_mismatch with the wrong remedy. repoBuild.ts:298-307 applies one 10 MiB cap with the largest-contributor report, then repoBuild.ts:326-333 runs validateHtml(html) with no maxBytes, so the default 512 KiB from packages/core/src/html-policy.ts:39 decides tier 0. Reproduced with a 700 KB tier 0 page: exit 1, code: "tier_mismatch", "Tier 0 HTML failed the static-page policy. Browser code requires tier 1 in patchy.config.ts: - HTML document is 700087 bytes; maximum is 524288 bytes." The server calls the same function with the real cap (PatchesApi.ts:229) and answers a tier 0 oversize as InvalidHtml, never tier_mismatch. So an agent branching on code is told the tier is wrong when the size is wrong, and feat(patchy): patchy publish from a repo #206's "report the largest contributors" never fires at the tier where an inlined image most easily blows the cap. Pass the tier's cap into validateHtml, and let the size check own too_large at both tiers.

Method

The shape is right: recovery before any fresh work, one persisted attempt carrying the whole request, refusal before persistence, and a repo-mode discriminator rather than a path. The key-addressed slot (State.ts:352-410) is more machinery than the rest of the file, but it buys atomic "one active attempt" without stale-lock recovery, which is the better trade; the fragile part is the two Schema.is guards over errno shapes (State.ts:78-88) — isOccupiedDirectory reaches into reason.cause.code of a PlatformError, and it fails closed if Effect ever rewraps, so it is acceptable but worth a comment saying so. prepareRepoPublish is one long function, but it is a fixed pipeline with no branching to speak of, and splitting it would cost more than it saves.

Summary: Standards: 3 findings; worst is ADR-0004 and the README no longer describing the four local refusal codes repo publish emits. Spec: 3 findings; worst is patchy.json's instance being outranked, ignored on send, and overwritten on success, which silently moves a repo's identity to another instance.

@github-actions github-actions Bot added the area:core Touches the core area label Sep 11, 2026
Base automatically changed from sdk/205-tier1-shell to main September 12, 2026 12:22
Implement #206: ordered repo build and owner-bound persisted publish recovery, repo share/delete targets, and interruption coverage. Keep the existing server transaction and replay path.
@allisonmahmood
allisonmahmood merged commit d304f75 into main Sep 12, 2026
7 checks passed
@allisonmahmood
allisonmahmood deleted the sdk/206-repo-publish branch September 12, 2026 12:52
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:core Touches the core 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(patchy): patchy publish from a repo

1 participant