@llm4ts/flow 3.3.0 → 4.0.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 (161) hide show
  1. package/dist/Bench.d.ts.map +1 -1
  2. package/dist/Bench.js +3 -7
  3. package/dist/Bench.js.map +1 -1
  4. package/dist/CapabilityGuard.d.ts.map +1 -1
  5. package/dist/CapabilityGuard.js +1 -0
  6. package/dist/CapabilityGuard.js.map +1 -1
  7. package/dist/CarriedNotes.d.ts.map +1 -1
  8. package/dist/CarriedNotes.js.map +1 -1
  9. package/dist/Context.d.ts.map +1 -1
  10. package/dist/Context.js +2 -8
  11. package/dist/Context.js.map +1 -1
  12. package/dist/CostTracker.d.ts +1 -1
  13. package/dist/CostTracker.d.ts.map +1 -1
  14. package/dist/CostTracker.js +2 -8
  15. package/dist/CostTracker.js.map +1 -1
  16. package/dist/EstimatedUsage.d.ts.map +1 -1
  17. package/dist/EstimatedUsage.js +4 -3
  18. package/dist/EstimatedUsage.js.map +1 -1
  19. package/dist/Evidence.d.ts.map +1 -1
  20. package/dist/Evidence.js +1 -0
  21. package/dist/Evidence.js.map +1 -1
  22. package/dist/Flow.d.ts +0 -1
  23. package/dist/Flow.d.ts.map +1 -1
  24. package/dist/Flow.js +0 -1
  25. package/dist/Flow.js.map +1 -1
  26. package/dist/FlowEvents.d.ts +98 -20
  27. package/dist/FlowEvents.d.ts.map +1 -1
  28. package/dist/FlowEvents.js +185 -131
  29. package/dist/FlowEvents.js.map +1 -1
  30. package/dist/FlowRecorder.d.ts +1 -1
  31. package/dist/FlowRecorder.d.ts.map +1 -1
  32. package/dist/FlowRecorder.js +4 -10
  33. package/dist/FlowRecorder.js.map +1 -1
  34. package/dist/GateTriage.d.ts +1 -1
  35. package/dist/GateTriage.d.ts.map +1 -1
  36. package/dist/GateTriage.js +1 -1
  37. package/dist/GateTriage.js.map +1 -1
  38. package/dist/Gates.d.ts +0 -1
  39. package/dist/Gates.d.ts.map +1 -1
  40. package/dist/Gates.js +1 -2
  41. package/dist/Gates.js.map +1 -1
  42. package/dist/GraphRules.d.ts +3 -1
  43. package/dist/GraphRules.d.ts.map +1 -1
  44. package/dist/GraphRules.js +2 -0
  45. package/dist/GraphRules.js.map +1 -1
  46. package/dist/JudgmentDataset.d.ts.map +1 -1
  47. package/dist/JudgmentDataset.js +1 -0
  48. package/dist/JudgmentDataset.js.map +1 -1
  49. package/dist/JudgmentEval.d.ts.map +1 -1
  50. package/dist/JudgmentEval.js +1 -0
  51. package/dist/JudgmentEval.js.map +1 -1
  52. package/dist/JudgmentLog.d.ts.map +1 -1
  53. package/dist/JudgmentLog.js +7 -13
  54. package/dist/JudgmentLog.js.map +1 -1
  55. package/dist/JudgmentTypes.d.ts.map +1 -1
  56. package/dist/JudgmentTypes.js +1 -0
  57. package/dist/JudgmentTypes.js.map +1 -1
  58. package/dist/NodePreflight.d.ts.map +1 -1
  59. package/dist/NodePreflight.js +2 -2
  60. package/dist/NodePreflight.js.map +1 -1
  61. package/dist/OracleGuard.d.ts +1 -1
  62. package/dist/OracleGuard.d.ts.map +1 -1
  63. package/dist/OracleGuard.js +2 -1
  64. package/dist/OracleGuard.js.map +1 -1
  65. package/dist/Orientation.d.ts.map +1 -1
  66. package/dist/Orientation.js +3 -5
  67. package/dist/Orientation.js.map +1 -1
  68. package/dist/Pack.d.ts +1 -1
  69. package/dist/Pack.d.ts.map +1 -1
  70. package/dist/Pack.js +0 -1
  71. package/dist/Pack.js.map +1 -1
  72. package/dist/ProgramJudge.d.ts +1 -4
  73. package/dist/ProgramJudge.d.ts.map +1 -1
  74. package/dist/ProgramJudge.js +2 -2
  75. package/dist/ProgramJudge.js.map +1 -1
  76. package/dist/Recheck.d.ts.map +1 -1
  77. package/dist/Recheck.js +1 -0
  78. package/dist/Recheck.js.map +1 -1
  79. package/dist/Retro.d.ts.map +1 -1
  80. package/dist/Retro.js +2 -3
  81. package/dist/Retro.js.map +1 -1
  82. package/dist/ReviewModel.d.ts.map +1 -1
  83. package/dist/ReviewModel.js +1 -0
  84. package/dist/ReviewModel.js.map +1 -1
  85. package/dist/Settings.d.ts +40 -1
  86. package/dist/Settings.d.ts.map +1 -1
  87. package/dist/Settings.js +45 -7
  88. package/dist/Settings.js.map +1 -1
  89. package/dist/Spans.d.ts.map +1 -1
  90. package/dist/Spans.js +2 -4
  91. package/dist/Spans.js.map +1 -1
  92. package/dist/Stories.d.ts.map +1 -1
  93. package/dist/Stories.js +2 -1
  94. package/dist/Stories.js.map +1 -1
  95. package/dist/Survey.d.ts +0 -2
  96. package/dist/Survey.d.ts.map +1 -1
  97. package/dist/Survey.js +1 -2
  98. package/dist/Survey.js.map +1 -1
  99. package/dist/Taskforce.d.ts +1 -1
  100. package/dist/Taskforce.d.ts.map +1 -1
  101. package/dist/Taskforce.js +0 -1
  102. package/dist/Taskforce.js.map +1 -1
  103. package/dist/TestEvidence.d.ts.map +1 -1
  104. package/dist/TestEvidence.js +4 -3
  105. package/dist/TestEvidence.js.map +1 -1
  106. package/dist/Workspace.d.ts.map +1 -1
  107. package/dist/Workspace.js +5 -22
  108. package/dist/Workspace.js.map +1 -1
  109. package/dist/settings/Registry.d.ts +5 -5
  110. package/dist/settings/Registry.d.ts.map +1 -1
  111. package/dist/settings/Registry.js +9 -7
  112. package/dist/settings/Registry.js.map +1 -1
  113. package/dist/settings/Value.d.ts +6 -1
  114. package/dist/settings/Value.d.ts.map +1 -1
  115. package/dist/settings/Value.js +9 -3
  116. package/dist/settings/Value.js.map +1 -1
  117. package/package.json +28 -38
  118. package/src/Bench.ts +6 -19
  119. package/src/CapabilityGuard.ts +1 -0
  120. package/src/CarriedNotes.ts +1 -0
  121. package/src/Context.ts +2 -8
  122. package/src/CostTracker.ts +3 -15
  123. package/src/EstimatedUsage.ts +4 -3
  124. package/src/Evidence.ts +1 -0
  125. package/src/Flow.ts +0 -2
  126. package/src/FlowEvents.ts +380 -153
  127. package/src/FlowRecorder.ts +7 -16
  128. package/src/GateTriage.ts +1 -1
  129. package/src/Gates.ts +1 -3
  130. package/src/GraphRules.ts +4 -1
  131. package/src/JudgmentDataset.ts +1 -0
  132. package/src/JudgmentEval.ts +1 -0
  133. package/src/JudgmentLog.ts +7 -18
  134. package/src/JudgmentTypes.ts +1 -0
  135. package/src/NodePreflight.ts +2 -4
  136. package/src/OracleGuard.ts +2 -1
  137. package/src/Orientation.ts +3 -5
  138. package/src/Pack.ts +0 -2
  139. package/src/ProgramJudge.ts +4 -6
  140. package/src/Recheck.ts +1 -0
  141. package/src/Retro.ts +2 -5
  142. package/src/ReviewModel.ts +1 -0
  143. package/src/Settings.ts +66 -8
  144. package/src/Spans.ts +2 -4
  145. package/src/Stories.ts +3 -5
  146. package/src/Survey.ts +1 -2
  147. package/src/Taskforce.ts +0 -2
  148. package/src/TestEvidence.ts +4 -3
  149. package/src/Workspace.ts +7 -24
  150. package/src/settings/Registry.ts +14 -7
  151. package/src/settings/Value.ts +13 -5
  152. package/dist/Classified.d.ts +0 -16
  153. package/dist/Classified.d.ts.map +0 -1
  154. package/dist/Classified.js +0 -52
  155. package/dist/Classified.js.map +0 -1
  156. package/dist/Mermaid.d.ts +0 -7
  157. package/dist/Mermaid.d.ts.map +0 -1
  158. package/dist/Mermaid.js +0 -98
  159. package/dist/Mermaid.js.map +0 -1
  160. package/src/Classified.ts +0 -72
  161. package/src/Mermaid.ts +0 -112
