@llm4ts/flow 4.12.0 → 4.14.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 (86) hide show
  1. package/dist/Approval.d.ts +1 -1
  2. package/dist/Approval.d.ts.map +1 -1
  3. package/dist/Artifacts.d.ts +2 -2
  4. package/dist/Artifacts.d.ts.map +1 -1
  5. package/dist/BenchReport.d.ts +2 -2
  6. package/dist/BenchReport.d.ts.map +1 -1
  7. package/dist/BoardSync.d.ts.map +1 -1
  8. package/dist/BoardSync.js +4 -4
  9. package/dist/BoardSync.js.map +1 -1
  10. package/dist/Control.d.ts +126 -0
  11. package/dist/Control.d.ts.map +1 -0
  12. package/dist/Control.js +152 -0
  13. package/dist/Control.js.map +1 -0
  14. package/dist/CostLedger.d.ts +2 -2
  15. package/dist/CostLedger.d.ts.map +1 -1
  16. package/dist/Equiv.d.ts +3 -3
  17. package/dist/Equiv.d.ts.map +1 -1
  18. package/dist/Flow.d.ts +1 -1
  19. package/dist/Flow.d.ts.map +1 -1
  20. package/dist/FlowContext.d.ts +3 -0
  21. package/dist/FlowContext.d.ts.map +1 -1
  22. package/dist/FlowContext.js.map +1 -1
  23. package/dist/FlowError.d.ts +31 -1
  24. package/dist/FlowError.d.ts.map +1 -1
  25. package/dist/FlowError.js +38 -1
  26. package/dist/FlowError.js.map +1 -1
  27. package/dist/FlowEvents.d.ts +27 -1
  28. package/dist/FlowEvents.d.ts.map +1 -1
  29. package/dist/FlowEvents.js +22 -1
  30. package/dist/FlowEvents.js.map +1 -1
  31. package/dist/Gates.d.ts +1 -1
  32. package/dist/Gates.d.ts.map +1 -1
  33. package/dist/GraphCache.d.ts +1 -1
  34. package/dist/GraphCache.d.ts.map +1 -1
  35. package/dist/Judgment.d.ts +2 -2
  36. package/dist/Judgment.d.ts.map +1 -1
  37. package/dist/Landing.d.ts +1 -1
  38. package/dist/Landing.d.ts.map +1 -1
  39. package/dist/NodePreflight.d.ts +1 -1
  40. package/dist/NodePreflight.d.ts.map +1 -1
  41. package/dist/Persistence.d.ts +2 -2
  42. package/dist/Persistence.d.ts.map +1 -1
  43. package/dist/PlanExecution.d.ts +2 -2
  44. package/dist/PlanExecution.d.ts.map +1 -1
  45. package/dist/ProgramJudge.d.ts +1 -1
  46. package/dist/ProgramJudge.d.ts.map +1 -1
  47. package/dist/Replay.d.ts +2 -2
  48. package/dist/Replay.d.ts.map +1 -1
  49. package/dist/Retro.d.ts +3 -3
  50. package/dist/Retro.d.ts.map +1 -1
  51. package/dist/Review.d.ts +5 -5
  52. package/dist/Review.d.ts.map +1 -1
  53. package/dist/ReviewCache.d.ts +1 -1
  54. package/dist/ReviewCache.d.ts.map +1 -1
  55. package/dist/Roster.d.ts +1 -1
  56. package/dist/Roster.d.ts.map +1 -1
  57. package/dist/RosterSeats.d.ts +1 -1
  58. package/dist/RosterSeats.d.ts.map +1 -1
  59. package/dist/Stories.d.ts +17 -4
  60. package/dist/Stories.d.ts.map +1 -1
  61. package/dist/Stories.js +123 -8
  62. package/dist/Stories.js.map +1 -1
  63. package/dist/StoryPlan.d.ts +2 -0
  64. package/dist/StoryPlan.d.ts.map +1 -1
  65. package/dist/StoryPlan.js +1 -0
  66. package/dist/StoryPlan.js.map +1 -1
  67. package/dist/WorkQueue.d.ts +1 -1
  68. package/dist/WorkQueue.d.ts.map +1 -1
  69. package/dist/WriterLock.d.ts +73 -0
  70. package/dist/WriterLock.d.ts.map +1 -0
  71. package/dist/WriterLock.js +142 -0
  72. package/dist/WriterLock.js.map +1 -0
  73. package/dist/settings/Registry.d.ts +8 -1
  74. package/dist/settings/Registry.d.ts.map +1 -1
  75. package/dist/settings/Registry.js +8 -0
  76. package/dist/settings/Registry.js.map +1 -1
  77. package/package.json +4 -2
  78. package/src/BoardSync.ts +7 -5
  79. package/src/Control.ts +256 -0
  80. package/src/FlowContext.ts +3 -0
  81. package/src/FlowError.ts +42 -1
  82. package/src/FlowEvents.ts +29 -1
  83. package/src/Stories.ts +162 -11
  84. package/src/StoryPlan.ts +3 -0
  85. package/src/WriterLock.ts +225 -0
  86. package/src/settings/Registry.ts +9 -0
