Architecture review — pi-subagent

2026-12-01 module seam leakage deep module

Hot spots scanned: workflow layer, workflow-supervisor, ultra layer, observation path

A canonical state module for the run

Strong in-process

src/workflow.ts · src/workflow-supervisor.ts · src/manager.ts · src/journal.ts · src/dashboard.ts · src/job-format.ts · src/render.ts · src/types.ts

Before — one run, four shapes

flowchart TB
  plan["WorkflowPlan — parse"] --> spec["WorkflowRunSpec — prepare"]
  spec --> dag["WorkflowRunState — supervisor local, dies when run() returns"]
  spec --> flat["Execution.tasks — flat TaskSnapshot[], the only shape that survives"]
  dag --> flat
  flat --> journal["journal — itemsByStep() rebuilds the step/item DAG"]
  flat --> dash["dashboard"]
  flat --> jf["job-format"]
  flat --> rend["render"]
  restore["restore() — fabricates AgentConfig, never restores the workflow"] -.-> flat
  linkStyle 4,8 stroke:#dc2626,stroke-width:2px
              

After — one deep run module, thin projections

run module

start cancel snapshot() journal()

stepTasks · itemTasks · pendingItems · itemCounts · attempts · restore identity — all inside

↓ projection   ·   ↓ projection   ·   ↓ projection

JobSnapshot

flat view for the job system

WorkflowJournal

audit record, built not rebuilt

presentTask

labels for display

Problem

One run exists as a plan, a prepared spec, a supervisor-local DAG, and a flat task array — and the journal plus three display modules reverse-engineer the step/item graph from rows that share a stepId, while restore fabricates agent configs and drops the workflow.

Solution

Promote the supervisor's run state to the run's canonical module, and make the snapshot, the journal, and task labels projections of it.

Wins

  • locality: one run, one module
  • retries get a home (attempts already anticipated)
  • journal stops rebuilding the DAG
  • restore keeps step identity, journal eligibility
  • leverage: one interface, three projections
  • tests: every projection from one state

Make the host interface the real seam

Strong in-process

src/workflow-supervisor.ts · src/manager.ts · test/workflow-run.test.ts

Before — the declared seam is bypassed

declared seam — WorkflowSupervisorHost (7 methods) MANAGER Execution.tasks InternalTask.snapshot · .result plannedTaskCount FIFO pool · settleTask cancel paths ×3 host interface (7) schedule · createTask settleTask · cancelledResult finalize · emit · now SUPERVISOR WorkflowRunState — local to run() release / launch / settle skip propagation cancel — its own policy execution.tasks ×6 snapshot ×11 · result ×7 plannedTaskCount += sets execution.cancelRequested

Red traffic crosses the seam directly; the two modules also type-import each other. One adapter (production) — the seam is hypothetical.

After — state inside, effects through the interface

real seam — narrow host interface MANAGER FIFO pool · workers Execution — job record snapshots · persistence job views (list · get · wait) Execution / InternalTask → job-state.ts (cycle gone) host interface schedule createTask settleTask finalize emit · now SUPERVISOR RunState — canonicalstepTasks · itemTasks · attempts release / settle / skip policy cancel — one policy toSnapshot() · toJournal() all effects through the interface

RunState stays inside; a fake host in tests becomes the second adapter — the seam turns real.

Problem

The supervisor's interface claims to be the only seam, but the supervisor reads and mutates manager-owned Execution/InternalTask fields directly — and no test ever fakes the host, so all 21 workflow-run tests go through a real manager.

Solution

Give the run state to the supervisor behind an honest, narrow interface (or a pure transition function the manager applies), and move the shared state types out of the manager module.

Wins

  • seam turns real: fake host adapter
  • DAG tests without a manager
  • cancellation policy in one place
  • type cycle between modules dies
  • interface shrinks to what's used
  • locality: state mutation in one module

Emit deltas through the observation seam

Strong local-substitutable

src/runner.ts · src/manager.ts · src/index.ts · src/job-format.ts · src/persistence.ts · src/activity.ts

Before — every transition re-projects the whole job

