Skip to content
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
e3008b3
refactor: name the middle execution tier a side chain (FIX-766)
claude Aug 14, 2026
315b831
docs: converge the JSDoc and changeset restatements the codemod could…
claude Aug 14, 2026
80bc3af
docs(guard): record the two coverage gaps found during implementation…
claude Aug 14, 2026
d645912
test: name the continuation helper for what it does (FIX-766)
claude Aug 14, 2026
6f0b89f
docs(guard): reattach the E2 docblock and correct its position count …
claude Aug 14, 2026
bb38cb8
test(devtool): pin the side-chain badge's visible text, not just its …
claude Aug 14, 2026
6ed2ff0
fix(guard): deny a closed set of retired names, not the word "work" (…
claude Aug 15, 2026
51b2927
fix(guard): close the denylist gap the closed-set design introduced (…
claude Aug 15, 2026
4bb9d36
fix: dual-read the persisted report key, prefilter the guard, fix tie…
claude Aug 15, 2026
e7d2bfe
fix: scope the guard's member rules, dual-read the status count, fix …
claude Aug 15, 2026
141b9b3
fix(guard): map each path builder to its own op-argument index (FIX-766)
claude Aug 15, 2026
4430471
docs: drop the deleted `work` config and retire the word in tier-2 pr…
claude Aug 15, 2026
72adcba
docs(guard): move the over-reach note out of the known-gaps list (FIX…
claude Aug 15, 2026
fcfb90c
docs: retire the tier vocabulary in packages/*/src code comments (FIX…
claude Aug 15, 2026
d96d773
docs: retire the tier vocabulary in packages/*/test comments (FIX-766)
claude Aug 15, 2026
f69447b
fix(guard): a backtick literal is a string too (FIX-766)
claude Aug 15, 2026
354e6b6
fix(guard): anchor the segment regex and route every branch through e…
claude Aug 15, 2026
a18556e
fix(guard): close the last pattern-rule over-reach, found by audit (F…
claude Aug 15, 2026
b91c728
fix: reject the removed `work` key loudly, and make its legacy test a…
claude Aug 15, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .agents/skills/create-block/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -219,7 +219,7 @@ const agentNoTools = generator({

- **BP-011**: Handlers must NOT call `block.run()` inside `execute`. Compose with a sequencer instead: `.step(generator).step(handler)`.
- **Sequencer DSL methods** beyond `.step()`:
- `workIf(condition, block)` — conditional background work
- `sideChainIf(condition, block)` — conditional background work
- `stepAll(blocks)` — parallel execution, collect all results
- `stepAny(blocks)` — try each in order, first success wins
- `race(blocks)` — parallel execution, first to finish wins
Expand Down
4 changes: 2 additions & 2 deletions .agents/skills/create-pattern/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ Before writing, read at least two existing patterns in `packages/patterns/src/`:
| `routedSpecialists/index.ts` | Session resources, router dispatch, controller loop, specialist composition |
| `task-board/index.ts` | TaskCollection substrate, dispatcher + worker registry, concurrent drain, mid-run enqueue |
| `response-auditor/index.ts` | Simpler pattern: linear chain, tap for side effects, evaluation criteria |
| `supervisor/index.ts` | forEachBackground for concurrent work, resource-based coordination |
| `supervisor/index.ts` | forEachSideChain for concurrent work, resource-based coordination |
| `eventActors/index.ts` | Stigmergic multi-agent coordination, actor dispatch, event-driven drain |

Also read:
Expand Down Expand Up @@ -244,7 +244,7 @@ Beyond the basics (`.step()`, `.doUntil()`, `.tap()`, `.loopBack()`), the sequen

| Method | Behavior |
|--------|----------|
| `workIf(condition, block)` | Conditional background work dispatch. No-op when falsy. |
| `sideChainIf(condition, block)` | Conditional background work dispatch. No-op when falsy. |
| `stepAll(blocks)` | Parallel execution of multiple blocks with the same input. Collects all results (like `Promise.all`). |
| `stepAny(blocks)` | Sequential attempt through blocks in order. Returns the first success, skips the rest. Throws `AggregateError` if all fail. |
| `race(blocks)` | Parallel execution, returns the first success, aborts the rest. Throws `AggregateError` if all fail. |
Expand Down
4 changes: 2 additions & 2 deletions .agents/skills/debug-flow/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -205,7 +205,7 @@ Summarize for the user:
|------|---------|-------------|
| **handler** | Arbitrary logic | `execute(input, ctx) → output`. No model integration. |
| **generator** | AI/LLM integration | Multi-step model loop with tool execution. Resolves model via `ctx.resolveModel()`. Streams text via `content.delta`. |
| **sequencer** | Block composition | Chains blocks via `.step()`. Supports `.parallel()`, `.forEach()`, `.rescue()`, `.branch()`, `.doWhile()`, `.work()`. |
| **sequencer** | Block composition | Chains blocks via `.step()`. Supports `.parallel()`, `.forEach()`, `.rescue()`, `.branch()`, `.doWhile()`, `.sideChain()`. |
| **router** | Dynamic dispatch | `execute(input, ctx)` returns one of N `routes` blocks to run. |

### Sequencer DSL Quick Reference
Expand All @@ -218,7 +218,7 @@ Summarize for the user:
.forEach(block) — Iterate array input, run block per item
.rescue([{ when: [...], block }]) — Error recovery
.branch({ name: [cond, block] }) — Route by condition
.work(block) — Non-aborting side effect
.sideChain(block) — Non-aborting side effect
.tap(block) — Side effect (preserves throughput)
.map(fn) — Pure data transformation
.doWhile(cond, block) — Loop while condition true
Expand Down
2 changes: 1 addition & 1 deletion .agents/skills/improve-codebase-architecture/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ Then use the Agent tool with `subagent_type=Explore` to walk the codebase. Don't
| Thin connector handler whose `execute` is `return { x: input.y }` | `.step()` chain bloated with adapter blocks | Use a connector function: `.step((v) => ({ x: v.y }), block)` (BP-013) |
| Handler that calls another block inside `execute` | Hidden composition; defeats observability | Lift to a sequencer (`BP-011`) |
| Handler returning its input unchanged | Items log polluted with echoes | Replace with `.tap()` (BP-012, BP-014) |
| Wrapper sequencer just to gate a `.step()` on a condition | Indirection that obscures control flow | `.stepIf` / `.workIf` / `.tapIf` (BP-036) |
| Wrapper sequencer just to gate a `.step()` on a condition | Indirection that obscures control flow | `.stepIf` / `.sideChainIf` / `.tapIf` (BP-036) |
| Multiple blocks each plumbing the same tools/context/resources into a generator | Capability-shaped duplication | Extract a `defineCapability` and use `uses: [cap]` |
| Generator `outputSchema` with `z.record` / `z.optional` / heterogeneous `z.union` | OpenAI strict-mode incompatibility | Collapse to fixed shape + nullable (BP-016) |
| `useEffect` doing derived-state computation in React layer | Renders out of sync, brittle to deps | `useMemo` (BP-010) |
Expand Down
2 changes: 1 addition & 1 deletion .agents/skills/issue-implement/implementer-prompt.md
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ Correct order:
4. **Refactor while green.** After all tests pass, look for: shallow
handlers (BP-013 connector functions instead), handlers that just
return their input (BP-014, use `.tap()`), wrapper sequencers
gating a single step (BP-036, use `.stepIf` / `.workIf` / `.tapIf`),
gating a single step (BP-036, use `.stepIf` / `.sideChainIf` / `.tapIf`),
repeated tool / context / resource wiring (extract a capability).
Never refactor while red.
5. **Verify the goal — slice-level only; defer the end-to-end check to the orchestrator.**
Expand Down
2 changes: 1 addition & 1 deletion .agents/skills/prototype/LOGIC.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ The piece that's actually answering the question — the candidate block / patte
Pick whichever construct best fits the question:

- **A handler block** when the question is about a single transformation or side-effect.
- **A sequencer** when the question is about composition: how does state flow through `.step()` / `.parallel()` / `.forEach()` / `.rescue()` / `.workIf()` chains, what gets emitted at each step.
- **A sequencer** when the question is about composition: how does state flow through `.step()` / `.parallel()` / `.forEach()` / `.rescue()` / `.sideChainIf()` chains, what gets emitted at each step.
- **A generator** when the question involves model behaviour or tool invocation. Use `mockGenerator` (from `@flow-state-dev/testing`) to make the loop deterministic during prototyping; swap to a real provider only if the question is specifically about provider behaviour.
- **A capability** when the question is "what does the right `uses: [cap]` surface look like for this set of tools/context/resources?"
- **A pattern factory** when the question is "what's the right input shape for this reusable composition?"
Expand Down
2 changes: 1 addition & 1 deletion .agents/skills/tdd/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ After all tests pass, look for:
- [ ] Repeated tool / context / resource wiring → extract a capability (`defineCapability`)
- [ ] Shallow handlers whose `execute` is a single transform → fold into the sequencer via `.map()` or a connector
- [ ] Handlers that just return their input → replace with `.tap()` (BP-012, BP-014)
- [ ] Wrapper sequencers gating a single step → replace with `.stepIf` / `.workIf` / `.tapIf` (BP-036)
- [ ] Wrapper sequencers gating a single step → replace with `.stepIf` / `.sideChainIf` / `.tapIf` (BP-036)
- [ ] Generator output schemas with `z.optional` / `z.default` / `z.record` / heterogeneous `z.union` → collapse to fixed + nullable (BP-016)
- [ ] Shallow modules in the broader area → use `improve-codebase-architecture` for deepening
- [ ] Run tests after each refactor step. **Never refactor while red.** Get to green first.
Expand Down
4 changes: 2 additions & 2 deletions .agents/skills/write-block-tests/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -216,7 +216,7 @@ it("is composable inside sequencers", async () => {

#### E2. Sequencer DSL Method Tests

Test DSL methods like `exitIf()`, `stepAll()`, and `workIf()`:
Test DSL methods like `exitIf()`, `stepAll()`, and `sideChainIf()`:

```typescript
it("exits early when exitIf condition is met", async () => {
Expand All @@ -242,7 +242,7 @@ it("runs parallel branches with stepAll", async () => {

it("conditionally runs background work", async () => {
const chain = seq({ name: "conditional-bg", inputSchema: z.any() })
.workIf((input) => input.needsCleanup, cleanupBlock)
.sideChainIf((input) => input.needsCleanup, cleanupBlock)
.step(mainBlock);

const result = await testSequencer(chain, { input: { needsCleanup: false } });
Expand Down
4 changes: 2 additions & 2 deletions .changeset/cross-process-abort-delivery.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,11 @@

Cancelling a request now stops it even when it is running in another process (FIX-1026). `session.abortRequest()` and `POST /abort` previously recorded the cancellation durably but nothing read it while the run was alive, so a detached request on a worker ran to completion. The process running the work now checks for a recorded cancellation on the heartbeat tick it already performs and tears the run down through the same path a same-process abort uses. Delivery is bounded by the flow's `heartbeatIntervalMs` (default 10s) and requires a request store shared across processes.

A cancellation accepted while a request is finishing its background work now settles that request as `aborted` rather than `completed`. A request that queued `.work()` tasks waits for them before writing its terminal status, and a cancel arriving during that wait does stop them — but the request still reported `completed`, telling the caller the opposite of what happened to their work.
A cancellation accepted while a request is finishing its background work now settles that request as `aborted` rather than `completed`. A request that queued `.sideChain()` tasks waits for them before writing its terminal status, and a cancel arriving during that wait does stop them — but the request still reported `completed`, telling the caller the opposite of what happened to their work.

The completion hooks follow that status. `onCompleted` fires only on terminal success, so an action's `onCompleted` and the flow's `request.onCompleted` no longer run for a request cancelled in that window — previously they ran, and could commit business side effects or send a success notification for a request whose own `onFinished` reported `aborted`. If you relied on `onCompleted` to mean "the action body finished", move that work to `onFinished` and branch on its `status`, which fires exactly once for every outcome. Text-to-speech synthesis for such a request is now abandoned rather than run to completion and then discarded.

Work dispatched by those completion hooks is now waited for too. Because `onCompleted` runs after the background-work barrier, a hook that fans out its own `.work()` tasks was queueing them into a wait that had already finished — the request returned while a notification or state write was still going, and those items could miss the final flush.
Work dispatched by those completion hooks is now waited for too. Because `onCompleted` runs after the background-work barrier, a hook that fans out its own `.sideChain()` tasks was queueing them into a wait that had already finished — the request returned while a notification or state write was still going, and those items could miss the final flush.

A cancellation recorded before a run starts now stops it regardless of how fast the request store answers. The check that catches a job cancelled while it was still queued happens before the action runs rather than alongside it, so an action shorter than one store read can no longer finish first and report `completed`. This costs one narrow store read on the request start path; a store failure there is logged and the request proceeds.

Expand Down
4 changes: 3 additions & 1 deletion .changeset/fix-663-work-signal-decoupling.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,6 @@
"@flow-state-dev/engine": minor
---

Decouple `.work()` background task lifetime from the request's transport-level abort signal. Background generators now survive transport teardown (client disconnect, SSE close, tab refresh) and abort only when the request is explicitly cancelled via the `/abort` endpoint or `session.abortRequest()`. This fixes background generators in Event Actors flows failing simultaneously with `"Invalid error response format: Gateway request failed: This operation was aborted"`. The same substitution applies to `.workIf()` and `.forEachBackground()` — their per-iteration abort check now breaks only on explicit cancellation. The AI Gateway abort error is also unwrapped (the original error is preserved as `cause`) so background failures surface a legible message instead of doubly-wrapped gateway noise. New `rootCause(err)` and `isAbortLike(err)` helpers are exported from `@flow-state-dev/core`. Flows that relied on client disconnect stopping background work should set a per-block timeout instead.
Decouple `.sideChain()` background task lifetime from the request's transport-level abort signal. Background generators now survive transport teardown (client disconnect, SSE close, tab refresh) and abort only when the request is explicitly cancelled via the `/abort` endpoint or `session.abortRequest()`. This fixes background generators in Event Actors flows failing simultaneously with `"Invalid error response format: Gateway request failed: This operation was aborted"`. The same substitution applies to `.sideChainIf()` and `.forEachSideChain()` — their per-iteration abort check now breaks only on explicit cancellation. The AI Gateway abort error is also unwrapped (the original error is preserved as `cause`) so background failures surface a legible message instead of doubly-wrapped gateway noise. New `rootCause(err)` and `isAbortLike(err)` helpers are exported from `@flow-state-dev/core`. Flows that relied on client disconnect stopping background work should set a per-block timeout instead.

(FIX-663)
4 changes: 3 additions & 1 deletion .changeset/fix-751-reactive-blocks.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
"@flow-state-dev/engine": patch
---

Add `reactTo` to `defineResource` and `defineResourceCollection` so a block runs automatically when a resource is created, has its state updated, or is deleted (bindings keyed `created`, `stateUpdated`, `deleted`). Each binding is a block or `{ block, when }`; the block runs blocking inside the originating turn with a `ResourceChange` payload (`key`, `ref`, `kind`, `state`, `prevState`, `evicted`) and can emit items, call models, and appear in traces. Type its input with the exported `resourceChangeSchema(stateSchema)`. For background, isolated fan-out, make the reactive block a sequencer that uses `.work()`. A `when` gate filters dispatch, and a reaction that throws fails the mutating turn.
Add `reactTo` to `defineResource` and `defineResourceCollection` so a block runs automatically when a resource is created, has its state updated, or is deleted (bindings keyed `created`, `stateUpdated`, `deleted`). Each binding is a block or `{ block, when }`; the block runs blocking inside the originating turn with a `ResourceChange` payload (`key`, `ref`, `kind`, `state`, `prevState`, `evicted`) and can emit items, call models, and appear in traces. Type its input with the exported `resourceChangeSchema(stateSchema)`. For background, isolated fan-out, make the reactive block a sequencer that uses `.sideChain()`. A `when` gate filters dispatch, and a reaction that throws fails the mutating turn.

The server dispatches these reactions in the same session and turn, ordering emitted items within the turn. A per-turn depth and fan-out budget guards against runaway cascades, emitting a `reactive_cascade_exceeded` error item instead of hanging when a reaction chain feeds back on itself.

(FIX-751)
2 changes: 1 addition & 1 deletion .changeset/fix-866-background-work-recovery.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
---
---

Internal (FIX-866): verify-and-harden regression coverage for crash-recovery of attached durable background work (`.work()` / `.forEachBackground()`) — mid-drain partial fan-out, failed-task-under-completed-parent, and cross-store (SQLite + Postgres) completed-trace replay — plus documentation of the contracts. No runtime or public API changes.
Internal (FIX-866): verify-and-harden regression coverage for crash-recovery of attached durable background work (`.sideChain()` / `.forEachSideChain()`) — mid-drain partial fan-out, failed-task-under-completed-parent, and cross-store (SQLite + Postgres) completed-trace replay — plus documentation of the contracts. No runtime or public API changes.
4 changes: 3 additions & 1 deletion .changeset/resource-cas-registry-driver.md
Original file line number Diff line number Diff line change
Expand Up @@ -76,10 +76,12 @@ terminal here, it suppresses a no-op before checking any version, it routes
single-field literal patches down a commutative path that writes without a
version check at all, and it has no cancellation. Resource writes stop on an
explicit abort of the request rather than persisting after it — but not on a
client disconnect, since background `.work()` tasks keep running past that and
client disconnect, since background `.sideChain()` tasks keep running past that and
their writes still have to land.

Task boards backed by a durable resource collection inherit this: a claim written
against a stale read is refused and re-applied rather than overwriting the worker
that won. The filesystem store remains the exception — it compares within a
single process, so a board fanned across replicas wants SQLite or Postgres.

(FIX-992)
62 changes: 62 additions & 0 deletions .changeset/side-chain-vocabulary.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
---
"@flow-state-dev/core": minor
"@flow-state-dev/contracts": minor
"@flow-state-dev/engine": minor
"@flow-state-dev/testing": minor
"@flow-state-dev/devtool": minor
---

The middle execution tier is now called a **side chain**, everywhere.

Work runs in one of three places: in the turn, alongside the turn, or outliving
the turn. The middle one had three names depending on where you met it — `work`
in the methods you called, `background` in one of its own methods, and "side
chain" in the page that taught it. `background` was doing the most damage,
because it also titles the page for the *third* tier and is the umbrella term
for all three at once.

So the tiers are now sayable in one breath: **main → side chain → detached**,
and `background` goes back to meaning the umbrella over all of them.

**The sequencer DSL:**

| Before | Now |
| --- | --- |
| `.work()` | `.sideChain()` |
| `.workIf()` | `.sideChainIf()` |
| `.waitForWork()` | `.waitForSideChain()` |
| `.forEachBackground()` | `.forEachSideChain()` |

**Values you read back.** `provenance.phase` is `"main" | "sideChain"` (was
`"main" | "work"`), `provenance.workGroupId` is now `sideChainGroupId`, and
`StatusItem.backgroundTasks` is now `sideChainTasks`. The `"work"` member of
`FlowErrorScope` is now `"sideChain"`.

**Types and functions.** `RequestWorkPool` and its result/options types are
`RequestSideChainPool*`; `getRequestWorkPool` and `createRequestWorkPool` are
`getRequestSideChainPool` / `createRequestSideChainPool`;
`composeBackgroundSignal` is `composeSideChainSignal`. In `@flow-state-dev/testing`,
`WorkTrace` is `SideChainTrace` and `TestSequencerResult.workResults` is
`sideChainResults`. The DevTool's trace badge reads **SC** instead of **BG**.

**Removed: the flow-level `work` config.** `WorkConfig` and the `work` member on
`FlowDefinition` / `FlowInstance` / `FlowInstanceOptions` / `FlowType` declared
four lifecycle hooks that nothing ever invoked — a hook set there had its
declared resources registered and was then never called. They are removed rather
than renamed, so the canonical name does not inherit a contract that does
nothing. If you want per-side-chain lifecycle hooks, they need building.

**One change is not just naming: this moves replay-log keys.** The tier's name
is a segment of a block's structural path (`…/work[3]` becomes
`…/sideChain[3]`), and that path is the key the replay log memoizes completed
children under. A request that is *in flight* across the deploy carrying this
change has its completed side chains filed under the old segment, so they are
not recognised and **will run a second time** on continuation. This affects only
requests interrupted before the upgrade and continued after it; nothing else
reads the path across a version boundary, and there is no migration to run.
Items stored before the upgrade keep `phase: "work"`, read back fine, and simply
render without the side-chain badge in the DevTool.

Completeness is enforced rather than asserted: `pnpm typecheck` now runs a check
that fails if the retired vocabulary reappears, in any of the four ways it was
encoded (FIX-766).
Loading
Loading