@tangle-network/agent-runtime 0.60.0 → 0.61.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/dist/agent.d.ts +1 -1
  2. package/dist/agent.js +1 -2
  3. package/dist/agent.js.map +1 -1
  4. package/dist/analyst-loop.d.ts +1 -1
  5. package/dist/{chunk-IN7WHMGZ.js → chunk-5V343QPB.js} +47 -7
  6. package/dist/chunk-5V343QPB.js.map +1 -0
  7. package/dist/chunk-7IXF3VUJ.js +59 -0
  8. package/dist/chunk-7IXF3VUJ.js.map +1 -0
  9. package/dist/{chunk-ZWGEA722.js → chunk-AU5MCNHO.js} +2 -2
  10. package/dist/chunk-IBRJTG7O.js +475 -0
  11. package/dist/chunk-IBRJTG7O.js.map +1 -0
  12. package/dist/{chunk-MMDIORZY.js → chunk-Q5R33I7Y.js} +4 -23
  13. package/dist/chunk-Q5R33I7Y.js.map +1 -0
  14. package/dist/{chunk-45D64J7B.js → chunk-VCOT7XEQ.js} +190 -99
  15. package/dist/chunk-VCOT7XEQ.js.map +1 -0
  16. package/dist/coder-DD5J5Onk.d.ts +52 -0
  17. package/dist/coordination-k29badiX.d.ts +381 -0
  18. package/dist/{delegates-C94qchkz.d.ts → delegates-CWMv_rKL.d.ts} +649 -21
  19. package/dist/index.d.ts +9 -6
  20. package/dist/index.js +9 -9
  21. package/dist/intelligence.d.ts +1 -1
  22. package/dist/{loop-runner-bin-Noz7P-mS.d.ts → loop-runner-bin-Bqt0hiNY.d.ts} +46 -12
  23. package/dist/loop-runner-bin.d.ts +7 -4
  24. package/dist/loop-runner-bin.js +4 -4
  25. package/dist/loops.d.ts +7 -6
  26. package/dist/loops.js +17 -6
  27. package/dist/mcp/bin.js +10 -10
  28. package/dist/mcp/bin.js.map +1 -1
  29. package/dist/mcp/index.d.ts +12 -12
  30. package/dist/mcp/index.js +7 -7
  31. package/dist/{openai-tools-d4GKwgya.d.ts → openai-tools-CA2N3-Ak.d.ts} +1 -1
  32. package/dist/profiles.d.ts +7 -9
  33. package/dist/profiles.js +5 -7
  34. package/dist/profiles.js.map +1 -1
  35. package/dist/{run-loop-CcqfR_gy.d.ts → run-loop-D3PwlG7J.d.ts} +1 -1
  36. package/dist/runtime.d.ts +30 -1046
  37. package/dist/runtime.js +17 -6
  38. package/dist/{types-CUzjRFZ3.d.ts → types-Crxftafi.d.ts} +2 -2
  39. package/dist/workflow.d.ts +2 -2
  40. package/dist/workflow.js +1 -2
  41. package/dist/workflow.js.map +1 -1
  42. package/dist/worktree-fanout-CBULEoVe.d.ts +1098 -0
  43. package/package.json +1 -1
  44. package/dist/chunk-45D64J7B.js.map +0 -1
  45. package/dist/chunk-4FEUFYOY.js +0 -282
  46. package/dist/chunk-4FEUFYOY.js.map +0 -1
  47. package/dist/chunk-7QYOXFCD.js +0 -293
  48. package/dist/chunk-7QYOXFCD.js.map +0 -1
  49. package/dist/chunk-IN7WHMGZ.js.map +0 -1
  50. package/dist/chunk-MMDIORZY.js.map +0 -1
  51. package/dist/coder-CybltHEm.d.ts +0 -163
  52. package/dist/coordination-Biw19JzN.d.ts +0 -944
  53. /package/dist/{chunk-ZWGEA722.js.map → chunk-AU5MCNHO.js.map} +0 -0
package/dist/runtime.d.ts CHANGED
@@ -1,22 +1,25 @@
1
- import { AgentProfile, BackendType, CreateSandboxOptions, SandboxInstance, SandboxEvent } from '@tangle-network/sandbox';
1
+ import { AgentProfile as AgentProfile$1, CreateSandboxOptions, SandboxInstance, SandboxEvent, BackendType } from '@tangle-network/sandbox';
2
2
  export { AgentProfile, CreateSandboxOptions, SandboxEvent, SandboxInstance } from '@tangle-network/sandbox';
3
- import { u as ResultBlobStore, v as SpawnJournal, N as NodeId, w as SpawnEvent, T as TreeView, x as Settled, y as AgentSpec, E as ExecutorRegistry, B as Budget, z as Agent, H as RootHandle, K as SupervisedResult, L as Spend, O as Scope, P as ExecutorFactory, U as Executor, V as UsageEvent, G as GitRunner, M as MakeWorkerAgent, a as CoordinationTools, A as AnalystRegistry, C as CoordinationEvent, l as QuestionPolicy, X as Supervisor } from './coordination-Biw19JzN.js';
4
- export { Y as BusEvent, Z as BusRecord, _ as BusStats, $ as EventBus, a0 as ExecutorContext, a1 as ExecutorResult, a2 as Handle, a3 as NodeSnapshot, a4 as NodeStatus, a5 as PublishOptions, a6 as Restart, a7 as RootSignal, a8 as Runtime, a9 as SpawnOpts, aa as SupervisorOpts, ab as WidenGate, ac as createEventBus } from './coordination-Biw19JzN.js';
3
+ import { g as ResultBlobStore, i as SpawnJournal, N as NodeId, b7 as SpawnEvent, b8 as TreeView, l as Settled, b9 as ExecutorFactory, A as Agent, B as Budget, S as Scope, k as SupervisedResult, m as Spend, ba as UsageEvent, h as AgentSpec, E as ExecutorRegistry, j as RootHandle, bb as Supervisor } from './delegates-CWMv_rKL.js';
4
+ export { n as Executor, bc as ExecutorContext, bd as ExecutorResult, be as Handle, bf as NodeSnapshot, bg as NodeStatus, bh as Restart, bi as RootSignal, bj as Runtime, bk as SpawnOpts, bl as SupervisorOpts, bm as WidenGate } from './delegates-CWMv_rKL.js';
5
5
  import { R as RuntimeHooks } from './runtime-hooks-C7JwKb9E.js';
6
- import { ChatClient, AnalystFinding, DefaultVerdict, AgentProfile as AgentProfile$1, AnalystRunInputs, ToolSpan, StreamingDetector, DetectorSignal, buildTrajectory } from '@tangle-network/agent-eval';
6
+ import { ChatClient, AnalystFinding, AgentProfile, AnalystRunInputs, ToolSpan, StreamingDetector, DetectorSignal, buildTrajectory } from '@tangle-network/agent-eval';
7
7
  export { DefaultVerdict } from '@tangle-network/agent-eval';
8
- import { I as Iteration, S as SandboxClient, b as LoopResult, e as LoopTokenUsage, R as RuntimeStreamEvent, A as AgentRunSpec, E as ExecCtx } from './types-CUzjRFZ3.js';
9
- export { D as Driver, F as LoopDecisionPayload, G as LoopEndedPayload, H as LoopIterationDispatchPayload, J as LoopIterationEndedPayload, M as LoopIterationStartedPayload, a as LoopLineageOptions, N as LoopPlanDescription, P as LoopPlanPayload, f as LoopSandboxPlacement, Q as LoopStartedPayload, T as LoopTeardownFailedPayload, g as LoopTraceEmitter, d as LoopTraceEvent, L as LoopWinner, O as OutputAdapter, U as ValidationCtx, V as Validator } from './types-CUzjRFZ3.js';
8
+ import { I as Iteration, S as SandboxClient, b as LoopResult, f as LoopTokenUsage, R as RuntimeStreamEvent, A as AgentRunSpec, E as ExecCtx } from './types-Crxftafi.js';
9
+ export { D as Driver, F as LoopDecisionPayload, G as LoopEndedPayload, H as LoopIterationDispatchPayload, J as LoopIterationEndedPayload, M as LoopIterationStartedPayload, a as LoopLineageOptions, N as LoopPlanDescription, P as LoopPlanPayload, e as LoopSandboxPlacement, Q as LoopStartedPayload, T as LoopTeardownFailedPayload, g as LoopTraceEmitter, d as LoopTraceEvent, L as LoopWinner, O as OutputAdapter, U as ValidationCtx, V as Validator } from './types-Crxftafi.js';
10
+ import { C as CorpusRecord, c as Corpus, O as Outcome, S as ScopeAnalyzeInput, d as AssertTraceDerivedFindings, e as SteerContext, f as ScopeAnalyst, F as FanoutOptions, g as CombinatorShape, h as ScopeWidenGate, L as LoopUntilSpec, P as PanelSpec, i as PipelineStage, W as WinnerStrategy, j as FanoutWinnerSelector, V as VerifySpec, k as WidenSpec, l as CorpusFilter, R as RenderCorpusToInstructionsOptions, D as DefinePersonaInput, m as Persona, n as RunPersonifiedOptions, o as ShapeRegistry, p as LoopShape, E as EqualKArm, q as EqualKOnCostOptions, r as EqualKVerdict, T as TrajectoryReportOptions, s as TrajectoryReport, t as DeliverableSpec } from './worktree-fanout-CBULEoVe.js';
11
+ export { A as AuthoredHarness, u as CoderCheckConstraints, v as CoderCheckInput, w as DefinePersona, x as EqualKOnCost, y as Fanout, z as FanoutSynthesis, B as FlatWidenGate, G as LoopUntil, H as LoopUntilState, I as Panel, J as PanelJudge, K as PanelVerdict, M as PatchDeliverableOptions, N as PersonaContext, Q as PersonaExecutors, U as Pipeline, X as RenderCorpusToInstructions, Y as RunPersonified, Z as ShapeBudget, _ as ShapeContext, $ as TrajectoryNode, a0 as TrajectoryReportFn, a1 as Verify, a2 as Widen, a3 as WidenDecision, a4 as WidenLineage, a5 as WorktreeCliExecutorOptions, a6 as WorktreeCommandResult, a as WorktreeFanoutOptions, b as WorktreePatchArtifact, a7 as countDiffLines, a8 as createWorktreeCliExecutor, a9 as gateOnDeliverable, aa as isNonEmptyPatch, ab as patchDelivered, ac as runCoderChecks, ad as touchedPathsFromPatch, ae as touchesSecretPath, af as worktreeFanout } from './worktree-fanout-CBULEoVe.js';
10
12
  import { Scenario, ProfileDispatchFn } from '@tangle-network/agent-eval/campaign';
11
- import { R as RunLoopOptions } from './run-loop-CcqfR_gy.js';
12
- export { c as createSandboxForSpec, d as defaultSelectWinner, r as runLoop } from './run-loop-CcqfR_gy.js';
13
+ import { R as RunLoopOptions } from './run-loop-D3PwlG7J.js';
14
+ export { c as createSandboxForSpec, d as defaultSelectWinner, r as runLoop } from './run-loop-D3PwlG7J.js';
13
15
  import { b as AnalystRegistryLike } from './types-p8dWBIXL.js';
14
16
  import { R as RouterConfig, T as ToolSpec } from './router-client-30Y_pca8.js';
15
17
  export { a as RouterChatResult, b as RouterChatToolsResult, c as RouterToolCall, d as RouterToolLoopResult, r as routerChatWithTools, e as routerChatWithUsage, f as routerToolLoop } from './router-client-30Y_pca8.js';
