@llm4ts/flow 3.3.0 → 3.4.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 (91) 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/Context.d.ts.map +1 -1
  5. package/dist/Context.js +2 -8
  6. package/dist/Context.js.map +1 -1
  7. package/dist/CostTracker.d.ts +1 -1
  8. package/dist/CostTracker.d.ts.map +1 -1
  9. package/dist/CostTracker.js +2 -8
  10. package/dist/CostTracker.js.map +1 -1
  11. package/dist/EstimatedUsage.d.ts.map +1 -1
  12. package/dist/EstimatedUsage.js +4 -3
  13. package/dist/EstimatedUsage.js.map +1 -1
  14. package/dist/FlowEvents.d.ts +100 -0
  15. package/dist/FlowEvents.d.ts.map +1 -1
  16. package/dist/FlowEvents.js +188 -107
  17. package/dist/FlowEvents.js.map +1 -1
  18. package/dist/FlowRecorder.d.ts +1 -1
  19. package/dist/FlowRecorder.d.ts.map +1 -1
  20. package/dist/FlowRecorder.js +4 -10
  21. package/dist/FlowRecorder.js.map +1 -1
  22. package/dist/GateTriage.d.ts +1 -1
  23. package/dist/GateTriage.d.ts.map +1 -1
  24. package/dist/GateTriage.js +1 -1
  25. package/dist/GateTriage.js.map +1 -1
  26. package/dist/GraphRules.d.ts +3 -1
  27. package/dist/GraphRules.d.ts.map +1 -1
  28. package/dist/GraphRules.js +2 -0
  29. package/dist/GraphRules.js.map +1 -1
  30. package/dist/JudgmentLog.d.ts.map +1 -1
  31. package/dist/JudgmentLog.js +5 -8
  32. package/dist/JudgmentLog.js.map +1 -1
  33. package/dist/NodePreflight.d.ts.map +1 -1
  34. package/dist/NodePreflight.js +2 -2
  35. package/dist/NodePreflight.js.map +1 -1
  36. package/dist/OracleGuard.d.ts +1 -1
  37. package/dist/OracleGuard.d.ts.map +1 -1
  38. package/dist/OracleGuard.js +1 -1
  39. package/dist/OracleGuard.js.map +1 -1
  40. package/dist/Orientation.d.ts.map +1 -1
  41. package/dist/Orientation.js +3 -5
  42. package/dist/Orientation.js.map +1 -1
  43. package/dist/Retro.d.ts.map +1 -1
  44. package/dist/Retro.js +2 -3
  45. package/dist/Retro.js.map +1 -1
  46. package/dist/Settings.d.ts +26 -0
  47. package/dist/Settings.d.ts.map +1 -1
  48. package/dist/Settings.js +30 -7
  49. package/dist/Settings.js.map +1 -1
  50. package/dist/Spans.d.ts.map +1 -1
  51. package/dist/Spans.js +2 -4
  52. package/dist/Spans.js.map +1 -1
  53. package/dist/Survey.d.ts +2 -4
  54. package/dist/Survey.d.ts.map +1 -1
  55. package/dist/Survey.js +2 -2
  56. package/dist/Survey.js.map +1 -1
  57. package/dist/TestEvidence.d.ts.map +1 -1
  58. package/dist/TestEvidence.js +4 -3
  59. package/dist/TestEvidence.js.map +1 -1
  60. package/dist/Workspace.d.ts.map +1 -1
  61. package/dist/Workspace.js +5 -22
  62. package/dist/Workspace.js.map +1 -1
  63. package/dist/settings/Registry.d.ts +5 -5
  64. package/dist/settings/Registry.d.ts.map +1 -1
  65. package/dist/settings/Registry.js +8 -7
  66. package/dist/settings/Registry.js.map +1 -1
  67. package/dist/settings/Value.d.ts +6 -1
  68. package/dist/settings/Value.d.ts.map +1 -1
  69. package/dist/settings/Value.js +8 -3
  70. package/dist/settings/Value.js.map +1 -1
  71. package/package.json +2 -2
  72. package/src/Bench.ts +6 -19
  73. package/src/Context.ts +2 -8
  74. package/src/CostTracker.ts +3 -15
  75. package/src/EstimatedUsage.ts +4 -3
  76. package/src/FlowEvents.ts +383 -117
  77. package/src/FlowRecorder.ts +7 -16
  78. package/src/GateTriage.ts +1 -1
  79. package/src/GraphRules.ts +4 -1
  80. package/src/JudgmentLog.ts +5 -13
  81. package/src/NodePreflight.ts +2 -4
  82. package/src/OracleGuard.ts +1 -1
  83. package/src/Orientation.ts +3 -5
  84. package/src/Retro.ts +2 -5
  85. package/src/Settings.ts +46 -7
  86. package/src/Spans.ts +2 -4
  87. package/src/Survey.ts +2 -2
  88. package/src/TestEvidence.ts +4 -3
  89. package/src/Workspace.ts +7 -24
  90. package/src/settings/Registry.ts +13 -7
  91. package/src/settings/Value.ts +12 -5
