@llm4ts/flow 2.52.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 +57 -1
  14. package/dist/FlowError.d.ts.map +1 -1
  15. package/dist/FlowError.js +75 -1
  16. package/dist/FlowError.js.map +1 -1
  17. package/dist/FlowEvents.d.ts +43 -1
  18. package/dist/FlowEvents.d.ts.map +1 -1
  19. package/dist/FlowEvents.js +47 -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 +264 -0
  54. package/dist/Roundtable.d.ts.map +1 -0
  55. package/dist/Roundtable.js +884 -0
  56. package/dist/Roundtable.js.map +1 -0
  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 +5 -2
  66. package/src/FlowError.ts +82 -1
  67. package/src/FlowEvents.ts +51 -0
  68. package/src/Memory.ts +151 -0
  69. package/src/Roundtable.ts +1150 -0
  70. package/src/Taskforce.ts +1248 -0
@@ -0,0 +1,1150 @@
1
+ import * as Effect from "effect/Effect"
2
+ import * as Schema from "effect/Schema"
3
+ import * as Option from "effect/Option"
4
+ import type { JsonSchema } from "@llm4ts/core/Models"
5
+ import { makeOpenPointsCollector, OpenPoint } from "./Decisions.ts"
6
+ import { MeetingInvalid, PersonaInvalid, TurnsInvalid } from "./FlowError.ts"
7
+ import { RoundtableTurnKind } from "./FlowEvents.ts"
8
+ import { Role } from "./Roster.ts"
9
+
10
+ /**
11
+ * The roundtable (ADR 0046): a meeting run by code. Chosen personas speak in
12
+ * turns about a topic toward a goal, agenda item by agenda item, until each
13
+ * item is settled or capped; then the Scribe writes the outline and the plan.
14
+ *
15
+ * This module is the pure half: the persona card, the meeting file, the turn
16
+ * record, what the turns imply (open objections, open questions, decisions,
17
+ * settled items) and the chair's `nextAction`. The flow wires seats, files
18
+ * and events around it.
19
+ */
20
+
21
+ // ---- Shared helpers -----------------------------------------------------------
22
+
23
+ const dash = " — "
24
+ const headerLine = /^([A-Za-z][A-Za-z ]*):\s*(.*)$/
25
+
26
+ const splitFirst = (text: string, separator: string): readonly [string, string | undefined] => {
27
+ const index = text.indexOf(separator)
28
+ return index < 0
29
+ ? [text.trim(), undefined]
30
+ : [text.slice(0, index).trim(), text.slice(index + separator.length).trim()]
31
+ }
32
+
33
+ const prose = (text: string): ReadonlyArray<string> =>
34
+ text.trim().length === 0 ? [] : text.trim().split("\n")
35
+
36
+ const sectionLines = (title: string, body: ReadonlyArray<string>): ReadonlyArray<string> => [
37
+ `## ${title}`,
38
+ "",
39
+ ...(body.length === 0 ? [] : [...body, ""])
40
+ ]
41
+
42
+ // ---- Personas -----------------------------------------------------------------
43
+
44
+ /**
45
+ * A persona card: what a speaker is. A role is a seat an executor takes; a
46
+ * persona is a voice. The order sorts attendees into speaking order.
47
+ */
48
+ /**
49
+ * The hands a specialist card has (ADR 0047, decision 4): nothing, a
50
+ * read-only view of the repository, commands run by code, or a throwaway
51
+ * worktree of its own.
52
+ */
53
+ export const ToolGrade = Schema.Literals(["none", "read-only", "commands", "workspace"])
54
+ export type ToolGrade = typeof ToolGrade.Type
55
+
56
+ const isToolGrade = (value: string): value is ToolGrade =>
57
+ ToolGrade.literals.some((grade) => grade === value)
58
+ const isRole = (value: string): value is Role => Role.literals.some((role) => role === value)
59
+
60
+ export class Persona extends Schema.Class<Persona>("Persona")({
61
+ name: Schema.String,
62
+ order: Schema.Int,
63
+ mandate: Schema.String,
64
+ caresAbout: Schema.String,
65
+ pushesBackOn: Schema.String,
66
+ neverDecidesAlone: Schema.String,
67
+ voice: Schema.String,
68
+ /** The Scribe's section skeleton for `outline.md`; other cards have none. */
69
+ outlineTemplate: Schema.optionalKey(Schema.String),
70
+ /** The Scribe's section skeleton for `plan.md`. */
71
+ planTemplate: Schema.optionalKey(Schema.String),
72
+ /** The Doc Writer's section skeleton for `result.md` (ADR 0047). */
73
+ resultTemplate: Schema.optionalKey(Schema.String),
74
+ /** What the card may touch in a taskforce (ADR 0047); absent means none. */
75
+ tools: Schema.optionalKey(ToolGrade),
76
+ /** The roster role the card speaks on in a taskforce; absent means planner. */
77
+ seat: Schema.optionalKey(Role)
78
+ }) {}
79
+
80
+ /** The order a card without one gets: after every bundled persona. */
81
+ export const defaultPersonaOrder = 100
82
+
83
+ const personaSections = {
84
+ mandate: "Mandate",
85
+ caresAbout: "Cares about",
86
+ pushesBackOn: "Pushes back on",
87
+ neverDecidesAlone: "Never decides alone",
88
+ voice: "Voice",
89
+ outlineTemplate: "Outline template",
90
+ planTemplate: "Plan template",
91
+ resultTemplate: "Result template",
92
+ tools: "Tools",
93
+ seat: "Seat"
94
+ } as const
95
+ type PersonaSection = keyof typeof personaSections
96
+ const personaSectionKeys: ReadonlyArray<PersonaSection> = [
97
+ "mandate",
98
+ "caresAbout",
99
+ "pushesBackOn",
100
+ "neverDecidesAlone",
101
+ "voice",
102
+ "outlineTemplate",
103
+ "planTemplate",
104
+ "resultTemplate",
105
+ "tools",
106
+ "seat"
107
+ ]
108
+ /** Sections whose body is a markdown skeleton: a `## ` line inside them is content, not a section. */
109
+ const templateSections: ReadonlyArray<PersonaSection> = [
110
+ "outlineTemplate",
111
+ "planTemplate",
112
+ "resultTemplate"
113
+ ]
114
+
115
+ const personaSectionOf = (title: string): PersonaSection | undefined =>
116
+ personaSectionKeys.find((key) => personaSections[key].toLowerCase() === title.toLowerCase())
117
+
118
+ /**
119
+ * Reads a card: optional `---` frontmatter with `name:` and `order:`, then
120
+ * one `## ` section per field. `fallbackName` is the file's name, used when
121
+ * the frontmatter has none.
122
+ */
123
+ export const parsePersona = Effect.fn("@llm4ts/flow/Roundtable.parsePersona")(function* (
124
+ fallbackName: string,
125
+ markdown: string
126
+ ): Effect.fn.Return<Persona, PersonaInvalid> {
127
+ const violations: Array<string> = []
128
+ const lines = markdown.split(/\r?\n/)
129
+ let name = fallbackName
130
+ let order = defaultPersonaOrder
131
+ let index = 0
132
+ if ((lines[0] ?? "").trim() === "---") {
133
+ index = 1
134
+ while (index < lines.length && (lines[index] ?? "").trim() !== "---") {
135
+ const field = headerLine.exec((lines[index] ?? "").trim())
136
+ if (field?.[1] !== undefined) {
137
+ const key = field[1].toLowerCase()
138
+ const value = (field[2] ?? "").trim()
139
+ if (key === "name" && value.length > 0) name = value
140
+ if (key === "order") {
141
+ const parsed = /^\d+$/.test(value) ? Number.parseInt(value, 10) : undefined
142
+ if (parsed === undefined) {
143
+ violations.push(`line ${index + 1}: order is a whole number, got: ${value}`)
144
+ } else {
145
+ order = parsed
146
+ }
147
+ }
148
+ }
149
+ index += 1
150
+ }
151
+ if (index >= lines.length) {
152
+ violations.push("line 1: the frontmatter opened here is never closed")
153
+ }
154
+ index += 1
155
+ }
156
+ const bodies: Record<PersonaSection, Array<string>> = {
157
+ mandate: [],
158
+ caresAbout: [],
159
+ pushesBackOn: [],
160
+ neverDecidesAlone: [],
161
+ voice: [],
162
+ outlineTemplate: [],
163
+ planTemplate: [],
164
+ resultTemplate: [],
165
+ tools: [],
166
+ seat: []
167
+ }
168
+ let current: PersonaSection | "unknown" | "none" = "none"
169
+ let fenced = false
170
+ for (; index < lines.length; index += 1) {
171
+ const raw = lines[index] ?? ""
172
+ const trimmed = raw.trim()
173
+ if (trimmed.startsWith("```")) fenced = !fenced
174
+ if (!fenced && trimmed.startsWith("## ")) {
175
+ const title = trimmed.slice(3).trim()
176
+ const key = personaSectionOf(title)
177
+ if (key !== undefined) {
178
+ current = key
179
+ continue
180
+ }
181
+ // A template is a skeleton of headings: its `## ` lines are its body.
182
+ if (current !== "unknown" && current !== "none" && templateSections.includes(current)) {
183
+ bodies[current].push(raw)
184
+ continue
185
+ }
186
+ violations.push(`line ${index + 1}: unknown section "${title}"`)
187
+ current = "unknown"
188
+ continue
189
+ }
190
+ if (current !== "unknown" && current !== "none") bodies[current].push(raw)
191
+ }
192
+ const text = (key: PersonaSection): string => bodies[key].join("\n").trim()
193
+ if (text("mandate").length === 0) violations.push("missing the `## Mandate` section")
194
+ const tools = text("tools")
195
+ if (tools.length > 0 && !isToolGrade(tools)) {
196
+ violations.push(`Tools is one of ${ToolGrade.literals.join(", ")}, got: ${tools}`)
197
+ }
198
+ const seat = text("seat")
199
+ if (seat.length > 0 && !isRole(seat)) {
200
+ violations.push(`Seat is one of ${Role.literals.join(", ")}, got: ${seat}`)
201
+ }
202
+ if (violations.length > 0) {
203
+ return yield* PersonaInvalid.make({ name: fallbackName, violations })
204
+ }
205
+ return Persona.make({
206
+ name,
207
+ order,
208
+ mandate: text("mandate"),
209
+ caresAbout: text("caresAbout"),
210
+ pushesBackOn: text("pushesBackOn"),
211
+ neverDecidesAlone: text("neverDecidesAlone"),
212
+ voice: text("voice"),
213
+ ...(bodies.outlineTemplate.length === 0 ? {} : { outlineTemplate: text("outlineTemplate") }),
214
+ ...(bodies.planTemplate.length === 0 ? {} : { planTemplate: text("planTemplate") }),
215
+ ...(bodies.resultTemplate.length === 0 ? {} : { resultTemplate: text("resultTemplate") }),
216
+ ...(isToolGrade(tools) ? { tools } : {}),
217
+ ...(isRole(seat) ? { seat } : {})
218
+ })
219
+ })
220
+
221
+ export const renderPersona = (persona: Persona): string =>
222
+ [
223
+ "---",
224
+ `name: ${persona.name}`,
225
+ `order: ${persona.order}`,
226
+ "---",
227
+ "",
228
+ ...personaSectionKeys.flatMap((key) => {
229
+ const body = persona[key]
230
+ return body === undefined ? [] : sectionLines(personaSections[key], prose(body))
231
+ })
232
+ ].join("\n")
233
+
234
+ // ---- The meeting file ---------------------------------------------------------
235
+
236
+ export const MeetingStatus = Schema.Literals([
237
+ "agenda-proposed",
238
+ "discussing",
239
+ "drafting",
240
+ "reviewing",
241
+ "done"
242
+ ])
243
+ export type MeetingStatus = typeof MeetingStatus.Type
244
+
245
+ /** One question the meeting settles, with a title. Numbered as the agenda lists it. */
246
+ export class AgendaItem extends Schema.Class<AgendaItem>("AgendaItem")({
247
+ number: Schema.Int,
248
+ title: Schema.String,
249
+ question: Schema.String
250
+ }) {}
251
+
252
+ /**
253
+ * The meeting file, `meeting.md`: the state of a roundtable, and the owner's
254
+ * only seat at the table. Answers are keyed by the id of the question turn
255
+ * they answer; feedback is free text that becomes an Owner turn on the next
256
+ * run. `drafts` counts how many times the Scribe has written the documents:
257
+ * each draft opens a new review round.
258
+ */
259
+ export class Meeting extends Schema.Class<Meeting>("Meeting")({
260
+ id: Schema.String,
261
+ status: MeetingStatus,
262
+ topic: Schema.String,
263
+ goal: Schema.String,
264
+ attendees: Schema.Array(Schema.String),
265
+ agenda: Schema.Array(AgendaItem),
266
+ answers: Schema.Array(OpenPoint),
267
+ feedback: Schema.String,
268
+ drafts: Schema.Int
269
+ }) {}
270
+
271
+ const meetingSections = { agenda: "Agenda", answers: "Answers", feedback: "Feedback" } as const
272
+ type MeetingSection = keyof typeof meetingSections
273
+ const meetingSectionKeys: ReadonlyArray<MeetingSection> = ["agenda", "answers", "feedback"]
274
+
275
+ const meetingSectionOf = (title: string): MeetingSection | undefined =>
276
+ meetingSectionKeys.find((key) => meetingSections[key].toLowerCase() === title.toLowerCase())
277
+
278
+ const isMeetingStatus = (value: string): value is MeetingStatus =>
279
+ MeetingStatus.literals.some((literal) => literal === value)
280
+
281
+ export const renderAgendaItem = (item: AgendaItem): string =>
282
+ `${item.number}. ${item.title}${dash}${item.question}`
283
+
284
+ export const renderMeeting = (meeting: Meeting): string =>
285
+ [
286
+ `# Roundtable: ${meeting.id}`,
287
+ "",
288
+ `Status: ${meeting.status}`,
289
+ `Topic: ${meeting.topic}`,
290
+ `Goal: ${meeting.goal}`,
291
+ `Attendees: ${meeting.attendees.join(", ")}`,
292
+ `Drafts: ${meeting.drafts}`,
293
+ "",
294
+ ...sectionLines(meetingSections.agenda, meeting.agenda.map(renderAgendaItem)),
295
+ ...sectionLines(
296
+ meetingSections.answers,
297
+ meeting.answers.flatMap((point) => [
298
+ `${point.number}. ${point.question}`,
299
+ ` answer:${(point.answer ?? "").trim().length === 0 ? "" : ` ${(point.answer ?? "").trim()}`}`
300
+ ])
301
+ ),
302
+ ...sectionLines(meetingSections.feedback, prose(meeting.feedback))
303
+ ].join("\n")
304
+
305
+ /** An open point as the file holds it: an empty answer is no answer. */
306
+ const settledPoint = (point: OpenPoint): OpenPoint =>
307
+ (point.answer ?? "").trim().length === 0
308
+ ? OpenPoint.make({ number: point.number, question: point.question })
309
+ : OpenPoint.make({
310
+ number: point.number,
311
+ question: point.question,
312
+ answer: (point.answer ?? "").trim()
313
+ })
314
+
315
+ export const parseMeeting = Effect.fn("@llm4ts/flow/Roundtable.parseMeeting")(function* (
316
+ markdown: string,
317
+ path?: string
318
+ ): Effect.fn.Return<Meeting, MeetingInvalid> {
319
+ const violations: Array<string> = []
320
+ let id: string | undefined
321
+ let status: MeetingStatus | undefined
322
+ let drafts = 0
323
+ const header: Record<string, string> = {}
324
+ let attendees: Array<string> | undefined
325
+ const agenda: Array<{ title: string; question: string }> = []
326
+ const points = makeOpenPointsCollector()
327
+ const feedback: Array<string> = []
328
+ let current: MeetingSection | "header" | "unknown" = "header"
329
+ let fenced = false
330
+ const lines = markdown.split(/\r?\n/)
331
+ for (let index = 0; index < lines.length; index += 1) {
332
+ const number = index + 1
333
+ const raw = lines[index] ?? ""
334
+ const trimmed = raw.trim()
335
+ if (trimmed.startsWith("```")) {
336
+ fenced = !fenced
337
+ if (current === "feedback") feedback.push(raw)
338
+ continue
339
+ }
340
+ if (!fenced && trimmed.startsWith("## ")) {
341
+ const title = trimmed.slice(3).trim()
342
+ const key = meetingSectionOf(title)
343
+ if (key === undefined) {
344
+ violations.push(`line ${number}: unknown section "${title}"`)
345
+ current = "unknown"
346
+ } else {
347
+ current = key
348
+ }
349
+ continue
350
+ }
351
+ if (current === "feedback") {
352
+ feedback.push(raw)
353
+ continue
354
+ }
355
+ if (fenced || trimmed.length === 0 || current === "unknown") continue
356
+ if (current === "header") {
357
+ const title = /^#\s+Roundtable:\s*(.+)$/i.exec(trimmed)
358
+ if (title?.[1] !== undefined) {
359
+ id = title[1].trim()
360
+ continue
361
+ }
362
+ const field = headerLine.exec(trimmed)
363
+ if (field?.[1] === undefined) continue
364
+ const name = field[1].toLowerCase()
365
+ const value = (field[2] ?? "").trim()
366
+ if (name === "status") {
367
+ if (isMeetingStatus(value)) {
368
+ status = value
369
+ } else {
370
+ violations.push(
371
+ `line ${number}: Status is one of ${MeetingStatus.literals.join(", ")}, got: ${value}`
372
+ )
373
+ status = "discussing"
374
+ }
375
+ } else if (name === "attendees") {
376
+ attendees = []
377
+ for (const entry of value.split(",")) {
378
+ const persona = entry.trim()
379
+ if (persona.length === 0) continue
380
+ if (attendees.includes(persona)) {
381
+ violations.push(`line ${number}: attendee listed twice: ${persona}`)
382
+ } else {
383
+ attendees.push(persona)
384
+ }
385
+ }
386
+ } else if (name === "drafts") {
387
+ if (/^\d+$/.test(value)) {
388
+ drafts = Number.parseInt(value, 10)
389
+ } else {
390
+ violations.push(`line ${number}: Drafts is a whole number, got: ${value}`)
391
+ }
392
+ } else {
393
+ header[name] = value
394
+ }
395
+ continue
396
+ }
397
+ if (current === "answers") {
398
+ const problem = points.add(number, trimmed)
399
+ if (problem !== undefined) violations.push(problem)
400
+ continue
401
+ }
402
+ const item = /^(\d+)\.\s+(.*)$/.exec(trimmed)
403
+ if (item !== null) {
404
+ const [title, question] = splitFirst(item[2] ?? "", dash.trim())
405
+ if (question === undefined || title.length === 0) {
406
+ violations.push(
407
+ `line ${number}: an agenda item is \`1. <title>${dash}<question>\`, got: ${trimmed}`
408
+ )
409
+ } else {
410
+ agenda.push({ title, question })
411
+ }
412
+ continue
413
+ }
414
+ const last = agenda.at(-1)
415
+ if (/^\s/.test(raw) && last !== undefined) {
416
+ last.question = `${last.question} ${trimmed}`.trim()
417
+ continue
418
+ }
419
+ violations.push(
420
+ `line ${number}: an agenda item is \`1. <title>${dash}<question>\`, got: ${trimmed}`
421
+ )
422
+ }
423
+ if (id === undefined) violations.push("missing the `# Roundtable: <id>` title")
424
+ if (status === undefined) violations.push("missing the `Status:` line")
425
+ if (header.topic === undefined) violations.push("missing the `Topic:` line")
426
+ if (header.goal === undefined) violations.push("missing the `Goal:` line")
427
+ if (attendees === undefined) violations.push("missing the `Attendees:` line")
428
+ else if (attendees.length === 0) violations.push("the `Attendees:` line names no persona")
429
+ if (fenced) violations.push("a code fence in the feedback is never closed")
430
+ if (
431
+ violations.length > 0 ||
432
+ id === undefined ||
433
+ status === undefined ||
434
+ attendees === undefined
435
+ ) {
436
+ return yield* MeetingInvalid.make({ ...(path === undefined ? {} : { path }), violations })
437
+ }
438
+ return Meeting.make({
439
+ id,
440
+ status,
441
+ topic: header.topic ?? "",
442
+ goal: header.goal ?? "",
443
+ attendees,
444
+ agenda: agenda.map((entry, index) =>
445
+ AgendaItem.make({ number: index + 1, title: entry.title, question: entry.question })
446
+ ),
447
+ answers: points.points.map(settledPoint),
448
+ feedback: feedback.join("\n").trim(),
449
+ drafts
450
+ })
451
+ })
452
+
453
+ // ---- Turns --------------------------------------------------------------------
454
+
455
+ /** The person who called the meeting, present through the meeting file only. */
456
+ export const ownerSpeaker = "Owner"
457
+ /** The code that runs the meeting; it speaks only to record a judgment. */
458
+ export const chairSpeaker = "Chair"
459
+
460
+ /** The kinds of turn, shared with the `RoundtableTurn` event the dashboard reads. */
461
+ export const TurnKind = RoundtableTurnKind
462
+ export type TurnKind = RoundtableTurnKind
463
+
464
+ /**
465
+ * One contribution on one agenda item in one round. `answers` names the
466
+ * turns it responds to: what an objection objects to, what an agreement
467
+ * closes, what a reply replies to. `blocking` is read on objections only,
468
+ * `needsHuman` and `assumption` on questions only.
469
+ */
470
+ export class Turn extends Schema.Class<Turn>("Turn")({
471
+ id: Schema.Int,
472
+ round: Schema.Int,
473
+ item: Schema.Int,
474
+ speaker: Schema.String,
475
+ kind: TurnKind,
476
+ answers: Schema.Array(Schema.Int),
477
+ blocking: Schema.Boolean,
478
+ needsHuman: Schema.Boolean,
479
+ assumption: Schema.optionalKey(Schema.String),
480
+ body: Schema.String
481
+ }) {}
482
+
483
+ const turnLine = Schema.fromJsonString(Turn)
484
+ const encodeTurnLine = Schema.encodeSync(turnLine)
485
+ const decodeTurnLine = Schema.decodeUnknownOption(turnLine)
486
+
487
+ /** One line of `turns.jsonl`. */
488
+ export const encodeTurn = (turn: Turn): string => encodeTurnLine(turn)
489
+
490
+ /** `turns.jsonl` back into turns, ids checked to run 1, 2, 3 … in file order. */
491
+ export const decodeTurns = Effect.fn("@llm4ts/flow/Roundtable.decodeTurns")(function* (
492
+ text: string,
493
+ path?: string
494
+ ): Effect.fn.Return<ReadonlyArray<Turn>, TurnsInvalid> {
495
+ const violations: Array<string> = []
496
+ const turns: Array<Turn> = []
497
+ const lines = text.split(/\r?\n/)
498
+ for (let index = 0; index < lines.length; index += 1) {
499
+ const line = (lines[index] ?? "").trim()
500
+ if (line.length === 0) continue
501
+ const decoded = decodeTurnLine(line)
502
+ if (Option.isNone(decoded)) {
503
+ violations.push(`line ${index + 1}: not a JSON turn: ${line.slice(0, 80)}`)
504
+ continue
505
+ }
506
+ const expected = turns.length + 1
507
+ if (decoded.value.id !== expected) {
508
+ violations.push(
509
+ `line ${index + 1}: turn id ${decoded.value.id} where ${expected} was expected`
510
+ )
511
+ }
512
+ turns.push(decoded.value)
513
+ }
514
+ if (violations.length > 0) {
515
+ return yield* TurnsInvalid.make({ ...(path === undefined ? {} : { path }), violations })
516
+ }
517
+ return turns
518
+ })
519
+
520
+ /** What an attendee returns for a turn; the chair stamps id, round, item and speaker. */
521
+ export class TurnProposal extends Schema.Class<TurnProposal>("TurnProposal")({
522
+ kind: TurnKind,
523
+ answers: Schema.Array(Schema.Int),
524
+ blocking: Schema.Boolean,
525
+ needsHuman: Schema.Boolean,
526
+ assumption: Schema.optionalKey(Schema.String),
527
+ body: Schema.String
528
+ }) {}
529
+
530
+ export const turnProposalJsonSchema: JsonSchema = {
531
+ type: "object",
532
+ properties: {
533
+ kind: { type: "string", enum: [...TurnKind.literals] },
534
+ answers: { type: "array", items: { type: "integer" } },
535
+ blocking: { type: "boolean" },
536
+ needsHuman: { type: "boolean" },
537
+ assumption: { type: "string" },
538
+ body: { type: "string" }
539
+ },
540
+ required: ["kind", "answers", "blocking", "needsHuman", "body"]
541
+ }
542
+
543
+ export interface TurnAt {
544
+ readonly id: number
545
+ readonly round: number
546
+ readonly item: number
547
+ readonly speaker: string
548
+ readonly existing: ReadonlyArray<Turn>
549
+ }
550
+
551
+ /**
552
+ * A proposal as the record can hold it: only earlier turns of the same item
553
+ * can be answered, only an objection blocks, only a question needs the owner
554
+ * and carries an assumption.
555
+ */
556
+ export const assembleTurn = (proposal: TurnProposal, at: TurnAt): Turn => {
557
+ const known = new Set(
558
+ at.existing.filter((turn) => turn.item === at.item && turn.id < at.id).map((turn) => turn.id)
559
+ )
560
+ const answers = [...new Set(proposal.answers)].filter((id) => known.has(id)).sort((a, b) => a - b)
561
+ const needsHuman = proposal.kind === "question" && proposal.needsHuman
562
+ const assumption = needsHuman ? (proposal.assumption ?? "").trim() : ""
563
+ return Turn.make({
564
+ id: at.id,
565
+ round: at.round,
566
+ item: at.item,
567
+ speaker: at.speaker,
568
+ kind: proposal.kind,
569
+ answers,
570
+ blocking: proposal.kind === "objection" && proposal.blocking,
571
+ needsHuman,
572
+ ...(assumption.length === 0 ? {} : { assumption }),
573
+ body: proposal.body.trim()
574
+ })
575
+ }
576
+
577
+ // ---- The agenda ---------------------------------------------------------------
578
+
579
+ export class AgendaProposal extends Schema.Class<AgendaProposal>("AgendaProposal")({
580
+ items: Schema.Array(Schema.Struct({ title: Schema.String, question: Schema.String }))
581
+ }) {}
582
+
583
+ export const agendaProposalJsonSchema: JsonSchema = {
584
+ type: "object",
585
+ properties: {
586
+ items: {
587
+ type: "array",
588
+ items: {
589
+ type: "object",
590
+ properties: { title: { type: "string" }, question: { type: "string" } },
591
+ required: ["title", "question"]
592
+ }
593
+ }
594
+ },
595
+ required: ["items"]
596
+ }
597
+
598
+ export const minAgendaItems = 3
599
+ export const maxAgendaItems = 7
600
+
601
+ const oneLine = (text: string): string => text.replace(/\s+/g, " ").trim()
602
+
603
+ /** The proposed items as the file can hold them: one line each, the title free of the separator, at most the cap. */
604
+ export const assembleAgenda = (proposal: AgendaProposal): ReadonlyArray<AgendaItem> =>
605
+ proposal.items.slice(0, maxAgendaItems).map((item, index) =>
606
+ AgendaItem.make({
607
+ number: index + 1,
608
+ title: oneLine(item.title).replaceAll(dash.trim(), "-"),
609
+ question: oneLine(item.question)
610
+ })
611
+ )
612
+
613
+ /** The fixed item after the proposed ones: does what was settled reach the goal? */
614
+ export const closingItem = (meeting: Meeting): AgendaItem =>
615
+ AgendaItem.make({
616
+ number: meeting.agenda.length + 1,
617
+ title: "Goal check",
618
+ question: "Does the solution, as settled above, reach the goal?"
619
+ })
620
+
621
+ /** The synthetic item the drafts are reviewed under, once per draft. */
622
+ export const reviewItem = (meeting: Meeting): AgendaItem =>
623
+ AgendaItem.make({
624
+ number: meeting.agenda.length + 2,
625
+ title: "Review of the drafts",
626
+ question: "Do the outline and the plan say what the room settled, and reach the goal?"
627
+ })
628
+
629
+ /** The items the discussion goes through, in order: the agenda, then the goal check. */
630
+ export const discussionItems = (meeting: Meeting): ReadonlyArray<AgendaItem> => [
631
+ ...meeting.agenda,
632
+ closingItem(meeting)
633
+ ]
634
+
635
+ export const itemOf = (meeting: Meeting, number: number): AgendaItem | undefined =>
636
+ [...discussionItems(meeting), reviewItem(meeting)].find((item) => item.number === number)
637
+
638
+ // ---- What the turns imply -----------------------------------------------------
639
+
640
+ const onItem = (turns: ReadonlyArray<Turn>, item: number): ReadonlyArray<Turn> =>
641
+ turns.filter((turn) => turn.item === item)
642
+
643
+ /** The objector, or the chair, agreed later that the objection is answered. */
644
+ const isResolved = (turns: ReadonlyArray<Turn>, objection: Turn): boolean =>
645
+ turns.some(
646
+ (turn) =>
647
+ turn.id > objection.id &&
648
+ turn.kind === "agreement" &&
649
+ turn.answers.includes(objection.id) &&
650
+ (turn.speaker === objection.speaker || turn.speaker === chairSpeaker)
651
+ )
652
+
653
+ /** Blocking objections on the item nobody entitled to has closed. */
654
+ export const openObjections = (turns: ReadonlyArray<Turn>, item: number): ReadonlyArray<Turn> =>
655
+ onItem(turns, item).filter(
656
+ (turn) => turn.kind === "objection" && turn.blocking && !isResolved(turns, turn)
657
+ )
658
+
659
+ /** Objections to a proposal that do not block it: recorded with the decision, never resolved. */
660
+ export const dissent = (turns: ReadonlyArray<Turn>, proposal: Turn): ReadonlyArray<Turn> =>
661
+ turns.filter(
662
+ (turn) => turn.kind === "objection" && !turn.blocking && turn.answers.includes(proposal.id)
663
+ )
664
+
665
+ /** Questions for the room with no later turn answering them. */
666
+ export const openQuestions = (turns: ReadonlyArray<Turn>, item: number): ReadonlyArray<Turn> =>
667
+ onItem(turns, item).filter(
668
+ (turn) =>
669
+ turn.kind === "question" &&
670
+ !turn.needsHuman &&
671
+ !turns.some(
672
+ (reply) => reply.id > turn.id && reply.kind !== "pass" && reply.answers.includes(turn.id)
673
+ )
674
+ )
675
+
676
+ /** Questions for the owner the owner has not answered yet. */
677
+ export const parkedQuestions = (turns: ReadonlyArray<Turn>): ReadonlyArray<Turn> =>
678
+ turns.filter(
679
+ (turn) =>
680
+ turn.kind === "question" &&
681
+ turn.needsHuman &&
682
+ !turns.some((reply) => reply.speaker === ownerSpeaker && reply.answers.includes(turn.id))
683
+ )
684
+
685
+ const roundComplete = (
686
+ meeting: Meeting,
687
+ turns: ReadonlyArray<Turn>,
688
+ item: number,
689
+ round: number
690
+ ): boolean =>
691
+ meeting.attendees.every((attendee) =>
692
+ turns.some((turn) => turn.item === item && turn.round === round && turn.speaker === attendee)
693
+ )
694
+
695
+ const maxRound = (turns: ReadonlyArray<Turn>, item: number): number =>
696
+ onItem(turns, item).reduce((most, turn) => Math.max(most, turn.round), 0)
697
+
698
+ /** The round the next turn on the item belongs to: the open one, or a new one after a complete one. */
699
+ export const currentRound = (
700
+ meeting: Meeting,
701
+ turns: ReadonlyArray<Turn>,
702
+ item: number
703
+ ): number => {
704
+ const most = maxRound(turns, item)
705
+ return most > 0 && roundComplete(meeting, turns, item, most) ? most + 1 : Math.max(most, 1)
706
+ }
707
+
708
+ export interface Caps {
709
+ /** Complete rounds an item gets before it is left open; an owner turn grants one more. */
710
+ readonly roundsPerItem: number
711
+ /** Turns in the whole discussion before drafting starts whatever is open. */
712
+ readonly maxTurns: number
713
+ }
714
+
715
+ export const defaultCaps: Caps = { roundsPerItem: 3, maxTurns: 40 }
716
+
717
+ export interface ItemState {
718
+ /** Complete rounds so far. */
719
+ readonly rounds: number
720
+ /** The round the next turn belongs to. */
721
+ readonly round: number
722
+ /** A complete round ended with no open blocking objection and no open question. */
723
+ readonly settled: boolean
724
+ /** Not settled, and out of rounds. */
725
+ readonly capped: boolean
726
+ }
727
+
728
+ export const itemState = (
729
+ meeting: Meeting,
730
+ turns: ReadonlyArray<Turn>,
731
+ item: number,
732
+ caps: Caps
733
+ ): ItemState => {
734
+ const most = maxRound(turns, item)
735
+ let rounds = 0
736
+ for (let round = 1; round <= most; round += 1) {
737
+ if (roundComplete(meeting, turns, item, round)) rounds += 1
738
+ }
739
+ const latestComplete = most > 0 && roundComplete(meeting, turns, item, most)
740
+ const open = openObjections(turns, item).length > 0 || openQuestions(turns, item).length > 0
741
+ const settled = latestComplete && !open
742
+ const ownerTurns = onItem(turns, item).filter((turn) => turn.speaker === ownerSpeaker).length
743
+ return {
744
+ rounds,
745
+ round: currentRound(meeting, turns, item),
746
+ settled,
747
+ capped: !settled && latestComplete && rounds >= caps.roundsPerItem + ownerTurns
748
+ }
749
+ }
750
+
751
+ export interface Decision {
752
+ readonly item: AgendaItem
753
+ readonly proposal: Turn
754
+ readonly dissent: ReadonlyArray<Turn>
755
+ }
756
+
757
+ /**
758
+ * Silence is consent: on an item that is settled or capped, every proposal
759
+ * with no open blocking objection against it is a decision, and the soft
760
+ * objections to it are its dissent.
761
+ */
762
+ export const decisions = (
763
+ meeting: Meeting,
764
+ turns: ReadonlyArray<Turn>,
765
+ caps: Caps
766
+ ): ReadonlyArray<Decision> =>
767
+ discussionItems(meeting).flatMap((item) => {
768
+ const state = itemState(meeting, turns, item.number, caps)
769
+ if (!state.settled && !state.capped) return []
770
+ const blocking = openObjections(turns, item.number)
771
+ return onItem(turns, item.number)
772
+ .filter(
773
+ (turn) =>
774
+ turn.kind === "proposal" &&
775
+ !blocking.some((objection) => objection.answers.includes(turn.id))
776
+ )
777
+ .map((proposal) => ({ item, proposal, dissent: dissent(turns, proposal) }))
778
+ })
779
+
780
+ // ---- The chair ----------------------------------------------------------------
781
+
782
+ export interface OwnerAnswer {
783
+ readonly question: Turn
784
+ readonly answer: string
785
+ }
786
+
787
+ export type ChairAction =
788
+ | { readonly _tag: "ProposeAgenda"; readonly speaker: string }
789
+ | { readonly _tag: "OpenDiscussion" }
790
+ | {
791
+ readonly _tag: "RecordOwner"
792
+ readonly answers: ReadonlyArray<OwnerAnswer>
793
+ readonly feedback: string
794
+ }
795
+ | {
796
+ readonly _tag: "Judge"
797
+ readonly item: AgendaItem
798
+ readonly objection: Turn
799
+ readonly reply: Turn
800
+ }
801
+ | {
802
+ readonly _tag: "Speak"
803
+ readonly item: AgendaItem
804
+ readonly round: number
805
+ readonly speaker: string
806
+ /** Open objections and questions aimed at this speaker's earlier turns. */
807
+ readonly addressed: ReadonlyArray<Turn>
808
+ }
809
+ | { readonly _tag: "Draft" }
810
+ | { readonly _tag: "Finalize"; readonly objections: ReadonlyArray<Turn> }
811
+ | { readonly _tag: "Done" }
812
+ | { readonly _tag: "Refused"; readonly reason: string }
813
+
814
+ /** Answers written in the file for parked questions, and feedback, not yet recorded as Owner turns. */
815
+ const pendingOwner = (
816
+ meeting: Meeting,
817
+ turns: ReadonlyArray<Turn>
818
+ ): { answers: ReadonlyArray<OwnerAnswer>; feedback: string } => {
819
+ const parked = parkedQuestions(turns)
820
+ const answers = meeting.answers.flatMap((point) => {
821
+ const answer = (point.answer ?? "").trim()
822
+ const question = parked.find((turn) => turn.id === point.number)
823
+ return answer.length === 0 || question === undefined ? [] : [{ question, answer }]
824
+ })
825
+ return { answers, feedback: meeting.feedback.trim() }
826
+ }
827
+
828
+ /** An open objection the objector has spoken past without closing, since the last reply to it. */
829
+ const judgeNeeded = (
830
+ turns: ReadonlyArray<Turn>,
831
+ item: number
832
+ ): { objection: Turn; reply: Turn } | undefined => {
833
+ for (const objection of openObjections(turns, item)) {
834
+ const reply = turns
835
+ .filter(
836
+ (turn) =>
837
+ turn.id > objection.id &&
838
+ turn.kind !== "pass" &&
839
+ turn.answers.includes(objection.id) &&
840
+ turn.speaker !== objection.speaker &&
841
+ turn.speaker !== chairSpeaker
842
+ )
843
+ .at(-1)
844
+ if (reply === undefined) continue
845
+ const objectorSpoke = turns.some(
846
+ (turn) => turn.id > reply.id && turn.item === item && turn.speaker === objection.speaker
847
+ )
848
+ const chairRuled = turns.some(
849
+ (turn) =>
850
+ turn.id > reply.id && turn.speaker === chairSpeaker && turn.answers.includes(objection.id)
851
+ )
852
+ if (objectorSpoke && !chairRuled) return { objection, reply }
853
+ }
854
+ return undefined
855
+ }
856
+
857
+ const speakOn = (
858
+ meeting: Meeting,
859
+ turns: ReadonlyArray<Turn>,
860
+ item: AgendaItem,
861
+ round: number
862
+ ): ChairAction => {
863
+ const speaker =
864
+ meeting.attendees.find(
865
+ (attendee) =>
866
+ !turns.some(
867
+ (turn) => turn.item === item.number && turn.round === round && turn.speaker === attendee
868
+ )
869
+ ) ??
870
+ meeting.attendees[0] ??
871
+ ""
872
+ const mine = new Set(
873
+ onItem(turns, item.number)
874
+ .filter((turn) => turn.speaker === speaker)
875
+ .map((turn) => turn.id)
876
+ )
877
+ const addressed = [...openObjections(turns, item.number), ...openQuestions(turns, item.number)]
878
+ .filter((turn) => turn.answers.some((id) => mine.has(id)))
879
+ .sort((left, right) => left.id - right.id)
880
+ return { _tag: "Speak", item, round, speaker, addressed }
881
+ }
882
+
883
+ /**
884
+ * What the run does next, from the files alone. The owner's words come
885
+ * first; then the agenda, the discussion item by item (a judgment before a
886
+ * turn when a stalemate needs breaking), the drafting, one review round per
887
+ * draft, and the end.
888
+ */
889
+ export const nextAction = (
890
+ meeting: Meeting,
891
+ turns: ReadonlyArray<Turn>,
892
+ caps: Caps
893
+ ): ChairAction => {
894
+ if (meeting.attendees.length === 0) {
895
+ return { _tag: "Refused", reason: "the meeting has no attendees" }
896
+ }
897
+ if (meeting.status === "agenda-proposed") {
898
+ return meeting.agenda.length === 0
899
+ ? { _tag: "ProposeAgenda", speaker: meeting.attendees[0] ?? "" }
900
+ : { _tag: "OpenDiscussion" }
901
+ }
902
+ if (meeting.agenda.length === 0) {
903
+ return {
904
+ _tag: "Refused",
905
+ reason:
906
+ "the meeting is discussing but has no agenda: delete the folder or set Status: agenda-proposed"
907
+ }
908
+ }
909
+ const owner = pendingOwner(meeting, turns)
910
+ if (owner.answers.length > 0 || owner.feedback.length > 0) {
911
+ return { _tag: "RecordOwner", answers: owner.answers, feedback: owner.feedback }
912
+ }
913
+ if (meeting.status === "done") return { _tag: "Done" }
914
+ if (meeting.status === "drafting") return { _tag: "Draft" }
915
+ if (meeting.status === "reviewing") {
916
+ const review = reviewItem(meeting)
917
+ const state = itemState(meeting, turns, review.number, caps)
918
+ return state.rounds >= meeting.drafts
919
+ ? { _tag: "Finalize", objections: openObjections(turns, review.number) }
920
+ : speakOn(meeting, turns, review, state.round)
921
+ }
922
+ if (turns.length >= caps.maxTurns) return { _tag: "Draft" }
923
+ for (const item of discussionItems(meeting)) {
924
+ const state = itemState(meeting, turns, item.number, caps)
925
+ if (state.settled || state.capped) continue
926
+ const stalemate = judgeNeeded(turns, item.number)
927
+ if (stalemate !== undefined) return { _tag: "Judge", item, ...stalemate }
928
+ return speakOn(meeting, turns, item, state.round)
929
+ }
930
+ return { _tag: "Draft" }
931
+ }
932
+
933
+ /** The owner's answers and feedback as turns: an answer on its question's item, feedback on the review item. */
934
+ export const recordOwner = (
935
+ meeting: Meeting,
936
+ turns: ReadonlyArray<Turn>,
937
+ action: Extract<ChairAction, { _tag: "RecordOwner" }>
938
+ ): ReadonlyArray<Turn> => {
939
+ const recorded: Array<Turn> = []
940
+ const ownerTurn = (item: number, answers: ReadonlyArray<number>, body: string): Turn => {
941
+ const all = [...turns, ...recorded]
942
+ return Turn.make({
943
+ id: all.length + 1,
944
+ round: currentRound(meeting, all, item),
945
+ item,
946
+ speaker: ownerSpeaker,
947
+ kind: "position",
948
+ answers: [...answers],
949
+ blocking: false,
950
+ needsHuman: false,
951
+ body
952
+ })
953
+ }
954
+ for (const { question, answer } of action.answers) {
955
+ recorded.push(ownerTurn(question.item, [question.id], answer))
956
+ }
957
+ if (action.feedback.length > 0) {
958
+ recorded.push(ownerTurn(reviewItem(meeting).number, [], action.feedback))
959
+ }
960
+ return recorded
961
+ }
962
+
963
+ // ---- Views ----------------------------------------------------------------------
964
+
965
+ const refs = (ids: ReadonlyArray<number>): string => ids.map((id) => `#${id}`).join(", ")
966
+
967
+ const firstLine = (text: string): string => {
968
+ const line = oneLine(text.split(/\r?\n/)[0] ?? "")
969
+ return line.length > 80 ? `${line.slice(0, 77)}...` : line
970
+ }
971
+
972
+ /** One turn as the notes show it: `**PO** #4 objection to #2, blocking: …`. */
973
+ export const renderTurn = (turn: Turn): string => {
974
+ if (turn.kind === "pass") return `**${turn.speaker}** #${turn.id} passes.`
975
+ const owner = turn.needsHuman ? " for the owner" : ""
976
+ const assuming = turn.assumption === undefined ? "" : ` (assuming: ${turn.assumption})`
977
+ const linked =
978
+ turn.answers.length === 0
979
+ ? ""
980
+ : turn.kind === "objection"
981
+ ? ` to ${refs(turn.answers)}`
982
+ : turn.kind === "agreement"
983
+ ? ` with ${refs(turn.answers)}`
984
+ : ` answering ${refs(turn.answers)}`
985
+ const blocking = turn.kind === "objection" && turn.blocking ? ", blocking" : ""
986
+ return `**${turn.speaker}** #${turn.id} ${turn.kind}${owner}${assuming}${linked}${blocking}: ${turn.body}`
987
+ }
988
+
989
+ const itemFooter = (state: ItemState, turns: number): string =>
990
+ state.settled
991
+ ? "Settled."
992
+ : state.capped
993
+ ? `Left open after ${state.rounds} rounds.`
994
+ : turns === 0
995
+ ? "Not discussed yet."
996
+ : "In progress."
997
+
998
+ /** `discussion.md`: the record as meeting notes, item by item, round by round. */
999
+ export const renderDiscussion = (
1000
+ meeting: Meeting,
1001
+ turns: ReadonlyArray<Turn>,
1002
+ caps: Caps
1003
+ ): string => {
1004
+ const review = reviewItem(meeting)
1005
+ const items = [
1006
+ ...discussionItems(meeting),
1007
+ ...(onItem(turns, review.number).length === 0 ? [] : [review])
1008
+ ]
1009
+ return [
1010
+ `# Discussion: ${meeting.topic}`,
1011
+ "",
1012
+ `Goal: ${meeting.goal}`,
1013
+ `Attendees: ${meeting.attendees.join(", ")}`,
1014
+ "",
1015
+ ...items.flatMap((item) => {
1016
+ const own = onItem(turns, item.number)
1017
+ const rounds = [...new Set(own.map((turn) => turn.round))].sort((a, b) => a - b)
1018
+ const state = itemState(meeting, turns, item.number, caps)
1019
+ return [
1020
+ `## ${renderAgendaItem(item)}`,
1021
+ "",
1022
+ ...rounds.flatMap((round) => [
1023
+ `### Round ${round}`,
1024
+ "",
1025
+ ...own.filter((turn) => turn.round === round).flatMap((turn) => [renderTurn(turn), ""])
1026
+ ]),
1027
+ item.number === review.number
1028
+ ? state.round > state.rounds
1029
+ ? "In progress."
1030
+ : "Reviewed."
1031
+ : itemFooter(state, own.length),
1032
+ ""
1033
+ ]
1034
+ })
1035
+ ].join("\n")
1036
+ }
1037
+
1038
+ /** `decisions.md`: one ADR-shaped entry per proposal that stood, with its dissent. */
1039
+ export const renderDecisions = (
1040
+ meeting: Meeting,
1041
+ turns: ReadonlyArray<Turn>,
1042
+ caps: Caps
1043
+ ): string => {
1044
+ const decided = decisions(meeting, turns, caps)
1045
+ return [
1046
+ `# Decisions: ${meeting.topic}`,
1047
+ "",
1048
+ ...(decided.length === 0
1049
+ ? ["No decision was reached.", ""]
1050
+ : decided.flatMap((decision, index) => [
1051
+ `## ${index + 1}. ${firstLine(decision.proposal.body)}`,
1052
+ "",
1053
+ `Item: ${renderAgendaItem(decision.item)}`,
1054
+ `Proposed by: ${decision.proposal.speaker} (#${decision.proposal.id}), round ${decision.proposal.round}`,
1055
+ "",
1056
+ ...prose(decision.proposal.body),
1057
+ "",
1058
+ ...(decision.dissent.length === 0
1059
+ ? ["No dissent."]
1060
+ : [
1061
+ "Dissent:",
1062
+ ...decision.dissent.map(
1063
+ (turn) => `- ${turn.speaker} (#${turn.id}): ${oneLine(turn.body)}`
1064
+ )
1065
+ ]),
1066
+ ""
1067
+ ]))
1068
+ ].join("\n")
1069
+ }
1070
+
1071
+ /** `open-questions.md`: what the owner owes the room, and what the room left open. */
1072
+ export const renderOpenQuestions = (
1073
+ meeting: Meeting,
1074
+ turns: ReadonlyArray<Turn>,
1075
+ caps: Caps
1076
+ ): string => {
1077
+ const parked = parkedQuestions(turns)
1078
+ const open = discussionItems(meeting).flatMap((item) => {
1079
+ const state = itemState(meeting, turns, item.number, caps)
1080
+ if (state.settled) return []
1081
+ const own = onItem(turns, item.number)
1082
+ const why = state.capped
1083
+ ? `left open after ${state.rounds} rounds`
1084
+ : own.length === 0
1085
+ ? "not discussed"
1086
+ : "in progress"
1087
+ return [
1088
+ `- ${renderAgendaItem(item)}: ${why}`,
1089
+ ...openObjections(turns, item.number).map(
1090
+ (turn) =>
1091
+ ` - #${turn.id} ${turn.speaker} objects${turn.answers.length === 0 ? "" : ` to ${refs(turn.answers)}`}, blocking: ${oneLine(turn.body)}`
1092
+ ),
1093
+ ...openQuestions(turns, item.number).map(
1094
+ (turn) => ` - #${turn.id} ${turn.speaker} asks: ${oneLine(turn.body)}`
1095
+ )
1096
+ ]
1097
+ })
1098
+ return [
1099
+ `# Open questions: ${meeting.topic}`,
1100
+ "",
1101
+ "## For the owner",
1102
+ "",
1103
+ ...(parked.length === 0
1104
+ ? ["None."]
1105
+ : parked.map(
1106
+ (turn) =>
1107
+ `- #${turn.id} ${turn.speaker}, item ${turn.item}: ${oneLine(turn.body)}${turn.assumption === undefined ? "" : ` (assuming: ${turn.assumption})`}`
1108
+ )),
1109
+ "",
1110
+ "## Left open by the room",
1111
+ "",
1112
+ ...(open.length === 0 ? ["Every item settled."] : open),
1113
+ ""
1114
+ ].join("\n")
1115
+ }
1116
+
1117
+ /** The meeting file with every parked question listed for the owner; answers already there are kept. */
1118
+ export const syncAnswers = (meeting: Meeting, turns: ReadonlyArray<Turn>): Meeting => {
1119
+ const listed = new Set(meeting.answers.map((point) => point.number))
1120
+ const missing = parkedQuestions(turns)
1121
+ .filter((turn) => !listed.has(turn.id))
1122
+ .map((turn) =>
1123
+ OpenPoint.make({ number: turn.id, question: `${oneLine(turn.body)} (${turn.speaker})` })
1124
+ )
1125
+ return Meeting.make({
1126
+ ...meeting,
1127
+ answers: [...meeting.answers, ...missing].sort((left, right) => left.number - right.number)
1128
+ })
1129
+ }
1130
+
1131
+ export interface Briefing {
1132
+ /** Decisions of the items before this one. */
1133
+ readonly decisions: ReadonlyArray<Decision>
1134
+ /** Questions parked for the owner so far, with their assumptions. */
1135
+ readonly parked: ReadonlyArray<Turn>
1136
+ /** Every turn on the item under discussion. */
1137
+ readonly current: ReadonlyArray<Turn>
1138
+ }
1139
+
1140
+ /** What an attendee reads before speaking on an item (ADR 0046, decision 8). */
1141
+ export const briefingFor = (
1142
+ meeting: Meeting,
1143
+ turns: ReadonlyArray<Turn>,
1144
+ item: number,
1145
+ caps: Caps
1146
+ ): Briefing => ({
1147
+ decisions: decisions(meeting, turns, caps).filter((decision) => decision.item.number < item),
1148
+ parked: parkedQuestions(turns),
1149
+ current: onItem(turns, item)
1150
+ })