package/src/Control.ts ADDED
@@ -0,0 +1,256 @@
1
+ import { join } from "node:path"
2
+ import * as Clock from "effect/Clock"
3
+ import * as Effect from "effect/Effect"
4
+ import * as Option from "effect/Option"
5
+ import * as Schema from "effect/Schema"
6
+ import type { PersistenceError } from "./FlowError.ts"
7
+ import { makeMemoryPlainFileStore, type PlainFileStoreShape } from "./Persistence.ts"
8
+ import { dependentsOf, type StoryPlan } from "./StoryPlan.ts"
9
+
10
+ /**
11
+ * The control inbox of a running epic (ADR 0057): what a person tells a live
12
+ * run. Commands are lines in an append-only log outside the checkout; the
13
+ * story scheduler polls it, applies each command once and answers with a
14
+ * receipt line. A command with no receipt is pending.
15
+ */
16
+
17
+ /** A story that failed in this run becomes ready again. */
18
+ export class RetryStory extends Schema.TaggedClass<RetryStory>()("RetryStory", {
19
+ story: Schema.String
20
+ }) {}
21
+
22
+ /** A story is not launched, or is interrupted; its dependents wait. */
23
+ export class SkipStory extends Schema.TaggedClass<SkipStory>()("SkipStory", {
24
+ story: Schema.String,
25
+ reason: Schema.String
26
+ }) {}
27
+
28
+ export const ControlAction = Schema.Union([RetryStory, SkipStory])
29
+ export type ControlAction = typeof ControlAction.Type
30
+
31
+ export const ControlLogVersion = 1
32
+
33
+ export class ControlCommand extends Schema.TaggedClass<ControlCommand>()("ControlCommand", {
34
+ schemaVersion: Schema.Literal(ControlLogVersion),
35
+ id: Schema.String,
36
+ /** Epoch milliseconds. */
37
+ at: Schema.Number,
38
+ /** Where it came from (`cli`, `mcp`, `chat:<user id>`): recorded, not authenticated. */
39
+ by: Schema.String,
40
+ command: ControlAction
41
+ }) {}
42
+
43
+ export const ControlOutcome = Schema.Literals(["applied", "refused", "expired"])
44
+ export type ControlOutcome = typeof ControlOutcome.Type
45
+
46
+ export class ControlReceipt extends Schema.TaggedClass<ControlReceipt>()("ControlReceipt", {
47
+ schemaVersion: Schema.Literal(ControlLogVersion),
48
+ id: Schema.String,
49
+ runId: Schema.String,
50
+ at: Schema.Number,
51
+ outcome: ControlOutcome,
52
+ /** Why it was refused. */
53
+ reason: Schema.optionalKey(Schema.String)
54
+ }) {}
55
+
56
+ const ControlLine = Schema.Union([ControlCommand, ControlReceipt])
57
+ const decodeLine = Schema.decodeUnknownOption(Schema.fromJsonString(ControlLine))
58
+ const encodeLine = Schema.encodeSync(Schema.fromJsonString(ControlLine))
59
+
60
+ export interface ControlLog {
61
+ /** Every command, oldest first, once per id. */
62
+ readonly commands: ReadonlyArray<ControlCommand>
63
+ /** The receipt of each answered command, by command id. */
64
+ readonly receipts: ReadonlyMap<string, ControlReceipt>
65
+ }
66
+
67
+ /** A log's commands and receipts; a line that does not decode (a torn write) is skipped. */
68
+ export const readControlLog = (text: string | undefined): ControlLog => {
69
+ const commands = new Map<string, ControlCommand>()
70
+ const receipts = new Map<string, ControlReceipt>()
71
+ for (const row of (text ?? "").split("\n")) {
72
+ if (row.trim().length === 0) continue
73
+ for (const line of Option.toArray(decodeLine(row))) {
74
+ if (line._tag === "ControlCommand") {
75
+ if (!commands.has(line.id)) commands.set(line.id, line)
76
+ } else {
77
+ receipts.set(line.id, line)
78
+ }
79
+ }
80
+ }
81
+ return { commands: [...commands.values()], receipts }
82
+ }
83
+
84
+ export interface ControlSubmission {
85
+ /** Supplied by the writer or generated; a second command with a known id is not written. */
86
+ readonly id?: string
87
+ readonly by: string
88
+ readonly command: ControlAction
89
+ }
90
+
91
+ export interface ControlInboxShape {
92
+ /** Commands without a receipt, oldest first. */
93
+ readonly pending: (epic: string) => Effect.Effect<ReadonlyArray<ControlCommand>, PersistenceError>
94
+ readonly receipt: (
95
+ epic: string,
96
+ receipt: {
97
+ readonly id: string
98
+ readonly runId: string
99
+ readonly outcome: ControlOutcome
100
+ readonly reason?: string
101
+ }
102
+ ) => Effect.Effect<void, PersistenceError>
103
+ /** Writes a command; returns the one already in the log when its id is known. */
104
+ readonly submit: (
105
+ epic: string,
106
+ submission: ControlSubmission
107
+ ) => Effect.Effect<ControlCommand, PersistenceError>
108
+ readonly log: (epic: string) => Effect.Effect<ControlLog, PersistenceError>
109
+ }
110
+
111
+ export interface ControlInboxOptions {
112
+ readonly files: PlainFileStoreShape
113
+ /** The directory of one checkout's logs; the runner and the shell name it. */
114
+ readonly root: string
115
+ /** A new command id; injectable so tests are deterministic. */
116
+ readonly newId?: () => string
117
+ }
118
+
119
+ const randomId = (): string =>
120
+ `c-${Date.now().toString(36)}-${Math.floor(Math.random() * 0x100000000).toString(16)}`
121
+
122
+ /** An epic's log file under a checkout's control directory. */
123
+ export const controlLogPath = (root: string, epic: string): string => join(root, `${epic}.jsonl`)
124
+
125
+ export const makeControlInbox = (options: ControlInboxOptions): ControlInboxShape => {
126
+ const newId = options.newId ?? randomId
127
+ const log = (epic: string) =>
128
+ options.files.read(controlLogPath(options.root, epic)).pipe(Effect.map(readControlLog))
129
+ const append = (epic: string, line: ControlCommand | ControlReceipt) =>
130
+ options.files.append(controlLogPath(options.root, epic), `${encodeLine(line)}\n`)
131
+ return {
132
+ log,
133
+ pending: (epic) =>
134
+ log(epic).pipe(
135
+ Effect.map(({ commands, receipts }) =>
136
+ commands.filter((command) => !receipts.has(command.id))
137
+ )
138
+ ),
139
+ receipt: (epic, receipt) =>
140
+ Effect.gen(function* () {
141
+ const at = yield* Clock.currentTimeMillis
142
+ yield* append(
143
+ epic,
144
+ ControlReceipt.make({
145
+ schemaVersion: ControlLogVersion,
146
+ id: receipt.id,
147
+ runId: receipt.runId,
148
+ at,
149
+ outcome: receipt.outcome,
150
+ ...(receipt.reason === undefined ? {} : { reason: receipt.reason })
151
+ })
152
+ )
153
+ }),
154
+ submit: (epic, submission) =>
155
+ Effect.gen(function* () {
156
+ const id = submission.id ?? newId()
157
+ const known = (yield* log(epic)).commands.find((command) => command.id === id)
158
+ if (known !== undefined) return known
159
+ const command = ControlCommand.make({
160
+ schemaVersion: ControlLogVersion,
161
+ id,
162
+ at: yield* Clock.currentTimeMillis,
163
+ by: submission.by,
164
+ command: submission.command
165
+ })
166
+ yield* append(epic, command)
167
+ return command
168
+ })
169
+ }
170
+ }
171
+
172
+ export interface MemoryControlInbox {
173
+ readonly inbox: ControlInboxShape
174
+ readonly files: Effect.Effect<Readonly<Record<string, string>>>
175
+ }
176
+
177
+ /** The in-memory inbox for tests; command ids count up from `c-1`. */
178
+ export const makeMemoryControlInbox = (root = "/control"): Effect.Effect<MemoryControlInbox> =>
179
+ Effect.gen(function* () {
180
+ const memory = yield* makeMemoryPlainFileStore()
181
+ let next = 0
182
+ return {
183
+ inbox: makeControlInbox({ files: memory.store, root, newId: () => `c-${++next}` }),
184
+ files: memory.files
185
+ }
186
+ })
187
+
188
+ /** Where every story of the plan stands in the scheduler when a command arrives. */
189
+ export interface ControlState {
190
+ readonly done: ReadonlySet<string>
191
+ readonly failed: ReadonlySet<string>
192
+ readonly skipped: ReadonlySet<string>
193
+ /** Stories on hold, with what each waits for. */
194
+ readonly waiting: ReadonlyMap<string, string>
195
+ readonly running: ReadonlySet<string>
196
+ /** Why the run launches no further story, when it does not. */
197
+ readonly halted?: string
198
+ }
199
+
200
+ export type ControlDecision =
201
+ | {
202
+ readonly _tag: "Retry"
203
+ readonly story: string
204
+ /** Dependents held behind the story, released with it. */
205
+ readonly release: ReadonlyArray<string>
206
+ }
207
+ | {
208
+ readonly _tag: "Skip"
209
+ readonly story: string
210
+ readonly reason: string
211
+ /** The story is running and must be interrupted. */
212
+ readonly interrupt: boolean
213
+ }
214
+ | { readonly _tag: "Refused"; readonly reason: string }
215
+
216
+ const refused = (reason: string): ControlDecision => ({ _tag: "Refused", reason })
217
+
218
+ /** What the scheduler said when it put a story on hold behind another. */
219
+ export const waitingFor = (story: string): string => `waiting for ${story}`
220
+
221
+ /** What a command does to a run: pure, so it is tested without a clock or a file. */
222
+ export const decideControl = (
223
+ plan: StoryPlan,
224
+ state: ControlState,
225
+ command: ControlAction
226
+ ): ControlDecision => {
227
+ const id = command.story
228
+ if (plan.story(id) === undefined) {
229
+ return refused(`'${id}' is not a story of epic ${plan.epicId}`)
230
+ }
231
+ if (state.done.has(id)) {
232
+ return refused(`story ${id} is done`)
233
+ }
234
+ if (command._tag === "SkipStory") {
235
+ return state.skipped.has(id)
236
+ ? refused(`story ${id} is already skipped`)
237
+ : { _tag: "Skip", story: id, reason: command.reason, interrupt: state.running.has(id) }
238
+ }
239
+ if (state.running.has(id)) {
240
+ return refused(`story ${id} is running`)
241
+ }
242
+ if (!state.failed.has(id)) {
243
+ return refused(`story ${id} did not fail in this run`)
244
+ }
245
+ if (state.halted !== undefined) {
246
+ return refused(`the run launches no further story: ${state.halted}`)
247
+ }
248
+ const dependents = new Set(dependentsOf(plan, id))
249
+ return {
250
+ _tag: "Retry",
251
+ story: id,
252
+ release: [...state.waiting]
253
+ .filter(([waiter, reason]) => dependents.has(waiter) && reason === waitingFor(id))
254
+ .map(([waiter]) => waiter)
255
+ }
256
+ }
@@ -1,3 +1,4 @@
1
+ import type { ControlInboxShape } from "./Control.ts"
1
2
  import * as Context from "effect/Context"