package/src/FlowEvents.ts CHANGED
@@ -1,11 +1,11 @@
1
1
  import * as Context from "effect/Context"
2
2
  import type * as Duration from "effect/Duration"
3
3
  import * as Effect from "effect/Effect"
4
- import * as Option from "effect/Option"
5
4
  import * as Layer from "effect/Layer"
6
5
  import * as PubSub from "effect/PubSub"
7
6
  import * as Ref from "effect/Ref"
8
7
  import * as Schema from "effect/Schema"
8
+ import * as Semaphore from "effect/Semaphore"
9
9
  import type * as Scope from "effect/Scope"
10
10
  import * as Stream from "effect/Stream"
11
11
  import { TokenUsage } from "@llm4ts/core/Models"
@@ -202,10 +202,6 @@ export class EvidenceChecked extends Schema.TaggedClass<EvidenceChecked>()("Evid
202
202
  lane: Schema.optionalKey(Schema.String)
203
203
  }) {}
204
204
 
205
- export class Declassified extends Schema.TaggedClass<Declassified>()("Declassified", {
206
- label: Schema.String
207
- }) {}
208
-
209
205
  /** A blackboard ruleset ran (ADR 0020): its board, trace and failures, for the trace file. */
210
206
  export class BlackboardRun extends Schema.TaggedClass<BlackboardRun>()("BlackboardRun", {
211
207
  ruleset: Schema.String,
@@ -519,7 +515,6 @@ export const FlowEvent = Schema.Union([
519
515
  CapabilityUnenforceable,
520
516
  EvidenceChecked,
521
517
  ReviewFindingDemoted,
522
- Declassified,
523
518
  ExecutorLeased,
524
519
  ExecutorReleased,
525
520
  ExecutorExcluded,
@@ -545,8 +540,7 @@ export const FlowEventsValues = Object.freeze({
545
540
  CapabilityDenied: (capability: string, operation: string): CapabilityDeniedEvent =>
546
541
  new CapabilityDeniedEvent({ capability, operation }),
547
542
  CapabilityUnenforceable: (detail: string): CapabilityUnenforceable =>
548
- new CapabilityUnenforceable({ detail }),
549
- Declassified: (label: string): Declassified => new Declassified({ label })
543
+ new CapabilityUnenforceable({ detail })
550
544
  })
551
545
 
552
546
  export interface FlowEventsShape {
@@ -574,117 +568,251 @@ export const shortenLaneArgs = (args: string, workDir: string | undefined): stri
574
568
  return args.split(`cd ${root} && `).join("").split(`${root}/`).join("")
575
569
  }
576
570
 
577
- const stamped = (
578
- event: FlowEvent,
579
- lane: string,
580
- executor: string | undefined,
581
- workDir: string | undefined,
582
- clone: number | undefined
583
- ): FlowEvent => {
584
- const tags = { lane, ...(executor === undefined ? {} : { executor }) }
585
- const usageTags = { ...tags, ...(clone === undefined ? {} : { clone }) }
586
- switch (event._tag) {
587
- case "TasksPlanned":
588
- return event.lane !== undefined ? event : TasksPlanned.make({ tasks: event.tasks, ...tags })
589
- case "TaskStarted":
590
- return event.lane !== undefined
591
- ? event
592
- : TaskStarted.make({
593
- index: event.index,
594
- count: event.count,
595
- title: event.title,
596
- ...(event.satisfies === undefined ? {} : { satisfies: event.satisfies }),
597
- ...tags,
598
- // A parallel task names its own coder, not the lane's (ADR 0034).
599
- ...(event.parallel === undefined ? {} : { parallel: event.parallel }),
600
- ...(event.executor === undefined ? {} : { executor: event.executor }),
601
- ...(event.clone === undefined ? {} : { clone: event.clone })
602
- })
603
- case "TaskCompleted":
604
- return event.lane !== undefined
605
- ? event
606
- : TaskCompleted.make({
607
- index: event.index,
608
- count: event.count,
609
- title: event.title,
610
- ...tags
611
- })
612
- case "StageStarted":
613
- return event.lane !== undefined ? event : StageStarted.make({ stage: event.stage, ...tags })
614
- case "StageCompleted":
615
- return event.lane !== undefined ? event : StageCompleted.make({ stage: event.stage, ...tags })
616
- case "StageFailed":
617
- return event.lane !== undefined
618
- ? event
619
- : StageFailed.make({ stage: event.stage, message: event.message, ...tags })
620
- case "Info":
621
- return event.lane !== undefined ? event : Info.make({ message: event.message, ...tags })
622
- case "ToolUse":
623
- return event.lane !== undefined
624
- ? event
625
- : ToolUse.make({
626
- tool: event.tool,
627
- args: shortenLaneArgs(event.args, workDir),
628
- ...(event.parent === undefined ? {} : { parent: event.parent }),
629
- ...tags
630
- })
631
- case "AssistantMessage":
632
- return event.lane !== undefined ? event : AssistantMessage.make({ text: event.text, ...tags })
633
- case "ReviewFindings":
634
- return event.lane !== undefined
635
- ? event
636
- : ReviewFindings.make({
637
- round: event.round,
638
- settled: event.settled,
639
- issues: event.issues,
640
- ...tags
641
- })
642
- case "UsageProgress":
643
- return event.lane !== undefined
644
- ? event
645
- : UsageProgress.make({
646
- call: event.call,
647
- ...(event.usage === undefined ? {} : { usage: event.usage }),
648
- ...(event.done === undefined ? {} : { done: event.done }),
649
- ...tags
650
- })
651
- case "TokensUsed":
652
- return event.lane !== undefined
653
- ? event
654
- : TokensUsed.make({
655
- agent: event.agent,
656
- usage: event.usage,
657
- ...(event.model === undefined ? {} : { model: event.model }),
658
- // The lane's clone is its coder's: a reviewer or judge on the
659
- // lane's events ran on another executor (ADR 0033).
660
- ...(event.agent === "coder" ? usageTags : tags)
661
- })
662
- // The lane's executor is its coder's: it names a coder call or tool, not
663
- // a reviewer's or judge's call made on another executor.
664
- case "Timed":
665
- return event.lane !== undefined
666
- ? event
667
- : Timed.make({
668
- ...event,
669
- lane,
670
- ...(executor !== undefined &&
671
- ((event.kind === "model" && event.label === "coder") || event.kind === "tool")
672
- ? { executor }
673
- : {})
674
- })
675
- case "Began":
676
- return event.lane !== undefined
677
- ? event
678
- : Began.make({
679
- ...event,
680
- lane,
681
- ...(executor !== undefined && event.kind === "model" && event.label === "coder"
682
- ? { executor }
683
- : {})
684
- })
685
- default:
686
- return event
571
+ export type FlowEventTag = FlowEvent["_tag"]
572
+ /** Each event class by its tag: what a table keyed by tag is typed over. */
573
+ export type FlowEventByTag = {
574
+ readonly [K in FlowEventTag]: Extract<FlowEvent, { readonly _tag: K }>
575
+ }
576
+ type Tag = FlowEventTag
577
+ type EventOf = FlowEventByTag
578
+
579
+ /** The lane an event is in, and the executor working it when the event names one. */
580
+ export interface LaneRef {
581
+ readonly lane: string
582
+ readonly executor?: string
583
+ }
584
+
585
+ /** What `withLane` knows of its lane when an event passes through it. */
586
+ export interface LaneTags {
587
+ readonly lane: string
588
+ readonly executor: string | undefined
589
+ readonly clone: number | undefined
590
+ readonly workDir: string | undefined
591
+ }
592
+
593
+ /**
594
+ * How an event stands to lanes. `none`: it has no lane. `carried`: its
595
+ * producer names the lane, and `withLane` leaves it alone. `stamped`:
596
+ * `withLane` names the lane on one published without, through `stamp`.
597
+ */
598
+ export interface LaneRule<E> {
599
+ readonly lane: "none" | "carried" | "stamped"
600
+ readonly read?: (event: E) => LaneRef | undefined
601
+ readonly stamp?: (event: E, tags: LaneTags) => E
602
+ }
603
+
604
+ interface Unlaned {
605
+ readonly lane: "none"
606
+ }
607
+ interface Carried<E> {
608
+ readonly lane: "carried"
609
+ readonly read: (event: E) => LaneRef | undefined
610
+ }
611
+ interface Stamped<E> extends Omit<Carried<E>, "lane"> {
612
+ readonly lane: "stamped"
613
+ readonly stamp: (event: E, tags: LaneTags) => E
614
+ }
615
+
616
+ const readLane = (event: {
617
+ readonly lane?: string
618
+ readonly executor?: string
619
+ }): LaneRef | undefined =>
620
+ event.lane === undefined
621
+ ? undefined
622
+ : { lane: event.lane, ...(event.executor === undefined ? {} : { executor: event.executor }) }
623
+
624
+ const unlaned: Unlaned = { lane: "none" }
625
+ const carried: Carried<{ readonly lane?: string }> = { lane: "carried", read: readLane }
626
+ const stamped = <E extends { readonly lane?: string; readonly executor?: string }>(
627
+ stamp: (event: E, tags: LaneTags) => E
628
+ ): Stamped<E> => ({ lane: "stamped", read: readLane, stamp })
629
+
630
+ /** The lane and, when it has one, the executor working it. */
631
+ const seat = (tags: LaneTags): LaneRef => ({
632
+ lane: tags.lane,
633
+ ...(tags.executor === undefined ? {} : { executor: tags.executor })
634
+ })
635
+
636
+ const laneRules = {
637
+ JudgmentObserved: unlaned,
638
+ BlackboardRun: unlaned,
639
+ StageStarted: stamped<StageStarted>((event, tags) =>
640
+ StageStarted.make({ stage: event.stage, ...seat(tags) })
641
+ ),
642
+ StageCompleted: stamped<StageCompleted>((event, tags) =>
643
+ StageCompleted.make({ stage: event.stage, ...seat(tags) })
644
+ ),
645
+ StageFailed: stamped<StageFailed>((event, tags) =>
646
+ StageFailed.make({ stage: event.stage, message: event.message, ...seat(tags) })
647
+ ),
648
+ Aborted: unlaned,
649
+ Info: stamped<Info>((event, tags) => Info.make({ message: event.message, ...seat(tags) })),
650
+ ToolUse: stamped<ToolUse>((event, tags) =>
651
+ ToolUse.make({
652
+ tool: event.tool,
653
+ args: shortenLaneArgs(event.args, tags.workDir),
654
+ ...(event.parent === undefined ? {} : { parent: event.parent }),
655
+ ...seat(tags)
656
+ })
657
+ ),
658
+ AssistantMessage: stamped<AssistantMessage>((event, tags) =>
659
+ AssistantMessage.make({ text: event.text, ...seat(tags) })
660
+ ),
661
+ TokensUsed: stamped<TokensUsed>((event, tags) =>
662
+ TokensUsed.make({
663
+ agent: event.agent,
664
+ usage: event.usage,
665
+ ...(event.model === undefined ? {} : { model: event.model }),
666
+ ...seat(tags),
667
+ // The lane's clone is its coder's: a reviewer or judge on the
668
+ // lane's events ran on another executor (ADR 0033).
669
+ ...(event.agent === "coder" && tags.clone !== undefined ? { clone: tags.clone } : {})
670
+ })
671
+ ),
672
+ UsageProgress: stamped<UsageProgress>((event, tags) =>
673
+ UsageProgress.make({
674
+ call: event.call,
675
+ ...(event.usage === undefined ? {} : { usage: event.usage }),
676
+ ...(event.done === undefined ? {} : { done: event.done }),
677
+ ...seat(tags)
678
+ })
679
+ ),
680
+ ReviewFindings: stamped<ReviewFindings>((event, tags) =>
681
+ ReviewFindings.make({
682
+ round: event.round,
683
+ settled: event.settled,
684
+ issues: event.issues,
685
+ ...(event.diffLines === undefined ? {} : { diffLines: event.diffLines }),
686
+ ...seat(tags)
687
+ })
688
+ ),
689
+ CapabilityUsed: unlaned,
690
+ CapabilityDenied: unlaned,
691
+ CapabilityUnenforceable: unlaned,
692
+ EvidenceChecked: carried,
693
+ ReviewFindingDemoted: carried,
694
+ ExecutorLeased: unlaned,
695
+ ExecutorReleased: unlaned,
696
+ ExecutorExcluded: unlaned,
697
+ ExecutorResumed: unlaned,
698
+ ExecutorHandedOver: unlaned,
699
+ StoryJudged: carried,
700
+ RoundtableTurn: carried,
701
+ BriefReported: carried,
702
+ // The lane's executor is its coder's: it names a coder call or tool, not
703
+ // a reviewer's or judge's call made on another executor.
704
+ Timed: stamped<Timed>((event, tags) =>
705
+ Timed.make({
706
+ ...event,
707
+ lane: tags.lane,
708
+ ...(tags.executor !== undefined &&
709
+ ((event.kind === "model" && event.label === "coder") || event.kind === "tool")
710
+ ? { executor: tags.executor }
711
+ : {})
712
+ })
713
+ ),
714
+ Began: stamped<Began>((event, tags) =>
715
+ Began.make({
716
+ ...event,
717
+ lane: tags.lane,
718
+ ...(tags.executor !== undefined && event.kind === "model" && event.label === "coder"
719
+ ? { executor: tags.executor }
720
+ : {})
721
+ })
722
+ ),
723
+ TasksPlanned: stamped<TasksPlanned>((event, tags) =>
724
+ TasksPlanned.make({ tasks: event.tasks, ...seat(tags) })
725
+ ),
726
+ TaskStarted: stamped<TaskStarted>((event, tags) =>
727
+ TaskStarted.make({
728
+ index: event.index,
729
+ count: event.count,
730
+ title: event.title,
731
+ ...(event.satisfies === undefined ? {} : { satisfies: event.satisfies }),
732
+ ...seat(tags),
733
+ // A parallel task names its own coder, not the lane's (ADR 0034).
734
+ ...(event.parallel === undefined ? {} : { parallel: event.parallel }),
735
+ ...(event.executor === undefined ? {} : { executor: event.executor }),
736
+ ...(event.clone === undefined ? {} : { clone: event.clone })
737
+ })
738
+ ),
739
+ TaskCompleted: stamped<TaskCompleted>((event, tags) =>
740
+ TaskCompleted.make({
741
+ index: event.index,
742
+ count: event.count,
743
+ title: event.title,
744
+ ...seat(tags)
745
+ })
746
+ ),
747
+ StoryStatusChanged: unlaned,
748
+ CriterionChecked: carried,
749
+ Parked: carried
750
+ } satisfies {
751
+ // An event with a `lane` field cannot be declared unlaned, nor the reverse.
752
+ readonly [K in Tag]: "lane" extends keyof EventOf[K]
753
+ ? Carried<EventOf[K]> | Stamped<EventOf[K]>
754
+ : Unlaned
755
+ }
756
+
757
+ /**
758
+ * Every event's standing to lanes. Exhaustive by type: adding an event class
759
+ * without an entry here fails `pnpm typecheck`.
760
+ */
761
+ export const eventLanes: { readonly [K in Tag]: LaneRule<EventOf[K]> } = laneRules
762
+
763
+ // A tag and its event are one value's, so the rule found by the tag takes the
764
+ // event. TypeScript does not correlate the two across the union; reading the
765
+ // rule through a generic key is the step that lets it.
766
+ const ruleOf = <K extends Tag>(tag: K): LaneRule<EventOf[K]> => eventLanes[tag]
767
+
768
+ /** The lane of any event that is in one, and its executor when the event names it. */
769
+ export const laneOf = (event: FlowEvent): LaneRef | undefined => ruleOf(event._tag).read?.(event)
770
+
771
+ const stampedWith = (event: FlowEvent, tags: LaneTags): FlowEvent => {
772
+ const rule = ruleOf(event._tag)
773
+ return rule.stamp === undefined || rule.read?.(event) !== undefined
774
+ ? event
775
+ : rule.stamp(event, tags)
776
+ }
777
+
778
+ export const LaneKind = Schema.Literals(["story", "attendee", "specialist"])
779
+ /** What a lane stands for: a story's coder (ADR 0022), a roundtable attendee (ADR 0046), or a taskforce specialist (ADR 0047). */
780
+ export type LaneKind = typeof LaneKind.Type
781
+
782
+ /** A lane as its opening stage names it. */
783
+ export interface LaneName {
784
+ readonly kind: LaneKind
785
+ readonly id: string
786
+ }
787
+
788
+ const isLaneKind = Schema.is(LaneKind)
789
+ const laneStagePattern = /^(\S+) (.+)$/u
790
+
791
+ /**
792
+ * The lane protocol, read side: a lane opens with a `StageStarted` whose stage
793
+ * is `<kind> <id>` and whose lane is that id (names may hold spaces), and
794
+ * closes when the same stage completes or fails.
795
+ */
796
+ const laneNamed = (stage: string, lane: string | undefined): LaneName | undefined => {
797
+ const [, kind, id] = laneStagePattern.exec(stage) ?? []
798
+ return kind !== undefined && isLaneKind(kind) && id !== undefined && id === lane
799
+ ? { kind, id }
800
+ : undefined
801
+ }
802
+
803
+ /** The lane this event opens, when it is the `StageStarted` that opens one. */
804
+ export const laneOpened = (event: FlowEvent): LaneName | undefined =>
805
+ event._tag === "StageStarted" ? laneNamed(event.stage, event.lane) : undefined
806
+
807
+ /** The lane this event closes, when it is the end of the stage that opened one. */
808
+ export const laneClosed = (
809
+ event: FlowEvent
810
+ ): (LaneName & { readonly failed: boolean }) | undefined => {
811
+ if (event._tag !== "StageCompleted" && event._tag !== "StageFailed") {
812
+ return undefined
687
813
  }
814
+ const named = laneNamed(event.stage, event.lane)
815
+ return named === undefined ? undefined : { ...named, failed: event._tag === "StageFailed" }
688
816
  }
689
817
 
690
818
  /**
@@ -696,7 +824,9 @@ export const withLane = (events: FlowEventsShape, lane: Lane): FlowEventsShape =
696
824
  publish: (event) =>
697
825
  Effect.flatMap(lane.executor ?? Effect.succeed(undefined), (executor) =>
698
826
  Effect.flatMap(lane.clone ?? Effect.succeed(undefined), (clone) =>
699
- events.publish(stamped(event, lane.lane, executor, lane.workDir, clone))
827
+ events.publish(
828
+ stampedWith(event, { lane: lane.lane, executor, clone, workDir: lane.workDir })
829
+ )
700
830
  )
701
831
  )
702
832
  })
@@ -737,10 +867,62 @@ export const makeCollectingFlowEvents: Effect.Effect<CollectingFlowEvents> = Eff
737
867
  })
738
868
  )
739
869
 
870
+ /** How a consumer stands against what the hub published; see `FlowEventHub.drained`. */
871
+ export interface DrainReport {
872
+ /** Every consumer handled every event it was owed, and none joined late. */
873
+ readonly complete: boolean
874
+ /** Consumers still short when the wait ended, and by how many events. */
875
+ readonly behind: ReadonlyArray<{ readonly name: string; readonly missing: number }>
876
+ /**
877
+ * Consumers meant to see the whole run that subscribed after events were
878
+ * published: those events never reached them, however long anyone waits.
879
+ */
880
+ readonly late: ReadonlyArray<{ readonly name: string; readonly missed: number }>
881
+ }
882
+
883
+ export interface FlowEventConsumer {
884
+ readonly name: string
885
+ /** Whether this consumer alone handled everything it was owed, within `timeout`. */
886
+ readonly caughtUp: (timeout?: Duration.Input) => Effect.Effect<boolean>
887
+ }
888
+
889
+ export interface ConsumeOptions {
890
+ /**
891
+ * `start` (the default): the consumer accounts for the whole run, so
892
+ * joining after an event was published is reported by `drained`. `now`:
893
+ * it is owed only what is published from here on.
894
+ */
895
+ readonly from?: "start" | "now"
896
+ }
897
+
740
898
  export interface FlowEventHub extends FlowEventsShape {
741
899
  readonly subscribe: Effect.Effect<PubSub.Subscription<FlowEvent>, never, Scope.Scope>
742
900
  readonly stream: Stream.Stream<FlowEvent>
743
901
  readonly publishedCount: Effect.Effect<number>
902
+ /**
903
+ * Runs `handle` on every event published from here on, in order, on a fiber
904
+ * of the scope. The one consumer loop: the hub counts what each consumer
905
+ * handled, so nobody keeps a counter of their own.
906
+ */
907
+ readonly consume: (
908
+ name: string,
909
+ handle: (event: FlowEvent) => Effect.Effect<void>,
910
+ options?: ConsumeOptions
911
+ ) => Effect.Effect<FlowEventConsumer, never, Scope.Scope>
912
+ /**
913
+ * Waits, at most `timeout`, for every live consumer to handle what it was
914
+ * owed, then says who fell short. A late subscriber ends the wait at once:
915
+ * no wait can bring back what it missed.
916
+ */
917
+ readonly drained: (timeout?: Duration.Input) => Effect.Effect<DrainReport>
918
+ }
919
+
920
+ interface ConsumerState {
921
+ readonly name: string
922
+ /** Events published before this consumer subscribed. */
923
+ readonly baseline: number
924
+ readonly wholeRun: boolean
925
+ readonly handled: Ref.Ref<number>
744
926
  }
745
927
 
746
928
  export const makeFlowEventHub = Effect.fn("@llm4ts/flow/FlowEvents.makeHub")(function* (
@@ -748,6 +930,40 @@ export const makeFlowEventHub = Effect.fn("@llm4ts/flow/FlowEvents.makeHub")(fun
748
930
  ): Effect.fn.Return<FlowEventHub> {
749
931
  const events = yield* PubSub.bounded<FlowEvent>(capacity)
750
932
  const published = yield* Ref.make(0)
933
+ const consumers = yield* Ref.make<ReadonlyArray<ConsumerState>>([])
934
+ // Held across a publish and its count, and across a subscription and the
935
+ // count it reads, so a consumer's baseline is exact: every event counted in
936
+ // it was published before the subscription, every later one reaches it.
937
+ const order = yield* Semaphore.make(1)
938
+
939
+ const missingOf = (consumer: ConsumerState, target: number): Effect.Effect<number> =>
940
+ Effect.map(Ref.get(consumer.handled), (handled) =>
941
+ Math.max(0, target - consumer.baseline - handled)
942
+ )
943
+
944
+ const waitFor = (
945
+ who: Effect.Effect<ReadonlyArray<ConsumerState>>,
946
+ timeout: Duration.Input
947
+ ): Effect.Effect<ReadonlyArray<{ readonly name: string; readonly missing: number }>> =>
948
+ Effect.gen(function* () {
949
+ const target = yield* Ref.get(published)
950
+ const behind = Effect.flatMap(who, (all) =>
951
+ Effect.forEach(all, (consumer) =>
952
+ Effect.map(missingOf(consumer, target), (missing) => ({ name: consumer.name, missing }))
953
+ ).pipe(Effect.map((rows) => rows.filter((row) => row.missing > 0)))
954
+ )
955
+ const poll: Effect.Effect<void> = Effect.suspend(() =>
956
+ Effect.flatMap(behind, (rows) =>
957
+ rows.length === 0 ? Effect.void : Effect.yieldNow.pipe(Effect.andThen(poll))
958
+ )
959
+ )
960
+ // Bounded on purpose. A consumer can fall permanently short, a handler
961
+ // that never returns among the ways, and an unbounded wait then pegs a
962
+ // core forever and swallows the end of the run.
963
+ yield* Effect.timeoutOption(poll, timeout)
964
+ return yield* behind
965
+ })
966
+
751
967
  return {
752
968
  // Counted AFTER delivery, and only when the PubSub accepted the event.
753
969
  // Tallying first meant a publish interrupted while backpressured (a
@@ -755,45 +971,56 @@ export const makeFlowEventHub = Effect.fn("@llm4ts/flow/FlowEvents.makeHub")(fun
755
971
  // permanently above anything a consumer could ever reach, and every
756
972
  // drain waiting on it never finished.
757
973
  publish: (event) =>
758
- PubSub.publish(events, event).pipe(
759
- Effect.flatMap((accepted) =>
760
- accepted ? Ref.update(published, (count) => count + 1) : Effect.void
761
- ),
762
- Effect.asVoid
974
+ order.withPermit(
975
+ PubSub.publish(events, event).pipe(
976
+ Effect.flatMap((accepted) =>
977
+ accepted ? Ref.update(published, (count) => count + 1) : Effect.void
978
+ ),
979
+ Effect.asVoid
980
+ )
763
981
  ),
764
982
  subscribe: PubSub.subscribe(events),
765
983
  stream: Stream.fromPubSub(events),
766
- publishedCount: Ref.get(published)
984
+ publishedCount: Ref.get(published),
985
+ consume: (name, handle, options) =>
986
+ Effect.gen(function* () {
987
+ const handled = yield* Ref.make(0)
988
+ const [subscription, baseline] = yield* order.withPermit(
989
+ Effect.all([PubSub.subscribe(events), Ref.get(published)])
990
+ )
991
+ const state: ConsumerState = {
992
+ name,
993
+ baseline,
994
+ wholeRun: options?.from !== "now",
995
+ handled
996
+ }
997
+ yield* Ref.update(consumers, (all) => [...all, state])
998
+ yield* Stream.fromSubscription(subscription).pipe(
999
+ Stream.runForEach((event) =>
1000
+ handle(event).pipe(Effect.andThen(Ref.update(handled, (count) => count + 1)))
1001
+ ),
1002
+ Effect.forkScoped
1003
+ )
1004
+ // A consumer whose scope closed handles nothing more: nobody waits on it.
1005
+ yield* Effect.addFinalizer(() =>
1006
+ Ref.update(consumers, (all) => all.filter((other) => other !== state))
1007
+ )
1008
+ return {
1009
+ name,
1010
+ caughtUp: (timeout = defaultDrainTimeout) =>
1011
+ Effect.map(waitFor(Effect.succeed([state]), timeout), (rows) => rows.length === 0)
1012
+ }
1013
+ }),
1014
+ drained: (timeout = defaultDrainTimeout) =>
1015
+ Effect.gen(function* () {
1016
+ const late = (yield* Ref.get(consumers))
1017
+ .filter((consumer) => consumer.wholeRun && consumer.baseline > 0)
1018
+ .map((consumer) => ({ name: consumer.name, missed: consumer.baseline }))
1019
+ const behind = yield* waitFor(Ref.get(consumers), late.length === 0 ? timeout : 0)
1020
+ return { complete: behind.length === 0 && late.length === 0, behind, late }
1021
+ })
767
1022
  }
768
1023
  })
769
1024
 
770
1025
  /** How long a consumer waits to catch up before the run moves on regardless. */
771
1026
  export const defaultDrainTimeout = "3 seconds"
772
-
773
- /**
774
- * The shared drain: wait until `consumed` has caught up with everything the
775
- * hub published, and report whether it did.
776
- *
777
- * Bounded on purpose, and the single copy of this loop. A consumer can fall
778
- * permanently short of the count — a subscription torn down early, an
779
- * event the PubSub refused — and an unbounded wait then pegs a core forever.
780
- * In the runner that swallowed the end of a run: every stage printed and
781
- * ticked green, and no cost summary ever following, because the summary is
782
- * written only once every consumer reports drained.
783
- */
784
- export const awaitConsumed = (
785
- hub: FlowEventHub,
786
- consumed: Ref.Ref<number>,
787
- timeout: Duration.Input = defaultDrainTimeout
788
- ): Effect.Effect<boolean> =>
789
- Effect.gen(function* () {
790
- const target = yield* hub.publishedCount
791
- const drain: Effect.Effect<void> = Effect.suspend(() =>
792
- Ref.get(consumed).pipe(
793
- Effect.flatMap((count) =>
794
- count >= target ? Effect.void : Effect.yieldNow.pipe(Effect.andThen(drain))
795
- )
796
- )
797
- )
798
- return Option.isSome(yield* Effect.timeoutOption(drain, timeout))
799
- })
@@ -5,10 +5,9 @@ import * as Ref from "effect/Ref"
5
5
  import * as Schema from "effect/Schema"
6
6
  import * as Semaphore from "effect/Semaphore"
7
7
  import type * as Scope from "effect/Scope"
8
- import * as Stream from "effect/Stream"
9
8
  import type { StreamRecorder } from "@llm4ts/core/observability/StreamRecorder"
10
9
  import type { JsonValue } from "@llm4ts/core/providers/CliSupport"
11
- import { awaitConsumed, type FlowEvent, type FlowEventHub } from "./FlowEvents.ts"
10
+ import type { FlowEvent, FlowEventHub } from "./FlowEvents.ts"
12
11
  import type { PlainFileStoreShape } from "./Persistence.ts"
13
12
 
14
13
  export class TraceLine extends Schema.Class<TraceLine>("TraceLine")({
@@ -60,7 +59,6 @@ export const makeFlowRecorder = Effect.fn("@llm4ts/flow/FlowRecorder.make")(func
60
59
  runId: string
61
60
  ): Effect.fn.Return<FlowRecorderShape> {
62
61
  const sequence = yield* Ref.make(0)
63
- const consumed = yield* Ref.make(0)
64
62
  const lock = yield* Semaphore.make(1)
65
63
  // Set by the first failed write and never cleared: a disk that refused one
66
64
  // line is not asked again, but every line it then loses is counted, so
@@ -113,21 +111,14 @@ export const makeFlowRecorder = Effect.fn("@llm4ts/flow/FlowRecorder.make")(func
113
111
  message
114
112
  }),
115
113
  consume: (hub) =>
116
- Effect.gen(function* () {
117
- const subscription = yield* hub.subscribe
118
- yield* Stream.fromSubscription(subscription).pipe(
119
- Stream.runForEach((event) =>
120
- // Progress is for the screen; the call's TokensUsed is the record.
121
- (event._tag === "UsageProgress" ? Effect.void : record(event)).pipe(
122
- Effect.andThen(Ref.update(consumed, (count) => count + 1))
123
- )
124
- ),
125
- Effect.forkScoped,
126
- Effect.asVoid
114
+ Effect.asVoid(
115
+ // Progress is for the screen; the call's TokensUsed is the record.
116
+ hub.consume("trace", (event) =>
117
+ event._tag === "UsageProgress" ? Effect.void : record(event)
127
118
  )
128
- }),
119
+ ),
129
120
  end: (outcome) => append("RunEnded", { outcome }),
130
- awaitDrained: (hub, timeout) => awaitConsumed(hub, consumed, timeout)
121
+ awaitDrained: (hub, timeout) => Effect.map(hub.drained(timeout), (report) => report.complete)
131
122
  }
132
123
  return recorder
133
124
  })
package/src/GateTriage.ts CHANGED
@@ -7,7 +7,7 @@ import * as Effect from "effect/Effect"
7
7
  import * as Schema from "effect/Schema"
8
8
  import type { PersistenceError } from "./FlowError.ts"
9
9
  import type { PlainFileStoreShape } from "./Persistence.ts"
10
- import { ReviewIssue, ReviewResult } from "./Review.ts"
10
+ import { ReviewIssue, ReviewResult } from "./ReviewModel.ts"
11
11
  import { fingerprintOf } from "./ReviewCache.ts"
12
12
 
13
13
  export const GateClass = Schema.Literals(["red", "hang", "crash"])