@llm4ts/flow 2.53.0 → 2.54.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 (70) 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 +1 -1
  12. package/dist/Flow.d.ts.map +1 -1
  13. package/dist/FlowError.d.ts +25 -1
  14. package/dist/FlowError.d.ts.map +1 -1
  15. package/dist/FlowError.js +33 -1
  16. package/dist/FlowError.js.map +1 -1
  17. package/dist/FlowEvents.d.ts +21 -1
  18. package/dist/FlowEvents.d.ts.map +1 -1
  19. package/dist/FlowEvents.js +19 -0
  20. package/dist/FlowEvents.js.map +1 -1
  21. package/dist/Gates.d.ts +1 -1
  22. package/dist/Gates.d.ts.map +1 -1
  23. package/dist/GraphCache.d.ts +1 -1
  24. package/dist/GraphCache.d.ts.map +1 -1
  25. package/dist/Judgment.d.ts +2 -2
  26. package/dist/Judgment.d.ts.map +1 -1
  27. package/dist/Landing.d.ts +1 -1
  28. package/dist/Landing.d.ts.map +1 -1
  29. package/dist/Memory.d.ts +35 -0
  30. package/dist/Memory.d.ts.map +1 -0
  31. package/dist/Memory.js +139 -0
  32. package/dist/Memory.js.map +1 -0
  33. package/dist/NodePreflight.d.ts +1 -1
  34. package/dist/NodePreflight.d.ts.map +1 -1
  35. package/dist/Persistence.d.ts +2 -2
  36. package/dist/Persistence.d.ts.map +1 -1
  37. package/dist/PlanExecution.d.ts +2 -2
  38. package/dist/PlanExecution.d.ts.map +1 -1
  39. package/dist/ProgramJudge.d.ts +1 -1
  40. package/dist/ProgramJudge.d.ts.map +1 -1
  41. package/dist/Replay.d.ts +2 -2
  42. package/dist/Replay.d.ts.map +1 -1
  43. package/dist/Retro.d.ts +3 -3
  44. package/dist/Retro.d.ts.map +1 -1
  45. package/dist/Review.d.ts +5 -5
  46. package/dist/Review.d.ts.map +1 -1
  47. package/dist/ReviewCache.d.ts +1 -1
  48. package/dist/ReviewCache.d.ts.map +1 -1
  49. package/dist/Roster.d.ts +1 -1
  50. package/dist/Roster.d.ts.map +1 -1
  51. package/dist/RosterSeats.d.ts +1 -1
  52. package/dist/RosterSeats.d.ts.map +1 -1
  53. package/dist/Roundtable.d.ts +17 -4
  54. package/dist/Roundtable.d.ts.map +1 -1
  55. package/dist/Roundtable.js +45 -6
  56. package/dist/Roundtable.js.map +1 -1
  57. package/dist/Stories.d.ts +1 -1
  58. package/dist/Stories.d.ts.map +1 -1
  59. package/dist/Taskforce.d.ts +293 -0
  60. package/dist/Taskforce.d.ts.map +1 -0
  61. package/dist/Taskforce.js +1063 -0
  62. package/dist/Taskforce.js.map +1 -0
  63. package/dist/WorkQueue.d.ts +1 -1
  64. package/dist/WorkQueue.d.ts.map +1 -1
  65. package/package.json +4 -2
  66. package/src/FlowError.ts +36 -1
  67. package/src/FlowEvents.ts +21 -0
  68. package/src/Memory.ts +151 -0
  69. package/src/Roundtable.ts +49 -6
  70. package/src/Taskforce.ts +1248 -0