2
3
  import type * as Effect from "effect/Effect"
3
4
  import type * as Scope from "effect/Scope"
@@ -69,6 +70,8 @@ export interface FlowContextShape {
69
70
  * this context's coder. Absent on a run with one executor per seat.
70
71
  */
71
72
  readonly roster?: RosterView
73
+ /** The control inbox of this checkout's epics (ADR 0057): the root context only. */
74
+ readonly control?: ControlInboxShape
72
75
  /** The trace this run writes (ADR 0022), when it writes one: the root context only. */
73
76
  readonly trace?: { readonly runId: string; readonly path: string }
74
77
  }
package/src/FlowError.ts CHANGED
@@ -226,6 +226,26 @@ export class EpicIncomplete extends Schema.TaggedError<EpicIncomplete>()("EpicIn
226
226
  }
227
227
  }
228
228
 
229
+ /**
230
+ * A run of an epic ended with stories failed, waiting or skipped (ADR 0058). Raised
231
+ * after the board, the report and the retro hint are written, so the run
232
+ * ends `failed` and its process exits non-zero.
233
+ */
234
+ export class EpicUnfinished extends Schema.TaggedError<EpicUnfinished>()("EpicUnfinished", {
235
+ epicId: Schema.String,
236
+ done: Schema.Int,
237
+ failed: Schema.Int,
238
+ waiting: Schema.Int,
239
+ skipped: Schema.Int,
240
+ report: Schema.String
241
+ }) {
242
+ get message(): string {
243
+ return `epic '${this.epicId}' is not finished: ${this.done} done, ${this.failed} failed, ${this.waiting} waiting${
244
+ this.skipped === 0 ? "" : `, ${this.skipped} skipped`
245
+ } — see ${this.report}; run the epic again to resume`
246
+ }
247
+ }
248
+
229
249
  /** Landing an epic failed; the target branch was left untouched. */