16
- import { a as CoderCheckConstraints } from './coder-CybltHEm.js';
17
- import { L as LocalHarness, r as runLocalHarness } from './local-harness-BE_h8szs.js';
18
+ import { M as MakeWorkerAgent, a as CoordinationTools, A as AnalystRegistry, C as CoordinationEvent, j as QuestionPolicy } from './coordination-k29badiX.js';
19
+ export { B as BusEvent, p as BusRecord, q as BusStats, E as EventBus, P as PublishOptions, r as createEventBus } from './coordination-k29badiX.js';
20
+ import { L as LocalHarness } from './local-harness-BE_h8szs.js';
18
21
  import { stuckLoopView, toolWasteView } from '@tangle-network/agent-eval/pipelines';
19
- import './delegates-C94qchkz.js';
22
+ import './coder-DD5J5Onk.js';
20
23
  import './substrate-CUgk7F7s.js';
21
24
  import 'node:child_process';
22
25
 
@@ -397,762 +400,6 @@ declare function deterministicCompletion<Task, Output>(check: (output: Output, h
397
400
  reasons?: string;
398
401
  }): CompletionAnalyst<Task, Output>;
399
402
 
400
- /**
401
- * @experimental
402
- *
403
- * The personify layer — the "act like X" knob on top of the recursive keystone.
404
- *
405
- * The keystone (`src/loops/supervise/`) is pure STRUCTURE: a recursive `Agent` atom inside
406
- * a budget-conserving `Scope`, an `ExecutorRegistry` mapping an `AgentSpec` to a runtime,
407
- * and a `Supervisor` that runs a root agent to a typed `SupervisedResult`. It carries no
408
- * CONTENT — no model, no prompt, no goal framing, no notion of "who this loop is".
409
- *
410
- * This layer adds exactly that content seam without inventing a second engine:
411
- * - A `Persona` is a thin record: the root `AgentSpec` (profile + harness + optional BYO
412
- * executor), a root `directive` (the goal framing handed to the chosen shape), a
413
- * `context` blob (who the loop is acting as), and the executor seams the registry needs.
414
- * `definePersona` builds it; it is data, not behavior.
415
- * - A `LoopShape` is a reusable act-body FACTORY: `(ctx: ShapeContext) => Agent`. The shape
416
- * owns the STRUCTURE (how to decompose / fan out / verify / synthesize); the persona's
417
- * content parameterizes it. A new shape is ONE file + one `registerShape` call.
418
- * - `Outcome<D>` is the contract every shape synthesizes into: a finished deliverable OR a
419
- * list of concrete blockers — "100% done or 100%-defined blockers", never a vague middle.
420
- *
421
- * Layering: this module imports ONLY keystone runtime types (`./supervise/types`) and the
422
- * substrate `AgentProfile`/`BackendType`. It typechecks standalone — no impl, no engine.
423
- * Extensibility is structural: `Persona` carries an open `extensions` bag so a later
424
- * world-model / memory field is additive (a new optional key), never a breaking change.
425
- */
426
-
427
- /**
428
- * The terminal contract Drew wants: a loop returns a FINISHED deliverable, or the concrete
429
- * list of blockers that stopped it — never a half-done best-effort coercion. A `blocked`
430
- * outcome with an empty `blockers` list is a contract violation (a shape that can't finish
431
- * MUST name why); impls fail loud on it rather than emitting a vacuous block.
432
- *
433
- * `Outcome` is the `Out` type a personified `Agent`/`Supervisor` is parameterized by, so the
434
- * keystone's typed `SupervisedResult<Outcome<D>>` carries it end to end with no coercion.
435
- */
436
- type Outcome<D> = {
437
- kind: 'done';
438
- deliverable: D;
439
- } | {
440
- kind: 'blocked';
441
- blockers: string[];
442
- };
443
- /**
444
- * The "act like X" record. A thin composition over the keystone's `AgentSpec`: it pairs the
445
- * root spec (the executor mapping for the root agent the shape builds) with the CONTENT a
446
- * shape consumes — the goal framing (`directive`) and who the loop is acting as (`context`).
447
- *
448
- * The framework never reads `directive`/`context` semantically; it threads them to the shape
449
- * verbatim through `ShapeContext`. This is the rule the mandate names: the FRAMEWORK is
450
- * structure, the PERSONA carries model/prompt/tools/directive. No model name, prompt, or
451
- * persona string is ever hardcoded in a shape or the engine.
452
- *
453
- * `D` is the deliverable type this persona's loops produce; it flows into `Outcome<D>`.
454
- */
455
- interface Persona<D = unknown> {
456
- /** Stable persona name — used as the trace/journal label root, never as content. */
457
- readonly name: string;
458
- /**
459
- * The root agent's executor mapping (profile + harness + optional BYO executor). The
460
- * shape's root `Agent` carries THIS as its `executorSpec`; child specs the shape spawns
461
- * are derived from / resolved against the same persona registry (see `ShapeContext`).
462
- */
463
- readonly root: AgentSpec;
464
- /** The goal framing handed to the shape — the "what to achieve", not "how". */
465
- readonly directive: string;
466
- /** Who the loop is acting as — the opaque persona context blob the shape may inject into
467
- * child tasks. Opaque to the framework; only the persona's profiles/prompts interpret it. */
468
- readonly context: PersonaContext;
469
- /**
470
- * The executor seams (router endpoint+key, sandbox client, cli bin) the built-in runtimes
471
- * read off `ExecutorContext.seams`, OR a fully pre-configured registry. The supervisor
472
- * threads an EMPTY seam bag to the root scope, so a persona that uses built-in metered
473
- * runtimes MUST supply a registry whose factories close over their seams (or BYO executors
474
- * on each `AgentSpec`). Carried here so `runPersonified` can build `SupervisorOpts.executors`.
475
- */
476
- readonly executors: PersonaExecutors;
477
- /**
478
- * Forward-compatible extension bag — a later world-model / memory / tool-budget field is an
479
- * additive key here, never a breaking change to the `Persona` shape. Opaque to the engine.
480
- */
481
- readonly extensions?: Readonly<Record<string, unknown>>;
482
- /** Phantom: binds the persona to its deliverable type so `runPersonified` infers `D` from
483
- * the persona and the chosen shape must agree. Type-only — never present at runtime. */
484
- readonly __deliverable?: D;
485
- }
486
- /** The persona context blob — who the loop is acting as. Open by intent: a persona names its
487
- * own role/audience/constraints; the framework treats it as opaque content. */
488
- interface PersonaContext {
489
- /** The role the loop embodies ("senior staff engineer", "equity research analyst", …). */
490
- readonly role: string;
491
- /** Optional freeform framing the persona's prompts/profiles consume. */
492
- readonly notes?: string;
493
- /** Open content bag — persona-specific fields a shape's child tasks may carry. */
494
- readonly [key: string]: unknown;
495
- }
496
- /**
497
- * How a persona supplies executor resolution. Either a pre-built registry (factories already
498
- * closed over their seams) OR the raw seam bag the engine uses to construct a registry +
499
- * thread the seams onto each spawn. Exactly one is required — fail loud if neither is set.
500
- */
501
- interface PersonaExecutors {
502
- /** A registry whose factories already capture their seams. Highest precedence. */
503
- readonly registry?: ExecutorRegistry;
504
- /** Raw seams to thread onto built-in runtimes (`router`/`sandbox`/`cli` keys). */
505
- readonly seams?: Readonly<Record<string, unknown>>;
506
- }
507
- /** The minimal input to build a `Persona`. Mirrors `Persona` but lets the builder default
508
- * the executors-supplied invariant check and freeze the record. */
509
- interface DefinePersonaInput<D = unknown> {
510
- readonly name: string;
511
- readonly root: AgentSpec;
512
- readonly directive: string;
513
- readonly context: PersonaContext;
514
- readonly executors: PersonaExecutors;
515
- readonly extensions?: Readonly<Record<string, unknown>>;
516
- /** Phantom: pins the input's deliverable type so `definePersona<D>` returns a `Persona<D>`
517
- * the caller's shape must agree with. Type-only — never supplied at a call site. */
518
- readonly __deliverable?: D;
519
- }
520
- /** Builds a frozen `Persona`, failing loud on the executors-supplied invariant (neither a
521
- * registry nor seams = an unresolvable persona). Pure — no I/O, no engine. */
522
- type DefinePersona = <D = unknown>(input: DefinePersonaInput<D>) => Persona<D>;
523
- /**
524
- * Budget knobs a shape reads to size its fanout/children WITHOUT owning the conserved pool.
525
- * The root budget lives on `SupervisorOpts.budget`; the shape only needs the per-child
526
- * sizing hints + the fanout width it is allowed to open. All ceilings — the pool reserves
527
- * against them and fails closed, so an over-eager shape can never overspend.
528
- */
529
- interface ShapeBudget {
530
- /** Per-child spawn budget the shape reserves for each leaf/sub-loop it opens. */
531
- readonly perChild: Budget;
532
- /** Max children a fanout step may open in one round (the shape's structural width). */
533
- readonly fanout: number;
534
- }
535
- /**
536
- * The construction context a `LoopShape` factory receives. Carries the persona's resolved
537
- * executor seams + the budget knobs, plus the ONE helper a shape needs to spawn a child
538
- * through the keystone: `spawnChild` resolves an `AgentSpec` (or a persona-derived child
539
- * profile) into an `Agent` the shape hands to `scope.spawn`. The shape never touches the
540
- * registry directly — it asks the context, keeping resolution single-sourced.
541
- */
542
- interface ShapeContext<D = unknown> {
543
- readonly persona: Persona<D>;
544
- readonly budget: ShapeBudget;
545
- /**
546
- * Wrap an `AgentSpec` into a leaf `Agent` carrying it as `executorSpec`, so the shape can
547
- * `scope.spawn(spawnChild(spec), task, opts)`. `name` labels the child for traces. The
548
- * returned agent's `act` is never invoked by the keystone (it is spawned, not run) — the
549
- * spec drives the resolved `Executor`; `act` exists only to satisfy the `Agent` shape.
550
- */
551
- spawnChild(name: string, spec: AgentSpec): Agent<unknown, Outcome<D>>;
552
- /** Derive a child `AgentSpec` from the persona's root spec with an overridden profile —
553
- * the seam a shape uses to give a worker a narrower role/prompt than the root persona. */
554
- childSpec(profile: AgentProfile, harness?: BackendType | null): AgentSpec;
555
- /** The scope analyst (selector≠judge firewall) the combinator steers from. Absent ⇒ the
556
- * dormant default (empty findings → gates read deliverables/state only). */
557
- readonly analyst?: ScopeAnalyst<D>;
558
- }
559
- /**
560
- * A reusable act-body factory. Given the persona's content + seams (`ShapeContext`), it
561
- * returns the root `Agent<Task, Outcome<D>>` whose `act` decomposes the task, fans out
562
- * children through `scope.spawn`, verifies/selects across their settlements (selector≠judge:
563
- * via `settledToIteration` + `defaultSelectWinner`, never re-ranking behind the driver), and
564
- * synthesizes the terminal `Outcome<D>`. The shape is STRUCTURE; the persona is CONTENT.
565
- */
566
- type LoopShape<Task, D> = (ctx: ShapeContext<D>) => Agent<Task, Outcome<D>>;
567
- /**
568
- * The open shape registry — the extension point that makes a new loop-shape ONE file + one
569
- * `registerShape` call with zero edits elsewhere. `resolve` returns a typed outcome (inspect
570
- * `succeeded` before `value`); `register` fails loud on a duplicate name.
571
- */
572
- interface ShapeRegistry {
573
- register<Task, D>(name: string, factory: LoopShape<Task, D>): void;
574
- resolve<Task, D>(name: string): {
575
- succeeded: true;
576
- value: LoopShape<Task, D>;
577
- } | {
578
- succeeded: false;
579
- error: string;
580
- };
581
- /** The registered shape names — for diagnostics + a fail-loud "unknown shape" message. */
582
- names(): string[];
583
- }
584
- /**
585
- * The end-to-end entrypoint. Builds the persona's root `Agent` from the chosen shape, then
586
- * runs it through a fresh `createSupervisor` over the persona's executors + the supplied
587
- * budget/journal/blobs. Returns the keystone's typed `SupervisedResult<Outcome<D>>` — a
588
- * `winner` carries the synthesized `Outcome<D>`; a `no-winner` is never coerced into one.
589
- *
590
- * `shape` is either a resolved `LoopShape` or a registered shape NAME (resolved through the
591
- * default registry). The journal/blobs default to in-memory impls in the engine when omitted
592
- * (durable FS impls are passed explicitly for a persisted run).
593
- */
594
- interface RunPersonifiedOptions<Task, D> {
595
- readonly persona: Persona<D>;
596
- /** A resolved shape factory OR a registered shape name. */
597
- readonly shape: LoopShape<Task, D> | string;
598
- readonly task: Task;
599
- readonly budget: Budget;
600
- /** Per-child sizing + fanout width handed to the shape. Defaults derive from `budget`. */
601
- readonly shapeBudget?: Partial<ShapeBudget>;
602
- /** Trace/journal root key. Defaults to the persona name + a run discriminator in the engine. */
603
- readonly runId?: string;
604
- readonly journal?: SpawnJournal;
605
- readonly blobs?: ResultBlobStore;
606
- /** Runtime recursion-depth ceiling, paired with the conserved pool. */
607
- readonly maxDepth?: number;
608
- /** OTP intensity breaker bounds, forwarded to the supervisor verbatim. */
609
- readonly maxRestarts?: number;
610
- readonly withinMs?: number;
611
- /** A live root handle to attach (view/signal/abort) before the run starts. */
612
- readonly handle?: RootHandle<Outcome<D>>;
613
- readonly now?: () => number;
614
- readonly signal?: AbortSignal;
615
- /** Optional scope analyst threaded into the shape's ShapeContext so loopUntil/widen steer
616
- * on trace-derived findings instead of the dormant empty default. */
617
- readonly analyst?: ScopeAnalyst<D>;
618
- /**
619
- * Lifecycle stream sink, forwarded to `SupervisorOpts.hooks` so the root `Scope`'s
620
- * `agent.spawn`/`agent.child` events flow to an observer (e.g. the Intelligence SDK's
621
- * trace export). Absent ⇒ no stream (the run is silent, as today).
622
- */
623
- readonly hooks?: RuntimeHooks;
624
- }
625
- /** The composed run signature. */
626
- type RunPersonified = <Task, D>(options: RunPersonifiedOptions<Task, D>) => Promise<SupervisedResult<Outcome<D>>>;
627
-
628
- /**
629
- * @experimental
630
- *
631
- * The RSI-wave type surface — the FROZEN contracts the wave's Core + Compose build to.
632
- *
633
- * The keystone (`../supervise/`) is pure execution structure: a recursive `Agent` atom in a
634
- * budget-conserving `Scope`, run to a typed `SupervisedResult` by a `Supervisor`. The persona
635
- * layer (`./types`, `./persona`) adds the "act like X" content seam (`Persona` = `AgentSpec` +
636
- * `directive` + `context`, `LoopShape = (ctx) => Agent`, `Outcome<D>`). This module freezes the
637
- * remaining four wave seams ON TOP of those — and nothing more:
638
- *
639
- * 1. GENERIC COMBINATORS — the content-free act-library. Five composable shapes
640
- * (`pipeline`/`fanout`/`loopUntil`/`panel`/`verify`) plus the streaming widener (G5). Each
641
- * is a `CombinatorShape` (a `LoopShape` whose `Agent.act` runs the combinator over `Scope`),
642
- * so a combinator IS just a `LoopShape` — no new engine type. The SHAPE is here; the DOMAIN
643
- * (model, prompt, role) stays on the `Persona`. There is no "research" or "code" combinator:
644
- * a research sweep is `fanout` under a research persona; a build is `pipeline` under a coder.
645
- * 2. ANALYST-ON-SCOPE (G1, a PORT) — `ScopeAnalyst` carries the round-synchronous driver's
646
- * analyze→findings→steer wire (dynamic.ts) across to the reactive `Scope`, behind
647
- * the same trace-derived firewall (`assertTraceDerivedFindings` semantics): a reactive
648
- * combinator steers from trace FINDINGS, never a child's raw `verdict`.
649
- * 3. CROSS-RUN CORPUS (G2) — `Corpus` is the DURABLE accreted-fact store, DISTINCT from the
650
- * per-run `SpawnJournal`/`ResultBlobStore`. `renderCorpusToInstructions` is the read-back:
651
- * it projects accreted facts into `AgentProfile.prompt.instructions` / `resources.instructions`
652
- * for the next run's persona (the learning-flywheel READ side).
653
- * 4. TRAJECTORY TRACE + COST LEDGER — `trajectoryReport(journal, blobs)` reconstructs the whole
654
- * spawn tree with per-node + rolled-up `Spend`; `equalKOnCost` compares arms on conserved
655
- * COST (tokens/usd), NOT raw iteration count — closing the leaf-fanout confound.
656
- *
657
- * Layering: imports ONLY keystone runtime types (`../supervise/types`), persona types
658
- * (`./types`), the substrate `AnalystFinding`/`AgentProfile`, and the durable-store interfaces.
659
- * Pure types/interfaces — this module typechecks standalone, owns no impl, invents no engine.
660
- */
661
-
662
- /**
663
- * A combinator is just a `LoopShape`: a factory `(ShapeContext) => Agent` whose `Agent.act`
664
- * runs the combinator's structure over the `Scope` (spawn children, drain `next()`, select via
665
- * the single-sourced `settledToIteration`+`defaultSelectWinner`, synthesize an `Outcome<D>`).
666
- * Aliased — NOT a new type — so a combinator stays a first-class shape the persona layer's
667
- * `runPersonified`/`ShapeRegistry` resolve with zero new machinery. The SHAPE is content-free;
668
- * the persona carries the domain.
669
- */
670
- type CombinatorShape<Task, D> = LoopShape<Task, D>;
671
- /**
672
- * `pipeline(stages)` — sequential composition: each stage's `Outcome.deliverable` feeds the next
673
- * stage's task (via `feed`). The first `blocked` stage short-circuits the whole pipeline (its
674
- * blockers ARE the pipeline's blockers — never coerced past a failed stage). The terminal
675
- * stage's `done` deliverable is the pipeline's deliverable. Spawns one child per stage in order;
676
- * a stage that the conserved pool cannot admit is a concrete blocker.
677
- *
678
- * No domain: "code build test" is `pipeline([plan, implement, integrate])` under a coder persona,
679
- * not a named shape. A stage names only its label + how to derive its task from the prior output.
680
- */
681
- interface PipelineStage<Task, StepIn, StepOut> {
682
- /** Trace/journal label for this stage's spawned child. */
683
- readonly label: string;
684
- /** Derive this stage's task from the prior stage's deliverable (or the root task for stage 0).
685
- * Pure projection — the framework never interprets the result; the resolved leaf does. */
686
- feed(prior: StepIn, ctx: ShapeContext<unknown>, rootTask: Task): unknown;
687
- /** Read this stage's settled child output into the typed `StepOut` the next stage feeds on.
688
- * Fail loud (return a `blocked`) when the child produced nothing usable for the next stage. */
689
- collect(settled: Settled<Outcome<StepOut>>): Outcome<StepOut>;
690
- }
691
- /** `pipeline(stages)` — build the sequential combinator from an ordered stage list. The first
692
- * stage's `StepIn` is the root `Task`; the last stage's `StepOut` is the deliverable `D`. */
693
- type Pipeline = <Task, D>(stages: ReadonlyArray<PipelineStage<Task, unknown, unknown>>) => CombinatorShape<Task, D>;
694
- /**
695
- * `fanout(items, { synthesize? })` — N children spawned in one round (one per item, bounded by
696
- * the conserved pool's fail-closed admission), drained via `scope.next()`, then optionally a
697
- * single SYNTHESIS child over the gathered results. Without `synthesize`, the combinator returns
698
- * the best-valid child via the single-sourced selector (selector≠judge). A round that admitted
699
- * zero children, or whose synthesis child could not be admitted, is a concrete blocker.
700
- *
701
- * No domain: a "research sweep over angles" is `fanout(angles, { synthesize: cite })` under a
702
- * research persona; a "fanout-vote" is `fanout(copies)` with the default selector. The item list
703
- * + the synthesis posture are the SHAPE's args; the prompt that turns an item into work is the
704
- * persona's.
705
- */
706
- interface FanoutOptions<Item, D> {
707
- /** One child task per item: `item` + the index discriminator. The persona's directive/context
708
- * is threaded in by the combinator; this only supplies the per-item discriminator. */
709
- itemTask(item: Item, index: number, ctx: ShapeContext<D>): unknown;
710
- /** Per-item child label (defaults to `item:<index>` in the impl). */
711
- label?(item: Item, index: number): string;
712
- /**
713
- * Optional per-item `AgentSpec` override. When set, each item's child is spawned against the
714
- * returned spec instead of `persona.root` — the seam a heterogeneous fanout uses to give each
715
- * item a DISTINCT executor (e.g. N authored harness profiles, each on its own worktree-CLI
716
- * leaf). Absent ⇒ every item runs against the persona's root spec (the homogeneous default).
717
- */
718
- itemSpec?(item: Item, index: number, ctx: ShapeContext<D>): AgentSpec;
719
- /**
720
- * Optional synthesis over the gathered child results: when present, the combinator spawns ONE
721
- * synthesis child whose task is built from the drained settlements, and its `done` output is
722
- * the deliverable. When absent, the deliverable is the best-valid child via `defaultSelectWinner`.
723
- * The synthesis child is a SEPARATE keystone agent (not a re-rank behind the driver).
724
- */
725
- synthesize?: FanoutSynthesis<D>;
726
- /**
727
- * Winner-selection strategy among the gathered `done` children when there is no `synthesize`.
728
- * Receives the SAME `Iteration[]` the default selector reads (each child's output is its
729
- * `Outcome<D>`), so a strategy is a thin re-sort (smallest-diff, highest-readiness, first-valid
730
- * …) over the candidates — NEVER a re-rank behind a judge. Default = `defaultSelectWinner`
731
- * semantics (best-valid-score, ties→earliest). Mutually exclusive with `synthesize` (a
732
- * synthesis child IS the selection); supplying both is a config error.
733
- */
734
- selectWinner?: FanoutWinnerSelector<D>;
735
- }
736
- /** A winner-selection strategy: argmax/sort over the gathered child iterations (each output is the
737
- * child's `Outcome<D>`), returning the chosen iteration or `undefined` when none qualifies. */
738
- type FanoutWinnerSelector<D> = (iterations: Iteration<unknown, Outcome<D>>[]) => {
739
- readonly output?: Outcome<D> | undefined;
740
- } | undefined;
741
- /** How a fanout's synthesis child is built + read. `synthesisTask` projects the drained child
742
- * settlements into the synthesis child's task; `collect` reads its settled output into the
743
- * deliverable `Outcome<D>`. */
744
- interface FanoutSynthesis<D> {
745
- synthesisTask(gathered: ReadonlyArray<Settled<Outcome<D>>>, ctx: ShapeContext<D>): unknown;
746
- collect(settled: Settled<Outcome<D>>): Outcome<D>;
747
- }
748
- /** `fanout(items, opts)` — build the fanout combinator over a static item list. */
749
- type Fanout = <Task, Item, D>(items: ReadonlyArray<Item>, opts: FanoutOptions<Item, D>) => CombinatorShape<Task, D>;
750
- /**
751
- * `loopUntil({ until, step })` — iterative deepening inside the conserved pool: spawn one `step`
752
- * child per round, ask `until` whether the accumulated state satisfies the goal, and stop when it
753
- * does OR when the pool can no longer admit a step (budget IS the loop bound — no unbounded
754
- * while). The deployable, non-oracle stop: `until` is the satisfiability gate, read from trace
755
- * findings + accumulated deliverables, never a fresh raw verdict the loop minted to stop itself.
756
- *
757
- * No domain: "refine until tests pass" is `loopUntil` with a coder persona + a `step` that edits
758
- * and an `until` that reads the test-finding; the combinator owns only the round/stop wiring.
759
- */
760
- interface LoopUntilSpec<Task, State, D> {
761
- /** Build the next step child's task from the root task + the state accumulated so far. */
762
- step(rootTask: Task, state: LoopUntilState<State>, ctx: ShapeContext<D>): unknown;
763
- /** Fold one settled step into the accumulated state (the loop's running deliverable candidate). */
764
- fold(prior: LoopUntilState<State>, settled: Settled<Outcome<D>>): LoopUntilState<State>;
765
- /**
766
- * The satisfiability gate: given the accumulated state + the round's trace findings, has the
767
- * goal been reached? Returns the terminal deliverable when satisfied, or `null` to keep going.
768
- * Reads `findings` (trace-derived), NOT a raw verdict score — the deployable-stop discipline.
769
- */
770
- until(state: LoopUntilState<State>, findings: ReadonlyArray<AnalystFinding>): Outcome<D> | null;
771
- /** Per-round step label (defaults to `step:<round>` in the impl). */
772
- label?(round: number): string;
773
- }
774
- /** The accumulated state `loopUntil` threads across rounds — the running candidate + the round
775
- * index, so `step`/`fold`/`until` are pure functions of it (replay-safe, no wall-clock). */
776
- interface LoopUntilState<State> {
777
- readonly round: number;
778
- readonly value: State;
779
- }
780
- /** `loopUntil(spec)` — build the iterative-deepening combinator. `seed` is the initial state. */
781
- type LoopUntil = <Task, State, D>(seed: State, spec: LoopUntilSpec<Task, State, D>) => CombinatorShape<Task, D>;
782
- /**
783
- * `panel(judges)` — M judges over ONE artifact, merged WRITE-ONLY (selector≠judge taken to its
784
- * limit). The combinator spawns the M judge children over the same input artifact, drains their
785
- * settlements, and MERGES their findings into a panel verdict via `merge` — a pure WRITE-ONLY
786
- * fold (a judge's output is never fed back to steer another judge, and the merge never re-ranks
787
- * the children behind the driver). The merged verdict gates the deliverable.
788
- *
789
- * No domain: a "code review panel" and an "essay rubric panel" are the same `panel` shape under
790
- * different personas; the rubric lives in each judge persona's profile, not the combinator.
791
- */
792
- interface PanelSpec<Artifact, D> {
793
- /** The M judge child specs: each is a persona-derived child (a narrower judge profile). The
794
- * combinator spawns one child per entry over the SAME `artifact` and never lets one judge's
795
- * output reach another's task (write-only). */
796
- readonly judges: ReadonlyArray<PanelJudge>;
797
- /** Build one judge child's task from the shared artifact under review + the judge descriptor. */
798
- judgeTask(artifact: Artifact, judge: PanelJudge, ctx: ShapeContext<D>): unknown;
799
- /**
800
- * Write-only merge: fold the M settled judge verdicts into the panel's terminal `Outcome<D>`.
801
- * Pure over the drained settlements — it MUST NOT spawn, re-judge, or feed one verdict into
802
- * another. A panel that reached no quorum is a concrete blocker (fail loud, never a vacuous done).
803
- */
804
- merge(verdicts: ReadonlyArray<PanelVerdict>, artifact: Artifact): Outcome<D>;
805
- }
806
- /** One judge in a panel — a labeled persona-derived judge child. Content (the rubric) lives in
807
- * the judge's profile; this carries only the label + the optional weight the merge may read. */
808
- interface PanelJudge {
809
- readonly label: string;
810
- /** Optional merge weight (a write-only hint the `merge` fold may use; default-equal in the impl). */
811
- readonly weight?: number;
812
- }
813
- /** One judge child's settled verdict, surfaced to the write-only `merge`. `down` judges carry no
814
- * verdict (excluded from the merge `n`, like an infra-errored cell). */
815
- interface PanelVerdict {
816
- readonly judge: PanelJudge;
817
- readonly verdict?: DefaultVerdict;
818
- /** The judge child's raw output — what it was asked to assess, for a merge that quotes it. */
819
- readonly output?: unknown;
820
- /** True when the judge child went `down` (no usable verdict — kept out of the merge denominator). */
821
- readonly down: boolean;
822
- }
823
- /** `panel(spec)` — build the M-judge write-only-merge combinator. */
824
- type Panel = <Task, Artifact, D>(spec: PanelSpec<Artifact, D>) => CombinatorShape<Task, D>;
825
- /**
826
- * `verify({ implement, verifier })` — the 2-node sequential gate: an IMPLEMENT child produces a
827
- * candidate, then a SEPARATE VERIFIER child's verdict GATES shippability. A `valid` verifier
828
- * verdict ships the implement deliverable; any other outcome (implement down, verifier down,
829
- * invalid verdict) becomes a concrete blocker carrying the failure verbatim — never a coerced
830
- * "done". The verifier is a distinct keystone agent (selector≠judge: the implement child does
831
- * not grade itself).
832
- *
833
- * No domain: "write code then run the test gate" and "draft then fact-check" are the same `verify`
834
- * shape under different personas; the gate rubric is the verifier persona's, not the combinator's.
835
- */
836
- interface VerifySpec<Task, Candidate, D> {
837
- /** Build the implement child's task from the root task. */
838
- implement(rootTask: Task, ctx: ShapeContext<D>): unknown;
839
- /** Build the verifier child's task from the implement child's settled candidate. */
840
- verifier(candidate: Settled<Outcome<Candidate>>, ctx: ShapeContext<D>): unknown;
841
- /** Project the gated (verifier-`valid`) candidate into the terminal deliverable. */
842
- collect(candidate: Settled<Outcome<Candidate>>, verdict: DefaultVerdict): Outcome<D>;
843
- /** Implement / verifier child labels (default `implement` / `verify` in the impl). */
844
- readonly implementLabel?: string;
845
- readonly verifierLabel?: string;
846
- }
847
- /** `verify(spec)` — build the 2-node implement→verifier-gate combinator. */
848
- type Verify = <Task, Candidate, D>(spec: VerifySpec<Task, Candidate, D>) => CombinatorShape<Task, D>;
849
- /**
850
- * `widen({ gate })` (G5) — the STREAMING spawn-on-completion driver. Unlike the static-fanout
851
- * combinators above, the widener REACTS to each `scope.next()`: as each child settles it consults
852
- * the `WidenGate` and, when a lineage is `promising`, widens by AT MOST ONE child toward it under
853
- * the remaining conserved pool. Defaults to FLAT (the gate never widens) so a gate run stays
854
- * non-widening and the R2 selector≠judge collision is dormant. `promising` is derived from the
855
- * round's analyst FINDINGS (via `ScopeAnalyst`, §2), NOT a child's raw `verdict` — the firewall.
856
- *
857
- * This is the progressive-widening (MCTS-PW) combinator: the one shape whose breadth is decided
858
- * at runtime from the diagnosis, not fixed at spawn. It is the mechanism the diverse-strategy-vs-
859
- * blind GATE is run with — kept FLAT by default until that gate returns positive (don't build
860
- * mechanism ahead of the gate).
861
- */
862
- interface WidenSpec<Seed, D> {
863
- /** The initial children to spawn before any widening — the seed lineages the gate widens from.
864
- * One child task per seed; bounded by the conserved pool's fail-closed admission. */
865
- readonly seeds: ReadonlyArray<Seed>;
866
- seedTask(seed: Seed, index: number, ctx: ShapeContext<D>): unknown;
867
- /**
868
- * The progressive-widening gate. Consulted on EVERY settled child with the round's
869
- * trace-derived `findings`; returns a widen decision (spawn one more toward a lineage) or a
870
- * stop. DEFAULTS to flat via `flatWidenGate` — never widens, so the firewall stays dormant.
871
- */
872
- readonly gate: ScopeWidenGate<D>;
873
- /** Build the widened child's task from the lineage the gate chose to extend. */
874
- widenTask(toward: WidenLineage<D>, ctx: ShapeContext<D>): unknown;
875
- /** Synthesize the terminal deliverable from every settled lineage (selector≠judge: the
876
- * single-sourced selector over the gathered children, never a re-judge). */
877
- synthesize(gathered: ReadonlyArray<Settled<Outcome<D>>>, ctx: ShapeContext<D>): Outcome<D>;
878
- }
879
- /**
880
- * The runtime widening gate (the reactive analogue of the keystone's `WidenGate`, lifted to read
881
- * trace FINDINGS instead of a raw verdict). `decide` is consulted per settled child; it MUST
882
- * derive `promising` from `findings`, never from `settled.verdict`, unless `judgeExempt` is
883
- * explicitly argued (the documented off-by-default escape hatch). Flat default never widens.
884
- */
885
- interface ScopeWidenGate<D> {
886
- decide(settled: Settled<Outcome<D>>, findings: ReadonlyArray<AnalystFinding>, budget: Scope<Outcome<D>>['budget']): WidenDecision<D>;
887
- /** When true, `decide` may read `settled.verdict` directly — collides with the steer firewall,
888
- * so it must be argued per cell, never defaulted on (mirrors the keystone `WidenGate`). */
889
- readonly judgeExempt?: boolean;
890
- }
891
- /** A widening decision: extend one lineage by one child, or stop widening. `flatWidenGate`
892
- * always returns `{ kind: 'stop' }`. */
893
- type WidenDecision<D> = {
894
- kind: 'widen';
895
- toward: WidenLineage<D>;
896
- } | {
897
- kind: 'stop';
898
- rationale?: string;
899
- };
900
- /** A lineage the gate may widen toward — the settled child that looked promising + the findings
901
- * that justified it (the trace-derived provenance the firewall requires). */
902
- interface WidenLineage<D> {
903
- readonly settled: Extract<Settled<Outcome<D>>, {
904
- kind: 'done';
905
- }>;
906
- readonly findings: ReadonlyArray<AnalystFinding>;
907
- }
908
- /** `widen(spec)` — build the streaming progressive-widening combinator. */
909
- type Widen = <Task, Seed, D>(spec: WidenSpec<Seed, D>) => CombinatorShape<Task, D>;
910
- /** The flat default `ScopeWidenGate` factory contract — never widens, keeping the R2 firewall
911
- * conflict dormant. Exported so a gate run can pass it explicitly and a test can assert the
912
- * default is flat. */
913
- type FlatWidenGate = <D>() => ScopeWidenGate<D>;
914
- /**
915
- * The reactive analyst seam — the PORT of the round-synchronous driver's `analyze` hook
916
- * (dynamic.ts) onto the reactive `Scope`. The old driver wired the analyst at round
917
- * boundaries (`plan` ran the analyst over `history` BEFORE the planner); the reactive `Scope` has
918
- * no rounds, so this carries the wire across: a combinator's `act` asks the `ScopeAnalyst` to turn
919
- * the settled children SO FAR into `AnalystFinding[]`, and steers from THOSE findings.
920
- *
921
- * The firewall is preserved (selector≠judge): `analyze` runs the trace-derived analyst and the
922
- * impl asserts `assertTraceDerivedFindings` semantics — a finding citing judge/verdict/score
923
- * `metric` evidence aborts the round. The steer decision reads `findings`, NEVER the children's
924
- * raw `verdict`. Fail loud — a throwing or non-array analyst aborts (no silent empty findings).
925
- */
926
- interface ScopeAnalyst<D> {
927
- /**
928
- * Turn the children settled so far into trace-derived findings. `settledSoFar` is the cursor-
929
- * ordered settlement list a combinator has drained (the reactive analogue of the old driver's
930
- * `history`). The impl runs the analyst, then enforces the trace-derived firewall before
931
- * returning — a judge-derived finding is rejected, not filtered.
932
- */
933
- analyze(input: ScopeAnalyzeInput<D>): Promise<ReadonlyArray<AnalystFinding>>;
934
- }
935
- /** Input to a `ScopeAnalyst.analyze` — the root task framing + the children settled so far. */
936
- interface ScopeAnalyzeInput<D> {
937
- /** Opaque root-task framing (whatever the combinator was invoked with). */
938
- readonly task: unknown;
939
- /** The children this combinator has drained off `scope.next()`, in cursor order. */
940
- readonly settledSoFar: ReadonlyArray<Settled<Outcome<D>>>;
941
- /** This combinator's scope id (the trace-correlation root for the analyst). */
942
- readonly nodeId: NodeId;
943
- }
944
- /**
945
- * How a combinator's `act` consumes findings to steer — the SINGLE firewalled steer surface a
946
- * reactive combinator reads. `loopUntil.until`, `widen` gate, and any future steer all funnel
947
- * through a `SteerContext` so the firewall is enforced in one place: `findings` is trace-derived
948
- * (the analyst already asserted it), and a combinator MUST NOT reach back to `settled.verdict`
949
- * for the steer decision. `lastValidScore` is provided for OBSERVABILITY only (rendering/traces),
950
- * explicitly NOT for steering — reading it to steer is the coupling the architecture forbids.
951
- */
952
- interface SteerContext<D> {
953
- readonly findings: ReadonlyArray<AnalystFinding>;
954
- readonly settledSoFar: ReadonlyArray<Settled<Outcome<D>>>;
955
- /** Observability-only: the best valid score seen so far. Rendering/trace use ONLY — steering
956
- * off this re-introduces selector=judge. Marked so a reviewer catches a misuse. */
957
- readonly lastValidScore?: number;
958
- }
959
- /**
960
- * The firewall assertion contract, re-stated for the reactive seam (PORT of
961
- * `assertTraceDerivedFindings`). A PROVENANCE check, not a content check: span/event/artifact/
962
- * finding refs and empty-evidence findings pass; only a `metric` ref whose uri is a
963
- * judge/verdict/score scheme is rejected. Fail loud — a tainted finding aborts. The impl lives in
964
- * `analyst.ts`; this type pins its signature so callers depend on the contract, not the impl.
965
- */
966
- type AssertTraceDerivedFindings = (findings: ReadonlyArray<AnalystFinding>) => void;
967
- /**
968
- * One accreted fact in the cross-run corpus — the learning-flywheel's durable unit. DISTINCT from
969
- * a `SpawnEvent` (a per-run decision record): a `CorpusRecord` is a fact a run LEARNED that a
970
- * FUTURE run should read back (the world-model for story 5). It is content the next persona reads,
971
- * not a replay input. Tagged + scored so `query`/`renderCorpusToInstructions` can project the
972
- * relevant, high-confidence subset.
973
- */
974
- interface CorpusRecord {
975
- readonly schemaVersion: '1.0.0';
976
- /** Stable id over identity-defining fields (claim + tags) so a re-learned fact dedups. */
977
- readonly id: string;
978
- /** The run that produced this fact (the journal `runId`/`root`) — provenance back to the trace. */
979
- readonly runId: NodeId;
980
- readonly producedAt: string;
981
- /** Coarse classification the query/render filters on (free-form, mirrors `AnalystFinding.area`). */
982
- readonly area: string;
983
- /** The accreted fact — the instruction-shaped statement the next run reads back. */
984
- readonly claim: string;
985
- /** Optional supporting detail the renderer may include under the claim. */
986
- readonly rationale?: string;
987
- /** Free-form tags for `query` filtering (domain, persona, surface). */
988
- readonly tags: ReadonlyArray<string>;
989
- /** 0..1 — the producing run's confidence in this fact (the render threshold reads it). */
990
- readonly confidence: number;
991
- /** Optional provenance back into the run that learned it (a finding id / outRef / span). */
992
- readonly evidence?: ReadonlyArray<{
993
- readonly kind: string;
994
- readonly uri: string;
995
- }>;
996
- }
997
- /** A corpus query filter — every field is an AND-narrowing; an omitted field does not constrain. */
998
- interface CorpusFilter {
999
- readonly area?: string;
1000
- /** Match records carrying ALL of these tags. */
1001
- readonly tags?: ReadonlyArray<string>;
1002
- /** Minimum confidence a record must clear to be returned (the render gate). */
1003
- readonly minConfidence?: number;
1004
- /** Only records from this run (rare — usually a cross-run read). */
1005
- readonly runId?: NodeId;
1006
- /** Cap the result count (most-confident first in the impl). */
1007
- readonly limit?: number;
1008
- }
1009
- /**
1010
- * The durable cross-run corpus — the learning-flywheel store. DISTINCT from `SpawnJournal`
1011
- * (per-run decisions, replay) and `ResultBlobStore` (per-run payloads): `Corpus` holds accreted
1012
- * FACTS across runs that the next run reads back. `InMemoryCorpus` + `FileCorpus` (JSONL) impls
1013
- * live in `corpus.ts` and MAY share a storage spine with the JSONL journal, but the INTERFACE is
1014
- * separate so a consumer never confuses a replay record with a learned fact.
1015
- *
1016
- * Fail-loud, typed-outcome boundary: `append` is idempotent on an identical record (same `id` +
1017
- * `claim`); a conflicting re-append under the same `id` is a typed error, never a silent overwrite.
1018
- */
1019
- interface Corpus {
1020
- /** Append one accreted fact. Idempotent on an identical record; returns a typed outcome —
1021
- * inspect `succeeded` before treating it as durable (no silent write-through on conflict). */
1022
- append(record: CorpusRecord): Promise<{
1023
- succeeded: true;
1024
- } | {
1025
- succeeded: false;
1026
- error: string;
1027
- }>;
1028
- /** Query accreted facts by filter — most-confident first. Returns the matching records (an
1029
- * empty array when none match is a valid result, NOT an error). */
1030
- query(filter: CorpusFilter): Promise<ReadonlyArray<CorpusRecord>>;
1031
- }
1032
- /**
1033
- * Project accreted corpus facts into an `AgentProfile`'s instruction seams — the learning-flywheel
1034
- * READ side. Reads the corpus through `filter`, renders the matching facts into instruction lines,
1035
- * and returns a NEW profile with them merged into `prompt.instructions` (the append-line seam) so
1036
- * the next run's persona reads the accreted world-model. Pure projection over the queried records;
1037
- * never mutates the input profile (returns a fresh one). The impl lives in `corpus.ts`.
1038
- *
1039
- * `resources.instructions` is `string | AgentProfileResourceRef`; `prompt.instructions` is
1040
- * `string[]`. The render targets `prompt.instructions` (additive lines) by default; a caller that
1041
- * wants the single-blob `resources.instructions` form passes `target: 'resources'`.
1042
- */
1043
- interface RenderCorpusToInstructionsOptions {
1044
- readonly corpus: Corpus;
1045
- readonly filter: CorpusFilter;
1046
- /** The profile to project the facts into. The result is a fresh profile — the input is unchanged. */
1047
- readonly profile: AgentProfile;
1048
- /** Where the rendered facts land: appended to `prompt.instructions[]` (default) or folded into
1049
- * the single-blob `resources.instructions` string. */
1050
- readonly target?: 'prompt' | 'resources';
1051
- /** Optional cap on rendered lines (most-confident first), independent of the query `limit`. */
1052
- readonly maxLines?: number;
1053
- }
1054
- /** `renderCorpusToInstructions(opts)` — the flywheel read-back projection. Async (queries the
1055
- * durable corpus); returns a fresh `AgentProfile` with the accreted facts merged in. */
1056
- type RenderCorpusToInstructions = (opts: RenderCorpusToInstructionsOptions) => Promise<AgentProfile>;
1057
- /**
1058
- * One node in the reconstructed trajectory tree — a driver OR a leaf, with its OWN spend and the
1059
- * spend ROLLED UP over its subtree. Reconstructed from the `SpawnJournal` (structure + per-node
1060
- * `Spend`) + the `ResultBlobStore` (the `out` artifact, rehydrated by `outRef`). The realized tree
1061
- * shape: `parent`/`children` are the actual spawn edges the run took, not a planned topology.
1062
- */
1063
- interface TrajectoryNode {
1064
- readonly id: NodeId;
1065
- readonly parent?: NodeId;
1066
- readonly children: ReadonlyArray<NodeId>;
1067
- readonly label: string;
1068
- readonly runtime: string;
1069
- /** Terminal status the journal recorded for this node. */
1070
- readonly status: 'done' | 'failed' | 'cancelled' | 'pending';
1071
- /** This node's OWN conserved spend (from its `settled` event). */
1072
- readonly ownSpend: Spend;
1073
- /** This node's spend PLUS every descendant's — the rolled-up subtree cost. The cost a parent
1074
- * "really" consumed inclusive of its children's fanout (the equal-k-on-cost basis). */
1075
- readonly rolledUpSpend: Spend;
1076
- /** The node's verdict, when its settlement carried one (observability — NOT a steer input). */
1077
- readonly verdict?: DefaultVerdict;
1078
- /** The rehydrated output artifact, when `withOutputs` was requested + the blob resolved. */
1079
- readonly output?: unknown;
1080
- readonly outRef?: string;
1081
- }
1082
- /** The whole reconstructed trajectory — the realized tree + its root-rolled-up total. The
1083
- * per-node + rolled-up `Spend` is the evidence both the trace viewer and `equalKOnCost` read. */
1084
- interface TrajectoryReport {
1085
- readonly root: NodeId;
1086
- /** Every node, in cursor/spawn order — the realized tree (`parent`/`children` are the real edges). */
1087
- readonly nodes: ReadonlyArray<TrajectoryNode>;
1088
- /** The root's rolled-up spend — the whole run's conserved total (tokens + usd + iterations + ms). */
1089
- readonly total: Spend;
1090
- /** Count of nodes by terminal status — a quick "how did the tree end" readout. */
1091
- readonly statusCounts: Readonly<Record<TrajectoryNode['status'], number>>;
1092
- }
1093
- /**
1094
- * `trajectoryReport(journal, blobs, root, { withOutputs? })` — reconstruct the whole tree with
1095
- * per-node + rolled-up `Spend`. Reads the journal for structure + spend and (when `withOutputs`)
1096
- * the blob store for each `done` node's artifact. Fail loud on a tree that was never journaled or
1097
- * a `done` node whose blob the store cannot rehydrate (a silent gap would mis-cost the tree). The
1098
- * impl lives in `trajectory.ts`.
1099
- */
1100
- interface TrajectoryReportOptions {
1101
- /** Rehydrate each `done` node's `output` from the blob store. Off by default (cost-only report). */
1102
- readonly withOutputs?: boolean;
1103
- }
1104
- /** `trajectoryReport(...)` — the tree+cost reconstructor. Async (reads journal + optionally blobs). */
1105
- type TrajectoryReportFn = (journal: SpawnJournal, blobs: ResultBlobStore, root: NodeId, options?: TrajectoryReportOptions) => Promise<TrajectoryReport>;
1106
- /**
1107
- * One arm of an equal-k comparison — a labeled trajectory (a `TrajectoryReport` is one arm's whole
1108
- * run). The arm's conserved COST is `report.total` (tokens + usd), which the sandbox executor
1109
- * already reports INCLUSIVE of a leaf's internal sub-agent fanout — so comparing arms on this cost
1110
- * (not raw `iterations`) closes the leaf-fanout confound: a treatment arm whose leaf fanned out
1111
- * internally is charged for that fanout in `total.tokens`/`total.usd`, not hidden behind one
1112
- * iteration count.
1113
- */
1114
- interface EqualKArm {
1115
- readonly label: string;
1116
- readonly report: TrajectoryReport;
1117
- }
1118
- /**
1119
- * The equal-k-on-cost verdict: whether every arm spent within `tolerance` of the others on the
1120
- * CONSERVED cost channels (tokens + usd), so a downstream metric comparison is "at equal k". Per-
1121
- * arm cost is surfaced so a caller can see HOW close. `withinTolerance: false` means the arms are
1122
- * NOT comparable at equal compute — a confound to report, not a result to publish.
1123
- */
1124
- interface EqualKVerdict {
1125
- readonly withinTolerance: boolean;
1126
- /** Per-arm conserved cost (the basis: tokens total + usd). */
1127
- readonly arms: ReadonlyArray<{
1128
- readonly label: string;
1129
- readonly tokens: number;
1130
- readonly usd: number;
1131
- readonly iterations: number;
1132
- }>;
1133
- /** The realized spread on each channel (max − min across arms), for the report. */
1134
- readonly spread: {
1135
- readonly tokens: number;
1136
- readonly usd: number;
1137
- };
1138
- /** The fractional tolerance the check used (spread / median ≤ tolerance per channel). */
1139
- readonly tolerance: number;
1140
- }
1141
- /**
1142
- * `equalKOnCost(arms, { tolerance? })` — assert arms are comparable at EQUAL conserved COST
1143
- * (tokens + usd), NOT raw iteration count. The conserved-pool guarantees `Σk` equal by
1144
- * construction WITHIN one supervised run; this checks it ACROSS arms (separate runs) where the
1145
- * pool cannot, so a cross-arm gate comparison can prove equal compute before claiming a win. The
1146
- * impl lives in `trajectory.ts`. Pure over the reports — no I/O.
1147
- */
1148
- interface EqualKOnCostOptions {
1149
- /** Max fractional spread (spread/median) per channel for arms to count as equal-k. Default in
1150
- * the impl (e.g. 0.05). A tighter tolerance = a stricter equal-compute claim. */
1151
- readonly tolerance?: number;
1152
- }
1153
- /** `equalKOnCost(arms, opts)` — the cross-arm equal-compute check on conserved cost. */
1154
- type EqualKOnCost = (arms: ReadonlyArray<EqualKArm>, options?: EqualKOnCostOptions) => EqualKVerdict;
1155
-
1156
403
  /**
1157
404
  * The third-person observer — the connective tissue that closes the loop.
1158
405
  *
@@ -1315,7 +562,7 @@ interface LoopDispatchOptions<Task, Output, Decision, TScenario extends Scenario
1315
562
  sandboxClient: SandboxClient;
1316
563
  /** Build the per-cell runLoop options from the scenario (+ profile, when
1317
564
  * used with `runProfileMatrix`). */
