Skip to content

feat(dev): pnpm dev runs a per-worktree local instance an agent can keep alive - #81

Merged
allisonmahmood merged 2 commits into
mainfrom
feat/dev-runner
Aug 28, 2026
Merged

allisonmahmood merged 2 commits into
mainfrom
feat/dev-runner

Conversation

@allisonmahmood

Copy link
Copy Markdown
Owner

What changed

There was no local instance an agent could start, keep using across turns and tear down cleanly: pnpm dev was turbo run dev, tied to the shell that ran it, with no Postgres, no seed and no way to run two worktrees at once.

pnpm dev is now an Effect 4 runner (scripts/dev/, the port's first Effect code). It computes a plan for the current worktree — ports hashed from the worktree path, state in .local/dev/ — starts embedded Postgres, migrates, seeds one dev company with a working token, starts the server, writes .local/dev/env and returns once /healthz answers. The processes live in a detached supervisor that owns one Effect scope, so either service exiting (or stop) tears the other down. status, stop, logs, reset and --dry-run --json round it out; docs/DEVELOPMENT.md documents all of it.

One behaviour change outside the runner: the vitest Postgres template now carries the same seed (acct_dev / patchy-dev-token) instead of a bootstrap dev-token. Every Postgres test bootstraps dev-token itself, so nothing depended on the template row.

Closes #70

How it was verified

  • Plan tests (scripts/dev/src/plan.test.ts): hash → ports, upward scan, plan.json round-trip, worktree detection — no processes.

  • Manually: pnpm dev healthy in ~3s; second pnpm dev is a no-op; CLI whoami and upload against .local/dev/env succeed; two worktrees side by side, stop in one leaves the other healthy; stop leaves no stray processes; reset re-initdbs and re-seeds; kill -9 of the postmaster closes the whole instance.

  • pnpm lint, pnpm typecheck (language-service warnings promoted to errors for scripts/dev), pnpm format:check, full pnpm test (57 files, 1820 tests).

  • pnpm test passes locally

  • Added or updated tests covering this change

Release impact

Tick exactly one.

  • Breaking — requires action from anyone already running this
  • Not breaking — no action required

Local development tooling only; no change to the CLI's public behaviour, the API, the schema or configuration.


Written by Claude Fable 5 via Claude Code.

There was no local instance an agent could start, keep alive across turns
and tear down cleanly; `pnpm dev` was `turbo run dev`, tied to the shell.

`pnpm dev` is now an Effect 4 CLI in `scripts/dev` (the `@patchy/dev`
workspace package). It computes a per-worktree plan (ports from a hash of
the worktree path, state in `.local/dev/`), spawns a detached supervisor
under `node --import tsx`, and returns when `/healthz` answers. The
supervisor owns one scope: embedded Postgres via `acquireRelease`, the
server via `ChildProcessSpawner` with SIGTERM-then-SIGKILL, so either
exiting tears down the other. `status`, `stop`, `logs` and `reset` act only
on the pids `plan.json` records; `--dry-run --json` prints the plan with no
side effects. The seed (one dev company, one admin token) is a SQL fixture
shared with the vitest Postgres template.

Closes #70

Co-Authored-By: Claude Fable 5 <[email protected]>
@github-actions github-actions Bot added area:ci CI, shared testing infrastructure, development scripts and tooling area:docs Touches the docs area size:l 501-1,000 changed lines labels Aug 28, 2026
@allisonmahmood

Copy link
Copy Markdown
Owner Author

Code review — PR 81 vs #70

Two-axis review of 5ea2e67 against origin/main, plus the extra asks: #70's intent vs what landed, the method, and YAGNI.


Standards

No Context.Service modules (correct: one consumer stays a module). Errors are Schema.TaggedError with structured fields and derived message; cause is Schema.Defect() on wrap sites. Known tags use Effect.catchTags. NodeRuntime.runMain is only at the CLI entry. applyDevSeed is an explicit Promise seam for vitest globalSetup. Namespace imports from effect/* subpaths are in place.

Hard (documented)

Functions return Effect.gen instead of Effect.fn("name") — node_modules/effect/AGENTS.md (“Avoid creating functions that return an Effect.gen, use Effect.fn”).

  • scripts/dev/src/plan.ts computePlan (93–115)
  • scripts/dev/src/main.ts isRunning (90–96); command bodies dev (154–159), status (222–245), logs (271–278), reset (281–293)
  • scripts/dev/src/supervisor.ts inner write (65–69)

findWorktree, readPlan/writePlan/writeEnv, start, stopInstance, supervise already use Effect.fn. Const effects (worktree, currentPlan, recordedPlan, postgresGone) are fine.

HttpClient hidden at the leaf — .agents/skills/effect-service-conventions/SKILL.md: acquire from the environment; compose the resource once in the application layer.

const healthy = (plan: Plan) =>
  HttpClient.get(`${plan.apiUrl}/healthz`).pipe(
    Effect.map((response) => response.status === 200),
    Effect.orElseSucceed(() => false),
    Effect.provide(FetchHttpClient.layer)
  );

Provide FetchHttpClient.layer next to NodeServices.layer at runMain; do not provide inside healthy.

Tests re-provide Platform per case — same skill / AGENTS.md: @effect/vitest it.layer for a shared layer, it.effect per case. plan.test.ts pipes Effect.provide(Platform) on every it.effect. Use it.layer(Platform) for the computePlan / findWorktree blocks. The isFree callback is an allowed test strategy, not a mock.

Judgement (smells; not violations)

  • Duplicated Code — pid liveness: alive in main.ts (63–71) vs the same process.kill(pid, 0) loop in supervisor.ts postgresGone (210–217). Share one helper.
  • Duplicated Code — postgresFlags (fsync=off, …) in supervisor.ts (96–103) and test/postgres.ts (37–44). A small shared constant next to PG_USER would do; do not pull Effect into globalSetup.
  • Divergent Change — main.ts mixes CLI wiring, pid probes, health, and start/stop. Process facts could live with alive in one module.
  • Feature Envy — layout(plan, path: Path.Path) (state.ts 13–19) takes the Path service. A sync helper is reasonable; Effect.fn + yield* Path.Path would match env acquisition if you want it strict.

@patchy/dev as a workspace script package is not a premature capability package: nothing imports the package name; seed.ts already has a second consumer (test/postgres.ts). Hardcoded DEV_TOKEN / PG_PASSWORD are local fixtures, not missing Config/Redacted.


Spec

Against issue #70, quoted per finding.

(a) Missing or partial

“Env goes straight to each child.” Server spawn in supervisor.ts sets extendEnv: true with only PORT / PATCHY_DB_DRIVER / DATABASE_URL / PATCHY_STORAGE_DIR / PATCHY_PUBLIC_BASE_URL. Effect merges those onto process.env (default is replace). Inherited PATCHY_STORAGE_DRIVER, Azure, bootstrap token, etc. still reach the child.

“each service via effect/unstable/process spawn with killSignal: SIGTERM + forceKillAfter.” Postgres is only acquireRelease around embedded-postgres. Teardown is postgres.stop() with timeout("15 seconds") then ignore — no spawn, no SIGTERM, no force-kill. Only the server has forceKillAfter: "5 seconds". (The spec also says “Postgres via acquireRelease”; the spawn/force-kill clause is unmet for Postgres.)

“--dry-run --json prints the resolved Plan … with no side effects.” currentPlan still hits /healthz and can throw SupervisorBusy instead of printing. Tests cover hash→ports, worktree walk, and PlanJson round-trip, not the CLI flag.

(b) Scope creep

“--dry-run --json prints the resolved Plan.” --json is also on status (a StatusReport, not a Plan), reset, and a plain start (main.ts; documented in docs/DEVELOPMENT.md).

Env also writes DATABASE_URL. Spec only asked PATCHY_API_URL / PATCHY_API_TOKEN.

(c) Implemented but wrong

“compute plan → … → start the server → write .local/dev/env + plan.json → print the plan” and “poll /healthz.” start writes a pid-less plan.json before spawning the supervisor. The supervisor then writes env + pids after spawn and before /healthz. The parent prints only after health.

That early write also weakens “Start is idempotent”: SupervisorBusy only fires if plan.pids exists (main.ts 119–121). The cold-initdb window they budget at ~60s is unguarded — a second pnpm dev sees no supervisor pid, computes a new plan, and can spawn another supervisor onto the same datadir.

Comment “Its env is exactly the plan, nothing inherited wins” (supervisor.ts 163–164) contradicts extendEnv: true.

Met (called out)

Language-service warnings are errors in scripts/dev/tsconfig.json. applyDevSeed is the vitest globalSetup path in test/postgres.ts. node --import tsx, detached+unref, hash ports, .local/ gitignore, docs/DEVELOPMENT.md, packages/db adapter, Fastify only spawned.


Intent (#70)

#70's product problem: an agent needs a local Patchy Cloud it can start, keep using across turns, and tear down cleanly — also the port's first Effect 4 code, so later port PRs have something to smoke on.

That problem is solved. pnpm dev is no longer turbo. Start detaches and waits on /healthz; a second call reprints the plan; two worktrees get hashed ports and their own .local/dev/; stop keeps state; reset wipes and reseeds; the seed token lands in env. The CLI surface is agent-shaped (--help/--version only, one-line errors, supervise unlisted). Plan tests with no processes match “first tests are plan-computation.”

The last mile is still “point the CLI at .local/dev/env by hand.” That is exactly #70's Done-when, so it is not a miss against the ticket. It is a miss against the product line in AGENTS.md (“they shouldn't have to think about weird configuration”). README still teaches PATCHY_BOOTSTRAP_API_TOKEN=dev-token pnpm --filter @patchy/server dev against :3000. Agents that open the repo will take that path, not this runner, and the token is deliberately not dev-token. Worth a README pointer in a follow-up, not more runner machinery.

No watch is honest, not a gap: #70 did not ask for it.


Method

The spec demanded this method, and the method is the right one. One foreground process cannot outlive an agent turn. Docker Compose / turbo+wait-on fail the ticket (embedded Postgres, “Turbo is not on the dev path,” Effect-first harness). Daemonizing is the supervisor.

Plan / plan.json is the right seam: one Schema is dry-run output, the start→supervisor handoff, and what status/stop read. That is not too much machinery. The cheap lock is optional pids — written too late (see Spec). Recording the supervisor pid at spawn, before unref, would close the dual-start hole without a new abstraction.

Effect is used as the tool, not as architecture-for-show: CLI, Schema, acquireRelease, TaggedError, runMain → interrupt, it.effect. No Context.Service for a one-consumer script. tryPromise around PostgresPatchyDb is the approved unported seam. Sleep-loops and the postgres pid probe are YAGNI-shaped, not impressive.

Seed shared with vitest is spec-demanded coupling. Sharing the rows is good. test/postgres.ts importing plan.ts constants via a relative path into scripts/dev is the directional leak; the fixture itself is not.

ChildProcess detached defaults to true on non-Windows. The server spawn does not set detached: false, so an unclean supervisor death (kill -9) leaves the server as well as Postgres. stop reaps leftovers; start does not. Same family as the pid-less window.


YAGNI

The tight parts should stay: one Plan schema, computePlan pure aside from isFree, Promise seed because vitest globalSetup is not Effect, ports.ts is one bind, logs dumps the file, supervise is unlisted.

Do not flag the plan hash/scan, detached supervisor + /healthz, seed sharing, language-service errors, or the subcommands. Those are #70.

What is extra or ugly:

  • --json on status / reset and the StatusReport schema. feat(dev): Effect dev runner behind pnpm dev #70 asked --dry-run --json of the Plan. Harmless for agents; not required.
  • stage on PostgresError / DatabaseSetupError. Never switched on — it only builds message. Fine under the “one error + operation discriminator” clause; not a second abstraction that needs to exist.
  • Comment lies, then the env is wrong. extendEnv: true vs “nothing inherited wins.” Close the env (extendEnv: false + PATH, and pin PATCHY_BOOTSTRAP_API_TOKEN / PATCHY_STORAGE_DRIVER) or delete the sentence.
  • Tab-protocol log queue (service\tline then indexOf("\t")). Queue {service, line} — or enqueue the formatted line. The “one writer” claim is already false: postgres goes through the queue; say and the server stream call write directly.
  • supervise is 175 lines. Postgres acquire, migrate/seed, spawn server can be three helpers; the scope still wraps them. Optional.
  • @patchy/dev identity. Nobody imports the package name. Keep the folder (workspace member is how turbo typechecks it); the @patchy/ name is not earning its keep.

Standards: 3 documented findings, 4 smell judgement calls. Worst: healthy provides FetchHttpClient.layer at the leaf instead of at runMain.

Spec: 3 partial, 2 scope, 2 wrong. Worst: start is not actually idempotent for the whole window it waits on /healthz — pid-less plan.json plus SupervisorBusy gated on plan.pids.

Review fixes on #81. `start` records the supervisor pid the moment it is
spawned, so a second `pnpm dev` during initdb refuses instead of starting a
second supervisor on the same data dir; `--dry-run` reports the recorded plan
in that window rather than failing. The server's env is closed (plan + PATH
and HOME) instead of extending the shell's, which the old comment claimed and
the code did not do. `/healthz` probes are bounded so a server that accepts
the socket but never answers does not hang the runner. Failures are mapped to
`CliError.UserError` inside the handlers so `Command.run` prints one line
instead of `runMain` printing a stack. `HttpClient` is provided at `runMain`;
pid probes and the Postgres fixture constants live in one place each;
handlers use `Effect.fn`; the plan tests share one `it.layer`. README points
at `pnpm dev`.

Co-Authored-By: Claude Fable 5 <[email protected]>
@allisonmahmood

Copy link
Copy Markdown
Owner Author

Thanks for the review — went through every item against the source. What changed in 2nd commit, and what I left alone and why.

Fixed

  • Start is not idempotent during the initdb window (Spec c, worst) — real. start now writes pids: { supervisor } the moment the supervisor is spawned (before the /healthz wait); Pids.server/postgres are optionalKey and filled in by the supervisor. A second pnpm dev in that window gets SupervisorBusy and exit 1. Verified by SIGSTOPing the server and starting again.
  • --dry-run could hit SupervisorBusy — real. Dry run now reports the recorded plan when a supervisor is alive; it can no longer fail. It still reads /healthz to decide "running"; that is read-only, which is what "no side effects" means here.
  • "Env goes straight to each child" / comment vs extendEnv: true — real. The server now gets a closed env: the plan plus PATH and HOME (via Config, not process.env), extendEnv: false. Verified with PATCHY_STORAGE_DRIVER=azure-blob PATCHY_BOOTSTRAP_API_TOKEN=leak pnpm dev reset — neither reaches the server (/proc/<pid>/environ).
  • HttpClient provided at the leaf — moved FetchHttpClient.layer next to NodeServices.layer at runMain.
  • Effect.gen-returning functions → Effect.fn — computePlan, isRunning, currentPlan, the log writer, and every command handler.
  • Tests re-provide the platform per case — it.layer(Platform) for the computePlan and findWorktree blocks.
  • Duplicated pid liveness / Postgres flags / directional import — process.ts owns alive/signal; seed.ts is the fixture home (DEV_TOKEN, PG_USER, PG_PASSWORD, PG_FLAGS), so test/postgres.ts imports the fixture only and plan.ts reads from it, not the other way round.
  • Tab-protocol log queue — the queue carries { service, line }; the comment now says what is true (Effect code writes directly, only the library callbacks go through the queue; each line is one writeAll).
  • README still teaches the :3000 path — took the follow-up now: the quickstart is pnpm install && pnpm dev and sources .local/dev/env.
  • Found while verifying: /healthz had no timeout, so a server that accepts the socket but never answers hung pnpm dev. Bounded at 2s. And the UserError mapping sat after Command.run, so failures printed a stack; it now sits inside each handler and Command.run prints the one line.

Not changed

  • Postgres not via spawn + forceKillAfter. feat(dev): Effect dev runner behind pnpm dev #70 says "Postgres via acquireRelease" in the same sentence; embedded-postgres owns that process and there is no clean way to forceKillAfter its pg_ctl. The release is bounded (timeout("15 seconds")), and a dead postmaster closes the scope via the probe. If we want SIGTERM/SIGKILL semantics for Postgres we should drop the library and spawn postgres ourselves — a separate decision.
  • detached on the server spawn. Effect's default is true on non-Windows, and that is what makes killProcessGroup (kill(-pid)) work on teardown. Neither setting kills the child when the supervisor is SIGKILLed; that is what stop's reaping of recorded pids is for.
  • --json on status/reset, DATABASE_URL in env. Cheap, agent-facing, and the ticket's Done-when has an agent driving this from a shell. Happy to drop if you'd rather keep the surface to the letter.
  • stage on the two setup errors, supervise length, the @patchy/dev name. stage is the sanctioned one-error-plus-operation shape; splitting supervise into three helpers is a taste call I'd rather make when a second reader needs it; the package needs some name to be a workspace member and @patchy/ is what the others use.

Lint, typecheck (language-service rules as errors for scripts/dev), format, and the full suite (57 files / 1820 tests) pass locally; CI was green on the first commit.

Written by Claude Fable 5 via Claude Code.

@allisonmahmood
allisonmahmood merged commit 132a3d3 into main Aug 28, 2026
7 checks passed
@allisonmahmood
allisonmahmood deleted the feat/dev-runner branch August 28, 2026 22:55
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: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(dev): Effect dev runner behind pnpm dev

1 participant