@@ -0,0 +1,1248 @@
1
+ /**
2
+ * taskforce (ADR 0047): the pure half of the delegation loop. The plan file
3
+ * and the reports are the state; this module parses and renders them,
4
+ * derives what is ready, blocked, checked and done, and tells the flow what
5
+ * to do next (`nextAction`). Nothing here talks to a model, a file or a
6
+ * process; the flow does.
7
+ */
8
+ import * as Effect from "effect/Effect"
9
+ import * as Schema from "effect/Schema"
10
+ import type { JsonSchema } from "@llm4ts/core/Models"
11
+ import { makeOpenPointsCollector, OpenPoint } from "./Decisions.ts"
12
+ import { PlanInvalid, ReportInvalid } from "./FlowError.ts"
13
+ import type { Persona } from "./Roundtable.ts"
14
+
15
+ export { ToolGrade } from "./Roundtable.ts"
16
+
17
+ const dash = " — "
18
+ const headerLine = /^([A-Za-z][A-Za-z ]*):\s*(.*)$/
19
+ const oneLine = (text: string): string => text.replace(/\s+/g, " ").trim()
20
+ const prose = (text: string): ReadonlyArray<string> =>
21
+ text.trim().length === 0 ? [] : text.trim().split(/\r?\n/)
22
+ const bulletLines = (text: string): ReadonlyArray<string> =>
23
+ prose(text)
24
+ .map((line) => line.trim().replace(/^-\s*/, "").trim())
25
+ .filter((line) => line.length > 0)
26
+
27
+ // ---- The plan file --------------------------------------------------------------
28
+
29
+ export const PlanStatus = Schema.Literals([
30
+ "planned",
31
+ "working",
32
+ "drafting",
33
+ "reviewing",
34
+ "fixing",
35
+ "distilling",
36
+ "done"
37
+ ])
38
+ export type PlanStatus = typeof PlanStatus.Type
39
+
40
+ const isPlanStatus = (value: string): value is PlanStatus =>
41
+ PlanStatus.literals.some((status) => status === value)
42
+
43
+ /** The eight fields of a brief, in the order the file shows them (pstack's template). */
44
+ export const briefFields = [
45
+ "GOAL",
46
+ "SCOPE",
47
+ "CONTEXT",
48
+ "ACCEPTANCE",
49
+ "VERIFY",
50
+ "TIMEBOX",
51
+ "FORBIDDEN",
52
+ "REPORT"
53
+ ] as const
54
+ type BriefField = (typeof briefFields)[number]
55
+ const fieldKeys = {
56
+ GOAL: "goal",
57
+ SCOPE: "scope",
58
+ CONTEXT: "context",
59
+ ACCEPTANCE: "acceptance",
60
+ VERIFY: "verify",
61
+ TIMEBOX: "timebox",
62
+ FORBIDDEN: "forbidden",
63
+ REPORT: "report"
64
+ } as const
65
+ const isBriefField = (value: string): value is BriefField =>
66
+ briefFields.some((field) => field === value)
67
+
68
+ /** One unit of delegated work: an owner, dependencies, a wave, the eight fields. */
69
+ export class Brief extends Schema.Class<Brief>("Brief")({
70
+ /** `B1`, `B2`, … in the order they were added to the plan. */
71
+ id: Schema.String,
72
+ title: Schema.String,
73
+ /** A specialist's name from the cast. */
74
+ owner: Schema.String,
75
+ dependsOn: Schema.Array(Schema.String),
76
+ /** The wave it was planned in: 1 the plan, 2 a re-plan or rework, the fix wave after a review. */
77
+ wave: Schema.Int,
78
+ goal: Schema.String,
79
+ scope: Schema.String,
80
+ context: Schema.String,
81
+ /** One line per criterion, as written (bullets kept). */
82
+ acceptance: Schema.String,
83
+ /** One command per line; only a `commands` card ever runs them. */
84
+ verify: Schema.String,
85
+ timebox: Schema.String,
86
+ forbidden: Schema.String,
87
+ /** What the report must hold, and which deliverable it feeds. */
88
+ report: Schema.String
89
+ }) {}
90
+
91
+ /** The Chief of Staff's verdict after a wave. */
92
+ export class GoalCheck extends Schema.Class<GoalCheck>("GoalCheck")({
93
+ wave: Schema.Int,
94
+ reached: Schema.Boolean,
95
+ note: Schema.String
96
+ }) {}
97
+
98
+ export class Plan extends Schema.Class<Plan>("TaskforcePlan")({
99
+ id: Schema.String,
100
+ status: PlanStatus,
101
+ goal: Schema.String,
102
+ /** File names the Doc Writer writes; `result.md` is always among them. */
103
+ deliverables: Schema.Array(Schema.String),
104
+ /** Every specialist present, the Chief of Staff and the Doc Writer included. */
105
+ cast: Schema.Array(Schema.String),
106
+ briefs: Schema.Array(Brief),
107
+ checks: Schema.Array(GoalCheck),
108
+ /** Questions for the owner, with the assumption the run took; an answer here reopens work. */
109
+ answers: Schema.Array(OpenPoint),
110
+ feedback: Schema.String,
111
+ /** Drafts the Doc Writer wrote: 0 none, 1 reviewed, 2 redrafted after the fix wave. */
112
+ drafts: Schema.Int,
113
+ /** Answer numbers already folded into a brief, so a rerun does not fold them twice. */
114
+ folded: Schema.Array(Schema.Int)
115
+ }) {}
116
+
117
+ /** The turn cap a TIMEBOX names (`20 turns`, `20`), when it names one. */
118
+ export const timeboxTurns = (brief: Brief): number | undefined => {
119
+ const match = /(\d+)/.exec(brief.timebox)
120
+ const turns = match === null ? undefined : Number.parseInt(match[1] ?? "", 10)
121
+ return turns === undefined || Number.isNaN(turns) || turns <= 0 ? undefined : turns
122
+ }
123
+
124
+ /** The VERIFY lines as commands: bullets stripped, blanks dropped. */
125
+ export const verifyCommands = (brief: Brief): ReadonlyArray<string> => bulletLines(brief.verify)
126
+
127
+ /** The ACCEPTANCE lines as criteria. */
128
+ export const acceptanceLines = (brief: Brief): ReadonlyArray<string> =>
129
+ bulletLines(brief.acceptance)
130
+
131
+ export const renderBrief = (brief: Brief): ReadonlyArray<string> => [
132
+ `### ${brief.id}. ${brief.title}`,
133
+ `Owner: ${brief.owner}`,
134
+ `Depends on: ${brief.dependsOn.length === 0 ? "-" : brief.dependsOn.join(", ")}`,
135
+ `Wave: ${brief.wave}`,
136
+ "",
137
+ ...briefFields.flatMap((field) => {
138
+ const body = brief[fieldKeys[field]]
139
+ const lines = prose(body)
140
+ return lines.length <= 1 ? [`${field}: ${lines[0] ?? ""}`.trimEnd()] : [`${field}:`, ...lines]
141
+ }),
142
+ ""
143
+ ]
144
+
145
+ const renderCheck = (check: GoalCheck): string =>
146
+ `- wave ${check.wave}: ${check.reached ? "reached" : "not reached"}${dash}${oneLine(check.note)}`
147
+
148
+ export const renderPlan = (plan: Plan): string =>
149
+ [
150
+ `# Taskforce: ${plan.id}`,
151
+ "",
152
+ `Status: ${plan.status}`,
153
+ `Goal: ${plan.goal}`,
154
+ `Deliverables: ${plan.deliverables.join(", ")}`,
155
+ `Cast: ${plan.cast.join(", ")}`,
156
+ `Drafts: ${plan.drafts}`,
157
+ `Folded: ${plan.folded.length === 0 ? "-" : plan.folded.join(", ")}`,
158
+ "",
159
+ "## Briefs",
160
+ "",
161
+ ...plan.briefs.flatMap(renderBrief),
162
+ "## Goal checks",
163
+ "",
164
+ ...(plan.checks.length === 0 ? ["- none"] : plan.checks.map(renderCheck)),
165
+ "",
166
+ "## Answers",
167
+ "",
168
+ ...plan.answers.flatMap((point) => [
169
+ `${point.number}. ${point.question}`,
170
+ ` answer:${(point.answer ?? "").trim().length === 0 ? "" : ` ${(point.answer ?? "").trim()}`}`
171
+ ]),
172
+ "",
173
+ "## Feedback",
174
+ "",
175
+ ...prose(plan.feedback),
176
+ ""
177
+ ].join("\n")
178
+
179
+ const settledPoint = (point: OpenPoint): OpenPoint =>
180
+ (point.answer ?? "").trim().length === 0
181
+ ? OpenPoint.make({ number: point.number, question: point.question })
182
+ : OpenPoint.make({
183
+ number: point.number,
184
+ question: point.question,
185
+ answer: (point.answer ?? "").trim()
186
+ })
187
+
188
+ type PlanSection = "briefs" | "checks" | "answers" | "feedback"
189
+ const planSections: Record<string, PlanSection> = {
190
+ briefs: "briefs",
191
+ "goal checks": "checks",
192
+ answers: "answers",
193
+ feedback: "feedback"
194
+ }
195
+
196
+ const splitList = (value: string): ReadonlyArray<string> =>
197
+ value === "-"
198
+ ? []
199
+ : value
200
+ .split(",")
201
+ .map((entry) => entry.trim())
202
+ .filter((entry) => entry.length > 0)
203
+
204
+ interface DraftBrief {
205
+ id: string
206
+ title: string
207
+ owner: string | undefined
208
+ dependsOn: ReadonlyArray<string>
209
+ wave: number | undefined
210
+ fields: Record<BriefField, Array<string>>
211
+ field: BriefField | undefined
212
+ line: number
213
+ }
214
+
215
+ const emptyFields = (): Record<BriefField, Array<string>> => ({
216
+ GOAL: [],
217
+ SCOPE: [],
218
+ CONTEXT: [],
219
+ ACCEPTANCE: [],
220
+ VERIFY: [],
221
+ TIMEBOX: [],
222
+ FORBIDDEN: [],
223
+ REPORT: []
224
+ })
225
+
226
+ export const parsePlan = Effect.fn("@llm4ts/flow/Taskforce.parsePlan")(function* (
227
+ markdown: string,
228
+ path?: string
229
+ ): Effect.fn.Return<Plan, PlanInvalid> {
230
+ const violations: Array<string> = []
231
+ let id: string | undefined
232
+ let status: PlanStatus | undefined
233
+ let drafts = 0
234
+ let folded: Array<number> = []
235
+ const header: Record<string, string> = {}
236
+ const briefs: Array<DraftBrief> = []
237
+ const checks: Array<GoalCheck> = []
238
+ const points = makeOpenPointsCollector()
239
+ const feedback: Array<string> = []
240
+ let current: PlanSection | "header" | "unknown" = "header"
241
+ let fenced = false
242
+ const lines = markdown.split(/\r?\n/)
243
+ for (let index = 0; index < lines.length; index += 1) {
244
+ const number = index + 1
245
+ const raw = lines[index] ?? ""
246
+ const trimmed = raw.trim()
247
+ if (trimmed.startsWith("```")) {
248
+ fenced = !fenced
249
+ if (current === "feedback") feedback.push(raw)
250
+ else if (current === "briefs") {
251
+ const brief = briefs.at(-1)
252
+ if (brief?.field !== undefined) brief.fields[brief.field].push(raw)
253
+ }
254
+ continue
255
+ }
256
+ if (!fenced && trimmed.startsWith("## ")) {
257
+ const title = trimmed.slice(3).trim()
258
+ const key = planSections[title.toLowerCase()]
259
+ if (key === undefined) {
260
+ violations.push(`line ${number}: unknown section "${title}"`)
261
+ current = "unknown"
262
+ } else {
263
+ current = key
264
+ }
265
+ continue
266
+ }
267
+ if (current === "feedback") {
268
+ feedback.push(raw)
269
+ continue
270
+ }
271
+ if (current === "briefs") {
272
+ const opened = /^###\s+(B\d+)\.\s+(.*)$/.exec(trimmed)
273
+ if (!fenced && opened !== null) {
274
+ briefs.push({
275
+ id: opened[1] ?? "",
276
+ title: (opened[2] ?? "").trim(),
277
+ owner: undefined,
278
+ dependsOn: [],
279
+ wave: undefined,
280
+ fields: emptyFields(),
281
+ field: undefined,
282
+ line: number
283
+ })
284
+ continue
285
+ }
286
+ const brief = briefs.at(-1)
287
+ if (brief === undefined) {
288
+ if (trimmed.length > 0) {
289
+ violations.push(
290
+ `line ${number}: a brief starts with \`### B1. <title>\`, got: ${trimmed}`
291
+ )
292
+ }
293
+ continue
294
+ }
295
+ const field = /^([A-Z]+):\s?(.*)$/.exec(fenced ? "" : raw)
296
+ if (field !== null && isBriefField(field[1] ?? "")) {
297
+ const name = field[1] ?? "GOAL"
298
+ if (isBriefField(name)) {
299
+ brief.field = name
300
+ const rest = (field[2] ?? "").trimEnd()
301
+ if (rest.trim().length > 0) brief.fields[name].push(rest)
302
+ }
303
+ continue
304
+ }
305
+ if (brief.field === undefined) {
306
+ const meta = headerLine.exec(trimmed)
307
+ if (meta?.[1] === undefined) {
308
+ if (trimmed.length > 0) {
309
+ violations.push(
310
+ `line ${number}: a brief's header is Owner:, Depends on:, Wave:, got: ${trimmed}`
311
+ )
312
+ }
313
+ continue
314
+ }
315
+ const name = meta[1].toLowerCase()
316
+ const value = (meta[2] ?? "").trim()
317
+ if (name === "owner") brief.owner = value
318
+ else if (name === "depends on") brief.dependsOn = splitList(value)
319
+ else if (name === "wave") {
320
+ if (/^\d+$/.test(value)) brief.wave = Number.parseInt(value, 10)
321
+ else violations.push(`line ${number}: Wave is a whole number, got: ${value}`)
322
+ } else {
323
+ violations.push(`line ${number}: unknown brief header ${meta[1]}`)
324
+ }
325
+ continue
326
+ }
327
+ brief.fields[brief.field].push(raw)
328
+ continue
329
+ }
330
+ if (fenced || trimmed.length === 0 || current === "unknown") continue
331
+ if (current === "header") {
332
+ const title = /^#\s+Taskforce:\s*(.+)$/i.exec(trimmed)
333
+ if (title?.[1] !== undefined) {
334
+ id = title[1].trim()
335
+ continue
336
+ }
337
+ const field = headerLine.exec(trimmed)
338
+ if (field?.[1] === undefined) continue
339
+ const name = field[1].toLowerCase()
340
+ const value = (field[2] ?? "").trim()
341
+ if (name === "status") {
342
+ if (isPlanStatus(value)) status = value
343
+ else {
344
+ violations.push(
345
+ `line ${number}: Status is one of ${PlanStatus.literals.join(", ")}, got: ${value}`
346
+ )
347
+ status = "working"
348
+ }
349
+ } else if (name === "drafts") {
350
+ if (/^\d+$/.test(value)) drafts = Number.parseInt(value, 10)
351
+ else violations.push(`line ${number}: Drafts is a whole number, got: ${value}`)
352
+ } else if (name === "folded") {
353
+ folded = splitList(value).flatMap((entry) =>
354
+ /^\d+$/.test(entry) ? [Number.parseInt(entry, 10)] : []
355
+ )
356
+ } else {
357
+ header[name] = value
358
+ }
359
+ continue
360
+ }
361
+ if (current === "answers") {
362
+ const problem = points.add(number, trimmed)
363
+ if (problem !== undefined) violations.push(problem)
364
+ continue
365
+ }
366
+ if (current === "checks") {
367
+ if (trimmed === "- none") continue
368
+ const check = /^-\s*wave\s+(\d+):\s*(reached|not reached)(?:\s*—\s*(.*))?$/.exec(trimmed)
369
+ if (check === null) {
370
+ violations.push(
371
+ `line ${number}: a goal check is \`- wave <n>: reached|not reached${dash}<note>\`, got: ${trimmed}`
372
+ )
373
+ } else {
374
+ checks.push(
375
+ GoalCheck.make({
376
+ wave: Number.parseInt(check[1] ?? "0", 10),
377
+ reached: check[2] === "reached",
378
+ note: (check[3] ?? "").trim()
379
+ })
380
+ )
381
+ }
382
+ }
383
+ }
384
+ if (id === undefined) violations.push("missing the `# Taskforce: <id>` title")
385
+ if (status === undefined) violations.push("missing the `Status:` line")
386
+ if (header.goal === undefined) violations.push("missing the `Goal:` line")
387
+ if (header.cast === undefined) violations.push("missing the `Cast:` line")
388
+ if (fenced) violations.push("a code fence is never closed")
389
+ for (const brief of briefs) {
390
+ if (brief.owner === undefined) violations.push(`line ${brief.line}: ${brief.id} has no Owner:`)
391
+ if (brief.wave === undefined) violations.push(`line ${brief.line}: ${brief.id} has no Wave:`)
392
+ }
393
+ if (violations.length > 0 || id === undefined || status === undefined) {
394
+ return yield* PlanInvalid.make({ ...(path === undefined ? {} : { path }), violations })
395
+ }
396
+ const text = (lines: ReadonlyArray<string>): string => lines.join("\n").trim()
397
+ return Plan.make({
398
+ id,
399
+ status,
400
+ goal: header.goal ?? "",
401
+ deliverables: splitList(header.deliverables ?? ""),
402
+ cast: splitList(header.cast ?? ""),
403
+ briefs: briefs.map((brief) =>
404
+ Brief.make({
405
+ id: brief.id,
406
+ title: brief.title,
407
+ owner: brief.owner ?? "",
408
+ dependsOn: brief.dependsOn,
409
+ wave: brief.wave ?? 1,
410
+ goal: text(brief.fields.GOAL),
411
+ scope: text(brief.fields.SCOPE),
412
+ context: text(brief.fields.CONTEXT),
413
+ acceptance: text(brief.fields.ACCEPTANCE),
414
+ verify: text(brief.fields.VERIFY),
415
+ timebox: text(brief.fields.TIMEBOX),
416
+ forbidden: text(brief.fields.FORBIDDEN),
417
+ report: text(brief.fields.REPORT)
418
+ })
419
+ ),
420
+ checks,
421
+ answers: points.points.map(settledPoint),
422
+ feedback: feedback.join("\n").trim(),
423
+ drafts,
424
+ folded
425
+ })
426
+ })
427
+
428
+ // ---- Validity (decision 3) --------------------------------------------------------
429
+
430
+ export interface Caps {
431
+ /** Waves in all, the fix wave included. */
432
+ readonly waves: number
433
+ /** Briefs in all. */
434
+ readonly briefs: number
435
+ }
436
+
437
+ export const defaultCaps: Caps = { waves: 3, briefs: 12 }
438
+ export const minBriefs = 2
439
+
440
+ const hasCycle = (briefs: ReadonlyArray<Brief>): boolean => {
441
+ const edges = new Map(briefs.map((brief) => [brief.id, brief.dependsOn]))
442
+ const state = new Map<string, "open" | "done">()
443
+ const visit = (id: string): boolean => {
444
+ const seen = state.get(id)
445
+ if (seen === "open") return true
446
+ if (seen === "done") return false
447
+ state.set(id, "open")
448
+ for (const next of edges.get(id) ?? []) if (edges.has(next) && visit(next)) return true
449
+ state.set(id, "done")
450
+ return false
451
+ }
452
+ return briefs.some((brief) => visit(brief.id))
453
+ }
454
+
455
+ /** Everything that stops a plan from running; empty when it may. */
456
+ export const planViolations = (plan: Plan, caps: Caps): ReadonlyArray<string> => {
457
+ const violations: Array<string> = []
458
+ if (plan.briefs.length < minBriefs || plan.briefs.length > caps.briefs) {
459
+ violations.push(`${minBriefs} to ${caps.briefs} briefs, got ${plan.briefs.length}`)
460
+ }
461
+ const ids = new Set<string>()
462
+ for (const brief of plan.briefs) {
463
+ if (ids.has(brief.id)) violations.push(`${brief.id}: listed twice`)
464
+ ids.add(brief.id)
465
+ }
466
+ for (const brief of plan.briefs) {
467
+ if (brief.title.trim().length === 0) violations.push(`${brief.id}: has no title`)
468
+ if (!plan.cast.includes(brief.owner)) {
469
+ violations.push(`${brief.id}: owner ${brief.owner} is not in the cast`)
470
+ }
471
+ for (const dependency of brief.dependsOn) {
472
+ if (!ids.has(dependency)) {
473
+ violations.push(`${brief.id}: depends on ${dependency}, which is not a brief`)
474
+ }
475
+ }
476
+ if (brief.goal.trim().length === 0) violations.push(`${brief.id}: GOAL is empty`)
477
+ if (acceptanceLines(brief).length === 0) violations.push(`${brief.id}: ACCEPTANCE is empty`)
478
+ }
479
+ if (hasCycle(plan.briefs)) violations.push("briefs depend on each other in a cycle")
480
+ for (const deliverable of plan.deliverables) {
481
+ const named = plan.briefs.some(
482
+ (brief) =>
483
+ brief.report.toLowerCase().includes(deliverable.toLowerCase()) ||
484
+ brief.goal.toLowerCase().includes(deliverable.toLowerCase())
485
+ )
486
+ if (!named) violations.push(`deliverable ${deliverable} is named by no brief`)
487
+ }
488
+ return violations
489
+ }
490
+
491
+ // ---- Proposals (what the models reply) ---------------------------------------------
492
+
493
+ export class BriefProposal extends Schema.Class<BriefProposal>("BriefProposal")({
494
+ title: Schema.String,
495
+ owner: Schema.String,
496
+ /** Brief ids (`B3`), the proposal's own numbered from the `from` the prompt names. */
497
+ dependsOn: Schema.Array(Schema.String),
498
+ goal: Schema.String,
499
+ scope: Schema.String,
500
+ context: Schema.String,
501
+ acceptance: Schema.Array(Schema.String),
502
+ verify: Schema.Array(Schema.String),
503
+ timebox: Schema.String,
504
+ forbidden: Schema.String,
505
+ report: Schema.String
506
+ }) {}
507
+
508
+ const briefProposalJsonSchema: JsonSchema = {
509
+ type: "object",
510
+ properties: {
511
+ title: { type: "string" },
512
+ owner: { type: "string" },
513
+ dependsOn: { type: "array", items: { type: "string" } },
514
+ goal: { type: "string" },
515
+ scope: { type: "string" },
516
+ context: { type: "string" },
517
+ acceptance: { type: "array", items: { type: "string" } },
518
+ verify: { type: "array", items: { type: "string" } },
519
+ timebox: { type: "string" },
520
+ forbidden: { type: "string" },
521
+ report: { type: "string" }
522
+ },
523
+ required: [
524
+ "title",
525
+ "owner",
526
+ "dependsOn",
527
+ "goal",
528
+ "scope",
529
+ "context",
530
+ "acceptance",
531
+ "verify",
532
+ "timebox",
533
+ "forbidden",
534
+ "report"
535
+ ]
536
+ }
537
+
538
+ export class PlanProposal extends Schema.Class<PlanProposal>("PlanProposal")({
539
+ deliverables: Schema.Array(Schema.String),
540
+ briefs: Schema.Array(BriefProposal)
541
+ }) {}
542
+
543
+ export const planProposalJsonSchema: JsonSchema = {
544
+ type: "object",
545
+ properties: {
546
+ deliverables: { type: "array", items: { type: "string" } },
547
+ briefs: { type: "array", items: briefProposalJsonSchema }
548
+ },
549
+ required: ["deliverables", "briefs"]
550
+ }
551
+
552
+ export class CheckProposal extends Schema.Class<CheckProposal>("CheckProposal")({
553
+ reached: Schema.Boolean,
554
+ note: Schema.String,
555
+ /** The second wave, when the goal is not reached and a re-plan is allowed; else empty. */
556
+ briefs: Schema.Array(BriefProposal)
557
+ }) {}
558
+
559
+ export const checkProposalJsonSchema: JsonSchema = {
560
+ type: "object",
561
+ properties: {
562
+ reached: { type: "boolean" },
563
+ note: { type: "string" },
564
+ briefs: { type: "array", items: briefProposalJsonSchema }
565
+ },
566
+ required: ["reached", "note", "briefs"]
567
+ }
568
+
569
+ export const ReportStatus = Schema.Literals(["PASS", "ISSUES", "BLOCKED"])
570
+ export type ReportStatus = typeof ReportStatus.Type
571
+ const isReportStatus = (value: string): value is ReportStatus =>
572
+ ReportStatus.literals.some((status) => status === value)
573
+
574
+ export class OwnerQuestion extends Schema.Class<OwnerQuestion>("OwnerQuestion")({
575
+ question: Schema.String,
576
+ /** What the specialist proceeded on, since nobody answers inside the run. */
577
+ assumption: Schema.String
578
+ }) {}
579
+
580
+ export class ReportProposal extends Schema.Class<ReportProposal>("ReportProposal")({
581
+ status: ReportStatus,
582
+ evidence: Schema.Array(Schema.String),
583
+ summary: Schema.String,
584
+ questions: Schema.Array(OwnerQuestion),
585
+ body: Schema.String
586
+ }) {}
587
+
588
+ export const reportProposalJsonSchema: JsonSchema = {
589
+ type: "object",
590
+ properties: {
591
+ status: { type: "string", enum: ["PASS", "ISSUES", "BLOCKED"] },
592
+ evidence: { type: "array", items: { type: "string" } },
593
+ summary: { type: "string" },
594
+ questions: {
595
+ type: "array",
596
+ items: {
597
+ type: "object",
598
+ properties: { question: { type: "string" }, assumption: { type: "string" } },
599
+ required: ["question", "assumption"]
600
+ }
601
+ },
602
+ body: { type: "string" }
603
+ },
604
+ required: ["status", "evidence", "summary", "questions", "body"]
605
+ }
606
+
607
+ export interface AssembleOptions {
608
+ /** The number the first proposed brief gets. */
609
+ readonly from: number
610
+ readonly wave: number
611
+ readonly cast: ReadonlyArray<Persona>
612
+ }
613
+
614
+ export interface AssembledBriefs {
615
+ readonly briefs: ReadonlyArray<Brief>
616
+ /** What was changed on the way: VERIFY dropped for want of an Operator. */
617
+ readonly notes: ReadonlyArray<string>
618
+ }
619
+
620
+ const joinLines = (lines: ReadonlyArray<string>): string =>
621
+ lines
622
+ .map((line) => oneLine(line))
623
+ .filter((line) => line.length > 0)
624
+ .map((line) => `- ${line}`)
625
+ .join("\n")
626
+
627
+ /**
628
+ * Proposed briefs as plan briefs: ids from `from`, titles one line,
629
+ * dependencies kept only when they name a brief that exists or is proposed,
630
+ * and VERIFY moved off every card that may not run commands onto a
631
+ * verifying brief owned by the first `commands` card, after the brief it
632
+ * checks (decision 5).
633
+ */
634
+ export const assembleBriefs = (
635
+ proposals: ReadonlyArray<BriefProposal>,
636
+ options: AssembleOptions,
637
+ existing: ReadonlyArray<string> = []
638
+ ): AssembledBriefs => {
639
+ const notes: Array<string> = []
640
+ const operator = options.cast.find((persona) => persona.tools === "commands")
641
+ const gradeOf = (owner: string) => options.cast.find((persona) => persona.name === owner)?.tools
642
+ let next = options.from
643
+ const proposed = proposals.map(() => `B${next++}`)
644
+ const known = new Set([...existing, ...proposed])
645
+ const briefs: Array<Brief> = []
646
+ const verifiers: Array<Brief> = []
647
+ proposals.forEach((proposal, index) => {
648
+ const id = proposed[index] ?? `B${options.from + index}`
649
+ const dependsOn = [...new Set(proposal.dependsOn.map((entry) => entry.trim()))]
650
+ .filter((entry) => known.has(entry) && entry !== id)
651
+ .sort(
652
+ (left, right) => Number.parseInt(left.slice(1), 10) - Number.parseInt(right.slice(1), 10)
653
+ )
654
+ const verify = joinLines(proposal.verify)
655
+ const runsCommands = gradeOf(proposal.owner) === "commands"
656
+ briefs.push(
657
+ Brief.make({
658
+ id,
659
+ title: oneLine(proposal.title),
660
+ owner: proposal.owner.trim(),
661
+ dependsOn,
662
+ wave: options.wave,
663
+ goal: proposal.goal.trim(),
664
+ scope: proposal.scope.trim(),
665
+ context: proposal.context.trim(),
666
+ acceptance: joinLines(proposal.acceptance),
667
+ verify: runsCommands ? verify : "",
668
+ timebox: oneLine(proposal.timebox),
669
+ forbidden: proposal.forbidden.trim(),
670
+ report: proposal.report.trim()
671
+ })
672
+ )
673
+ if (runsCommands || verify.length === 0) return
674
+ if (operator === undefined) {
675
+ notes.push(
676
+ `${id}: VERIFY dropped — no card in the cast runs commands (add the Operator with --agents)`
677
+ )
678
+ return
679
+ }
680
+ const verifier = `B${next++}`
681
+ verifiers.push(
682
+ Brief.make({
683
+ id: verifier,
684
+ title: `Verify ${id}`,
685
+ owner: operator.name,
686
+ dependsOn: [id],
687
+ wave: options.wave,
688
+ goal: `Run the checks for ${id} and report what each said.`,
689
+ scope: `The repository as ${id} left it; write nothing.`,
690
+ context: `${id}'s report is in reports/${id}.md.`,
691
+ acceptance: "- Every command's exit code and output are in the report, unparaphrased.",
692
+ verify,
693
+ timebox: "1 run of each command",
694
+ forbidden: "Fixing anything; running a command the VERIFY list does not name.",
695
+ report: `reports/${verifier}.md with the commands, exit codes and output.`
696
+ })
697
+ )
698
+ })
699
+ return { briefs: [...briefs, ...verifiers], notes }
700
+ }
701
+
702
+ // ---- Reports -------------------------------------------------------------------------
703
+
704
+ export class Report extends Schema.Class<Report>("BriefReport")({
705
+ brief: Schema.String,
706
+ status: ReportStatus,
707
+ /** 1 the first dispatch, 2 the retry after BLOCKED. */
708
+ attempt: Schema.Int,
709
+ evidence: Schema.Array(Schema.String),
710
+ summary: Schema.String,
711
+ questions: Schema.Array(OwnerQuestion),
712
+ body: Schema.String
713
+ }) {}
714
+
715
+ export const renderReport = (report: Report, title: string): string =>
716
+ [
717
+ `# ${report.brief}: ${oneLine(title)}`,
718
+ `Status: ${report.status}`,
719
+ `Attempt: ${report.attempt}`,
720
+ `Evidence: ${report.evidence.length === 0 ? "-" : report.evidence.map(oneLine).join(", ")}`,
721
+ `Summary: ${oneLine(report.summary)}`,
722
+ ...report.questions.map(
723
+ (question) =>
724
+ `Question: ${oneLine(question.question)} (assuming: ${oneLine(question.assumption)})`
725
+ ),
726
+ "",
727
+ report.body.trim(),
728
+ ""
729
+ ].join("\n")
730
+
731
+ export const parseReport = Effect.fn("@llm4ts/flow/Taskforce.parseReport")(function* (
732
+ markdown: string,
733
+ path?: string
734
+ ): Effect.fn.Return<Report, ReportInvalid> {
735
+ const violations: Array<string> = []
736
+ const lines = markdown.split(/\r?\n/)
737
+ let brief: string | undefined
738
+ let status: ReportStatus | undefined
739
+ let attempt = 1
740
+ let evidence: ReadonlyArray<string> = []
741
+ let summary = ""
742
+ const questions: Array<OwnerQuestion> = []
743
+ let index = 0
744
+ for (; index < lines.length; index += 1) {
745
+ const trimmed = (lines[index] ?? "").trim()
746
+ if (trimmed.length === 0) break
747
+ const title = /^#\s+(B\d+):\s*(.*)$/.exec(trimmed)
748
+ if (title !== null) {
749
+ brief = title[1]
750
+ continue
751
+ }
752
+ const field = headerLine.exec(trimmed)
753
+ if (field?.[1] === undefined) {
754
+ violations.push(`line ${index + 1}: not a report header line: ${trimmed}`)
755
+ continue
756
+ }
757
+ const name = field[1].toLowerCase()
758
+ const value = (field[2] ?? "").trim()
759
+ if (name === "status") {
760
+ if (isReportStatus(value)) status = value
761
+ else violations.push(`line ${index + 1}: Status is PASS, ISSUES or BLOCKED, got: ${value}`)
762
+ } else if (name === "attempt") {
763
+ if (/^\d+$/.test(value)) attempt = Number.parseInt(value, 10)
764
+ else violations.push(`line ${index + 1}: Attempt is a whole number, got: ${value}`)
765
+ } else if (name === "evidence") evidence = splitList(value)
766
+ else if (name === "summary") summary = value
767
+ else if (name === "question") {
768
+ const parts = /^(.*?)\s*\(assuming:\s*(.*)\)$/.exec(value)
769
+ questions.push(
770
+ OwnerQuestion.make(
771
+ parts === null
772
+ ? { question: value, assumption: "" }
773
+ : { question: (parts[1] ?? "").trim(), assumption: (parts[2] ?? "").trim() }
774
+ )
775
+ )
776
+ } else violations.push(`line ${index + 1}: unknown report header ${field[1]}`)
777
+ }
778
+ if (brief === undefined) violations.push("missing the `# B<n>: <title>` title")
779
+ if (status === undefined) violations.push("missing the `Status:` line")
780
+ if (violations.length > 0 || brief === undefined || status === undefined) {
781
+ return yield* ReportInvalid.make({ ...(path === undefined ? {} : { path }), violations })
782
+ }
783
+ return Report.make({
784
+ brief,
785
+ status,
786
+ attempt,
787
+ evidence,
788
+ summary,
789
+ questions,
790
+ body: lines.slice(index).join("\n").trim()
791
+ })
792
+ })
793
+
794
+ // ---- Derived state (decision 6) -----------------------------------------------------
795
+
796
+ export const reportOf = (reports: ReadonlyArray<Report>, id: string): Report | undefined =>
797
+ reports.find((report) => report.brief === id)
798
+
799
+ /** PASS and ISSUES end a brief; BLOCKED ends it on the second attempt. */
800
+ export const isFinal = (report: Report): boolean =>
801
+ report.status !== "BLOCKED" || report.attempt >= 2
802
+
803
+ const finallyBlocked = (report: Report | undefined): boolean =>
804
+ report !== undefined && report.status === "BLOCKED" && isFinal(report)
805
+
806
+ export const currentWave = (plan: Plan): number =>
807
+ plan.briefs.reduce((wave, brief) => Math.max(wave, brief.wave), 0)
808
+
809
+ const openBriefs = (plan: Plan, reports: ReadonlyArray<Report>): ReadonlyArray<Brief> =>
810
+ plan.briefs.filter((brief) => {
811
+ const report = reportOf(reports, brief.id)
812
+ return report === undefined || !isFinal(report)
813
+ })
814
+
815
+ /** The reason a brief cannot run: a dependency finally blocked. */
816
+ const deadReason = (brief: Brief, reports: ReadonlyArray<Report>): string | undefined => {
817
+ const dead = brief.dependsOn.filter((id) => finallyBlocked(reportOf(reports, id)))
818
+ return dead.length === 0 ? undefined : `depends on ${dead.join(", ")}, blocked twice`
819
+ }
820
+
821
+ /** Open briefs whose dependencies all ended well: what the next dispatch runs together. */
822
+ export const readyBriefs = (plan: Plan, reports: ReadonlyArray<Report>): ReadonlyArray<Brief> =>
823
+ openBriefs(plan, reports).filter(
824
+ (brief) =>
825
+ deadReason(brief, reports) === undefined &&
826
+ brief.dependsOn.every((id) => {
827
+ const report = reportOf(reports, id)
828
+ return report !== undefined && isFinal(report)
829
+ })
830
+ )
831
+
832
+ export interface OwnerAnswer {
833
+ readonly number: number
834
+ readonly question: string
835
+ readonly answer: string
836
+ }
837
+
838
+ export type Action =
839
+ | { readonly _tag: "ProposePlan" }
840
+ | { readonly _tag: "Open" }
841
+ | {
842
+ readonly _tag: "RecordOwner"
843
+ readonly answers: ReadonlyArray<OwnerAnswer>
844
+ readonly feedback: string
845
+ }
846
+ | { readonly _tag: "Dispatch"; readonly briefs: ReadonlyArray<Brief>; readonly attempt: number }
847
+ | { readonly _tag: "Skip"; readonly brief: Brief; readonly reason: string }
848
+ | { readonly _tag: "Check"; readonly wave: number; readonly mayReplan: boolean }
849
+ | { readonly _tag: "Draft"; readonly redraft: boolean }
850
+ | { readonly _tag: "Review" }
851
+ | { readonly _tag: "Distill" }
852
+ | { readonly _tag: "Done" }
853
+ | { readonly _tag: "Refused"; readonly reason: string }
854
+
855
+ const pendingOwner = (plan: Plan): { answers: ReadonlyArray<OwnerAnswer>; feedback: string } => ({
856
+ answers: plan.answers.flatMap((point) => {
857
+ const answer = (point.answer ?? "").trim()
858
+ return answer.length === 0 || plan.folded.includes(point.number)
859
+ ? []
860
+ : [{ number: point.number, question: point.question, answer }]
861
+ }),
862
+ feedback: plan.feedback.trim()
863
+ })
864
+
865
+ /** What the loop does next, from the plan and the reports alone. */
866
+ export const nextAction = (plan: Plan, reports: ReadonlyArray<Report>, caps: Caps): Action => {
867
+ if (plan.status === "planned") {
868
+ return plan.briefs.length === 0 ? { _tag: "ProposePlan" } : { _tag: "Open" }
869
+ }
870
+ const owner = pendingOwner(plan)
871
+ if (owner.answers.length > 0 || owner.feedback.length > 0) {
872
+ return { _tag: "RecordOwner", answers: owner.answers, feedback: owner.feedback }
873
+ }
874
+ switch (plan.status) {
875
+ case "working":
876
+ case "fixing": {
877
+ const open = openBriefs(plan, reports)
878
+ if (open.length === 0) {
879
+ if (plan.status === "fixing") return { _tag: "Draft", redraft: true }
880
+ const wave = currentWave(plan)
881
+ const checked = plan.checks.some((check) => check.wave === wave)
882
+ if (!checked) {
883
+ return {
884
+ _tag: "Check",
885
+ wave,
886
+ mayReplan: plan.checks.length === 0 && wave < caps.waves
887
+ }
888
+ }
889
+ return { _tag: "Draft", redraft: plan.drafts > 0 }
890
+ }
891
+ for (const brief of open) {
892
+ const reason = deadReason(brief, reports)
893
+ if (reason !== undefined) return { _tag: "Skip", brief, reason }
894
+ }
895
+ const ready = readyBriefs(plan, reports)
896
+ if (ready.length === 0) {
897
+ return { _tag: "Refused", reason: "the open briefs wait on each other" }
898
+ }
899
+ // A brief back from BLOCKED runs alone, on its second attempt.
900
+ const retry = ready.find((brief) => reportOf(reports, brief.id) !== undefined)
901
+ return retry === undefined
902
+ ? { _tag: "Dispatch", briefs: ready, attempt: 1 }
903
+ : { _tag: "Dispatch", briefs: [retry], attempt: 2 }
904
+ }
905
+ case "drafting":
906
+ return { _tag: "Draft", redraft: plan.drafts > 0 }
907
+ case "reviewing":
908
+ return { _tag: "Review" }
909
+ case "distilling":
910
+ return { _tag: "Distill" }
911
+ case "done":
912
+ return { _tag: "Done" }
913
+ }
914
+ }
915
+
916
+ // ---- The owner (decision 9) ----------------------------------------------------------
917
+
918
+ export interface Recorded {
919
+ readonly plan: Plan
920
+ /** Briefs to add to the plan: a rework per answer, a fix for feedback. */
921
+ readonly briefs: ReadonlyArray<Brief>
922
+ readonly notes: ReadonlyArray<string>
923
+ }
924
+
925
+ const nextId = (plan: Plan, added: number): string => `B${plan.briefs.length + added + 1}`
926
+
927
+ /** The brief an answer's question came from: `(B3, assuming: …)` in the question text. */
928
+ const askingBrief = (plan: Plan, question: string): Brief | undefined => {
929
+ const match = /\((B\d+)(?:,|\))/.exec(question)
930
+ return match === null ? undefined : plan.briefs.find((brief) => brief.id === match[1])
931
+ }
932
+
933
+ /**
934
+ * Folds the owner's words in: an answer reopens the brief that asked, with
935
+ * the answer in its CONTEXT, one wave on; feedback becomes a fix brief for
936
+ * the Doc Writer. At the wave cap the answer is folded and nothing is added.
937
+ */
938
+ export const recordOwner = (
939
+ plan: Plan,
940
+ action: Extract<Action, { _tag: "RecordOwner" }>,
941
+ caps: Caps,
942
+ docWriter = "Doc Writer"
943
+ ): Recorded => {
944
+ const notes: Array<string> = []
945
+ const briefs: Array<Brief> = []
946
+ const wave = currentWave(plan) + 1
947
+ const capped = wave > caps.waves
948
+ for (const answer of action.answers) {
949
+ const asked = askingBrief(plan, answer.question)
950
+ if (capped) {
951
+ notes.push(
952
+ `answer ${answer.number} folded without rework: wave ${wave} is past the cap of ${caps.waves}`
953
+ )
954
+ continue
955
+ }
956
+ const id = nextId(plan, briefs.length)
957
+ briefs.push(
958
+ Brief.make({
959
+ id,
960
+ title:
961
+ asked === undefined
962
+ ? `Rework after answer ${answer.number}`
963
+ : `Rework ${asked.id}: ${asked.title}`,
964
+ owner: asked?.owner ?? docWriter,
965
+ dependsOn: [],
966
+ wave,
967
+ goal: asked?.goal ?? `Fold the owner's answer into the deliverables.`,
968
+ scope: asked?.scope ?? "",
969
+ context: [
970
+ asked?.context ?? "",
971
+ `The owner answered question ${answer.number} (${oneLine(answer.question)}): ${oneLine(answer.answer)}. Redo the work on that answer, not the assumption.`
972
+ ]
973
+ .filter((line) => line.length > 0)
974
+ .join("\n"),
975
+ acceptance: asked?.acceptance ?? "- The answer is reflected.",
976
+ verify: "",
977
+ timebox: asked?.timebox ?? "",
978
+ forbidden: asked?.forbidden ?? "",
979
+ report: `reports/${id}.md${asked === undefined ? "" : `, replacing reports/${asked.id}.md`}`
980
+ })
981
+ )
982
+ }
983
+ if (action.feedback.length > 0) {
984
+ if (capped) {
985
+ notes.push(
986
+ `feedback recorded without a fix wave: wave ${wave} is past the cap of ${caps.waves}`
987
+ )
988
+ } else {
989
+ const id = nextId(plan, briefs.length)
990
+ briefs.push(
991
+ Brief.make({
992
+ id,
993
+ title: "Fix: the owner's feedback",
994
+ owner: docWriter,
995
+ dependsOn: [],
996
+ wave,
997
+ goal: "Address the owner's feedback in the deliverables.",
998
+ scope: plan.deliverables.join(", "),
999
+ context: `The owner wrote: ${action.feedback}`,
1000
+ acceptance: "- The feedback is addressed and nothing else changed.",
1001
+ verify: "",
1002
+ timebox: "",
1003
+ forbidden: "Rewriting what the feedback does not touch.",
1004
+ report: `reports/${id}.md with what changed and why.`
1005
+ })
1006
+ )
1007
+ }
1008
+ }
1009
+ const status: PlanStatus =
1010
+ briefs.length === 0
1011
+ ? plan.status
1012
+ : action.feedback.length > 0 && action.answers.length === 0
1013
+ ? "fixing"
1014
+ : "working"
1015
+ return {
1016
+ plan: Plan.make({
1017
+ ...plan,
1018
+ status,
1019
+ feedback: "",
1020
+ folded: [...new Set([...plan.folded, ...action.answers.map((answer) => answer.number)])].sort(
1021
+ (left, right) => left - right
1022
+ )
1023
+ }),
1024
+ briefs,
1025
+ notes
1026
+ }
1027
+ }
1028
+
1029
+ /** Questions the reports raised, added under `## Answers` once each, with the assumption. */
1030
+ export const syncAnswers = (plan: Plan, reports: ReadonlyArray<Report>): Plan => {
1031
+ const known = new Set(plan.answers.map((point) => point.question))
1032
+ const added: Array<OpenPoint> = []
1033
+ let number = plan.answers.reduce((max, point) => Math.max(max, point.number), 0)
1034
+ for (const report of reports) {
1035
+ for (const question of report.questions) {
1036
+ const text = `${oneLine(question.question)} (${report.brief}, assuming: ${oneLine(question.assumption)})`
1037
+ if (known.has(text)) continue
1038
+ known.add(text)
1039
+ number += 1
1040
+ added.push(OpenPoint.make({ number, question: text }))
1041
+ }
1042
+ }
1043
+ return added.length === 0 ? plan : Plan.make({ ...plan, answers: [...plan.answers, ...added] })
1044
+ }
1045
+
1046
+ // ---- The review (decision 7) ----------------------------------------------------------
1047
+
1048
+ export const Bucket = Schema.Literals(["act-on", "consider", "noted", "dismissed"])
1049
+ export type Bucket = typeof Bucket.Type
1050
+
1051
+ export class Finding extends Schema.Class<Finding>("Finding")({
1052
+ id: Schema.Int,
1053
+ lens: Schema.String,
1054
+ title: Schema.String,
1055
+ /** A path, a section, a line. */
1056
+ where: Schema.String,
1057
+ /** The brief whose work it is about, or empty when it is about a deliverable. */
1058
+ brief: Schema.String,
1059
+ detail: Schema.String,
1060
+ bucket: Bucket,
1061
+ reason: Schema.String
1062
+ }) {}
1063
+
1064
+ export class LensFindings extends Schema.Class<LensFindings>("LensFindings")({
1065
+ findings: Schema.Array(
1066
+ Schema.Struct({
1067
+ title: Schema.String,
1068
+ where: Schema.String,
1069
+ brief: Schema.String,
1070
+ detail: Schema.String
1071
+ })
1072
+ )
1073
+ }) {}
1074
+
1075
+ export const lensFindingsJsonSchema: JsonSchema = {
1076
+ type: "object",
1077
+ properties: {
1078
+ findings: {
1079
+ type: "array",
1080
+ items: {
1081
+ type: "object",
1082
+ properties: {
1083
+ title: { type: "string" },
1084
+ where: { type: "string" },
1085
+ brief: { type: "string" },
1086
+ detail: { type: "string" }
1087
+ },
1088
+ required: ["title", "where", "brief", "detail"]
1089
+ }
1090
+ }
1091
+ },
1092
+ required: ["findings"]
1093
+ }
1094
+
1095
+ export class LeadProposal extends Schema.Class<LeadProposal>("LeadProposal")({
1096
+ verdicts: Schema.Array(
1097
+ Schema.Struct({
1098
+ id: Schema.Int,
1099
+ bucket: Schema.Literals(["consider", "noted", "dismissed"]),
1100
+ reason: Schema.String
1101
+ })
1102
+ )
1103
+ }) {}
1104
+
1105
+ export const leadProposalJsonSchema: JsonSchema = {
1106
+ type: "object",
1107
+ properties: {
1108
+ verdicts: {
1109
+ type: "array",
1110
+ items: {
1111
+ type: "object",
1112
+ properties: {
1113
+ id: { type: "integer" },
1114
+ bucket: { type: "string", enum: ["consider", "noted", "dismissed"] },
1115
+ reason: { type: "string" }
1116
+ },
1117
+ required: ["id", "bucket", "reason"]
1118
+ }
1119
+ }
1120
+ },
1121
+ required: ["verdicts"]
1122
+ }
1123
+
1124
+ const bucketTitles: Record<Bucket, string> = {
1125
+ "act-on": "Act on",
1126
+ consider: "Consider",
1127
+ noted: "Noted",
1128
+ dismissed: "Dismissed"
1129
+ }
1130
+
1131
+ export const renderReview = (findings: ReadonlyArray<Finding>): string =>
1132
+ [
1133
+ "# Review",
1134
+ "",
1135
+ ...Bucket.literals.flatMap((bucket) => {
1136
+ const these = findings.filter((finding) => finding.bucket === bucket)
1137
+ return [
1138
+ `## ${bucketTitles[bucket]}`,
1139
+ "",
1140
+ ...(these.length === 0
1141
+ ? ["- none"]
1142
+ : these.flatMap((finding) => [
1143
+ `- ${finding.id}. ${oneLine(finding.title)} (${finding.lens}${finding.brief.length === 0 ? "" : `, ${finding.brief}`}; ${oneLine(finding.where)})`,
1144
+ ` ${oneLine(finding.detail)}${finding.reason.length === 0 ? "" : ` — ${oneLine(finding.reason)}`}`
1145
+ ])),
1146
+ ""
1147
+ ]
1148
+ })
1149
+ ].join("\n")
1150
+
1151
+ export interface FixWave {
1152
+ readonly briefs: ReadonlyArray<Brief>
1153
+ /** Act-on findings beyond the brief cap. */
1154
+ readonly dropped: ReadonlyArray<Finding>
1155
+ }
1156
+
1157
+ /** One fix brief per act-on finding, for the owner of the work it is about, the Doc Writer otherwise. */
1158
+ export const fixBriefs = (
1159
+ plan: Plan,
1160
+ findings: ReadonlyArray<Finding>,
1161
+ caps: Caps,
1162
+ docWriter: string
1163
+ ): FixWave => {
1164
+ const wave = currentWave(plan) + 1
1165
+ const briefs: Array<Brief> = []
1166
+ const dropped: Array<Finding> = []
1167
+ for (const finding of findings) {
1168
+ if (finding.bucket !== "act-on") continue
1169
+ if (plan.briefs.length + briefs.length >= caps.briefs) {
1170
+ dropped.push(finding)
1171
+ continue
1172
+ }
1173
+ const about = plan.briefs.find((brief) => brief.id === finding.brief)
1174
+ const id = nextId(plan, briefs.length)
1175
+ briefs.push(
1176
+ Brief.make({
1177
+ id,
1178
+ title: `Fix: ${oneLine(finding.title)}`,
1179
+ owner: about?.owner ?? docWriter,
1180
+ dependsOn: [],
1181
+ wave,
1182
+ goal: `Address the review finding: ${oneLine(finding.title)}.`,
1183
+ scope: about?.scope ?? plan.deliverables.join(", "),
1184
+ context: `The ${finding.lens} lens found, at ${oneLine(finding.where)}: ${oneLine(finding.detail)}${about === undefined ? "" : ` (about ${about.id}: ${about.title})`}`,
1185
+ acceptance: "- The finding no longer holds.\n- Nothing the finding does not touch changed.",
1186
+ verify: "",
1187
+ timebox: about?.timebox ?? "",
1188
+ forbidden: about?.forbidden ?? "Changing what the finding does not touch.",
1189
+ report: `reports/${id}.md with what changed and the evidence.`
1190
+ })
1191
+ )
1192
+ }
1193
+ return { briefs, dropped }
1194
+ }
1195
+
1196
+ // ---- Views ---------------------------------------------------------------------------------
1197
+
1198
+ /** What nobody in the run could settle: finally blocked briefs with the assumption taken, and unanswered questions. */
1199
+ export const renderOpenQuestions = (plan: Plan, reports: ReadonlyArray<Report>): string => {
1200
+ const blocked = plan.briefs.flatMap((brief) => {
1201
+ const report = reportOf(reports, brief.id)
1202
+ return finallyBlocked(report) && report !== undefined ? [{ brief, report }] : []
1203
+ })
1204
+ const unanswered = plan.answers.filter((point) => (point.answer ?? "").trim().length === 0)
1205
+ return [
1206
+ `# Open questions: ${plan.id}`,
1207
+ "",
1208
+ "## Blocked briefs",
1209
+ "",
1210
+ ...(blocked.length === 0
1211
+ ? ["- none"]
1212
+ : blocked.map(
1213
+ ({ brief, report }) =>
1214
+ `- ${brief.id} ${oneLine(brief.title)} (${brief.owner}): ${oneLine(report.summary)}`
1215
+ )),
1216
+ "",
1217
+ "## For the owner",
1218
+ "",
1219
+ ...(unanswered.length === 0
1220
+ ? ["- none"]
1221
+ : unanswered.map((point) => `- ${point.number}. ${point.question}`)),
1222
+ "",
1223
+ `Answer under '## Answers' in plan.md and rerun.`,
1224
+ ""
1225
+ ].join("\n")
1226
+ }
1227
+
1228
+ // ---- The trail (decision 8) -------------------------------------------------------------------
1229
+
1230
+ export interface TrailRow {
1231
+ readonly ts: string
1232
+ readonly phase: string
1233
+ readonly decision: string
1234
+ readonly why: string
1235
+ readonly evidence: string
1236
+ readonly result: string
1237
+ }
1238
+
1239
+ export const trailHeader = "ts\tphase\tdecision\twhy\tevidence\tresult"
1240
+
1241
+ /** A cell on one line, with a leading `=`, `+`, `-` or `@` quoted so a spreadsheet reads it as text. */
1242
+ const cell = (text: string): string => {
1243
+ const flat = oneLine(text)
1244
+ return /^[=+\-@]/.test(flat) ? `'${flat}` : flat
1245
+ }
1246
+
1247
+ export const renderTrailRow = (row: TrailRow): string =>
1248
+ [row.ts, row.phase, row.decision, row.why, row.evidence, row.result].map(cell).join("\t")