1318
- toLoopOptions: (scenario: TScenario, profile: AgentProfile$1) => LoopOptionsForDispatch<Task, Output, Decision>;
565
+ toLoopOptions: (scenario: TScenario, profile: AgentProfile) => LoopOptionsForDispatch<Task, Output, Decision>;
1319
566
  /** Map the finished loop to the artifact the judges score. Default:
1320
567
  * `result.winner?.output`. A loop with no winner yields `undefined` (judges
1321
568
  * skip the cell) — but the loop's token usage is STILL reported, so the
@@ -1815,6 +1062,19 @@ declare function buildSteerContext<D>(findings: ReadonlyArray<AnalystFinding>, s
1815
1062
  * names at least one blocker (a shape that cannot finish MUST say why — `blocked([])` throws).
1816
1063
  */
1817
1064
 
1065
+ /**
1066
+ * The single content-free valid-only winner selector. Among the gated-VALID children only
1067
+ * (`verdict.valid === true`), pick by `strategy` — best score / smallest delivered artifact /
1068
+ * earliest — ties broken by earliest index; returns `undefined` when NONE is valid (an ungated
1069
+ * output can never win — the deliverable gate is the point). `sizeOf` (for `'smallest-artifact'`)
1070
+ * reads the child's settled deliverable — the raw value a leaf settles, or the unwrapped `Outcome<D>`
1071
+ * a delegate path produces; a domain passes e.g. patch diff-lines. This is the de-duplicated home of
1072
+ * the selection logic previously copied per role.
1073
+ */
1074
+ declare function selectValidWinner<D>(opts?: {
1075
+ strategy?: WinnerStrategy;
1076
+ sizeOf?: (deliverable: D) => number;
1077
+ }): FanoutWinnerSelector<D>;
1818
1078
  /**
1819
1079
  * `pipeline(stages)` — run the stages in order, feeding each stage's `done` deliverable into the
1820
1080
  * next stage's task. The first stage that ends `blocked` (a child that went down, a child the
@@ -1949,7 +1209,7 @@ declare class FileCorpus implements Corpus {
1949
1209
  * An empty query result returns a fresh COPY of the profile with no instruction change (a valid
1950
1210
  * "nothing learned yet" read, not an error).
1951
1211
  */