230
250
  export class LandingFailed extends Schema.TaggedError<LandingFailed>()("LandingFailed", {
231
251
  epicBranch: Schema.String,
@@ -437,6 +457,25 @@ export class PlanPending extends Schema.TaggedError<PlanPending>()("PlanPending"
437
457
  }
438
458
  }
439
459
 
460
+ /** A writing run was asked for on a checkout another run is writing (ADR 0058). */
461
+ export class CheckoutBusy extends Schema.TaggedError<CheckoutBusy>()("CheckoutBusy", {
462
+ workDir: Schema.String,
463
+ lockPath: Schema.String,
464
+ pid: Schema.Int,
465
+ runId: Schema.String,
466
+ flow: Schema.optionalKey(Schema.String),
467
+ /** `children`: the run is gone, processes it started are not. */
468
+ alive: Schema.Literals(["run", "children"]),
469
+ groups: Schema.Array(Schema.Int)
470
+ }) {
471
+ get message(): string {
472
+ const run = `run ${this.runId}${this.flow === undefined ? "" : ` (${this.flow})`}`
473
+ return this.alive === "run"
474
+ ? `${this.workDir} is being written by ${run}, pid ${this.pid}; a second writing run is not started. Stop that run first`
475
+ : `${run} is gone, but processes it started are still running and may write to ${this.workDir} (process group ${this.groups.join(", ")}). End them and run again; if they are not that run's, remove ${this.lockPath}`
476
+ }
477
+ }
478
+
440
479
  export const FlowError = Schema.Union([
441
480
  PersistenceError,
442
481
  PlanParseError,
@@ -458,6 +497,7 @@ export const FlowError = Schema.Union([
458
497
  RosterExhausted,
459
498
  RosterInvalid,
460
499
  EpicIncomplete,
500
+ EpicUnfinished,
461
501
  LandingFailed,
462
502
  StoryFailed,
463
503
  Stalled,
@@ -474,6 +514,7 @@ export const FlowError = Schema.Union([
474
514
  AgendaPending,
475
515
  PlanInvalid,
476
516
  ReportInvalid,
477
- PlanPending
517
+ PlanPending,
518
+ CheckoutBusy
478
519
  ])
479
520
  export type FlowError = typeof FlowError.Type
package/src/FlowEvents.ts CHANGED
@@ -386,10 +386,34 @@ export class StoryStatusChanged extends Schema.TaggedClass<StoryStatusChanged>()
386
386
  "StoryStatusChanged",
387
387
  {
388
388
  id: Schema.String,
389
- status: Schema.Literals(["planned", "active", "waiting", "done", "failed", "skipped"])
389
+ status: Schema.Literals(["planned", "active", "waiting", "done", "failed", "skipped"]),
390
+ /** Why a story failed, waits or was skipped (ADR 0057). */
391
+ reason: Schema.optionalKey(Schema.String)
390
392
  }
391
393
  ) {}
392
394
 
395
+ const controlFields = {
396
+ /** The command's id in the control log. */
397
+ id: Schema.String,
398
+ command: Schema.Literals(["RetryStory", "SkipStory"]),
399
+ story: Schema.String,
400
+ /** Where the command came from, as its writer said. */
401
+ by: Schema.String,
402
+ reason: Schema.optionalKey(Schema.String)
403
+ }
404
+
405
+ /** A command from the control inbox changed the run (ADR 0057). */
406
+ export class ControlApplied extends Schema.TaggedClass<ControlApplied>()(
407
+ "ControlApplied",
408
+ controlFields
409
+ ) {}
410
+
411
+ /** A command from the control inbox was refused; `reason` says why (ADR 0057). */
412
+ export class ControlRefused extends Schema.TaggedClass<ControlRefused>()(
413
+ "ControlRefused",
414
+ controlFields
415
+ ) {}
416
+
393
417
  export class ExecutorLeased extends Schema.TaggedClass<ExecutorLeased>()("ExecutorLeased", {
394
418
  executor: Schema.String,
395
419
  role: Schema.String,
@@ -525,6 +549,8 @@ export const FlowEvent = Schema.Union([
525
549
  TaskStarted,
526
550
  TaskCompleted,
527
551
  StoryStatusChanged,
552
+ ControlApplied,
553
+ ControlRefused,
528
554
  CriterionChecked,
529
555
  Parked
530
556
  ])
@@ -741,6 +767,8 @@ const laneRules = {
741
767
  })
742
768
  ),
743
769
  StoryStatusChanged: unlaned,
770
+ ControlApplied: unlaned,
771
+ ControlRefused: unlaned,
744
772
  CriterionChecked: carried,
745
773
  Parked: carried
746
774
  } satisfies {
package/src/Stories.ts CHANGED
@@ -7,6 +7,7 @@
7
7
  import * as Clock from "effect/Clock"
8
8
  import * as Effect from "effect/Effect"
9
9
  import * as Exit from "effect/Exit"
10
+ import * as Fiber from "effect/Fiber"
10
11
  import * as Option from "effect/Option"
11
12
  import * as Queue from "effect/Queue"
12
13
  import * as Ref from "effect/Ref"
@@ -49,6 +50,8 @@ import {
49
50
  withLane,
50
51
  type FlowEventsShape
51
52
  } from "./FlowEvents.ts"
53
+ import { ControlApplied, ControlRefused } from "./FlowEvents.ts"
54
+ import { decideControl, waitingFor, type ControlInboxShape } from "./Control.ts"
52
55
  import { timeEffect, withTimedRole } from "./Timing.ts"
53
56
  import { statusPaths, type GitToolShape } from "./GitTool.ts"
54
57
  import {
@@ -206,8 +209,11 @@ export const frozenTestsGate = (
206
209
 
207
210
  export const EpicReportVersion = 1
208
211
 
209
- /** `waiting`: on hold behind a failed predecessor, runs once that is fixed. */
210
- export const OutcomeStatus = Schema.Literals(["done", "failed", "waiting"])
212
+ /**
213
+ * `waiting`: on hold behind a failed or skipped predecessor, runs once that
214
+ * is done. `skipped`: left out of this run by a control command (ADR 0057).
215
+ */
216
+ export const OutcomeStatus = Schema.Literals(["done", "failed", "waiting", "skipped"])
211
217
  export type OutcomeStatus = typeof OutcomeStatus.Type
212
218
 
213
219
  export class StoryOutcome extends Schema.Class<StoryOutcome>("StoryOutcome")({
@@ -249,7 +255,9 @@ export const renderEpicReport = (report: EpicReport): string => {
249
255
  "> the CLI seats report no usage. They are not measurements.",
250
256
  "",
251
257
  `- Epic branch: \`${report.epicBranch}\``,
252
- `- Stories: ${report.stories.length} (done ${report.count("done")}, failed ${report.count("failed")}, waiting ${report.count("waiting")})`,
258
+ `- Stories: ${report.stories.length} (done ${report.count("done")}, failed ${report.count("failed")}, waiting ${report.count("waiting")}${
259
+ report.count("skipped") === 0 ? "" : `, skipped ${report.count("skipped")}`
260
+ })`,
253
261
  "",
254
262
  "| Story | Status | Branch | Est. tokens | Est. cost | Note |",
255
263
  "| --- | --- | --- | --- | --- | --- |"
@@ -896,6 +904,15 @@ export interface StoriesOptions {
896
904
  * executor stops launching stories instead of failing each in turn.
897
905
  */
898
906
  readonly awaitRecovery?: (reason: string) => Effect.Effect<void, FlowError>
907
+ /**
908
+ * The control inbox (ADR 0057): retry and skip commands for this run's
909
+ * stories, polled while it runs. Absent, the run is not steered.
910
+ */
911
+ readonly control?: ControlInboxShape
912
+ /** How often the inbox is read; default two seconds. */
913
+ readonly controlPollMs?: number
914
+ /** The epic's name in the inbox: its state folder. Default: the plan's epic id. */
915
+ readonly controlEpic?: string
899
916
  }
900
917
 
901
918
  /**
@@ -2703,6 +2720,7 @@ export const implementStoriesFlow = Effect.fn("@llm4ts/flow/Stories.implement")(
2703
2720
  done: byStatus("done"),
2704
2721
  failed: byStatus("failed"),
2705
2722
  waiting: byStatus("waiting"),
2723
+ skipped: byStatus("skipped"),
2706
2724
  running: yield* Ref.get(running)
2707
2725
  }
2708
2726
  })
@@ -2720,11 +2738,12 @@ export const implementStoriesFlow = Effect.fn("@llm4ts/flow/Stories.implement")(
2720
2738
  dependent === undefined ||
2721
2739
  current.done.has(id) ||
2722
2740
  current.failed.has(id) ||
2741
+ current.skipped.has(id) ||
2723
2742
  current.waiting.has(id)
2724
2743
  ) {
2725
2744
  continue
2726
2745
  }
2727
- const reason = `waiting for ${story.id}`
2746
+ const reason = waitingFor(story.id)
2728
2747
  yield* record(StoryOutcome.make({ id, title: dependent.title, status: "waiting", reason }))
2729
2748
  yield* board.wait(id, reason)
2730
2749
  }
@@ -2736,10 +2755,126 @@ export const implementStoriesFlow = Effect.fn("@llm4ts/flow/Stories.implement")(
2736
2755
  let toldLaunch: string | undefined
2737
2756
  /** Stories retried once after the serving engine recovered. */
2738
2757
  const recovered = new Set<string>()
2758
+ /** The fiber of each running story, so a skip can interrupt it. */
2759
+ const fibers = new Map<string, Fiber.Fiber<void>>()
2760
+
2761
+ // ---- Control inbox (ADR 0057) ---------------------------------------------
2762
+ const control = options.control
2763
+ const controlRunId = context.trace?.runId ?? "run"
2764
+ const controlEpic = options.controlEpic ?? plan.epicId
2765
+ const forget = (ids: ReadonlySet<string>): Effect.Effect<void> =>
2766
+ Ref.update(outcomes, (current) => current.filter((outcome) => !ids.has(outcome.id)))
2767
+ // A command is for the run live when it was written: what a run finds at
2768
+ // its start, or leaves at its end, expires.
2769
+ const expireControl =
2770
+ control === undefined
2771
+ ? Effect.void
2772
+ : Effect.gen(function* () {
2773
+ for (const command of yield* control.pending(controlEpic)) {
2774
+ yield* control.receipt(controlEpic, {
2775
+ id: command.id,
2776
+ runId: controlRunId,
2777
+ outcome: "expired"
2778
+ })
2779
+ }
2780
+ })
2781
+ const applyControl =
2782
+ control === undefined
2783
+ ? Effect.void
2784
+ : Effect.gen(function* () {
2785
+ for (const command of yield* control.pending(controlEpic)) {
2786
+ const current = yield* progress
2787
+ const known = yield* Ref.get(outcomes)
2788
+ const decision = decideControl(
2789
+ plan,
2790
+ {
2791
+ done: current.done,
2792
+ failed: current.failed,
2793
+ skipped: current.skipped,
2794
+ running: current.running,
2795
+ waiting: new Map(
2796
+ known.flatMap((outcome) =>
2797
+ outcome.status === "waiting"
2798
+ ? [[outcome.id, outcome.reason ?? ""] as const]
2799
+ : []
2800
+ )
2801
+ ),
2802
+ ...(halted === undefined ? {} : { halted })
2803
+ },
2804
+ command.command
2805
+ )
2806
+ const told = {
2807
+ id: command.id,
2808
+ command: command.command._tag,
2809
+ story: command.command.story,
2810
+ by: command.by
2811
+ }
2812
+ let refusal = decision._tag === "Refused" ? decision.reason : undefined
2813
+ if (decision._tag === "Skip" && decision.interrupt) {
2814
+ const fiber = fibers.get(decision.story)
2815
+ if (fiber !== undefined) {
2816
+ yield* Fiber.interrupt(fiber)
2817
+ // It ended on its own first: its result is in the queue.
2818
+ if (Exit.isSuccess(yield* Fiber.await(fiber))) {
2819
+ refusal = `story ${decision.story} finished before it could be skipped`
2820
+ }
2821
+ }
2822
+ }
2823
+ if (refusal !== undefined) {
2824
+ yield* control.receipt(controlEpic, {
2825
+ id: command.id,
2826
+ runId: controlRunId,
2827
+ outcome: "refused",
2828
+ reason: refusal
2829
+ })
2830
+ yield* events.publish(ControlRefused.make({ ...told, reason: refusal }))
2831
+ continue
2832
+ }
2833
+ if (decision._tag === "Retry") {
2834
+ yield* forget(new Set([decision.story, ...decision.release]))
2835
+ }
2836
+ if (decision._tag === "Skip") {
2837
+ const story = plan.story(decision.story)
2838
+ if (story !== undefined) {
2839
+ fibers.delete(story.id)
2840
+ yield* Ref.update(running, (set) => {
2841
+ const next = new Set(set)
2842
+ next.delete(story.id)
2843
+ return next
2844
+ })
2845
+ yield* forget(new Set([story.id]))
2846
+ yield* record(
2847
+ StoryOutcome.make({
2848
+ id: story.id,
2849
+ title: story.title,
2850
+ status: "skipped",
2851
+ reason: decision.reason
2852
+ })
2853
+ )
2854
+ yield* board.skip(story.id, decision.reason)
2855
+ yield* holdDependents(story)
2856
+ }
2857
+ }
2858
+ yield* control.receipt(controlEpic, {
2859
+ id: command.id,
2860
+ runId: controlRunId,
2861
+ outcome: "applied"
2862
+ })
2863
+ yield* events.publish(
2864
+ ControlApplied.make({
2865
+ ...told,
2866
+ ...(decision._tag === "Skip" ? { reason: decision.reason } : {})
2867
+ })
2868
+ )
2869
+ }
2870
+ })
2871
+
2872
+ yield* expireControl
2739
2873
 
2740
2874
  yield* Effect.scoped(
2741
2875
  Effect.gen(function* () {
2742
2876
  while (true) {
2877
+ yield* applyControl
2743
2878
  /** The roster's coder capacity when a ready story was left waiting for it. */
2744
2879
  let starvedAt: number | undefined
2745
2880
  if (halted === undefined) {
@@ -2761,9 +2896,13 @@ export const implementStoriesFlow = Effect.fn("@llm4ts/flow/Stories.implement")(
2761
2896
  const launching = ready.slice(0, Math.max(0, slots))
2762
2897
  for (const story of launching) {
2763
2898
  yield* Ref.update(running, (set) => new Set([...set, story.id]))
2764
- yield* Effect.forkScoped(
2765
- attempt(story).pipe(
2766
- Effect.flatMap((completion) => Queue.offer(completions, completion))
2899
+ fibers.set(
2900
+ story.id,
2901
+ yield* Effect.forkScoped(
2902
+ attempt(story).pipe(
2903
+ Effect.flatMap((completion) => Queue.offer(completions, completion)),
2904
+ Effect.asVoid
2905
+ )
2767
2906
  )
2768
2907
  )
2769
2908
  }
@@ -2810,17 +2949,27 @@ export const implementStoriesFlow = Effect.fn("@llm4ts/flow/Stories.implement")(
2810
2949
  // grows (an executor back from a cooldown, a health probe, a resume),
2811
2950
  // not when the next running story happens to end.
2812
2951
  const roster = context.roster
2813
- const next: Option.Option<Completion> =
2952
+ const completed = Effect.map(Queue.take(completions), Option.some)
2953
+ const grown =
2814
2954
  starvedAt === undefined || roster === undefined
2815
- ? Option.some(yield* Queue.take(completions))
2816
- : yield* Effect.raceFirst(
2817
- Effect.map(Queue.take(completions), Option.some),
2955
+ ? completed
2956
+ : Effect.raceFirst(
2957
+ completed,
2818
2958
  Effect.as(roster.capacityChanged("coder", starvedAt), Option.none<Completion>())
2819
2959
  )
2960
+ // With an inbox, the wait also ends every poll interval, and the top
2961
+ // of the loop reads the commands.
2962
+ const next: Option.Option<Completion> = yield* control === undefined
2963
+ ? grown
2964
+ : Effect.raceFirst(
2965
+ grown,
2966
+ Effect.as(Effect.sleep(options.controlPollMs ?? 2000), Option.none<Completion>())
2967
+ )
2820
2968
  if (Option.isNone(next)) {
2821
2969
  continue
2822
2970
  }
2823
2971
  const completion = next.value
2972
+ fibers.delete(completion.story.id)
2824
2973
  yield* Ref.update(running, (set) => {
2825
2974
  const next = new Set(set)
2826
2975
  next.delete(completion.story.id)
@@ -2884,6 +3033,8 @@ export const implementStoriesFlow = Effect.fn("@llm4ts/flow/Stories.implement")(
2884
3033
  })
2885
3034
  )
2886
3035
 
3036
+ yield* expireControl
3037
+
2887
3038
  if (halted !== undefined) {
2888
3039
  const stopped = halted
2889
3040
  yield* events.publish(
package/src/StoryPlan.ts CHANGED
@@ -267,6 +267,8 @@ export interface StoryProgress {
267
267
  readonly failed: ReadonlySet<string>
268
268
  /** On hold behind a failed predecessor. */
269
269
  readonly waiting: ReadonlySet<string>
270
+ /** Left out of this run by a control command (ADR 0057). */
271
+ readonly skipped?: ReadonlySet<string>
270
272
  readonly running: ReadonlySet<string>
271
273
  }
272
274
 
@@ -277,6 +279,7 @@ export const readyStories = (plan: StoryPlan, progress: StoryProgress): Readonly
277
279
  !progress.done.has(story.id) &&
278
280
  !progress.failed.has(story.id) &&
279
281
  !progress.waiting.has(story.id) &&
282
+ progress.skipped?.has(story.id) !== true &&
280
283
  !progress.running.has(story.id) &&
281
284
  story.dependsOn.every((dependency) => progress.done.has(dependency))
282
285
  )