Skip to content

feat(software-factory): factory up and factory run, one command each - #868

Merged
blove merged 28 commits into
mainfrom
blove/factory-up-run
Sep 30, 2026
Merged

blove merged 28 commits into
mainfrom
blove/factory-up-run

Conversation

@blove

@blove blove commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

The last item of the framework-gaps spec (§7). Plan: docs/superpowers/plans/2026-09-28-factory-up-and-run.md. It includes the plan, whose decisions D1-D25 Brian accepted.

The live replay of #714 is done (Task 12, D22). Work order wo-90261db33dd81830 went through both gates, with Brian deciding each, and exported. The spec's §7 as-landed note has the full record. The replay found two defects, fixed in this PR:

  • One Ctrl-C killed up mid-stop. The tsx CLI's signal relay SIGKILLed up, orphaning the workers. The factory script now runs node --import tsx, and the real-apps lane starts through pnpm factory up.
  • The controller stalled 13–26 s during every verification. The baseline capture re-verified the whole bundle once per file. It now verifies once; the longest block is about 170 ms. The framework half is perf(workspace): validate source-bundle base64 in one pass #878.

What it adds

pnpm factory up                          # from examples/software-factory
pnpm factory run --issue 714 [--pin <sha>]
  • factory.config.ts. The state directory plus controller, builder and drafter ports on loopback. It is validated strictly and fails closed on near-misses. The state directory may not sit inside any app root, and that check compares real paths on disk. Every factory command reads it; the environment wins, with a warning.
  • up.
    • Checks both locks, the built apps, ports, Docker and the drafter image (never pulls), then starts b4 start --host 127.0.0.1 for all three apps, detached.
    • Generates a worker token, or takes FACTORY_WORKER_TOKEN. The OpenAI key comes from the environment or .env (this checkout, then the main worktree; never the target repository). It goes to the builder and drafter only.
    • The controller's environment also drops *_API_KEY, OPENAI_*, ANTHROPIC_*, AWS_*, GH_TOKEN and GITHUB_TOKEN.
    • Waits for /readyz, then runs reconcile once, bounded.
    • Child output is prefixed and redacted, then copied to <state>/logs/.
    • One Ctrl-C (or SIGTERM or SIGHUP) stops the controller first, then the workers, each with a 20 s grace, then SIGKILLs any group still running. It reports each exit, and the stop is clean only if every app exits with code 0.
    • Two locks, on the state directory and the checkout, keep it to one up per checkout. A lock held by a killed up names its orphans.
  • run.
    • Creates or resumes the issue's work order and follows intake, image builds, dispatch and verification.
    • Stops at both gates. It shows exactly what factory review shows. It approves only when a person types the digest prefix at a terminal (stdin and stderr). Otherwise it exits 3 with the review command. Approval flags are refused by name.
    • A transitive source-pin test fails if run reaches any approving call. It was tested by planting violations.
    • Never retries or cancels. It follows an approval already in flight and stops, never prompting, on an expired bundle. Exit codes: 0 exported, 3 waiting on a person, 130 Ctrl-C (the work continues), 1 otherwise.

Review

The plan had an independent review before any code. That review caught, among other things, a Ctrl-C that would have killed apps mid-shutdown. Every task had a review, gates and secrets first, then the branch had a final review. The fixes are recorded in the plan's as-landed notes. Examples:

  • a lock left behind by a failed start;
  • a state-directory check a .. name or a symlink could bypass;
  • a stale lock steering a person toward denying a valid bundle;
  • a finally-block that would have reported a SIGKILLed app as a clean stop.

Verification (local, Node 24)

  • Unit tests: controller 1151 passed, server 27 passed, drafter 17 passed.
  • test:sandbox: 14 files passed and 1 skipped (opt-in); 33 tests passed and 5 skipped, in 310 s. The new real-apps up lane checks three things:
    • neither secret appears in the output, the logs or the lock;
    • every app exits with code 0;
    • it also works in a fresh checkout with no build output.
  • pnpm lint, pnpm check:build-cache, node scripts/check-docs.mjs and the factory typechecks pass.

Examples only, so there is no changeset.

🤖 Generated with Claude Code

blove and others added 22 commits September 29, 2026 22:34
…pec's last item