1952
- declare function renderCorpusToInstructions(opts: RenderCorpusToInstructionsOptions): Promise<AgentProfile>;
1212
+ declare function renderCorpusToInstructions(opts: RenderCorpusToInstructionsOptions): Promise<AgentProfile$1>;
1953
1213
 
1954
1214
  /**
1955
1215
  * @experimental
@@ -2821,42 +2081,6 @@ declare function pickChampion(means: Record<string, {
2821
2081
  declare function selectChampion(report: BenchmarkReport, fieldOrder: string[], policy: ChampionPolicy, epsilon: number): ChampionPick;
2822
2082
  declare function runStrategyEvolution(cfg: StrategyEvolutionConfig): Promise<EvolutionReport>;
2823
2083
 
2824
- /**
2825
- * @experimental
2826
- *
2827
- * The completion-oracle: **settled ⟺ DELIVERED.**
2828
- *
2829
- * Foreman's one hard lesson (0/18 self-improvement deliverables) — "done" must mean a check
2830
- * PASSED, not the agent's say-so. `gateOnDeliverable` wraps an `Executor` so its settlement
2831
- * is `valid` ONLY when the deliverable check passes. The child still RUNS and settles (its
2832
- * spend is conserved into the pool either way), but a child that ran WITHOUT delivering
2833
- * settles `valid:false` — so a keep-best driver never counts it as done, and a gate never
2834
- * inflates with self-judged wins.
2835
- *
2836
- * Dual-purpose by construction:
2837
- * - product: the agent fleet only advances on real, checked deliverables.
2838
- * - proof: the gate's `valid` is the honest settle — equal-k comparisons can't be gamed by an
2839
- * arm that "ran" without producing the artifact.
2840
- *
2841
- * The check is a DEPLOYABLE oracle — a test command, a state verifier, the commit0 judge —
2842
- * read off the child's output, never the model judging itself. A throwing check is
2843
- * fail-closed (not delivered), never a crash.
2844
- */
2845
-
2846
- interface DeliverableSpec<Out = unknown> {
2847
- /** The deployable check that decides DELIVERED. `settled.valid ⟺ this resolves true`. */
2848
- check: (out: Out) => boolean | Promise<boolean>;
2849
- /** What the spawn was supposed to produce — surfaced in traces/reports. */
2850
- describe?: string;
2851
- }
2852
- /**
2853
- * Wrap an `Executor` so its settlement `valid` reflects the deliverable check, not the
2854
- * inner verdict. Handles both `execute` shapes (one-shot `Promise<ExecutorResult>` and
2855
- * streaming `AsyncIterable<UsageEvent>` + `resultArtifact()`); the check runs once the inner
2856
- * executor has produced its output. The inner `score` is preserved; only `valid` is gated.
2857
- */
2858
- declare function gateOnDeliverable<Out>(inner: Executor<Out>, deliverable: DeliverableSpec<Out>): Executor<Out>;
2859
-
2860
2084
  /**
2861
2085
  * @experimental
2862
2086
  *
@@ -2993,246 +2217,6 @@ declare function spendFromUsageEvents(events: UsageEvent[]): Spend;
2993
2217
  */
