feat(sdk): record a named step DAG for authored flows

Merged
KH
2mo ago
+999-20

What / why

Agent Relay Cloud can't draw a TypeScript (authored) flow's run as a graph today. Step ids like agent-4 carry no name and no dependency edges. A prospect wants to watch a DAG of parallel agents run, so every authored step now records:

  • label: the f.agent name (it was discarded before with void name), the first 60 characters of an f.run command on one line, or the f.hook name. f.llm and f.human have no label.
  • after: the step's causal predecessors, transitively reduced.

Unchanged: step ids, admission keys and resume identity. This is observational metadata only and never gates execution.

How the edges are found (src/authored-step-graph.ts)

The edges are captured synchronously in the AuthoredFlowOperation constructor, from executionAsyncId() at the moment f.* is called. From there:

  1. The walk goes backward over the existing promise graph (trigger, resolutionCause and creationContext edges; see the new AuthoredPromiseGraph.causesOf).
  2. It stops when it reaches a step's own promise.
  3. Promise.all and Promise.allSettled aggregates expand to every member. The runtime only links an aggregate to the member that settled last. The member lists come from the combinator interception that already exists; a Step thenable maps to its operation's promise. race and any follow only the winner.
  4. The result is transitively reduced: a candidate that is an ancestor of another candidate is dropped.
  5. Cost stays bounded. The frontier is memoized per invocation context, and a walk that reaches an already-answered context reuses its answer. Measured: about 44 edge lookups per step at both 100 and 1000 sequential steps. The walk is capped at 10k nodes, and past the cap the record says afterTruncated: true rather than guessing.

Helper, MCP and plugin effects write no index record. The walk passes through them, so an after entry never names a step the index doesn't contain.

Record schema change (optional, backward compatible)

relayflows.authored-step.v1, on both admitted and completed records:

{
  index: 'relayflows.authored-step.v1',
  step: string, runId: string, state: 'admitted' | 'completed',
  completionReason?: string, kernelStep?: string,
  label?: string,          // bounded to 256 chars like other fields
  after?: string[],        // step ids, at most 32
  afterTruncated?: true,   // present only when `after` is incomplete
}

The root completion journalSteps entries get the same three optional fields. A step with no label and no predecessors writes exactly the old shape. isAuthoredStepRecord validates the new fields and skips malformed records, as it already does. The current Cloud reader (packages/core/src/bootstrap/lib/relayflow-v2-authored-index.ts) ignores unknown fields, and authored-root.ts / authored-node-runner.ts already tolerate extra journalSteps fields. The Cloud PR that draws the graph consumes these fields.

Tests

New:

  • tests/authored-step-graph.test.ts (13 tests), against a real lifecycle:
    • parallel fan-out draws no sibling edges
    • a→b→c stays a chain
    • await Promise.all(deps) depends on all deps, whichever settled last; same for allSettled
    • race follows only the winner
    • diamond reduction
    • async wrapper functions
    • the examples/task-graph pattern: a map of promises, each awaiting Promise.all of its deps, then run → agent → run
    • a fan-in of 40 is capped at 32 and marked afterTruncated
    • 300 sequential steps each list only their predecessor
    • the node cap stops a 50k-node walk and marks it truncated
    • the f.run label is on one line and truncated at 60 chars
  • tests/authored-step-graph-live.test.ts: through the live kernel and local agent. Labels and after appear on the admitted and completed stream records, on journalSteps, and after a readAuthoredStepIndex round-trip. Ids are unchanged.
  • tests/authored-step-index.test.ts (+4): round-trip, old shape when there are no edges, bounds, and malformed records skipped.

Updated, because they pin the journalSteps or index shape and an f.run/f.agent step now carries its label: authored-declined.test.ts, authored-flow.test.ts, agent-transcript-live.test.ts.

Results, run locally in the worktree with RELAYFLOWD_BIN set to a kernel built by ops/cargo.sh:

  • npm run typecheck: exit 0
  • npm run build && npm run typecheck:tests: exit 0
  • vitest run (full): Tests 28 failed | 2605 passed | 17 skipped (2650). None of the failures come from this change:
    • authored-node-runtime.test.ts: needs bun 1.4.0, but the machine has 1.3.14. Also fails on main.
    • canonical-software-factory.test.ts (3) and stuck-run-triage.test.ts (22): expected an @relayflows/surface flow handle, a module-resolution issue in this worktree's local install. Unchanged main in the same worktree gives the same 25 failures.
    • cli-watch.test.ts (2) and cli.test.ts (1): 5s timeouts. They pass when rerun, and on main a different cli.test.ts test times out the same way.
  • The step-graph, index, lifecycle, operation, flow and declined files together: Tests 127 passed (127).
  • agent-transcript-live.test.ts: 4 passed.

Review round 1 (cf3b3ea1)

  • Combinator edges depend on the outcome. Fulfilled all, rejected any and every allSettled expand to all members. A rejected all, a fulfilled any and every race keep only the member that settled them. The outcome is read with util.inspect; no handler is attached, so an author's unhandled rejection stays visible.
  • Truncation is carried through the reduction. A step's node keeps whether its own after was incomplete, and a join that reduces against it is marked afterTruncated.
  • after is bounded on read. isAuthoredStepRecord rejects after with more than 32 entries.
  • Long-running steps. A step in flight for 30 000 polls (3 times the walk limit) still gives its dependents exact, untruncated after lists. The walk stops at the step's own promise and never enters its internal chain; the dependents' walks visit 7 nodes at most.

Overlap with fix/sdk-parallel-local-agents

That branch reworks AuthoredPromiseGraph and authored-flow-lifecycle.ts to fix a CPU stall in the completion gate.

  • It adds a causesOf(asyncId): number[] to authored-promise-graph.ts that is identical to the one this PR adds, with the same signature, body and position. When rebasing, keep a single copy.
  • In authored-flow-lifecycle.ts, this PR changes only registerCombinator (collecting member ids and one stepGraph.registerAggregate call), registerOperation/stepEdges, and two lines in close(). The step-graph logic itself lives in the new authored-step-graph.ts.

🤖 Generated with Claude Code


[!NOTE]
Medium Risk
Changes promise-lifecycle instrumentation and extends durable journal/index schema, but metadata is optional and does not affect execution or admission; incorrect edges would only mislead graph UI.

Overview
Authored TypeScript flows now emit observational DAG metadata so Cloud can draw named graphs: each indexed step and matching journalSteps entry may include optional label (f.agent / f.hook names, kept whole up to 256 chars or omitted—not f.run commands) and after (transitively reduced causal predecessors, capped at 32 with afterTruncated when incomplete).

The SDK adds AuthoredStepGraph, wired through AuthoredFlowLifecycle and AuthoredFlowOperation at step invocation: it walks the existing promise graph backward (stopping at step frontiers, expanding Promise.all / allSettled / any / race by settlement outcome) and threads the resulting edges into admitted/completed relayflows.authored-step.v1 records. Step ids, admission keys, and resume identity are unchanged; steps with no graph fields keep the old record shape. Docs and unit/live tests cover combinator behavior, walk limits, label safety, and index round-trips.

Reviewed by Cursor Bugbot for commit ea36f070d666ee93f2a7db8e0e692522262d4f01. Bugbot is set up for automated code reviews on this repo. Configure here.


Summary by cubic

Records a human label and causal predecessors for every authored step so Agent Relay Cloud can draw a TypeScript flow's run as a named DAG of parallel agents. Step ids, admission keys, and resume identity are unchanged; the new fields are observational metadata and never gate execution.

Edges and labels

  • label is the f.agent name (previously discarded) or the f.hook name, kept whole and omitted — never cut — past 256 characters; f.run, f.llm, and f.human have none.
  • after lists the step's causal predecessors, computed by walking the promise graph back from the invocation context. Promise.all/allSettled expand to every member only when the aggregate had to wait for all of them (a fulfilled all, a rejected any); race, a rejected all, and a fulfilled any follow only the member whose settlement settled them.
  • An aggregate's settlement is read with inspect without attaching a handler, so a rejected aggregate stays an unhandled rejection; the read pins colors, compact, and sorted explicitly, which process-wide inspect defaults could otherwise change.
  • Walks are memoized per invocation context and capped at 10k nodes; every predecessor entry inspected during reduction counts toward the cap, duplicates included, so a wide fan-in stays bounded. Past the cap, or when a join reduces against an incomplete list, the record says afterTruncated: true instead of guessing.
  • relayflows.authored-step.v1 records and root journalSteps entries gain optional label, after (at most 32), and afterTruncated; a step with neither writes the old shape, and existing readers ignore the new fields.

Diagnostics

  • A failed local agent worker closes the journal client the flow shares; subsequent journal requests now name the worker's failure (or the socket's error/close) as the cause instead of failing with a bare "not connected".

Agent Relay sessions

  • claude session a41ce5ec · opened via gh pr create · last active 2026-09-22