package/src/FlowEvents.ts CHANGED
@@ -6,6 +6,7 @@ import * as Layer from "effect/Layer"
6
6
  import * as PubSub from "effect/PubSub"
7
7
  import * as Ref from "effect/Ref"
8
8
  import * as Schema from "effect/Schema"
9
+ import * as Semaphore from "effect/Semaphore"
9
10
  import type * as Scope from "effect/Scope"
10
11
  import * as Stream from "effect/Stream"
11
12
  import { TokenUsage } from "@llm4ts/core/Models"
@@ -574,117 +575,252 @@ export const shortenLaneArgs = (args: string, workDir: string | undefined): stri
574
575
  return args.split(`cd ${root} && `).join("").split(`${root}/`).join("")
575
576
  }
576
577
 
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
578
+ export type FlowEventTag = FlowEvent["_tag"]
579
+ /** Each event class by its tag: what a table keyed by tag is typed over. */
580
+ export type FlowEventByTag = {
581
+ readonly [K in FlowEventTag]: Extract<FlowEvent, { readonly _tag: K }>
582
+ }
583
+ type Tag = FlowEventTag
584
+ type EventOf = FlowEventByTag
585
+
586
+ /** The lane an event is in, and the executor working it when the event names one. */
587
+ export interface LaneRef {
588
+ readonly lane: string
589
+ readonly executor?: string
590
+ }
591
+
592
+ /** What `withLane` knows of its lane when an event passes through it. */
593
+ export interface LaneTags {
594
+ readonly lane: string
595
+ readonly executor: string | undefined
596
+ readonly clone: number | undefined
597
+ readonly workDir: string | undefined
598
+ }
599
+
600
+ /**
601
+ * How an event stands to lanes. `none`: it has no lane. `carried`: its
602
+ * producer names the lane, and `withLane` leaves it alone. `stamped`:
603
+ * `withLane` names the lane on one published without, through `stamp`.
604
+ */
605
+ export interface LaneRule<E> {
606
+ readonly lane: "none" | "carried" | "stamped"
607
+ readonly read?: (event: E) => LaneRef | undefined
608
+ readonly stamp?: (event: E, tags: LaneTags) => E
609
+ }
610
+
611
+ interface Unlaned {
612
+ readonly lane: "none"
613
+ }
614
+ interface Carried<E> {
615
+ readonly lane: "carried"
616
+ readonly read: (event: E) => LaneRef | undefined
617
+ }
618
+ interface Stamped<E> extends Omit<Carried<E>, "lane"> {
619
+ readonly lane: "stamped"
620
+ readonly stamp: (event: E, tags: LaneTags) => E
621
+ }
622
+
623
+ const readLane = (event: {
624
+ readonly lane?: string
625
+ readonly executor?: string
626
+ }): LaneRef | undefined =>
627
+ event.lane === undefined
628
+ ? undefined
629
+ : { lane: event.lane, ...(event.executor === undefined ? {} : { executor: event.executor }) }
630
+
631
+ const unlaned: Unlaned = { lane: "none" }
632
+ const carried: Carried<{ readonly lane?: string }> = { lane: "carried", read: readLane }
633
+ const stamped = <E extends { readonly lane?: string; readonly executor?: string }>(
634
+ stamp: (event: E, tags: LaneTags) => E
635
+ ): Stamped<E> => ({ lane: "stamped", read: readLane, stamp })
636
+
637
+ /** The lane and, when it has one, the executor working it. */
638
+ const seat = (tags: LaneTags): LaneRef => ({
639
+ lane: tags.lane,
640
+ ...(tags.executor === undefined ? {} : { executor: tags.executor })
641
+ })
642
+
643
+ const laneRules = {
644
+ JudgmentObserved: unlaned,
645
+ BlackboardRun: unlaned,
646
+ StageStarted: stamped<StageStarted>((event, tags) =>
647
+ StageStarted.make({ stage: event.stage, ...seat(tags) })
648
+ ),
649
+ StageCompleted: stamped<StageCompleted>((event, tags) =>
650
+ StageCompleted.make({ stage: event.stage, ...seat(tags) })
651
+ ),
652
+ StageFailed: stamped<StageFailed>((event, tags) =>
653
+ StageFailed.make({ stage: event.stage, message: event.message, ...seat(tags) })
654
+ ),
655
+ Aborted: unlaned,
656
+ Info: stamped<Info>((event, tags) => Info.make({ message: event.message, ...seat(tags) })),
657
+ ToolUse: stamped<ToolUse>((event, tags) =>
658
+ ToolUse.make({
659
+ tool: event.tool,
660
+ args: shortenLaneArgs(event.args, tags.workDir),
661
+ ...(event.parent === undefined ? {} : { parent: event.parent }),
662
+ ...seat(tags)
663
+ })
664
+ ),
665
+ AssistantMessage: stamped<AssistantMessage>((event, tags) =>
666
+ AssistantMessage.make({ text: event.text, ...seat(tags) })
667
+ ),
668
+ TokensUsed: stamped<TokensUsed>((event, tags) =>
669
+ TokensUsed.make({
670
+ agent: event.agent,
671
+ usage: event.usage,
672
+ ...(event.model === undefined ? {} : { model: event.model }),
673
+ ...seat(tags),
674
+ // The lane's clone is its coder's: a reviewer or judge on the
675
+ // lane's events ran on another executor (ADR 0033).
676
+ ...(event.agent === "coder" && tags.clone !== undefined ? { clone: tags.clone } : {})
677
+ })
678
+ ),
679
+ UsageProgress: stamped<UsageProgress>((event, tags) =>
680
+ UsageProgress.make({
681
+ call: event.call,
682
+ ...(event.usage === undefined ? {} : { usage: event.usage }),
683
+ ...(event.done === undefined ? {} : { done: event.done }),
684
+ ...seat(tags)
685
+ })
686
+ ),
687
+ ReviewFindings: stamped<ReviewFindings>((event, tags) =>
688
+ ReviewFindings.make({
689
+ round: event.round,
690
+ settled: event.settled,
691
+ issues: event.issues,
692
+ ...(event.diffLines === undefined ? {} : { diffLines: event.diffLines }),
693
+ ...seat(tags)
694
+ })
695
+ ),
696
+ CapabilityUsed: unlaned,
697
+ CapabilityDenied: unlaned,
698
+ CapabilityUnenforceable: unlaned,
699
+ EvidenceChecked: carried,
700
+ ReviewFindingDemoted: carried,
701
+ Declassified: unlaned,
702
+ ExecutorLeased: unlaned,
703
+ ExecutorReleased: unlaned,
704
+ ExecutorExcluded: unlaned,
705
+ ExecutorResumed: unlaned,
706
+ ExecutorHandedOver: unlaned,
707
+ StoryJudged: carried,
708
+ RoundtableTurn: carried,
709
+ BriefReported: carried,
710
+ // The lane's executor is its coder's: it names a coder call or tool, not
711
+ // a reviewer's or judge's call made on another executor.
712
+ Timed: stamped<Timed>((event, tags) =>
713
+ Timed.make({
714
+ ...event,
715
+ lane: tags.lane,
716
+ ...(tags.executor !== undefined &&
717
+ ((event.kind === "model" && event.label === "coder") || event.kind === "tool")
718
+ ? { executor: tags.executor }
719
+ : {})
720
+ })
721
+ ),
722
+ Began: stamped<Began>((event, tags) =>
723
+ Began.make({
724
+ ...event,
725
+ lane: tags.lane,
726
+ ...(tags.executor !== undefined && event.kind === "model" && event.label === "coder"
727
+ ? { executor: tags.executor }
728
+ : {})
729
+ })
730
+ ),
731
+ TasksPlanned: stamped<TasksPlanned>((event, tags) =>
732
+ TasksPlanned.make({ tasks: event.tasks, ...seat(tags) })
733
+ ),
734
+ TaskStarted: stamped<TaskStarted>((event, tags) =>
735
+ TaskStarted.make({
736
+ index: event.index,
737
+ count: event.count,
738
+ title: event.title,
739
+ ...(event.satisfies === undefined ? {} : { satisfies: event.satisfies }),
740
+ ...seat(tags),
741
+ // A parallel task names its own coder, not the lane's (ADR 0034).
742
+ ...(event.parallel === undefined ? {} : { parallel: event.parallel }),
743
+ ...(event.executor === undefined ? {} : { executor: event.executor }),
744
+ ...(event.clone === undefined ? {} : { clone: event.clone })
745
+ })
746
+ ),
747
+ TaskCompleted: stamped<TaskCompleted>((event, tags) =>
748
+ TaskCompleted.make({
749
+ index: event.index,
750
+ count: event.count,
751
+ title: event.title,
752
+ ...seat(tags)
753
+ })
754
+ ),
755
+ StoryStatusChanged: unlaned,
756
+ CriterionChecked: carried,
757
+ Parked: carried
758
+ } satisfies {
759
+ // An event with a `lane` field cannot be declared unlaned, nor the reverse.
760
+ readonly [K in Tag]: "lane" extends keyof EventOf[K]
761
+ ? Carried<EventOf[K]> | Stamped<EventOf[K]>
762
+ : Unlaned
763
+ }
764
+
765
+ /**
766
+ * Every event's standing to lanes. Exhaustive by type: adding an event class
767
+ * without an entry here fails `pnpm typecheck`.
768
+ */
769
+ export const eventLanes: { readonly [K in Tag]: LaneRule<EventOf[K]> } = laneRules
770
+
771
+ // A tag and its event are one value's, so the rule found by the tag takes the
772
+ // event. TypeScript does not correlate the two across the union; reading the
773
+ // rule through a generic key is the step that lets it.
774
+ const ruleOf = <K extends Tag>(tag: K): LaneRule<EventOf[K]> => eventLanes[tag]
775
+
776
+ /** The lane of any event that is in one, and its executor when the event names it. */
777
+ export const laneOf = (event: FlowEvent): LaneRef | undefined => ruleOf(event._tag).read?.(event)
778
+
779
+ const stampedWith = (event: FlowEvent, tags: LaneTags): FlowEvent => {
780
+ const rule = ruleOf(event._tag)
781
+ return rule.stamp === undefined || rule.read?.(event) !== undefined
782
+ ? event
783
+ : rule.stamp(event, tags)
784
+ }
785
+
786
+ export const LaneKind = Schema.Literals(["story", "attendee", "specialist"])
787
+ /** What a lane stands for: a story's coder (ADR 0022), a roundtable attendee (ADR 0046), or a taskforce specialist (ADR 0047). */
788
+ export type LaneKind = typeof LaneKind.Type
789
+
790
+ /** A lane as its opening stage names it. */
791
+ export interface LaneName {
792
+ readonly kind: LaneKind
793
+ readonly id: string
794
+ }
795
+
796
+ const isLaneKind = Schema.is(LaneKind)
797
+ const laneStagePattern = /^(\S+) (.+)$/u
798
+
799
+ /**
800
+ * The lane protocol, read side: a lane opens with a `StageStarted` whose stage
801
+ * is `<kind> <id>` and whose lane is that id (names may hold spaces), and
802
+ * closes when the same stage completes or fails.
803
+ */
804
+ const laneNamed = (stage: string, lane: string | undefined): LaneName | undefined => {
805
+ const [, kind, id] = laneStagePattern.exec(stage) ?? []
806
+ return kind !== undefined && isLaneKind(kind) && id !== undefined && id === lane
807
+ ? { kind, id }
808
+ : undefined
809
+ }
810
+
811
+ /** The lane this event opens, when it is the `StageStarted` that opens one. */
812
+ export const laneOpened = (event: FlowEvent): LaneName | undefined =>
813
+ event._tag === "StageStarted" ? laneNamed(event.stage, event.lane) : undefined
814
+
815
+ /** The lane this event closes, when it is the end of the stage that opened one. */
816
+ export const laneClosed = (
817
+ event: FlowEvent
818
+ ): (LaneName & { readonly failed: boolean }) | undefined => {
819
+ if (event._tag !== "StageCompleted" && event._tag !== "StageFailed") {
820
+ return undefined
687
821
  }
822
+ const named = laneNamed(event.stage, event.lane)
823
+ return named === undefined ? undefined : { ...named, failed: event._tag === "StageFailed" }
688
824
  }