sequenceDiagram
  participant C as child
  participant R as runner
  participant M as manager
  participant I as index.ts
  participant P as session log
  C->>R: message_end
  R->>M: onUpdate — full messages array copied
  M->>M: emit → snapshot() — structuredClone of every task
  M->>I: onJobChange(whole JobSnapshot)
  I->>I: manager.list(true) — clone of every active job
  I->>P: appendEntry(persistedJob) — another clone
  Note over M,P: per task transition, ×256 tasks ≈ O(N²) clones; one 256-row snapshot ≈ 12 MiB
              

After — compact events, one checkpoint

task startedtask finisheditem releasedstep settledterminal checkpoint

formatJob

default: per-step summary + the last succeeded step's answer; verbose behind a flag

wait on a run

returns the journal's bounded output — the consolidated answer, by default

Events carry what changed (job id, status, changed rows); the whole snapshot is written once, at the terminal transition.

Problem

The observation interface carries whole-state projections — the runner copies the full transcript per message, the manager clones the full job per transition, and wait returns every step and item output with no aggregate bound, so caps stay per-row while cost grows O(N²) in tasks.

Solution

Emit compact change events plus one checkpoint at the terminal transition, and make the pull paths return bounded summaries by default.

Wins

  • persistence: O(N²) → O(N)
  • parent context receives summary only
  • leverage: bounded wait output
  • checkpoint concentrates the write
  • dashboard refresh stops re-cloning
ADR-0006 tension, not violation: the push notice correctly carries only the last succeeded step, but the pull path the ultra guidance recommends — subagent_jobs wait — returns every intermediate output, the opposite of the consolidated answer the ADR exists to protect. Deepening this seam strengthens the ADR.

Collapse the step-shape mirrors

Strong in-process

src/workflows.ts · src/workflow.ts · src/types.ts · src/journal.ts · src/persistence.ts

Before — one shape, hand-synced in eight places

WorkflowStep

idagenttaskneedseachmodelcwd

STEP_FIELDS

idagenttaskneedseachmodelcwd

Expanded…

idagenttaskneedseachmodelcwd

Prepared…Step

idneedstemplateeachprepared

PreparedTask

agenttaskcwdstepIditemitemValue

sync debt — hand-maintained elsewhere

journal.planInputs — 7 fields re-enumerated; miss one and the inputHash replay contract drifts silently

persistence validators — already drifted: validTask never checks step; validJob skips startedAt · finishedAt · errorMessage · timedOut

After — one list, derived projections

WorkflowStep — the one field list

idagenttaskneedseachmodelcwd

↓ ↓ ↓

projections

Pick<WorkflowStep, …> — ExpandedWorkflowStep deleted

inputHash

hash the canonical plan object — new fields included by default

validators

derive from the type — TypeBox is already a dependency

Problem

A step's shape is re-enumerated by hand in five types and three field lists, and the copies have already drifted — a new step field must be added in up to eight places or it silently vanishes from the journal hash, restore, or both.

Solution

Keep one canonical step type and derive the projections, the journal hash input, and the persistence validators from it.

Wins

  • new step fields: one edit
  • inputHash cannot silently drift
  • validators derive from the type
  • restore stops dropping fields
  • locality: the shape lives once
  • deletion test: three lists deleted

Untangle workflow.ts and workflows.ts

Worth exploring in-process

src/workflow.ts · src/workflows.ts · src/index.ts · src/workflow-supervisor.ts

Before — one letter apart, three concerns inside

workflow.ts

run spec · interpolation · /workflow command parser

args + run-shape validation

workflows.ts

plan parsing · discovery · caps

──▶ workflow-supervisor imports validateWorkflowExpansion — plan parsing in the runtime path

──▶ index.ts imports the command parser — a CLI concern in the run-types module

──▶ every conversation about "workflow" starts with: which file?

After — one concern per module, honest names

workflow-
plan.ts

parse · discover · caps

workflow-
run.ts

run spec · interpolation · release validation

workflow-
command.ts

/workflow parser · formatter

──▶ supervisor → workflow-run (no plan-parsing import)

──▶ index → workflow-command (CLI concern isolated)

──▶ names answer "which file?"

Problem

Two modules differ by one letter, and workflow.ts holds three concerns — run types, interpolation, and the /workflow command parser — so tracing one each-step spans six modules and every navigation starts with disambiguating the file names.

Solution

Rename by concern — plan, run, command — so each module has one job and a name that says what it is.