up starts the controller, builder and drafter on loopback with a generated
worker token, waits for readiness, reconciles and supervises; run carries an
issue's work order to each person's gate and stops there, never approving.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Children are detached and stopped by up alone, one SIGTERM each, since
b4 start dies by default action on a second signal mid-close. Adds test
isolation from the committed config, the approval window, a guarded
interactive seam, checkout and state locks taken over by rename, .env
resolution through the main worktree, pnpm --silent, and a bounded boot
reconcile.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…fig load fails closed

The state directory check compared path.relative strings and failed open:
`controller/..cache` (rel "..cache" starts with ".."), case variants on a
case-insensitive volume, and symlinks into an app root all passed. It is now
lexical (only ".." or "../" leaves) and physical: the nearest existing
ancestor is realpath'd and it and its ancestors are compared with each app
root by device and inode, which answers per volume for case and Unicode
normalization.

Also: the replaced-key table is read with Object.hasOwn; a default export
that is not a plain object is refused (a promise says to export the object
itself); an import failure names the file; the CLI usage documents
--config none and INIT_CWD; port bounds and all four owned-variable
conflicts are pinned; the plan records FACTORY_ARTIFACTS_DIR and
FACTORY_EXPORT_DIR as a follow-up.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… budget, guards its test seam

`review` splits into `reviewOutcome`, which returns sent/declined/refused without printing,
and a wrapper that prints it with the same exit codes, so `run` can fold a review into its
own single JSON document. An intake review now warns loudly when the work order's remaining
active budget is below twice its drafted target's verifier deadline, the rule dispatch
enforces, now extracted as `budgetShortfallFor` and shared with the factory. The
FACTORY_CLI_INTERACTIVE seam is honoured only under vitest and announces itself on stderr;
otherwise the prompt needs both stdin and stderr to be TTYs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… check failure

- interactive() compared FACTORY_CLI_INTERACTIVE's VITEST guard for truthiness,
  so VITEST=false (a falsy-looking string) would still enable the test seam;
  compare === "true", the exact value vitest sets.
- applyConfigDefaults warns when exactly one of FACTORY_CONTROLLER_URL /
  FACTORY_STATE_DIR is set in the environment and the other is filled from the
  config, naming both sources, since reads could then come from one registry
  while writes go to another controller.
- intakeBudgetWarning silently returned undefined when loadTaskRecipe threw;
  it now also prints "budget not checked: <reason>" to stderr, so an operator
  sees why no budget warning appeared instead of nothing.
- Removed a stray blank line splitting the `create --issue` USAGE paragraph.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…on's gate and stops there

`factory run --issue <n> | --task <id> | <workOrderId>` creates or resumes one work order,
runs intake and dispatch (following work it did not start through the journal), and at each
gate calls review's own reviewOutcome with no digest, no approval flag, no key and no note:
the display, and only at a terminal the person's typed prefix. It refuses --approve,
--reject, --digest, --note, --revision and --bundle by name (and --key and the other options
it would ignore); --yes/--auto-approve stay unknown options. Exit 0 only when exported, 3 when
waiting on a person, 130 on Ctrl-C, 1 otherwise. A bundle the window recorded by `up` says has
expired, or one refused as expired, stops with the deny and cancel commands and is never
prompted for again. A source pin (mutation-checked) holds runCommand to that one review call.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ocks