2994
2218
  declare function createBudgetPool(root: Budget, now?: () => number): BudgetPool;
2995
2219
 
2996
- /**
2997
- * @experimental
2998
- *
2999
- * The ONE worktree-harness execution core. The physical act — run a supervisor-authored
3000
- * `AgentProfile` on a local coding-harness CLI (claude / codex / opencode) against a fresh git
3001
- * worktree off `repoRoot`, capture the diff, derive the test/typecheck PASS signals, then clean
3002
- * up — lives here ONCE. Two executors adapt it to two ports without re-implementing it:
3003
- * - `createWorktreeCliExecutor` — the `Scope`/`Supervisor` leaf `Executor`.
3004
- * - `createInProcessExecutor` — the `runLoop` `SandboxClient` / coder-delegate path.
3005
- *
3006
- * §1.5 by construction: the authored `profile.prompt.systemPrompt` + `profile.model.default`
3007
- * reach the harness through `harnessInvocation` HERE, so neither port can drop them — the exact
3008
- * bug that existed while the in-process path called `runLocalHarness` with only the task prompt.
3009
- *
3010
- * Lifecycle: `createWorktree` → `harnessInvocation` + `runLocalHarness` → `captureWorktreeDiff`
3011
- * (BEFORE checks, so the patch is the harness's output, not polluted by files a test run writes)
3012
- * → the configured test/typecheck commands in the live worktree → return the result + a `cleanup`
3013
- * the caller invokes at its own teardown point. A throw cleans up before propagating, so a failed
3014
- * run never leaks a worktree.
3015
- */
3016
-
3017
- /** Outcome of one verification command run in the worktree (test or typecheck). */
3018
- interface WorktreeCommandResult {
3019
- /** The shell command line that was run. */
3020
- command: string;
3021
- /** Did the command exit 0? The PASS signal a deliverable gate / coder output reads. */
3022
- passed: boolean;
3023
- /** OS exit code, or `null` when killed before exit. */
3024
- exitCode: number | null;
3025
- /** Combined stdout+stderr (capped) — surfaced in traces for diagnosis. */
3026
- output: string;
3027
- }
3028
- /** The canonical result of one worktree-harness run, projected by each port to its own shape. */
3029
- interface WorktreeHarnessResult {
3030
- /** The branch the worktree was cut on (`delegate/<runId>`). */
3031
- branch: string;
3032
- /** `git diff` of the worktree against its base — the unified patch the harness produced. */
3033
- patch: string;
3034
- /** Shortstat-derived change counts. */
3035
- stats: {
3036
- filesChanged: number;
3037
- insertions: number;
3038
- deletions: number;
3039
- };
3040
- /** The harness subprocess outcome. */
3041
- harness: {
3042
- name: LocalHarness;
3043
- exitCode: number | null;
3044
- timedOut: boolean;
3045
- killedBySignal: NodeJS.Signals | null;
3046
- durationMs: number;
3047
- stdout: string;
3048
- stderr: string;
3049
- };
3050
- /** Verification signals derived in the live worktree (present only when commands were given). */
3051
- checks?: {
3052
- tests?: WorktreeCommandResult;
3053
- typecheck?: WorktreeCommandResult;
3054
- };
3055
- }
3056
- /** The single shell-command-in-worktree runner seam (replaces the per-executor copies). */
3057
- type WorktreeCheckRunner = (opts: {
3058
- command: string;
3059
- cwd: string;
3060
- timeoutMs: number;
3061
- signal?: AbortSignal;
3062
- }) => Promise<{
3063
- exitCode: number | null;
3064
- output: string;
3065
- }>;
3066
-
3067
- /**
3068
- * @experimental
3069
- *
3070
- * The worktree-CLI leaf executor — a supervisor-authored `AgentProfile` driving a local
3071
- * coding-harness CLI (claude / codex / opencode) on its OWN git worktree, surfaced as the open
3072
- * `Executor<Out>` port (`./types`). It is a LEAF executor: it plugs straight into the
3073
- * `Scope`/`Supervisor` recursion and `gateOnDeliverable`, so it IS the canonical recursive path
3074
- * (no `runLoop`/virtual-SandboxInstance shim in between).
3075
- *
3076
- * This is a THIN adapter: the physical act (worktree → profile-aware harness invocation → diff →
3077
- * checks → cleanup) lives ONCE in `runWorktreeHarness` (`../../mcp/worktree-harness`), shared with
3078
- * the `runLoop`/coder-delegate `createInProcessExecutor`. This executor only projects that core's
3079
- * result onto the `Executor` port (artifact + spend) and owns the teardown point. The §1.5 payload
3080
- * (authored systemPrompt + model) reaches the harness inside the core, not here.
3081
- *
3082
- * Token accounting: a harness CLI does not surface usage, so this executor is `budgetExempt: true`
3083
- * — its spend is NOT metered against the conserved pool and its iterations are EXCLUDED from the
3084
- * equal-k arms by construction (mirrors `cliExecutor`).
3085
- */
3086
-
3087
- /** Terminal artifact of one worktree-CLI run — the canonical worktree-harness result (the captured
3088
- * diff + the harness's run record + the derived checks). */
3089
- type WorktreePatchArtifact = WorktreeHarnessResult;
3090
- /** @experimental */
3091
- interface WorktreeCliExecutorOptions {
3092
- /** Absolute path to the git checkout the worktree is cut from. */
3093
- repoRoot: string;
3094
- /** The SUPERVISOR-AUTHORED profile (the §1.5 payload: systemPrompt + model). */
3095
- profile: AgentProfile;
3096
- /** Which local harness CLI drives this leaf (`claude` | `codex` | `opencode`). */
3097
- harness: LocalHarness;
3098
- /** The per-task instruction handed to the harness (composed under the system prompt). */
3099
- taskPrompt: string;
3100
- /** Unique id for the worktree path + branch. Defaults to a fresh UUID. */
3101
- runId?: string;
3102
- /** Override the base ref the worktree is cut from (default `HEAD`). */
3103
- baseRef?: string;
3104
- /** Wall-clock cap per harness subprocess (ms). Default 5 min (the `runLocalHarness` default). */
3105
- harnessTimeoutMs?: number;
3106
- /**
3107
- * Shell command run in the live worktree to derive the tests-PASS signal (e.g. `pnpm test`).
3108
- * Its exit code becomes `artifact.checks.tests.passed`. Omit to skip (no signal derived).
3109
- */
3110
- testCmd?: string;
3111
- /** Shell command run in the live worktree to derive the typecheck-PASS signal (e.g. `pnpm typecheck`). */
3112
- typecheckCmd?: string;
3113
- /** Wall-clock cap per verification command (ms). Default = `harnessTimeoutMs` or 5 min. */
3114
- checkTimeoutMs?: number;
3115
- /** Test seam — inject a git runner so unit tests drive the worktree helpers without git. */
3116
- runGit?: GitRunner;
3117
- /** Test seam — inject the harness runner so unit tests script a `LocalHarnessResult`. */
3118
- runHarness?: typeof runLocalHarness;
3119
- /** Test seam — inject the verification-command runner so unit tests script test/typecheck
3120
- * outcomes without spawning a real shell. Defaults to a `/bin/sh -c` spawn in the worktree. */
3121
- runCommand?: WorktreeCheckRunner;
3122
- }
3123
- /**
3124
- * Build a worktree-CLI leaf `Executor`. Per-spawn (a fresh worktree + abort + teardown each), so a
3125
- * fanout of N profiles = N parallel worktrees that never clobber each other.
3126
- *
3127
- * Fail-loud: an empty `repoRoot`/`harness`/`taskPrompt` throws at construction. `resultArtifact()`
3128
- * before `execute()` resolves throws.
3129
- *
3130
- * @experimental
3131
- */
3132
- declare function createWorktreeCliExecutor(options: WorktreeCliExecutorOptions): Executor<WorktreePatchArtifact>;
3133
-
3134
- /**
3135
- * @experimental
3136
- *
3137
- * `coderDeliverable` — the mechanical coder gate, re-homed as a generic `DeliverableSpec` over
3138
- * the worktree-CLI artifact. It is the ONE place the coder-domain checks reach the generic
3139
- * `gateOnDeliverable` path: a `fanout(createWorktreeCliExecutor)` of authored harness profiles,
3140
- * each `gateOnDeliverable(coderDeliverable(...))`, winner via `defaultSelectWinner`.
3141
- *
3142
- * The checks themselves are NOT re-implemented here — `runCoderChecks` (`../../profiles/coder`)
3143
- * is the single source of the no-op / always-on secret-path floor / forbidden-path / diff-size /
3144
- * test / typecheck logic, shared with `createCoderValidator`. This factory only adapts the
3145
- * `WorktreePatchArtifact` shape (its `checks` carry the test/typecheck PASS signals the executor
3146
- * derived in the live worktree) into the check inputs and returns the boolean the gate consumes.
3147
- *
3148
- * Test/typecheck enforcement is OPT-IN per `require`: when a command was not run in the worktree
3149
- * (the executor's `testCmd`/`typecheckCmd` were omitted) the corresponding signal is treated as
3150
- * passed UNLESS `require` lists it — so a gate that demands a tests-pass on an artifact that never
3151
- * ran tests fails closed (the honest outcome) rather than passing on a missing signal.
3152
- */
3153
-
3154
- /** @experimental */
3155
- interface CoderDeliverableOptions extends CoderCheckConstraints {
3156
- /**
3157
- * Which verification signals the gate REQUIRES to be present-and-passing. A required signal
3158
- * that the artifact never derived (the command was not configured on the executor) fails the
3159
- * gate closed. Unlisted signals default to passed-when-absent (the executor simply didn't run
3160
- * that command). Default `[]` — gate on no-op / secret / forbidden / diff-size only.
3161
- */
3162
- require?: ReadonlyArray<'tests' | 'typecheck'>;
3163
- }
3164
- /**
3165
- * Build the coder `DeliverableSpec<WorktreePatchArtifact>`: `check(artifact)` runs the shared
3166
- * mechanical gate (`runCoderChecks`) over the captured patch + the worktree-derived pass signals
3167
- * and returns whether the patch is DELIVERED (the `valid` conjunction).
3168
- *
3169
- * @experimental
3170
- */
3171
- declare function coderDeliverable(options?: CoderDeliverableOptions): DeliverableSpec<WorktreePatchArtifact>;
3172
-
3173
- /**
3174
- * @experimental
3175
- *
3176
- * `worktreeCoderFanout` — the GENERIC coding combinator: a `fanout` of N supervisor-authored
3177
- * harness profiles, each on its OWN worktree-CLI leaf, each `gateOnDeliverable(coderDeliverable)`,
3178
- * winner via `defaultSelectWinner` (or a thin re-sort strategy). It is the canonical replacement
3179
- * for the role-coupled multi-harness coder driver: no `runLoop` driver, no `multiHarnessCoderFanout`
3180
- * harness-list config — the harness list is the fanout's item list, the §1.5 profile is authored
3181
- * per item, and the mechanical gate is the re-homed `coderDeliverable`.
3182
- *
3183
- * The shape is content-free at the `fanout` layer; this builder only assembles the coder-domain
3184
- * pieces (the worktree-CLI executor + the coder deliverable + the diff/readiness selectors) into
3185
- * the generic combinator's `itemSpec`/`selectWinner` seams. Nothing here re-implements selection,
3186
- * gating, or fanout — it composes the existing primitives.
3187
- */
3188
-
3189
- /** @experimental One authored harness profile in a coder fanout: the §1.5 profile + which local
3190
- * harness CLI drives it. The supervisor authors `profile` per sub-task; `harness` chooses the leaf. */
3191
- interface AuthoredCoderHarness {
3192
- /** A short label for the worktree branch + trace node. */
3193
- name: string;
3194
- /** The supervisor-authored `AgentProfile` (systemPrompt + model reach the harness via §1.5). */
3195
- profile: AgentProfile;
3196
- /** Which local harness CLI drives this leaf. */
3197
- harness: 'claude' | 'codex' | 'opencode';
3198
- /** Per-harness model/runId/baseRef overrides flow through the profile + these. */
3199
- runId?: string;
3200
- baseRef?: string;
3201
- }
3202
- /** @experimental Winner-selection among the gated coder candidates. `highest-score` is the
3203
- * `defaultSelectWinner` default; the rest are thin re-sorts over the same iterations. */
3204
- type CoderWinnerStrategy = 'highest-score' | 'smallest-diff' | 'first-valid';
3205
- /** @experimental */
3206
- interface WorktreeCoderFanoutOptions extends CoderDeliverableOptions {
3207
- /** Absolute path to the git checkout each worktree is cut from. */
3208
- repoRoot: string;
3209
- /** The per-task instruction handed to every harness (composed under each profile's systemPrompt). */
3210
- taskPrompt: string;
3211
- /** The authored harness profiles — one fanout item (and one worktree-CLI leaf) each. */
3212
- harnesses: ReadonlyArray<AuthoredCoderHarness>;
3213
- /** Shell command run in each worktree to derive the tests-PASS signal. */
3214
- testCmd?: string;
3215
- /** Shell command run in each worktree to derive the typecheck-PASS signal. */
3216
- typecheckCmd?: string;
3217
- /** Wall-clock cap per harness subprocess (ms). */
3218
- harnessTimeoutMs?: number;
3219
- /** Winner-selection strategy. Default `highest-score`. */
3220
- winnerStrategy?: CoderWinnerStrategy;
3221
- /** Test seams forwarded to every worktree-CLI leaf (inject git/harness/command runners so the
3222
- * whole fanout runs offline). Production callers leave these unset. */
3223
- runGit?: WorktreeCliExecutorOptions['runGit'];
3224
- runHarness?: WorktreeCliExecutorOptions['runHarness'];
3225
- runCommand?: WorktreeCliExecutorOptions['runCommand'];
3226
- }
3227
- /**
3228
- * Build the coder fanout combinator. Run it with `runPersonified({ persona, shape, task, budget })`
3229
- * — equal-k holds by construction (the conserved budget pool bounds the N leaves), and selection is
3230
- * the single-sourced `defaultSelectWinner` (or a thin re-sort), never a judge.
3231
- *
3232
- * @experimental
3233
- */
3234
- declare function worktreeCoderFanout<Task>(options: WorktreeCoderFanoutOptions): CombinatorShape<Task, WorktreePatchArtifact>;
3235
-
3236
2220
  /**
3237
2221
  * @experimental
3238
2222
  *
@@ -4070,4 +3054,4 @@ declare function runInWorkspace<T>(ws: Workspace, body: (cwd: string) => Promise
4070
3054
  commitOnInvalid?: boolean;
4071
3055
  }): Promise<WorkspaceRun<T>>;
4072
3056
 
4073
- export { Agent, AgentRunSpec, AgentSpec, type AgenticOptions, type AgenticRunResult, type AgenticSurface, type AgenticTask, type AgenticTool, type AnytimeReport, type AnytimeStrategySummary, type AnytimeTaskCurve, type ArtifactHandle, type AssertTraceDerivedFindings, type AuditIntentInput, type AuditIntentOptions, type AuthorStrategyOptions, type AuthoredCoderHarness, type AuthoredProfile, type AuthoredStrategy, type BenchmarkCell, type BenchmarkConfig, type BenchmarkLift, type BenchmarkReport, type BenchmarkStrategySummary, type BenchmarkTaskRow, type BridgeSeam, Budget, type BudgetPool, type BudgetReadout, type ChampionPick, type ChampionPolicy, type CheckpointCapableBox, type CliSeam, type CliWorktreeSeam, type CoderDeliverableOptions, type CoderWinnerStrategy, type CombinatorShape, type CompletionAnalyst, type CompletionEvidence, type CompletionPolicy, type CompletionVerdict, type CoordinationDriverOptions, type CoordinationMcpHandle, type Corpus, type CorpusFilter, type CorpusRecord, type CreateScopeAnalystOptions, type CriuCapableClient, type DefinePersona, type DefinePersonaInput, type Deliverable, type DeliverableSpec, type DriverChat, type DriverMessage, type DriverToolCall, type DriverTurn, type Environment, type EqualKArm, type EqualKOnCost, type EqualKOnCostOptions, type EqualKVerdict, type EvolutionArchiveNode, type EvolutionAuthor, type EvolutionBandInfo, type EvolutionCandidate, type EvolutionGeneration, type EvolutionReport, ExecCtx, Executor, type ExecutorConfig, ExecutorFactory, ExecutorRegistry, type Fanout, type FanoutOptions, type FanoutSynthesis, type FanoutWinnerSelector, FileCorpus, FileResultBlobStore, FileSpawnJournal, type FlatWidenGate, type ForkCapableBox, type GitWorkspaceOptions, type HarvestCorpusOptions, type HarvestFailure, type HarvestReport, InMemoryCorpus, InMemoryResultBlobStore, InMemorySpawnJournal, type Inbox, type InboxMessage, type IntentAudit, Iteration, type LoopDispatchOptions, type LoopOptionsForDispatch, LoopResult, type LoopShape, LoopTokenUsage, type LoopUntil, type LoopUntilSpec, type LoopUntilState, type McpEndpoint, type McpEnvironmentOptions, type NestedScopeSeam, NodeId, type Observation, type ObserveInput, type ObserveOptions, type OpenSandboxRunOptions, type Outcome, type Panel, type PanelJudge, type PanelSpec, type PanelVerdict, type Persona, type PersonaContext, type PersonaExecutors, type Pipeline, type PipelineStage, type PromotionGateOptions, type PromotionVerdict, type RegistryAnalyzeProjection, type RenderCorpusToInstructions, type RenderCorpusToInstructionsOptions, type ReservationTicket, ResultBlobStore, RootHandle, RouterConfig, type RouterSeam, type RouterToolsSeam, type RunAgenticOptions, RunLoopOptions, type RunPersonified, type RunPersonifiedOptions, type SandboxCapabilities, SandboxClient, type SandboxLineage, type SandboxLineageHandle, type SandboxRun, type SandboxSeam, Scope, type ScopeAnalyst, type ScopeAnalyzeInput, type ScopeWidenGate, type SessionCapableBox, type SessionMessageLike, type SessionTraceBox, Settled, type ShapeBudget, type ShapeContext, type ShapeRegistry, type Shell, type ShotPersona, type ShotSpec, SpawnEvent, SpawnJournal, Spend, type SteerContext, type Strategy, type StrategyCtx, type StrategyEvolutionConfig, type StrategyResult, SupervisedResult, Supervisor, type SurfaceScore, type ToolPartDecoder, ToolSpec, type ToolStepInput, type TraceSource, type TrajectoryAnalysis, type TrajectoryNode, type TrajectoryReport, type TrajectoryReportFn, type TrajectoryReportOptions, TreeView, type TurnResult, UsageEvent, type UsageSink, type VerifierEnvironmentOptions, type Verify, type VerifySpec, type WatchTraceOptions, type WaterfallCollector, type WaterfallReport, type WaterfallSpan, type Widen, type WidenDecision, type WidenLineage, type WidenSpec, type Workspace, type WorkspaceCommit, type WorkspaceRun, type WorktreeCliExecutorOptions, type WorktreeCoderFanoutOptions, type WorktreeCommandResult, type WorktreePatchArtifact, acquireSandbox, adaptiveRefine, analyzeTrace, anytimeReport, asAuthoredProfile, assertStrategyContract, assertTraceDerivedFindings, auditIntent, authorStrategy, authoredWorker, breadthDriver, buildSteerContext, builtinShapes, cliWorktreeExecutor, coderDeliverable, completionAuthorizes, contentAddress, coordinationDriverAgent, createBudgetPool, createExecutor, createExecutorRegistry, createInbox, createMcpEnvironment, createPartsTraceSource, createPushTraceSource, createRootHandle, createSandboxLineage, createScope, createScopeAnalyst, createShapeRegistry, createSupervisor, createVerifierEnvironment, createWaterfallCollector, createWorktreeCliExecutor, decodeAnthropicPart, decodeOpenAiPart, decodeOpencodePart, decodeToolPart, defaultAnalystInstruction, defaultAuditorInstruction, defaultToolDetectors, definePersona, defineStrategy, depthDriver, deterministicCompletion, discriminatingMeans, driverChild, driverExecutorFactory, driverRuntime, equalKOnCost, extractLlmCallEvent, fanout, flatWidenGate, gateOnDeliverable, gitWorkspace, harvestCorpus, inlineSandboxClient, isDriverSpec, jjWorkspace, localShell, loopDispatch, loopUntil, mapSandboxEvent, materializeTreeView, nestedScopeSeamKey, observe, openSandboxRun, panel, pickChampion, pipeline, printBenchmarkReport, probeSandboxCapabilities, promotionGate, refine, registerShape, registryScopeAnalyst, renderAnytimeTable, renderCorpusToInstructions, renderReport, replaySpawnTree, reportLoopUsage, routerDriverChat, runAgentic, runBenchmark, runInWorkspace, runPersonified, runStrategyEvolution, sample, sampleThenRefine, sandboxSessionTraceSource, selectChampion, sentinelCompletion, serveCoordinationMcp, settledToIteration, spendFromUsageEvents, stopSentinel, strategyAuthorContract, supervisorSkill, toToolSpan, toolPartDecoders, trajectoryReport, verify, watchTrace, widen, withDriverExecutor, worktreeCoderFanout };
3057
+ export { Agent, AgentRunSpec, AgentSpec, type AgenticOptions, type AgenticRunResult, type AgenticSurface, type AgenticTask, type AgenticTool, type AnytimeReport, type AnytimeStrategySummary, type AnytimeTaskCurve, type ArtifactHandle, AssertTraceDerivedFindings, type AuditIntentInput, type AuditIntentOptions, type AuthorStrategyOptions, type AuthoredProfile, type AuthoredStrategy, type BenchmarkCell, type BenchmarkConfig, type BenchmarkLift, type BenchmarkReport, type BenchmarkStrategySummary, type BenchmarkTaskRow, type BridgeSeam, Budget, type BudgetPool, type BudgetReadout, type ChampionPick, type ChampionPolicy, type CheckpointCapableBox, type CliSeam, type CliWorktreeSeam, CombinatorShape, type CompletionAnalyst, type CompletionEvidence, type CompletionPolicy, type CompletionVerdict, type CoordinationDriverOptions, type CoordinationMcpHandle, Corpus, CorpusFilter, CorpusRecord, type CreateScopeAnalystOptions, type CriuCapableClient, DefinePersonaInput, type Deliverable, DeliverableSpec, type DriverChat, type DriverMessage, type DriverToolCall, type DriverTurn, type Environment, EqualKArm, EqualKOnCostOptions, EqualKVerdict, type EvolutionArchiveNode, type EvolutionAuthor, type EvolutionBandInfo, type EvolutionCandidate, type EvolutionGeneration, type EvolutionReport, ExecCtx, type ExecutorConfig, ExecutorFactory, ExecutorRegistry, FanoutOptions, FanoutWinnerSelector, FileCorpus, FileResultBlobStore, FileSpawnJournal, type ForkCapableBox, type GitWorkspaceOptions, type HarvestCorpusOptions, type HarvestFailure, type HarvestReport, InMemoryCorpus, InMemoryResultBlobStore, InMemorySpawnJournal, type Inbox, type InboxMessage, type IntentAudit, Iteration, type LoopDispatchOptions, type LoopOptionsForDispatch, LoopResult, LoopShape, LoopTokenUsage, LoopUntilSpec, type McpEndpoint, type McpEnvironmentOptions, type NestedScopeSeam, NodeId, type Observation, type ObserveInput, type ObserveOptions, type OpenSandboxRunOptions, Outcome, PanelSpec, Persona, PipelineStage, type PromotionGateOptions, type PromotionVerdict, type RegistryAnalyzeProjection, RenderCorpusToInstructionsOptions, type ReservationTicket, ResultBlobStore, RootHandle, RouterConfig, type RouterSeam, type RouterToolsSeam, type RunAgenticOptions, RunLoopOptions, RunPersonifiedOptions, type SandboxCapabilities, SandboxClient, type SandboxLineage, type SandboxLineageHandle, type SandboxRun, type SandboxSeam, Scope, ScopeAnalyst, ScopeAnalyzeInput, ScopeWidenGate, type SessionCapableBox, type SessionMessageLike, type SessionTraceBox, Settled, ShapeRegistry, type Shell, type ShotPersona, type ShotSpec, SpawnEvent, SpawnJournal, Spend, SteerContext, type Strategy, type StrategyCtx, type StrategyEvolutionConfig, type StrategyResult, SupervisedResult, Supervisor, type SurfaceScore, type ToolPartDecoder, ToolSpec, type ToolStepInput, type TraceSource, type TrajectoryAnalysis, TrajectoryReport, TrajectoryReportOptions, TreeView, type TurnResult, UsageEvent, type UsageSink, type VerifierEnvironmentOptions, VerifySpec, type WatchTraceOptions, type WaterfallCollector, type WaterfallReport, type WaterfallSpan, WidenSpec, WinnerStrategy, type Workspace, type WorkspaceCommit, type WorkspaceRun, acquireSandbox, adaptiveRefine, analyzeTrace, anytimeReport, asAuthoredProfile, assertStrategyContract, assertTraceDerivedFindings, auditIntent, authorStrategy, authoredWorker, breadthDriver, buildSteerContext, builtinShapes, cliWorktreeExecutor, completionAuthorizes, contentAddress, coordinationDriverAgent, createBudgetPool, createExecutor, createExecutorRegistry, createInbox, createMcpEnvironment, createPartsTraceSource, createPushTraceSource, createRootHandle, createSandboxLineage, createScope, createScopeAnalyst, createShapeRegistry, createSupervisor, createVerifierEnvironment, createWaterfallCollector, decodeAnthropicPart, decodeOpenAiPart, decodeOpencodePart, decodeToolPart, defaultAnalystInstruction, defaultAuditorInstruction, defaultToolDetectors, definePersona, defineStrategy, depthDriver, deterministicCompletion, discriminatingMeans, driverChild, driverExecutorFactory, driverRuntime, equalKOnCost, extractLlmCallEvent, fanout, flatWidenGate, gitWorkspace, harvestCorpus, inlineSandboxClient, isDriverSpec, jjWorkspace, localShell, loopDispatch, loopUntil, mapSandboxEvent, materializeTreeView, nestedScopeSeamKey, observe, openSandboxRun, panel, pickChampion, pipeline, printBenchmarkReport, probeSandboxCapabilities, promotionGate, refine, registerShape, registryScopeAnalyst, renderAnytimeTable, renderCorpusToInstructions, renderReport, replaySpawnTree, reportLoopUsage, routerDriverChat, runAgentic, runBenchmark, runInWorkspace, runPersonified, runStrategyEvolution, sample, sampleThenRefine, sandboxSessionTraceSource, selectChampion, selectValidWinner, sentinelCompletion, serveCoordinationMcp, settledToIteration, spendFromUsageEvents, stopSentinel, strategyAuthorContract, supervisorSkill, toToolSpan, toolPartDecoders, trajectoryReport, verify, watchTrace, widen, withDriverExecutor };