689
825
 
690
826
  /**
@@ -696,7 +832,9 @@ export const withLane = (events: FlowEventsShape, lane: Lane): FlowEventsShape =
696
832
  publish: (event) =>
697
833
  Effect.flatMap(lane.executor ?? Effect.succeed(undefined), (executor) =>
698
834
  Effect.flatMap(lane.clone ?? Effect.succeed(undefined), (clone) =>
699
- events.publish(stamped(event, lane.lane, executor, lane.workDir, clone))
835
+ events.publish(
836
+ stampedWith(event, { lane: lane.lane, executor, clone, workDir: lane.workDir })
837
+ )
700
838
  )
701
839
  )
702
840
  })
@@ -737,10 +875,62 @@ export const makeCollectingFlowEvents: Effect.Effect<CollectingFlowEvents> = Eff
737
875
  })
738
876
  )
739
877
 
878
+ /** How a consumer stands against what the hub published; see `FlowEventHub.drained`. */
879
+ export interface DrainReport {
880
+ /** Every consumer handled every event it was owed, and none joined late. */
881
+ readonly complete: boolean
882
+ /** Consumers still short when the wait ended, and by how many events. */
883
+ readonly behind: ReadonlyArray<{ readonly name: string; readonly missing: number }>
884
+ /**
885
+ * Consumers meant to see the whole run that subscribed after events were
886
+ * published: those events never reached them, however long anyone waits.
887
+ */
888
+ readonly late: ReadonlyArray<{ readonly name: string; readonly missed: number }>
889
+ }
890
+
891
+ export interface FlowEventConsumer {
892
+ readonly name: string
893
+ /** Whether this consumer alone handled everything it was owed, within `timeout`. */
894
+ readonly caughtUp: (timeout?: Duration.Input) => Effect.Effect<boolean>
895
+ }
896
+
897
+ export interface ConsumeOptions {
898
+ /**
899
+ * `start` (the default): the consumer accounts for the whole run, so
900
+ * joining after an event was published is reported by `drained`. `now`:
901
+ * it is owed only what is published from here on.
902
+ */
903
+ readonly from?: "start" | "now"
904
+ }
905
+
740
906
  export interface FlowEventHub extends FlowEventsShape {
741
907
  readonly subscribe: Effect.Effect<PubSub.Subscription<FlowEvent>, never, Scope.Scope>
742
908
  readonly stream: Stream.Stream<FlowEvent>
743
909
  readonly publishedCount: Effect.Effect<number>
910
+ /**
911
+ * Runs `handle` on every event published from here on, in order, on a fiber
912
+ * of the scope. The one consumer loop: the hub counts what each consumer
913
+ * handled, so nobody keeps a counter of their own.
914
+ */
915
+ readonly consume: (
916
+ name: string,
917
+ handle: (event: FlowEvent) => Effect.Effect<void>,
918
+ options?: ConsumeOptions
919
+ ) => Effect.Effect<FlowEventConsumer, never, Scope.Scope>
920
+ /**
921
+ * Waits, at most `timeout`, for every live consumer to handle what it was
922
+ * owed, then says who fell short. A late subscriber ends the wait at once:
923
+ * no wait can bring back what it missed.
924
+ */
925
+ readonly drained: (timeout?: Duration.Input) => Effect.Effect<DrainReport>
926
+ }
927
+
928
+ interface ConsumerState {
929
+ readonly name: string
930
+ /** Events published before this consumer subscribed. */
931
+ readonly baseline: number
932
+ readonly wholeRun: boolean
933
+ readonly handled: Ref.Ref<number>
744
934
  }
