mirror of
https://github.com/fabro-sh/fabro.git
synced 2026-12-03 00:47:18 +00:00
## Summary
Replaces the single `queued` pre-execution state with explicit `pending`
and `runnable` states, and wires approve/deny actions for
parent-generated child runs that require human approval before they can
execute. This diff covers the web UI and OpenAPI spec layers of that
change.
## What changed
**Run status model**
- `queued` is removed from all TypeScript types, display maps, column
routing, and tests.
- `pending` (awaiting approval) and `runnable` (eligible for the
scheduler) replace it as distinct board columns and `RunStatus` variants
with their own labels and colors (`runnable` gets cyan; `pending` stays
muted).
**Approval actions**
- New `approveRun` / `denyRun` API calls in `run-actions.ts` invoke the
new `POST /runs/{id}/approve` and `POST /runs/{id}/deny` endpoints.
- `canApprove` predicate requires both `status.kind === "pending"` and
`lifecycle.approval?.state === "pending"` — a run whose status is
pending but has no approval record does not expose the action.
- `useApproveRun` / `useDenyRun` mutations in `mutations.ts` follow the
same pattern as `useCancelRun`.
- `ActionsMenu` in `run-detail.tsx` gains Approve (lifecycle group) and
Deny (destructive group) menu items.
**Board and event plumbing**
- `columnForStatus` now routes `pending → pending column` and `runnable
→ runnable column`; `submitted` stays in the pending column.
- `BOARD_STATUS_EVENTS` and `RUN_SUMMARY_EVENTS` replace `run.queued`
with `run.start_requested`, `run.pending`, `run.approved`, `run.denied`,
and `run.runnable`.
- The `pending` column is hidden when empty (same behaviour the old
`queued` column had).
**Waterfall phases (`run-phases.ts`)**
- `queued` phase is removed; `pending` and `runnable` phases are added
in order.
- The submitted phase closes at `run.start_requested` rather than
`run.queued`.
- Each phase derives its timestamps from its own event rather than a
single `firstTs` lookup, making multi-phase pre-execution timelines
accurate.
**OpenAPI spec**
- `POST /api/v1/runs/{id}/approve` and `POST /api/v1/runs/{id}/deny`
endpoints added with 200/404/409 responses.
- `startRun` description updated to describe the pending/runnable
branching behaviour.
- `cancelRun` description updated to reference `pending`/`runnable`
instead of `queued`.
### Plan Summary
- **Task 3** (OpenAPI schema additions for approve/deny endpoints) —
complete in this diff.
- **Task 6** (Web UI surfaces: board columns, run-detail actions,
waterfall phases, event subscriptions) — complete in this diff.
- **Task 7** (doc cleanup: references to `queued` replaced in plans,
brainstorms, and QA docs) — complete in this diff.
### Fabro Details
<details>
<summary>Ran 9 stages in 127m 37s for $104.98</summary>
| Stage | Duration | Cost | Retries |
|---|---|---|---|
| start | 0s | – | 0 |
| toolchain | 2s | – | 0 |
| preflight_compile | 2m 15s | – | 0 |
| preflight_lint | 2m 29s | – | 0 |
| implement | 92m 10s | $91.53 | 0 |
| simplify_opus | 18m 35s | $10.65 | 0 |
| simplify_gpt | 7m 36s | $2.81 | 0 |
| verify | 3m 42s | – | 0 |
| fmt | 3s | – | 0 |
| **Total** | **127m 37s** | **$104.98** | **0** |
</details>
<details>
<summary>Ran <code>ImplementPlan.fabro</code> (12 nodes and 15
edges)</summary>
```dot
digraph ImplementPlan {
graph [
goal="Implement and simplify",
model_stylesheet="
* { model: claude-opus-4-7; }
"
]
rankdir=LR
start [shape=Mdiamond, label="Start"]
exit [shape=Msquare, label="Exit"]
toolchain [label="Toolchain", shape=parallelogram, script="command -v cargo >/dev/null || { curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y && sudo ln -sf $HOME/.cargo/bin/* /usr/local/bin/; }; cargo --version 2>&1", max_retries=0]
preflight_compile [label="Preflight Compile", shape=parallelogram, script="cargo check -q --workspace 2>&1", max_retries=0]
preflight_lint [label="Preflight Lint", shape=parallelogram, script="cargo +nightly-2026-04-14 clippy -q --workspace --all-targets -- -D warnings 2>&1", max_retries=0]
fix_lints [label="Fix Lints", prompt="The preflight lint step failed. Read the build output from context and fix all clippy lint warnings.", max_visits=3]
implement [label="Implement", prompt="Read the plan file referenced in the goal and implement every step. Make all the code changes described in the plan. Use red/green TDD.", model="gpt-55", reasoning_effort="xhigh"]
simplify_opus [label="Simplify (Opus)", prompt="@prompts/simplify.md"]
simplify_gpt [label="Simplify (GPT-55)", prompt="@prompts/simplify.md", model="gpt-55"]
verify [label="Verify", shape=parallelogram, script="cargo +nightly-2026-04-14 clippy -q --workspace --all-targets -- -D warnings 2>&1 && cargo nextest run --cargo-quiet --workspace --status-level fail 2>&1 && cargo dev docs refresh 2>&1 && cargo dev docs check 2>&1", goal_gate=true, retry_target="fixup"]
fixup [label="Fixup", prompt="The verify step failed. Read the build output from context and fix all clippy lint warnings, test failures, and generated docs errors.", max_visits=3]
fmt [label="Format", shape=parallelogram, script="cargo +nightly-2026-04-14 fmt --all 2>&1", max_retries=0]
start -> toolchain
toolchain -> preflight_compile [condition="outcome=succeeded"]
toolchain -> exit
preflight_compile -> preflight_lint [condition="outcome=succeeded"]
preflight_compile -> exit
preflight_lint -> implement [condition="outcome=succeeded"]
preflight_lint -> fix_lints
fix_lints -> preflight_lint
implement -> simplify_opus -> simplify_gpt -> verify
verify -> fmt [condition="outcome=succeeded"]
verify -> fixup
fixup -> verify
fmt -> exit
}
```
</details>
⚒️ Generated with [Fabro](https://fabro.sh)
---------
Co-authored-by: Fabro <noreply@fabro.sh>
Co-authored-by: fabro <fabro@anthropic.com>
Co-authored-by: Bryan Helmkamp <bryan@brynary.com>
14 KiB
14 KiB
Subprocess Run Workers And Signal Control
Summary
- Move workflow execution out of
fabro serverinto one hidden worker subprocess per run. - Use Unix signals for lifecycle control, but keep the server as the sole durable writer for run events, projections, and summaries.
- Stream canonical worker events back to the server over the worker stdout pipe so the event log, SSE, and API status stay coherent without multi-process append races.
Scope Boundaries
In scope:
- replace in-process run execution with supervised worker subprocesses
- repurpose hidden
fabro __runnerinto hiddenfabro __run-worker - use signals for
cancel,pause, andunpause - make the server the only writer to a run's durable event stream
- define a worker spawn contract, stdout/stderr contract, and control priority rules
- add request and effect events for run control
- phase delivery so subprocess cancel lands before pause and procline polish
Out of scope:
- non-Unix parity for worker supervision
- crash-time worker reattachment in the first delivery
- changing the current public control routes away from
/runs/{id}/cancel,/pause, and/unpause - changing terminal cancellation away from durable
status=failedwithstatus_reason=cancelled
Problem Frame
The intended architecture is server-supervised subprocess workers, not server-local async tasks. The current plan also assumed both server and worker could append to the same run event stream, but the current RunDatabase writer is process-local: sequence allocation, event cache, and watch fanout are held in per-process memory. That makes multi-process writes and cross-process watch_events_from() unsafe as a foundation for this refactor.
The revised plan therefore needs to solve four things explicitly:
- control delivery without shared in-process primitives
- durable event ordering without multi-process writers
- server observation of worker state transitions
- clear priority and override rules when multiple control requests arrive
Key Decisions
- Hidden worker command
- Rename hidden
fabro __runnerto hiddenfabro __run-worker. __run-workerexecutes a single run locally and does not call back into the server API.
- Rename hidden
- Single-writer rule
- The server is the only process that appends durable run events, updates run projections, and drives SSE.
- The worker must not open a write-capable
RunDatabase. - The worker may open the run store read-only for manifest and checkpoint reads only.
- Worker-to-server event path
- Worker stdout is reserved for newline-delimited canonical
RunEventJSON objects. - The worker builds canonical events once, using the existing event model, and writes them to stdout.
- The server reads stdout, validates each event, appends it to the run store, and fans it out to SSE and any in-process listeners.
- This replaces the current assumption that the worker writes directly to the run store.
- Worker stdout is reserved for newline-delimited canonical
- Worker stderr and logs
- Worker stderr is not part of the event stream.
- The server captures worker stderr, writes it to a per-run log file under the run scratch directory, and mirrors lines into server tracing with the run id attached.
- Worker spawn contract
- The server spawns
fabro __run-worker --run-id <id> --mode <start|resume> --storage-dir <dir>. - If the active config path is required to reproduce local runtime behavior, pass
--config <path>as well. - The worker does not need a server address because it does not talk HTTP to the server.
- The server spawns
- Control delivery
cancelsendsSIGTERMto the worker process.- After the grace timeout, the server sends
SIGKILLto the worker process group. pausesendsSIGUSR1.unpausesendsSIGUSR2.- Do not use
SIGSTOP/SIGCONTfor API pause and unpause.
- Control priority and conflict rules
- Priority is
cancel > pause > unpause. pending_controlremains a single value and later accepted requests overwrite lower-priority pending requests.cancelis accepted fromsubmitted,runnable,starting,running, orpaused.- A
cancelrequest overwrites a pendingpauseorunpause. pauseis accepted only when observed status isrunningandpending_controlisnull.unpauseis accepted only when observed status ispausedandpending_controlisnull.- A lower-priority request while a higher-priority request is pending returns
409. - If
pauseis pending andcancelarrives before the worker reaches a safe point, the worker must skiprun.pausedand terminate through the normal cancel path. - If the run is already paused and
cancelarrives, the worker must exit the pause wait and cancel immediately.
- Priority is
- Signal handling in the worker
SIGTERMrequests cooperative cancellation.SIGUSR1requests cooperative pause.SIGUSR2requests cooperative unpause.- Pause takes effect only at safe points such as between stages, before retry sleeps, before entering or resuming human waits, and at existing cancellation checkpoints.
- Event naming
- Use
run.cancel.requested,run.pause.requested, andrun.unpause.requestedfor accepted control requests. - Use
run.pausedandrun.unpausedfor observed worker transitions. - Keep terminal cancellation on
run.failedwithreason=cancelled. - Avoid
run.resumedbecauseresumealready means resume-from-checkpoint elsewhere in the system.
- Use
- Restart behavior in the first delivery
- Do not attempt PID-based worker reattachment in the first delivery.
- On graceful server shutdown, terminate active workers before exit.
- On server startup, any non-terminal run with stale worker metadata from a prior server process is marked interrupted or terminated and its worker metadata is cleared.
- Robust crash-time reattachment is deferred to a later phase and must include process identity verification before any signal delivery.
- API shape
- Keep the current control routes and verbs.
- Extend
RunStatusResponsewithstatus_reasonandpending_control. - Extend durable
StoreRunSummarywithpending_control. - Control endpoints return the current observed status plus
pending_control; they do not report the requested action as completed until the worker emits the corresponding effect event.
- Process titles
- Server titles:
fabro server bootfabro server unix:/path/to/socketfabro server tcp:127.0.0.1:3000fabro server stopping
- Worker titles use the existing 12-character short run-id convention:
fabro <short-id> startfabro <short-id> resumefabro <short-id> initfabro <short-id> runningfabro <short-id> waitingfabro <short-id> pausedfabro <short-id> cancellingfabro <short-id> succeededfabro <short-id> failedfabro <short-id> cancelled
- Server titles:
Delivery Plan
Phase 1: Subprocess execution and signal cancel
- Spawn one worker subprocess per started run.
- Make the server the sole event-store writer.
- Stream canonical worker events over stdout into the server.
- Route worker stderr into per-run log files and server tracing.
- Implement signal-based
cancelonly. - Do not support crash-time worker reattachment in this phase.
Phase 2: Control request events and API status enrichment
- Add
run.cancel.requestedandpending_control. - Extend
RunStatusResponseandStoreRunSummarywithstatus_reasonandpending_control. - Update status projections so accepted cancel requests surface immediately without pretending the run has already terminated.
Phase 3: Pause and unpause
- Add
SIGUSR1andSIGUSR2handling. - Add
run.pause.requested,run.unpause.requested,run.paused, andrun.unpaused. - Implement the priority and overwrite rules defined above.
Phase 4: Procline polish and optional crash-time recovery
- Add title helpers and short-id process titles.
- If crash-time worker recovery is still wanted, design it as a separate pass with explicit worker identity verification before any PID-based signaling.
Implementation Changes
1. Server supervision and worker pipes
- Replace the current
tokio::spawn(execute_run(...))path inlib/crates/fabro-server/src/server.rswith worker subprocess spawning. - Introduce a server-side supervisor record for live runs that stores:
- observed status
- created time
- local error text
- worker PID
- worker PGID
- worker mode (
startorresume) - current
pending_control - handles for worker stdout and stderr tasks
- On worker spawn:
- set process-group isolation
- capture stdout and stderr
- start one task that parses stdout into canonical
RunEvents and appends them to the run store - start one task that drains stderr into a per-run log file and tracing
- set observed status to
starting
- On worker exit:
- if the worker already produced a terminal run event, clear live worker metadata only
- if no terminal run event was appended, append a terminal failure with
reason=terminated
2. Workflow engine event sink refactor
- Refactor run execution so the worker path no longer depends on direct run-store writes from inside
fabro-workflow. - Introduce a run-event sink abstraction used by workflow execution, retro, pull-request creation, and any remaining bypass paths that currently append directly to the run store.
- For worker execution, the sink serializes canonical
RunEventJSON lines to stdout. - Preserve the current event-strategy rule that the canonical
RunEventis built exactly once and reused for all downstream sinks.
3. Worker execution and safe-point control
- Rewrite
lib/crates/fabro-cli/src/commands/run/runner.rsinto the__run-workerentrypoint that:- loads the run manifest and checkpoint state read-only from storage
- executes
operations::startoroperations::resume - owns the workflow
Emitter - translates OS signals into local cooperative control flags
- At safe points:
- if cancel is requested, terminate through the existing cancellation path
- if pause is requested and cancel is not pending, emit
run.paused, block until unpause or cancel, then emitrun.unpausedwhen execution continues
- Make cancel override a paused state immediately.
4. Event model and projection updates
- Extend
fabro-workflowevent types andfabro-typesEventBodywith:run.cancel.requestedrun.pause.requestedrun.unpause.requestedrun.pausedrun.unpaused
- Keep request events server-originated and effect events worker-originated.
- Update
lib/crates/fabro-store/src/run_state.rsso projections:- track
pending_control - do not let request events overwrite observed status
- apply
run.pausedandrun.unpausedto observed status - continue projecting terminal cancellation as
status=failedandstatus_reason=cancelled
- track
- Extend durable
RunSummarywithpending_control.
5. API and client updates
- Update
docs/api-reference/fabro-api.yamlwith:- a new
RunControlActionschema usingcancel,pause, andunpause pending_controlonRunStatusResponsestatus_reasononRunStatusResponsepending_controlonStoreRunSummary
- a new
- Define control endpoint behavior as:
- validate whether the action is currently allowed
- apply the priority and overwrite rules above
- append the corresponding request event
- update
pending_control - send the signal if a live worker exists
- return the current observed status response
- Regenerate both generated API clients after the OpenAPI change.
6. Process title cleanup
- Keep using
fabro_proc::title_init()andfabro_proc::title_set(). - Add helpers for server title updates by bind and lifecycle phase, and worker title updates by short run id and worker phase.
- Keep procline verification lightweight; do not build brittle exact-string end-to-end assertions around process titles.
Test Plan
- Single-writer and event-path tests
- worker execution path opens the run store read-only only
- worker stdout emits valid newline-delimited canonical
RunEventpayloads - server appends worker-streamed events in order and SSE reflects the appended stream
- worker stderr is captured into the per-run log file
- Cancel tests
- starting a runnable run spawns a worker subprocess and records PID and PGID
POST /runs/{id}/cancelappendsrun.cancel.requested, setspending_control=cancel, sendsSIGTERM, and later converges to durablefailedwithstatus_reason=cancelled- cancelling a submitted or runnable run reaches durable
failed/cancelledwithout spawning a worker - an unresponsive worker is escalated from worker
SIGTERMto process-groupSIGKILL
- Pause and unpause tests
POST /runs/{id}/pauseon a running worker appendsrun.pause.requested, setspending_control=pause, and later projectspausedPOST /runs/{id}/unpauseon a paused worker appendsrun.unpause.requested, setspending_control=unpause, and later projectsrunning- pause followed by cancel before a safe point never produces
run.paused - cancel while paused exits the pause wait and converges to durable
failed/cancelled - lower-priority actions while a higher-priority action is pending return
409and append no request event
- Startup behavior tests
- graceful server shutdown terminates active workers
- startup clears stale worker metadata and marks prior non-terminal runs interrupted or terminated
- Verification commands
cargo nextest run -p fabro-servercargo nextest run -p fabro-workflowcargo nextest run -p fabro-storecargo nextest run -p fabro-clicargo fmt --check --allcargo clippy --workspace -- -D warnings
Assumptions
- This refactor is Unix-first and may explicitly reject or defer non-Unix worker supervision behavior.
- The first delivery optimizes for correct subprocess supervision and durable event ordering, not crash-time worker survival across server restarts.
pauseandunpauseare cooperative safe-point transitions, not immediate OS-level stop and continue.- The short run id remains the first 12 characters of the ULID, matching current CLI presentation.