@llm4ts/flow 4.11.5 → 4.13.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 (72) 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/CostLedger.d.ts +2 -2
  8. package/dist/CostLedger.d.ts.map +1 -1
  9. package/dist/Equiv.d.ts +3 -3
  10. package/dist/Equiv.d.ts.map +1 -1
  11. package/dist/Flow.d.ts +3 -1
  12. package/dist/Flow.d.ts.map +1 -1
  13. package/dist/Flow.js +11 -4
  14. package/dist/Flow.js.map +1 -1
  15. package/dist/FlowError.d.ts +30 -1
  16. package/dist/FlowError.d.ts.map +1 -1
  17. package/dist/FlowError.js +37 -1
  18. package/dist/FlowError.js.map +1 -1
  19. package/dist/Gates.d.ts +1 -1
  20. package/dist/Gates.d.ts.map +1 -1
  21. package/dist/GraphCache.d.ts +1 -1
  22. package/dist/GraphCache.d.ts.map +1 -1
  23. package/dist/Judgment.d.ts +2 -2
  24. package/dist/Judgment.d.ts.map +1 -1
  25. package/dist/Landing.d.ts +1 -1
  26. package/dist/Landing.d.ts.map +1 -1
  27. package/dist/NodePreflight.d.ts +1 -1
  28. package/dist/NodePreflight.d.ts.map +1 -1
  29. package/dist/Persistence.d.ts +34 -4
  30. package/dist/Persistence.d.ts.map +1 -1
  31. package/dist/Persistence.js +42 -4
  32. package/dist/Persistence.js.map +1 -1
  33. package/dist/PlanExecution.d.ts +9 -2
  34. package/dist/PlanExecution.d.ts.map +1 -1
  35. package/dist/PlanExecution.js +31 -6
  36. package/dist/PlanExecution.js.map +1 -1
  37. package/dist/ProgramJudge.d.ts +1 -1
  38. package/dist/ProgramJudge.d.ts.map +1 -1
  39. package/dist/Replay.d.ts +2 -2
  40. package/dist/Replay.d.ts.map +1 -1
  41. package/dist/Retro.d.ts +3 -3
  42. package/dist/Retro.d.ts.map +1 -1
  43. package/dist/Review.d.ts +5 -5
  44. package/dist/Review.d.ts.map +1 -1
  45. package/dist/ReviewCache.d.ts +1 -1
  46. package/dist/ReviewCache.d.ts.map +1 -1
  47. package/dist/Roster.d.ts +1 -1
  48. package/dist/Roster.d.ts.map +1 -1
  49. package/dist/RosterSeats.d.ts +1 -1
  50. package/dist/RosterSeats.d.ts.map +1 -1
  51. package/dist/Stories.d.ts +1 -1
  52. package/dist/Stories.d.ts.map +1 -1
  53. package/dist/Stories.js +2 -1
  54. package/dist/Stories.js.map +1 -1
  55. package/dist/WorkQueue.d.ts +1 -1
  56. package/dist/WorkQueue.d.ts.map +1 -1
  57. package/dist/WriterLock.d.ts +73 -0
  58. package/dist/WriterLock.d.ts.map +1 -0
  59. package/dist/WriterLock.js +142 -0
  60. package/dist/WriterLock.js.map +1 -0
  61. package/dist/settings/Registry.d.ts +8 -1
  62. package/dist/settings/Registry.d.ts.map +1 -1
  63. package/dist/settings/Registry.js +8 -0
  64. package/dist/settings/Registry.js.map +1 -1
  65. package/package.json +3 -2
  66. package/src/Flow.ts +15 -5
  67. package/src/FlowError.ts +39 -1
  68. package/src/Persistence.ts +90 -4
  69. package/src/PlanExecution.ts +66 -9
  70. package/src/Stories.ts +2 -0
  71. package/src/WriterLock.ts +225 -0
  72. package/src/settings/Registry.ts +9 -0
@@ -4,6 +4,7 @@ import * as Fiber from "effect/Fiber"
4
4
  import * as Queue from "effect/Queue"