The first half of `factory up` (Task 7): a per-start worker token (or
FACTORY_WORKER_TOKEN, checked as the workers check it), OPENAI_API_KEY from
the environment or the one line of the checkout's or main worktree's .env
(never FACTORY_REPO_ROOT), each app's environment (key to the workers only,
URLs and state to the controller, HOST/PORT dropped), a preflight that
reports every problem at once (owned variables, B4_PERMISSIONS_MODE, key,
built CLI, ports, Docker, the drafter's base image, never pulled), and two
locks (state directory and checkout) taken by wx, a stale one taken over by
rename, a reused pid not a holder, orphaned children named and never
killed. Neither secret reaches a message, a log line or a lock file.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…al in flight, pins its reach

- The approval window comes from <state>/up.lock only while that up still runs
  (heldLockController, up's own held check); a stale lock's window is unknown.
- At the export gate, run asks the runtime whether the work order's thread is
  busy (GET /threads/<id>) and follows an approval re-verifying instead of
  prompting; when the runtime cannot answer and an approve_started is open since
  the bundle parked, it says an approval may be in flight rather than "nothing
  was approved".
- The source pin is transitive: every local name runCommand reaches must be on
  an explicit allow-list, and no reached helper may approve, deny, cancel or
  interrupt (reviewOutcome stays the one door, pinned by its arguments).
- A create racing another run on the same key (409 run_in_flight) waits and
  resends, landing on the same row; SIGINT is handled before the health check;
  Ctrl-C at a gate says the work order waits on a person; stray positionals are
  refused (run 714 -> use --issue 714).
- The interrupted-run test asserts Ctrl-C cancels nothing.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… sees no credentials, .env lines parse as dotenv's

Task 7 review fixes:
- Locks are created whole (temp file + link, never over an existing one); a
  stale lock is taken over only under a `<lock>.takeover` mutex (judged by pid
  and command like the lock when a crash left it), re-judged there, and
  replaced by renaming a whole record over it. A non-EEXIST failure on the
  checkout lock releases the state lock already taken.
- The controller's environment drops every *_API_KEY, OPENAI_*, ANTHROPIC_*,
  AWS_* and GH_TOKEN/GITHUB_TOKEN (a deny-list; D7's as-landed text says the
  workers still inherit the operator's other variables).
- The OPENAI_API_KEY .env line: an unquoted ` #` comment tail, matching single
  or double quotes, CRLF; a value with whitespace or a stray quote is refused
  without echoing it.
- up's own git and ps run without OPENAI_API_KEY and FACTORY_WORKER_TOKEN.
- Tests capture what preflight prints and assert neither secret appears; the
  mode-000 .env test is skipped as root; the plan's Task 10 .gitignore now
  reads `.up.lock*` for the lock's siblings.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ops the three apps

- Each app is spawned detached (its own process group) with stdin ignored; its
  lines go to stdout as `<app> │ <line>` and to <state>/logs/<app>.log, up's
  own lines also to <state>/logs/up.log.
- up waits for /readyz on all three (failing at once when one exits, with its
  last lines), then sends the reconcile route once, bounded at 120 s and
  abandoned on a stop.
- SIGINT, SIGTERM or SIGHUP stops: the stop line names the work orders in
  active states, then one SIGTERM to the controller, then to both workers,
  each with a 20 s grace before SIGKILL of its group; a second signal more
  than a second later SIGKILLs every group at once. Each exit is logged by
  code or signal; clean only when every child exited with code 0.
- A child that exits on its own stops the others and up exits 1.
- A closed stdout (`up | head`) switches output off instead of crashing, so a
  pipe cannot orphan the children.
- `factory up [--config <path>]` in the CLI; any other option refused.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… Ctrl-C

The Docker lane starts the real controller, builder and drafter under up
with a known worker token and a dummy key, checks readiness, the 403 to an
unauthenticated worker, the lock's settings and the CLI reading the same
config, then sends one SIGINT to up's group: every app exits with code 0,
never by signal, and neither secret appears in up's output, any log or the
lock. Confirmed from a fresh worktree with no .b4 under any app: b4 start
needs no build or typegen output.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…mes orphans before ports, redacts its children and kills a leader's leftovers

Review of Task 8: a child with no pid no longer records pid -1 or keeps the
locks (kill(-1, 0) succeeded); both locks are judged read-only before the
port check; child output is redacted before the tail, logs and stdout, and
logs/ is 0700; a group that outlives its leader is SIGKILLed and the stop is
not clean. Also: per-test free ports, a binding controller-first test, a
readiness-timeout test, a logs/ failure releases both locks, release removes
every lock even when one fails, .env refuses backticks and duplicate keys,
pipe read errors are warnings, and an empty tail prints no dangling colon.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…e ignored

An orchestration-only package.json (not a workspace member) whose factory
script is pnpm --silent --filter @b4-example/software-factory-controller
factory, and a local .npmrc (reporter=silent) so the outer pnpm run prints
no banner either: stdout is the CLI's JSON alone and exit 3 reaches the
shell. .gitignore covers the state directory, the checkout lock and its
.takeover/.new-*/.stale-* siblings, and factory.config.local.ts.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
README: a Quickstart before the manual runbook (renamed Run it by hand):
up's config, refusals, token and key handling, redacted logs, readiness,
the bounded reconcile, the ordered detached stop, the two locks; run's
resume, both gates (typed prefix at a TTY only, exit 3 otherwise, no
approval flag), exit codes 0/3/130/1, and why the quickstart sets
FACTORY_MAX_ACTIVE_MS and FACTORY_APPROVAL_TTL_MS. The CLI's config
defaults and FACTORY_CONFIG join the environment section.

Spec §7: the two glue rows updated, an as-landed note, the recorded
follow-ups, and the live #714 replay marked pending (Task 12).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…er scrub as it is

The by-hand runbook's controller and CLI now use examples/software-factory/.factory, the
directory factory.config.ts names, so skipping step 4's exports no longer reads a registry
that does not exist. The README and spec §7 state the controller's deny-list exactly and that
other variables still reach it; the README notes the .npmrc silences all pnpm output in the
example directory, how a relative --config resolves under pnpm --dir, and that the factory-up
lane takes the checkout lock. D18 as landed records the .npmrc.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…on form, factory.config.ts as an input

The approval source pin now checks the forbidden patterns against the whole of run-steps.ts
and its reach walk sees exported, class and var declarations. The controller-first stop test
gets 10 s of stop headroom. turbo declares factory.config.ts as an input of the controller's
test and typecheck.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@vercel

vercel Bot commented Sep 30, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

1 Skipped Deployment
Project Deployment Actions Updated
b4-run Ignored Ignored Preview Sep 30, 2026 9:40pm UTC

Request Review

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Automated approval: this PR received an intelligent (AI) code review. See the review comments on this PR.

… escape every regex metacharacter

CodeQL read the fake app's deliberate secret printing as clear-text
logging, and the source pin's regex escaped only $.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ish its ordered stop

Under `pnpm factory up` one Ctrl-C reaches up three times within milliseconds: the
group's SIGINT, the inner pnpm's relayed SIGINT, and a SIGTERM (pnpm turns the outer
pnpm's relayed second SIGINT into SIGTERM). pnpm never escalates, but the tsx CLI's
relay SIGKILLs a child that does not report each signal within about 30 ms (and its
concurrent relays share one waiter), so up, busy starting its stop, was killed after
the controller and the detached workers were orphaned. The controller's `factory`
script now runs `node --import tsx src/cli.ts`: the same loader, no relay layer.

A default-suite test runs the script's launcher over a busy stand-in with the signals
pnpm delivers; the real-apps lane now starts up through `pnpm factory up` itself and
asserts the checkout lock is released.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
blove and others added 3 commits September 30, 2026 13:37
…ce, not once per file

captureTargetBaseline decoded each captured file through readSourceFile, which
re-verifies the whole source bundle on every call: ~57 ms x 343 files for the
cli target, one 13-20 s synchronous block during intake's oracle proof, the
first verification and approve's re-verification, with /healthz unanswered.
Verify the bundle once and decode each verified entry directly; same digest,
same file text. test/baseline-event-loop.test.ts binds the verification count
and the longest block over a 400 x 6 KB capture. The plan records the stall
and the controller's remaining synchronous calls as a follow-up.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…e sh is dash

pnpm runs a script with `sh -c`. bash (macOS) execs a lone command; dash
(Debian, Ubuntu) forks it and dies of the terminal's SIGINT itself.

- factory-launcher: start the factory script's command without a shell, as
  bash's exec does, so every platform drives the harder case (all three of
  pnpm's signals reach the stand-in) and a dying shell can no longer end the
  wait before the stand-in writes its last event. The script must be plain
  words for that; the test asserts it. A tsx-CLI launcher still fails it on
  Linux.
- factory-up integration: wait for "close" (up holds the pipes until it
  exits) and accept only the outer pnpm's Ctrl-C conventions, code 0, code
  130 or SIGINT; up's own outcome stays asserted on what it printed, the
  lock and the processes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@blove
blove merged commit 0d70d89 into main Sep 30, 2026
30 of 31 checks passed
@blove
blove deleted the blove/factory-up-run branch September 30, 2026 23:09

This branch was successfully deployed

1 active (outdated) and 1 inactive deployments
vercel-preview — 8f35a0f9 Deployed Sep 30, 2026 by blove via vercel-native #2506
Preview — 0d727bad Deployed Sep 30, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants