/** * # Canonical FlowIR type contract * * This module formalizes the **canonical FlowIR** (Flow Intermediate * Representation) type contract for the overstory-convergence roadmap. It is a * **superset** of the implicit shape that `./translate.ts` already produces * (mirrored structurally in `./meta.ts`): every `FlowIR`/`FlowIRNode` emitted * by `translateTaskflow` satisfies the types defined here, and these types add * the missing formalization — a closed `FlowIRNodeKind` literal union, an * explicit `FlowIREdge` model, structural `FlowIRBudget`/`FlowIRMeta`, and * optional lightweight TypeBox guards. * * **Provenance & ownership (Q2=B, Q5=own):** this is pi-taskflow's *own* type * contract — not vendored from overstory. `flowir/compile.ts` (batch 2 of the * roadmap) will emit this canonical shape; the event-sourced kernel executes * it. `translate.ts`'s 1:1 projection is a *read-only stub* that already * conforms to this contract today, so formalizing here is purely additive — * it must not break `translate.ts`, `meta.ts`, `hash.ts`, or any barrel. * * **Compatibility note:** the canonical `FlowIRNode.kind` is the closed * `FlowIRNodeKind` literal union (the closed set of native phase kinds = `PHASE_TYPES`), whereas * `meta.ts`'s `FlowIRNode.kind` is `string` (a 1:1 projection). Every value * `translate.ts` produces for `kind` (`phase.type ?? "agent"`) is a member of * `FlowIRNodeKind`, so the canonical type is a strict refinement that * subsumes the stub output. Code that needs the looser projection can keep * using `meta.ts`; code that wants the closed contract imports from here. * * **Purity:** zero runtime deps beyond `typebox`. No IO, no Date, no * randomness. Guards are pure functions over plain JSON values. * * @see docs/internal/overstory-convergence-roadmap.md §3 (M1), §6 (compile seam) * @see docs/internal/rfc-flowir-compilation.md */ import { Type } from "typebox"; import { type PhaseType } from "../schema.ts"; import type { EffectDecl } from "../effects/types.ts"; /** * The closed set of pi-taskflow phase kinds, derived 1:1 from the exported * {@link PHASE_TYPES} in `../schema.ts` (single source of truth). This is the * canonical `FlowIRNode.kind` vocabulary. `translate.ts` sets * `kind = phase.type ?? "agent"`, so every node it emits is a member of this * union. Adding a phase kind requires updating `PHASE_TYPES` only — FlowIR * follows automatically. * * | kind | purpose | * |-------------|----------------------------------------------------------| * | `agent` | single subagent call | * | `parallel` | static concurrent branches | * | `map` | dynamic fan-out over an array (one subagent per item) | * | `gate` | quality gate — can halt the flow on VERDICT: BLOCK | * | `reduce` | aggregate multiple upstream outputs into one | * | `approval` | human-in-the-loop pause (approve/reject/edit) | * | `flow` | run a saved sub-taskflow as a single phase | * | `loop` | repeat body until condition, convergence, or max iters | * | `tournament`| N competing variants + judge picks best / aggregates | * | `script` | run a shell command (no LLM, zero tokens) | */ export declare const FlowIRNodeKind: Type.TUnsafe<"agent" | "approval" | "expand" | "flow" | "gate" | "loop" | "map" | "parallel" | "race" | "reduce" | "script" | "tournament">; /** @see PHASE_TYPES — same closed set as the DSL. */ export type FlowIRNodeKind = PhaseType; /** * A single canonical FlowIR node — one per pi-taskflow phase. * * This is a **superset** of the node shape `translate.ts` emits. The stub * attaches exactly `{ id, kind, inject, emits, when? }`; this contract * additionally formalizes the optional fields a genuine compiler (batch 2, * `flowir/compile.ts`) and the event-sourced kernel will populate: * * - `task` — the resolved (interpolated) task prompt, when materialized. * - `condRef` — a reference to a compiled condition descriptor (the lowered * form of `when`; see `flowir/cond.ts`). Absent on the stub, * which passes `when` through verbatim. * - `deps` — explicit `dependsOn` edges carried onto the node (the stub * folds these into `inject`; a compiler may keep them * separate for the edge model). * - `join` — join mode (`"all"` default, or `"any"` for OR-join). * - `timeout` — per-call ms cap (agent-running phases). * - `payload` — stable, hash-addressed DSL payload fields not otherwise * represented above (for example branch bodies, script command, * map source, flow/expand definitions, output contracts). * * All added fields are **optional** so the stub's minimal output remains valid. */ export interface FlowIRNode { /** Unique phase identifier (referenced via `{steps..output}`). */ id: string; /** The native phase kind — a member of {@link FlowIRNodeKind}. */ kind: FlowIRNodeKind; /** * Synthesized declared reads: the upstream step ids whose outputs this * node injects. In the stub this is `{steps.X}` refs ∪ `dependsOn` * (minus self); a genuine compiler lowers this to overstory's inject * model. */ inject: string[]; /** What this node emits — currently `[id]` (1:1 projection). */ emits: string[]; /** Raw `when` guard passthrough (stub: not rewritten to IR conditions). */ when?: string; /** Resolved (interpolated) task prompt, when materialized by a compiler. */ task?: string; /** Reference to a compiled condition descriptor (lowered `when`). */ condRef?: string; /** Explicit `dependsOn` edges carried onto the node (optional). */ deps?: string[]; /** Join mode: `"all"` (default AND-join) or `"any"` (OR-join). */ join?: "all" | "any"; /** Per-subagent-call ms cap (agent-running phases). */ timeout?: number; /** Runtime-affecting DSL payload not otherwise modeled by the core node fields. */ payload?: Record; /** * Trusted Effects (0.3 MVP): declared side effects for this node. * Shape is {@link EffectDecl}[]; deep validation is `validateEffectIR` / * the effects verifier (TypeBox here only checks presence of an array). */ effects?: EffectDecl[]; } /** * A directed edge in the FlowIR DAG. `from` is the upstream (producer) node * id; `to` is the downstream (consumer) node id. The stub projection encodes * edges implicitly via `FlowIRNode.inject` (and `dependsOn`); a genuine * compiler may emit an explicit `edges` list for graph consumers (renderers, * topo sorters). When present, `edges` must be consistent with `inject`. */ export interface FlowIREdge { /** Upstream (producer) node id. */ from: string; /** Downstream (consumer) node id. */ to: string; } /** * Run-wide observed-usage stop-loss. Once reported usage exceeds it, no new * model call is admitted and remaining phases are skipped; a call already in * flight may overshoot the threshold. Ordinary budgeted DAG layers and * map/parallel/tournament fan-out use serial admission, limiting new-call * overshoot to one call. A `race` necessarily admits competing branches * together, so all already-active race branches may contribute overshoot. * Structurally identical to the DSL `Budget` (schema.ts); mirrored * here so the FlowIR contract is self-contained and doesn't leak DSL types to * pure IR consumers (the event-sourced kernel). */ export interface FlowIRBudget { /** Stop admitting calls once observed accumulated cost exceeds this many USD. */ maxUSD?: number; /** Stop admitting calls once observed accumulated input+output tokens exceed this. */ maxTokens?: number; } /** * Optional flow-level metadata attached to a compiled FlowIR. Populated by a * genuine compiler; absent on the stub (which carries metadata in * `TaskflowIRMeta`, not on the IR itself). Kept loose (`Record`) so the contract is forward-compatible without churn. */ export interface FlowIRMeta { /** Origin tool/host (e.g. `"pi"`, `"codex"`). */ source?: string; /** Schema version of the IR emitter. */ irVersion?: number; /** Free-form compiler diagnostics / annotations. */ annotations?: Record; [key: string]: unknown; } /** * The canonical compiled FlowIR. A **superset** of `meta.ts`'s `FlowIR`: * - `version` is formalized (maps to the DSL `Taskflow.version`). * - `edges` is the optional explicit edge model (absent on the stub). * - `meta` is the optional flow-level metadata (absent on the stub). * * Every `FlowIR` produced by `translateTaskflow` — `{ name, nodes, args?, * budget?, concurrency? }` — satisfies this contract (the added fields are all * optional). `compile.ts` (batch 2) emits the full canonical form. */ export interface FlowIR { /** Workflow name (the DSL `Taskflow.name`). */ name: string; /** DSL schema version (maps to `Taskflow.version`, default 1). */ version?: number; /** The flat list of IR nodes (one per phase). */ nodes: FlowIRNode[]; /** Optional explicit edge list (consistent with `inject`). */ edges?: FlowIREdge[]; /** Declared invocation arguments (DSL `Taskflow.args`). */ args?: Record; /** Run-wide observed-usage stop-loss; an in-flight call may overshoot. */ budget?: FlowIRBudget; /** Default max concurrent subagents. */ concurrency?: number; /** Flow-level idle watchdog (ms) — included in the canonical hash (cache * identity via definition hash). Mirrors the DSL `Taskflow.idleTimeout`. */ idleTimeout?: number; /** Optional flow-level metadata (compiler-populated). */ meta?: FlowIRMeta; } /** * TypeBox schema mirroring {@link FlowIRNode}. Used by the structural guards * below. Kept in sync by construction (the `Static` of this schema *is* * `FlowIRNode`); if the interface above drifts, this schema must be updated to * match. */ export declare const FlowIRNodeSchema: Type.TObject<{ id: Type.TString; kind: Type.TUnsafe<"agent" | "approval" | "expand" | "flow" | "gate" | "loop" | "map" | "parallel" | "race" | "reduce" | "script" | "tournament">; inject: Type.TArray; emits: Type.TArray; when: Type.TOptional; task: Type.TOptional; condRef: Type.TOptional; deps: Type.TOptional>; join: Type.TOptional, Type.TLiteral<"any">]>>; timeout: Type.TOptional; payload: Type.TOptional>; effects: Type.TOptional>>; }>; /** * TypeBox schema mirroring {@link FlowIREdge}. */ export declare const FlowIREdgeSchema: Type.TObject<{ from: Type.TString; to: Type.TString; }>; /** * TypeBox schema mirroring {@link FlowIR}. */ export declare const FlowIRSchema: Type.TObject<{ name: Type.TString; version: Type.TOptional; nodes: Type.TArray; inject: Type.TArray; emits: Type.TArray; when: Type.TOptional; task: Type.TOptional; condRef: Type.TOptional; deps: Type.TOptional>; join: Type.TOptional, Type.TLiteral<"any">]>>; timeout: Type.TOptional; payload: Type.TOptional>; effects: Type.TOptional>>; }>>; edges: Type.TOptional>>; args: Type.TOptional>; budget: Type.TOptional; maxTokens: Type.TOptional; }>>; concurrency: Type.TOptional; meta: Type.TOptional>; }>; /** * Narrow an `unknown` value to a {@link FlowIRNode}. Pure, synchronous, * fail-closed: returns `false` for anything that is not a plain object with * a string `id`, a valid `kind`, and string-array `inject`/`emits`. Does not * throw. This is a *structural* check (not a deep TypeBox decode) so it stays * cheap and dependency-light; use {@link assertFlowIR} for full validation. */ export declare function isFlowIRNode(value: unknown): value is FlowIRNode; /** * Assert that a value is a well-formed {@link FlowIR}. Throws a descriptive * `Error` (not an `AssertionError`) on the first structural violation — * fail-closed, so a malformed IR can never silently reach the kernel. Uses * the lightweight structural checks (no external validator); for full schema * decoding, decode `FlowIRSchema` with a TypeBox-compatible checker. * * @throws {Error} if `value` is not a valid `FlowIR`. */ export declare function assertFlowIR(value: unknown): asserts value is FlowIR; //# sourceMappingURL=schema.d.ts.map