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