Wins

  • AI-navigability: names answer "which file?"
  • locality: one concern per module
  • CLI concern leaves the run module
  • low risk, mechanical move

One presentation module, three surfaces

Worth exploring in-process

src/render.ts · src/job-format.ts · src/dashboard.ts · src/index.ts

Before — three projections, three rulebooks

render.ts
TUI

(skipped)

failed →

errorMessage ∥ stderr ∥ output

job-format.ts
tool text

(skipped: reason)

failed →

Error: … + output

dashboard.ts
TUI

errorMessage ?? "(skipped)"

failed →

output only

isFailedResult lives in the TUI renderer but decides the subagent tool's model-facing error (index.ts:89)

formatUsageStats pulls the TUI module into the tool-text path

renderSubagentResult's workflow branch is unreachable from production — test-only

After — one rulebook, thin surfaces

task presentation module

one rule per task state — skipped, failed, running, labels — behind one interface

↓    ↓    ↓

render

TUI formatting only

job-format

tool text

dashboard

TUI rows

The failure predicate moves out of the renderer; the surfaces keep their distinct layouts but share the rules.

Problem

The same task state is rendered by three modules with three divergent rulebooks — skipped, failed, and labels each differ — and the failure predicate that decides the model-facing tool error lives inside the TUI renderer, whose workflow branch nothing in production can reach.

Solution

Merge the rules into one presentation module and leave the three surfaces as thin adapters over it.

Wins

  • one rule per task state
  • three test suites become one
  • unreachable renderer branch deleted
  • failure predicate leaves the TUI
  • locality: wording changes touch once

Thread cap limits through the run spec

Worth exploring in-process

src/workflows.ts · src/prepare.ts · src/workflow-supervisor.ts · src/index.ts · src/config.ts

Before — three callers, three sources of truth

flowchart TB
  env["process.env.PI_SUBAGENT_WORKFLOW_MAX_ITEMS"]
  v["validateWorkflowExpansion(options ?? env)"]
  start["prepare — start-time call: every each-step count is 0, cannot fail"]
  rel["supervisor — release-time call: re-reads process.env"]
  card["index — review card: load-time config value"]
  start --> v
  rel --> v
  env -.-> v
  card -. can disagree with enforcement .-> rel
  linkStyle 3 stroke:#dc2626,stroke-width:2px
              

Tests that want a custom cap must mutate global process.env (the suite runs single-threaded to make that safe).

After — limits ride the run spec

config (load time)

one value, captured once

↓

WorkflowRunSpec.limits

required argument — no env seam, review card and enforcement share it

↓

release-time check

uses spec.limits; the no-op start call becomes validatePlanShape

Tests inject caps through the interface; the run path never touches process.env.

Problem

Cap enforcement reads process.env at release time while the review card and ultra guidance use the value captured at extension load, the start-time call is a guaranteed no-op, and a run-level cap violation is reported as a plan-validation error on the step.

Solution

Make limits a required argument captured once and threaded through the run spec, and say exactly what the start-time check checks.

Wins

  • cap semantics in one argument
  • tests stop mutating process.env
  • review card matches enforcement
  • no-op check becomes honest shape check

Left alone — passed the deletion test

TaskRunner / ProcessRunner seam — two real adapters (process + FakeRunner); the model the supervisor seam should copy.

PrepareContext — structural seam with a compile-time guard; tests pass a small fake.

output.ts · activity.ts — deep, pure, property-tested; only their call sites are costly (candidate 3).

config.ts — consistent fallback cascade, tested.

The DAG algorithm itself — release order, skips, fail-soft items well covered (21 run tests + TLA+ spec); the interface around it is the problem, not the code.

ultra-keyword · ultra-notify — real modules with direct tests. ultra.ts is thin and its start formatter duplicates workflow's — fold into candidate 6, don't restructure the layer.

Top recommendation

Make the host interface the real seam

It is the enabling move: once the run state sits behind an honest interface, candidate 1 builds directly on it (promote that state to the canonical run module), a fake host becomes the second adapter that makes the seam real, and the DAG's skip, cancel, and item semantics gain a test surface that no longer fabricates manager internals or needs temp agent directories. It is also the lowest-risk of the three structural candidates — mostly moving types and narrowing mutations, with the 21 existing run tests as the safety net.