5
5
  import * as Semaphore from "effect/Semaphore"
6
6
  import {
7
+ Info,
7
8
  StageCompleted,
8
9
  StageFailed,
9
10
  StageStarted,
@@ -15,7 +16,7 @@ import {
15
16
  import { withKindSpan, type SpanOptions } from "./Spans.ts"
16
17
  import { FlowAborted, describeFlowError, type FlowError } from "./FlowError.ts"
17
18
  import { taskGraph, type Plan, type Task, type TaskNode } from "./Plan.ts"
18
- import type { PlanStoreShape } from "./Persistence.ts"
19
+ import type { PlanStoreShape, TaskAttemptsShape } from "./Persistence.ts"
19
20
  import { pathWithin } from "./StoryPlan.ts"
20
21
 
21
22
  const errorMessage = describeFlowError
@@ -68,15 +69,53 @@ const withSatisfies = (description: string): { readonly satisfies?: ReadonlyArra
68
69
  return satisfies === undefined ? {} : { satisfies }
69
70
  }
70
71
 
72
+ /** What a task's run is told about the runs before it (ADR 0056). */
73
+ export interface TaskAttempt {
74
+ /** Earlier runs of this task that a dead process cut off; 0 on a first run. */
75
+ readonly cutOff: number
76
+ }
77
+
78
+ /**
79
+ * Runs a task under the plan's cut-off journal: marked before, unmarked when
80
+ * it ends while the process lives. `lock` keeps tasks that run at once from
81
+ * writing the journal over each other.
82
+ */
83
+ const journaled = <A, E, R>(
84
+ attempts: TaskAttemptsShape | undefined,
85
+ lock: Semaphore.Semaphore,
86
+ events: FlowEventsShape,
87
+ task: Task,
88
+ run: (attempt: TaskAttempt) => Effect.Effect<A, E, R>
89
+ ): Effect.Effect<A, E | FlowError, R> => {
90
+ if (attempts === undefined) {
91
+ return run({ cutOff: 0 })
92
+ }
93
+ return Effect.gen(function* () {
94
+ const cutOff = yield* lock.withPermit(attempts.begin(task.title))
95
+ if (cutOff > 0) {
96
+ yield* events.publish(
97
+ Info.make({
98
+ message: `task "${task.title}": ${cutOff} earlier run(s) were cut off before they finished`
99
+ })
100
+ )
101
+ }
102
+ return yield* Effect.onExit(run({ cutOff }), (exit) =>
103
+ Effect.ignore(lock.withPermit(attempts.end(task.title, Exit.isSuccess(exit))))
104
+ )
105
+ })
106
+ }
107
+
71
108
  export const implementTaskLoop = Effect.fn("@llm4ts/flow/PlanExecution.implementTaskLoop")(
72
109
  function* <E, R>(
73
110
  store: PlanStoreShape,
74
111
  events: FlowEventsShape,
75
112
  planPath: string,
76
113
  plan: Plan,
77
- perTask: (task: Task, planSoFar: Plan) => Effect.Effect<void, E, R>
114
+ perTask: (task: Task, planSoFar: Plan, attempt: TaskAttempt) => Effect.Effect<void, E, R>
78
115
  ): Effect.fn.Return<Plan, E | FlowError, R> {
79
116
  let current = plan
117
+ const attempts = store.attempts?.(planPath)
118
+ const lock = yield* Semaphore.make(1)
80
119
  const count = plan.tasks.length
81
120
  yield* events.publish(
82
121
  TasksPlanned.make({
@@ -93,7 +132,12 @@ export const implementTaskLoop = Effect.fn("@llm4ts/flow/PlanExecution.implement
93
132
  yield* events.publish(
94
133
  TaskStarted.make({ index, count, title: task.title, ...withSatisfies(task.description) })
95
134
  )
96
- yield* stage(events, task.title, perTask(task, current))
135
+ const planSoFar = current
136
+ yield* stage(
137
+ events,
138
+ task.title,
139
+ journaled(attempts, lock, events, task, (attempt) => perTask(task, planSoFar, attempt))
140
+ )
97
141
  current = current.complete(task.title)
98
142
  yield* store.save(planPath, current)
99
143
  yield* events.publish(TaskCompleted.make({ index, count, title: task.title }))
@@ -134,6 +178,8 @@ export interface AsideRequest {
134
178
  /** The plan's size, for `task n/m`. */
135
179
  readonly count: number
136
180
  readonly planSoFar: Plan
181
+ /** What the task's run is told about the runs before it (ADR 0056). */
182
+ readonly attempt: TaskAttempt
137
183
  /** Runs `effect` while no task runs at home: the merge back into the story. */
138
184
  readonly exclusive: <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>
139
185
  /** Says the task started, on the coder it got; call it once that coder is held. */
@@ -170,7 +216,7 @@ export const implementTaskGraph = Effect.fn("@llm4ts/flow/PlanExecution.implemen
170
216
  events: FlowEventsShape,
171
217
  planPath: string,
172
218
  plan: Plan,
173
- perTask: (task: Task, planSoFar: Plan) => Effect.Effect<void, E, R>,
219
+ perTask: (task: Task, planSoFar: Plan, attempt: TaskAttempt) => Effect.Effect<void, E, R>,
174
220
  parallel: ParallelTasks<E2, R2>
175
221
  ): Effect.fn.Return<Plan, E | E2 | FlowError, R | R2> {
176
222
  const graph = taskGraph(plan)
@@ -191,8 +237,10 @@ export const implementTaskGraph = Effect.fn("@llm4ts/flow/PlanExecution.implemen
191
237
  const last = new Set<number>()
192
238
  const running = new Map<number, "home" | "aside">()
193
239
  const fibers: Array<Fiber.Fiber<unknown, unknown>> = []
194
- const finished = yield* Queue.unbounded<Finished<E | E2>>()
240
+ const finished = yield* Queue.unbounded<Finished<E | E2 | FlowError>>()
195
241
  const home = yield* Semaphore.make(1)
242
+ const attempts = store.attempts?.(planPath)
243
+ const journal = yield* Semaphore.make(1)
196
244
  const exclusive = <A, EX, RX>(effect: Effect.Effect<A, EX, RX>) => home.withPermit(effect)
197
245
 
198
246
  const started = (
@@ -235,7 +283,13 @@ export const implementTaskGraph = Effect.fn("@llm4ts/flow/PlanExecution.implemen
235
283
  exclusive(
236
284
  Effect.andThen(
237
285
  started(pick),
238
- stage(events, pick.task.title, perTask(pick.task, snapshot))
286
+ stage(
287
+ events,
288
+ pick.task.title,
289
+ journaled(attempts, journal, events, pick.task, (attempt) =>
290
+ perTask(pick.task, snapshot, attempt)
291
+ )
292
+ )
239
293
  )
240
294
  ).pipe(
241
295
  Effect.as(undefined),
@@ -258,10 +312,11 @@ export const implementTaskGraph = Effect.fn("@llm4ts/flow/PlanExecution.implemen
258
312
  continue
259
313
  }
260
314
  running.set(node.index, "aside")
261
- const request: AsideRequest = {
315
+ const request = (attempt: TaskAttempt): AsideRequest => ({
262
316
  node,
263
317
  count,
264
318
  planSoFar: current,
319
+ attempt,
265
320
  exclusive,
266
321
  announce: (coder) =>
267
322
  started(node, {
@@ -269,10 +324,12 @@ export const implementTaskGraph = Effect.fn("@llm4ts/flow/PlanExecution.implemen
269
324
  ...(coder.executor === undefined ? {} : { executor: coder.executor }),
270
325
  ...(coder.clone === undefined ? {} : { clone: coder.clone })
271
326
  })
272
- }
327
+ })
273
328
  fibers.push(
274
329
  yield* Effect.forkChild(
275
- parallel.aside(request).pipe(
330
+ journaled(attempts, journal, events, node.task, (attempt) =>
331
+ parallel.aside(request(attempt))
332
+ ).pipe(
276
333
  Effect.exit,
277
334
  Effect.flatMap((exit) => Queue.offer(finished, { kind: "aside", node, exit }))
278
335
  )
package/src/Stories.ts CHANGED
@@ -62,6 +62,7 @@ import {
62
62
  } from "./Perimeter.ts"
63
63
  import {
64
64
  loadVersioned,
65
+ attemptsPath,
65
66
  makePlanStore,
66
67
  saveVersioned,
67
68
  type PlainFileStoreShape
@@ -1298,6 +1299,7 @@ export const implementStoriesFlow = Effect.fn("@llm4ts/flow/Stories.implement")(
1298
1299
  // fresh branch would inherit "every task complete" and skip the coder.
1299
1300
  // The notes its tasks carried describe the old definition: gone too.
1300
1301
  yield* files.remove(planPath(story))
1302
+ yield* files.remove(attemptsPath(planPath(story)))
1301
1303
  yield* files.remove(notesPath(story))
1302
1304
  yield* files.remove(redTestsPath(options.stateDir, story.id))
1303
1305
  stored = undefined
@@ -0,0 +1,225 @@
1
+ import * as Effect from "effect/Effect"
2
+ import * as Option from "effect/Option"
3
+ import * as Schema from "effect/Schema"
4
+ import type * as Scope from "effect/Scope"
5
+ import * as Semaphore from "effect/Semaphore"
6
+ import { CheckoutBusy, PersistenceError } from "./FlowError.ts"
7
+ import { makeMemoryPlainFileStore, type PlainFileStoreShape } from "./Persistence.ts"
8
+
9
+ /**
10
+ * One writing run per checkout, across processes (ADR 0058). The flow process
11
+ * itself holds a lock file outside the checkout for as long as it runs, so a
12
+ * run started from a terminal, from the operator server or from anything
13
+ * else is refused while another one writes.
14
+ *
15
+ * The file names the run's pid and the process groups of the children it has
16
+ * running. A lock whose run is gone still holds while one of those groups is
17
+ * alive: a coding agent that outlived a killed flow keeps writing.
18
+ */
19
+ export class WriterHolder extends Schema.Class<WriterHolder>("WriterHolder")({
20
+ pid: Schema.Int,
21
+ runId: Schema.String,
22
+ flow: Schema.optionalKey(Schema.String),
23
+ workDir: Schema.String,
24
+ startedAt: Schema.Number,
25
+ /** Process groups of the children the run has running right now. */
26
+ groups: Schema.Array(Schema.Int)
27
+ }) {}
28
+
29
+ const decodeHolder = Schema.decodeUnknownOption(Schema.fromJsonString(WriterHolder))
30
+ const encodeHolder = Schema.encodeSync(Schema.fromJsonString(WriterHolder))
31
+
32
+ /** What the lock needs from the machine; the Node host is in the runner. */
33
+ export interface WriterLockHost {
34
+ readonly files: PlainFileStoreShape
35
+ /** Creates the file with its contents only when it does not exist; false when it does. */
36
+ readonly createExclusive: (
37
+ path: string,
38
+ contents: string
39
+ ) => Effect.Effect<boolean, PersistenceError>
40
+ readonly isAlive: (pid: number) => boolean
41
+ /** True while any process of the group `pgid` leads is alive. */
42
+ readonly groupAlive: (pgid: number) => boolean
43
+ /** This process. */
44
+ readonly pid: number
45
+ }
46
+
47
+ export interface WriterLockRequest {
48
+ /** The lock file of the checkout. */
49
+ readonly path: string
50
+ readonly workDir: string
51
+ readonly runId: string
52
+ readonly flow?: string
53
+ readonly startedAt: number
54
+ }
55
+
56
+ export interface HeldWriterLock {
57
+ /** Records the process groups of the children running now. */
58
+ readonly setGroups: (groups: ReadonlyArray<number>) => Effect.Effect<void>
59
+ }
60
+
61
+ /** Who holds a checkout: its run, or only processes that run left behind. */
62
+ export interface LiveHolder {
63
+ readonly holder: WriterHolder
64
+ readonly alive: "run" | "children"
65
+ readonly groups: ReadonlyArray<number>
66
+ }
67
+
68
+ export interface WriterLockShape {
69
+ /** Holds the checkout until the scope closes; `CheckoutBusy` when another run has it. */
70
+ readonly hold: (
71
+ request: WriterLockRequest
72
+ ) => Effect.Effect<HeldWriterLock, CheckoutBusy | PersistenceError, Scope.Scope>
73
+ /** The live holder of a lock file, if any. */
74
+ readonly holder: (path: string) => Effect.Effect<LiveHolder | undefined, PersistenceError>
75
+ }
76
+
77
+ export const checkoutBusy = (path: string, live: LiveHolder): CheckoutBusy =>
78
+ CheckoutBusy.make({
79
+ workDir: live.holder.workDir,
80
+ lockPath: path,
81
+ pid: live.holder.pid,
82
+ runId: live.holder.runId,
83
+ alive: live.alive,
84
+ groups: live.groups,
85
+ ...(live.holder.flow === undefined ? {} : { flow: live.holder.flow })
86
+ })
87
+
88
+ const guardStepMs = 25
89
+ const guardAttempts = 200
90
+
91
+ export const makeWriterLock = (host: WriterLockHost): WriterLockShape => {
92
+ const readHolder = (path: string) =>
93
+ host.files
94
+ .read(path)
95
+ .pipe(
96
+ Effect.map((text) =>
97
+ text === undefined ? undefined : Option.getOrUndefined(decodeHolder(text))
98
+ )
99
+ )
100
+
101
+ const liveOf = (holder: WriterHolder | undefined): LiveHolder | undefined => {
102
+ if (holder === undefined) return undefined
103
+ if (host.isAlive(holder.pid)) return { holder, alive: "run", groups: [] }
104
+ const groups = holder.groups.filter((group) => host.groupAlive(group))
105
+ return groups.length === 0 ? undefined : { holder, alive: "children", groups }
106
+ }
107
+
108
+ // Check-and-take must be one step across processes. A guard file, created
109
+ // exclusively, serializes it; a guard whose process is gone is removed.
110
+ const takeGuard = (guard: string): Effect.Effect<void, PersistenceError> =>
111
+ Effect.gen(function* () {
112
+ for (let attempt = 0; attempt < guardAttempts; attempt++) {
113
+ if (yield* host.createExclusive(guard, String(host.pid))) return
114
+ const owner = Number((yield* host.files.read(guard)) ?? "")
115
+ if (!Number.isInteger(owner) || !host.isAlive(owner)) {
116
+ yield* host.files.remove(guard)
117
+ } else {
118
+ yield* Effect.sleep(guardStepMs)
119
+ }
120
+ }
121
+ return yield* PersistenceError.make({
122
+ message: `could not take ${guard}: another llm4ts process holds it; remove the file if none is starting`
123
+ })
124
+ })
125
+
126
+ const guarded = <A, E>(path: string, body: Effect.Effect<A, E>) => {
127
+ const guard = `${path}.guard`
128
+ return Effect.acquireUseRelease(
129
+ takeGuard(guard),
130
+ () => body,
131
+ () => Effect.ignore(host.files.remove(guard))
132
+ )
133
+ }
134
+
135
+ const hold: WriterLockShape["hold"] = (request) => {
136
+ const mine = (groups: ReadonlyArray<number>): string =>
137
+ encodeHolder(
138
+ new WriterHolder({
139
+ pid: host.pid,
140
+ runId: request.runId,
141
+ workDir: request.workDir,
142
+ startedAt: request.startedAt,
143
+ groups: [...groups],
144
+ ...(request.flow === undefined ? {} : { flow: request.flow })
145
+ })
146
+ )
147
+ const take = guarded(
148
+ request.path,
149
+ Effect.gen(function* () {
150
+ const current = yield* readHolder(request.path)
151
+ // A run nested in this process shares the outer run's hold.
152
+ if (current?.pid === host.pid) return false
153
+ const live = liveOf(current)
154
+ if (live !== undefined) return yield* checkoutBusy(request.path, live)
155
+ yield* host.files.writeAtomic(request.path, mine([]))
156
+ return true
157
+ })
158
+ )
159
+ const release = (owned: boolean) =>
160
+ owned
161
+ ? Effect.ignore(
162
+ Effect.gen(function* () {
163
+ const current = yield* readHolder(request.path)
164
+ if (current?.pid === host.pid && current.runId === request.runId) {
165
+ yield* host.files.remove(request.path)
166
+ }
167
+ })
168
+ )
169
+ : Effect.void
170
+ return Effect.acquireRelease(take, release).pipe(
171
+ Effect.map((owned) => ({
172
+ setGroups: (groups) =>
173
+ owned ? Effect.ignore(host.files.writeAtomic(request.path, mine(groups))) : Effect.void
174
+ }))
175
+ )
176
+ }
177
+
178
+ return { hold, holder: (path) => readHolder(path).pipe(Effect.map(liveOf)) }
179
+ }
180
+
181
+ export interface MemoryWriterLockHost {
182
+ readonly host: WriterLockHost
183
+ readonly files: Effect.Effect<Readonly<Record<string, string>>>
184
+ readonly setAlive: (pid: number, alive: boolean) => void
185
+ readonly setGroupAlive: (pgid: number, alive: boolean) => void
186
+ }
187
+
188
+ /** The in-memory host for tests: `pid` is alive from the start. */
189
+ export const makeMemoryWriterLockHost = (
190
+ pid: number,
191
+ shared?: MemoryWriterLockHost
192
+ ): Effect.Effect<MemoryWriterLockHost> =>
193
+ Effect.gen(function* () {
194
+ if (shared !== undefined) {
195
+ shared.setAlive(pid, true)
196
+ return { ...shared, host: { ...shared.host, pid } }
197
+ }
198
+ const memory = yield* makeMemoryPlainFileStore()
199
+ const exclusive = yield* Semaphore.make(1)
200
+ const alive = new Set<number>([pid])
201
+ const groups = new Set<number>()
202
+ const toggle = (set: Set<number>) => (member: number, on: boolean) => {
203
+ if (on) set.add(member)
204
+ else set.delete(member)
205
+ }
206
+ return {
207
+ host: {
208
+ files: memory.store,
209
+ createExclusive: (path, contents) =>
210
+ exclusive.withPermits(1)(
211
+ Effect.gen(function* () {
212
+ if ((yield* memory.store.read(path)) !== undefined) return false
213
+ yield* memory.store.writeAtomic(path, contents)
214
+ return true
215
+ })
216
+ ),
217
+ isAlive: (candidate) => alive.has(candidate),
218
+ groupAlive: (candidate) => groups.has(candidate),
219
+ pid
220
+ },
221
+ files: memory.files,
222
+ setAlive: toggle(alive),
223
+ setGroupAlive: toggle(groups)
224
+ }
225
+ })
@@ -783,6 +783,15 @@ export const settings = {
783
783
  doc: "The Gemini model the bridge reasons with."
784
784
  }),
785
785
 
786
+ // ---- run lifecycle ---------------------------------------------------------
787
+ LLM4TS_WRITER_LOCK: setting({
788
+ group: "launch",
789
+ scope: "global",
790
+ value: Value.toggle,
791
+ fallback: fallback.value(true, "on"),
792
+ doc: "One writing run per checkout: a second one is refused while the first, or a process it started, is alive. off lets runs write side by side."
793
+ }),
794
+
786
795
  // ---- operator ---------------------------------------------------------------
787
796
  LLM4TS_MCP_TOKEN: setting({
788
797
  group: "operator",