745
935
 
746
936
  export const makeFlowEventHub = Effect.fn("@llm4ts/flow/FlowEvents.makeHub")(function* (
@@ -748,6 +938,40 @@ export const makeFlowEventHub = Effect.fn("@llm4ts/flow/FlowEvents.makeHub")(fun
748
938
  ): Effect.fn.Return<FlowEventHub> {
749
939
  const events = yield* PubSub.bounded<FlowEvent>(capacity)
750
940
  const published = yield* Ref.make(0)
941
+ const consumers = yield* Ref.make<ReadonlyArray<ConsumerState>>([])
942
+ // Held across a publish and its count, and across a subscription and the
943
+ // count it reads, so a consumer's baseline is exact: every event counted in
944
+ // it was published before the subscription, every later one reaches it.
945
+ const order = yield* Semaphore.make(1)
946
+
947
+ const missingOf = (consumer: ConsumerState, target: number): Effect.Effect<number> =>
948
+ Effect.map(Ref.get(consumer.handled), (handled) =>
949
+ Math.max(0, target - consumer.baseline - handled)
950
+ )
951
+
952
+ const waitFor = (
953
+ who: Effect.Effect<ReadonlyArray<ConsumerState>>,
954
+ timeout: Duration.Input
955
+ ): Effect.Effect<ReadonlyArray<{ readonly name: string; readonly missing: number }>> =>
956
+ Effect.gen(function* () {
957
+ const target = yield* Ref.get(published)
958
+ const behind = Effect.flatMap(who, (all) =>
959
+ Effect.forEach(all, (consumer) =>
960
+ Effect.map(missingOf(consumer, target), (missing) => ({ name: consumer.name, missing }))
961
+ ).pipe(Effect.map((rows) => rows.filter((row) => row.missing > 0)))
962
+ )
963
+ const poll: Effect.Effect<void> = Effect.suspend(() =>
964
+ Effect.flatMap(behind, (rows) =>
965
+ rows.length === 0 ? Effect.void : Effect.yieldNow.pipe(Effect.andThen(poll))
966
+ )
967
+ )
968
+ // Bounded on purpose. A consumer can fall permanently short, a handler
969
+ // that never returns among the ways, and an unbounded wait then pegs a
970
+ // core forever and swallows the end of the run.
971
+ yield* Effect.timeoutOption(poll, timeout)
972
+ return yield* behind
973
+ })
974
+
751
975
  return {
752
976
  // Counted AFTER delivery, and only when the PubSub accepted the event.
753
977
  // Tallying first meant a publish interrupted while backpressured (a
@@ -755,15 +979,54 @@ export const makeFlowEventHub = Effect.fn("@llm4ts/flow/FlowEvents.makeHub")(fun
755
979
  // permanently above anything a consumer could ever reach, and every
756
980
  // drain waiting on it never finished.
757
981
  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
982
+ order.withPermit(
983
+ PubSub.publish(events, event).pipe(
984
+ Effect.flatMap((accepted) =>
985
+ accepted ? Ref.update(published, (count) => count + 1) : Effect.void
986
+ ),
987
+ Effect.asVoid
988
+ )
763
989
  ),
764
990
  subscribe: PubSub.subscribe(events),
765
991
  stream: Stream.fromPubSub(events),
766
- publishedCount: Ref.get(published)
992
+ publishedCount: Ref.get(published),
993
+ consume: (name, handle, options) =>
994
+ Effect.gen(function* () {
995
+ const handled = yield* Ref.make(0)
996
+ const [subscription, baseline] = yield* order.withPermit(
997
+ Effect.all([PubSub.subscribe(events), Ref.get(published)])
998
+ )
999
+ const state: ConsumerState = {
1000
+ name,
1001
+ baseline,
1002
+ wholeRun: options?.from !== "now",
1003
+ handled
1004
+ }
1005
+ yield* Ref.update(consumers, (all) => [...all, state])
1006
+ yield* Stream.fromSubscription(subscription).pipe(
1007
+ Stream.runForEach((event) =>
1008
+ handle(event).pipe(Effect.andThen(Ref.update(handled, (count) => count + 1)))
1009
+ ),
1010
+ Effect.forkScoped
1011
+ )
1012
+ // A consumer whose scope closed handles nothing more: nobody waits on it.
1013
+ yield* Effect.addFinalizer(() =>
1014
+ Ref.update(consumers, (all) => all.filter((other) => other !== state))
1015
+ )
1016
+ return {
1017
+ name,
1018
+ caughtUp: (timeout = defaultDrainTimeout) =>
1019
+ Effect.map(waitFor(Effect.succeed([state]), timeout), (rows) => rows.length === 0)
1020
+ }
1021
+ }),
1022
+ drained: (timeout = defaultDrainTimeout) =>
1023
+ Effect.gen(function* () {
1024
+ const late = (yield* Ref.get(consumers))
1025
+ .filter((consumer) => consumer.wholeRun && consumer.baseline > 0)
1026
+ .map((consumer) => ({ name: consumer.name, missed: consumer.baseline }))
1027
+ const behind = yield* waitFor(Ref.get(consumers), late.length === 0 ? timeout : 0)
1028
+ return { complete: behind.length === 0 && late.length === 0, behind, late }
1029
+ })
767
1030
  }
768
1031
  })
769
1032
 
@@ -780,6 +1043,9 @@ export const defaultDrainTimeout = "3 seconds"
780
1043
  * In the runner that swallowed the end of a run: every stage printed and
781
1044
  * ticked green, and no cost summary ever following, because the summary is
782
1045
  * written only once every consumer reports drained.
1046
+ *
1047
+ * @deprecated Use `hub.consume`, which counts for the consumer, and
1048
+ * `hub.drained` or the consumer's `caughtUp`.
783
1049
  */
784
1050
  export const awaitConsumed = (
785
1051
  hub: FlowEventHub,
@@ -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"])
package/src/GraphRules.ts CHANGED
@@ -3,7 +3,6 @@ import * as Schema from "effect/Schema"
3
3
  import { PlanParseError } from "./FlowError.ts"
4
4
  import { fingerprintOf } from "./ReviewCache.ts"
5
5
  import type { CoverageRule } from "./SpecChecks.ts"
6
- import type { JoinMatch } from "./Survey.ts"
7
6
 
8
7
  /**
9
8
  * The pack's graph vocabulary (ADR 0030). A `## Node:` rule names a sub-file
@@ -39,6 +38,10 @@ export class EdgeRule extends Schema.Class<EdgeRule>("EdgeRule")({
39
38
  unknown: Schema.optionalKey(Schema.Literals(["keep", "drop"]))
40
39
  }) {}
41
40
 
41
+ /** How a survey edge's target was reached from what the source names. */
42
+ export const JoinMatch = Schema.Literals(["exact", "prefix", "extension"])
43
+ export type JoinMatch = typeof JoinMatch.Type
44
+
42
45
  /**
43
46
  * `exact`: trimmed string equality. `exact-ci`: the same ignoring case (an EL
44
47
  * `${invoiceBean}` against a class `InvoiceBean`). `url`: servlet-spec