@llm4ts/shell 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.
@@ -0,0 +1,1117 @@
1
+ /**
2
+ * taskforce (ADR 0047): the flow half of the delegation loop. What is ready,
3
+ * blocked, checked and done is `@llm4ts/flow/Taskforce`; this module reads
4
+ * and writes the run's files, builds the prompts, drives the seats, the
5
+ * worktrees, the process executor and the judgment service, writes the
6
+ * trail, and reports to the person.
7
+ */
8
+ import { join } from "node:path";
9
+ import * as Effect from "effect/Effect";
10
+ import * as Schema from "effect/Schema";
11
+ import { truthOf } from "@llm4ts/core/judgment/Judgment";
12
+ import { truth } from "@llm4ts/core/judgment/Schemas";
13
+ import { cap } from "@llm4ts/flow/Context";
14
+ import { completeAndPublish } from "@llm4ts/flow/Flow";
15
+ import { BriefReported, Info, StageCompleted, StageStarted } from "@llm4ts/flow/FlowEvents";
16
+ import { FlowAborted, PlanInvalid, PlanPending } from "@llm4ts/flow/FlowError";
17
+ import { decide, judgeOrEscalate } from "@llm4ts/flow/Judgment";
18
+ import { recall, renderRunNote, RunNote, runNoteJsonSchema } from "@llm4ts/flow/Memory";
19
+ import { parsePersona } from "@llm4ts/flow/Roundtable";
20
+ import { acceptanceLines, assembleBriefs, CheckProposal, checkProposalJsonSchema, currentWave, Finding, fixBriefs, GoalCheck, isFinal, LeadProposal, leadProposalJsonSchema, LensFindings, lensFindingsJsonSchema, nextAction, parsePlan, parseReport, Plan, PlanProposal, planProposalJsonSchema, planViolations, recordOwner, renderOpenQuestions, renderPlan, renderReport, renderReview, renderTrailRow, Report, ReportProposal, reportProposalJsonSchema, reportOf, syncAnswers, trailHeader, verifyCommands } from "@llm4ts/flow/Taskforce";
21
+ import { structuredAndPublish } from "@llm4ts/flow/Usage";
22
+ import { ScriptUsage } from "@llm4ts/runner/FlowArgs";
23
+ import { terminalSafe } from "@llm4ts/runner/Terminal";
24
+ import { meetingSlug, personasDir } from "./roundtable.js";
25
+ import { bundledSpecialistCards, chiefName, memoryName, selectableSpecialists, writerName } from "./taskforce-personas.js";
26
+ export { personasDir };
27
+ // ---- Flags ----------------------------------------------------------------------
28
+ export const taskforceUsage = [
29
+ 'usage: llm4ts run taskforce --repo <dir> "<goal>" -- [--agents "Researcher,Engineer,..."] [--run <id>]',
30
+ " [--context <dir>] [--waves <n>] [--briefs <n>] [--parallel <n>] [--turns <n>]",
31
+ " [--no-pause] [--keep-work] [--no-memory]",
32
+ " llm4ts run taskforce --repo <dir> -- --run <id> # continue or finish a run",
33
+ " llm4ts run taskforce --repo <dir> -- --eject-personas # write the bundled cards to .llm4ts/personas/",
34
+ " llm4ts run taskforce --repo <dir> -- --list # the repository's runs",
35
+ " --agents <names> specialists by card name; default: Researcher,Engineer,Operator,Reviewer,Memory Manager",
36
+ " (the Chief of Staff and the Doc Writer are always present)",
37
+ " --run <id> the run folder under .llm4ts/taskforce/; default: a slug of the goal",
38
+ " --context <dir> documents every brief reads (standards, architecture notes)",
39
+ " --waves <n> waves in all, the fix wave included (default 3)",
40
+ " --briefs <n> briefs in all (default 12)",
41
+ " --parallel <n> briefs run at once (default: the roster's slots, else 1)",
42
+ " --turns <n> the coder's turn cap on every Engineer brief (default 30)",
43
+ " --no-pause do not stop after the plan is proposed; only declared commands then run",
44
+ " --keep-work keep the Engineer's worktrees when the run is done",
45
+ " --no-memory neither recall nor write memory notes",
46
+ "The plan file is the state: .llm4ts/taskforce/<id>/plan.md. Edit the briefs, answer the",
47
+ "questions under '## Answers', write under '## Feedback', and rerun."
48
+ ].join("\n");
49
+ export const parseTaskforceArgs = (argv) => Effect.gen(function* () {
50
+ let agents;
51
+ let run;
52
+ let context;
53
+ let waves;
54
+ let briefs;
55
+ let parallel;
56
+ let turns;
57
+ let noPause = false;
58
+ let keepWork = false;
59
+ let noMemory = false;
60
+ let ejectPersonas = false;
61
+ let list = false;
62
+ const rest = [];
63
+ for (let index = 0; index < argv.length; index += 1) {
64
+ const argument = argv[index] ?? "";
65
+ const is = (name) => argument === name || argument.startsWith(`${name}=`);
66
+ const valued = (name) => {
67
+ const value = argument.includes("=") ? argument.slice(name.length + 1) : argv[index + 1];
68
+ if (!argument.includes("="))
69
+ index += 1;
70
+ return value === undefined || value.trim().length === 0 || value.startsWith("--")
71
+ ? ScriptUsage.make({ message: `${name} needs a value\n${taskforceUsage}` })
72
+ : Effect.succeed(value.trim());
73
+ };
74
+ const counted = (name) => Effect.flatMap(valued(name), (value) => /^\d+$/.test(value) && Number.parseInt(value, 10) > 0
75
+ ? Effect.succeed(Number.parseInt(value, 10))
76
+ : ScriptUsage.make({ message: `${name} needs a positive number, got: ${value}` }));
77
+ if (is("--agents"))
78
+ agents = (yield* valued("--agents"))
79
+ .split(",")
80
+ .map((name) => name.trim())
81
+ .filter((name) => name.length > 0);
82
+ else if (is("--run"))
83
+ run = yield* valued("--run");
84
+ else if (is("--context"))
85
+ context = yield* valued("--context");
86
+ else if (is("--waves"))
87
+ waves = yield* counted("--waves");
88
+ else if (is("--briefs"))
89
+ briefs = yield* counted("--briefs");
90
+ else if (is("--parallel"))
91
+ parallel = yield* counted("--parallel");
92
+ else if (is("--turns"))
93
+ turns = yield* counted("--turns");
94
+ else if (argument === "--no-pause")
95
+ noPause = true;
96
+ else if (argument === "--keep-work")
97
+ keepWork = true;
98
+ else if (argument === "--no-memory")
99
+ noMemory = true;
100
+ else if (argument === "--eject-personas")
101
+ ejectPersonas = true;
102
+ else if (argument === "--list")
103
+ list = true;
104
+ else
105
+ rest.push(argument);
106
+ }
107
+ return {
108
+ agents,
109
+ run,
110
+ context,
111
+ waves,
112
+ briefs,
113
+ parallel,
114
+ turns,
115
+ noPause,
116
+ keepWork,
117
+ noMemory,
118
+ ejectPersonas,
119
+ list,
120
+ rest
121
+ };
122
+ });
123
+ // ---- Places -------------------------------------------------------------------
124
+ export const runsDir = (workDir) => join(workDir, ".llm4ts", "taskforce");
125
+ export const runDir = (workDir, id) => join(runsDir(workDir), id);
126
+ /** The repository's command allowlist for `--no-pause`, one command per line. */
127
+ export const commandsPath = (workDir) => join(runsDir(workDir), "commands.md");
128
+ export const lensesDir = (workDir) => join(workDir, ".llm4ts", "lenses");
129
+ export const runSlug = meetingSlug;
130
+ const runFiles = (dir) => ({
131
+ plan: join(dir, "plan.md"),
132
+ report: (id) => join(dir, "reports", `${id}.md`),
133
+ commandLog: (id) => join(dir, "reports", `${id}-commands.log`),
134
+ diff: (id) => join(dir, "work", `${id}.diff`),
135
+ review: join(dir, "review.md"),
136
+ trail: join(dir, "decisions.tsv"),
137
+ openQuestions: join(dir, "open-questions.md"),
138
+ deliverable: (name) => join(dir, name)
139
+ });
140
+ /**
141
+ * The cards the run uses: bundled ones, each replaced by a custom card of
142
+ * the same name (`.llm4ts/personas/<name>.md`, read by the caller). The
143
+ * Chief of Staff and the Doc Writer are always present; the Memory Manager
144
+ * is present while memory is on; `agents` picks the rest.
145
+ */
146
+ export const resolveCast = Effect.fn("taskforce.resolveCast")(function* (custom, agents, memory) {
147
+ const cards = { ...bundledSpecialistCards, ...custom };
148
+ const personas = new Map();
149
+ for (const [name, text] of Object.entries(cards)) {
150
+ personas.set(name, yield* parsePersona(name, text));
151
+ }
152
+ const fixed = [chiefName, writerName];
153
+ const known = [...personas.keys()].filter((name) => !fixed.includes(name));
154
+ const missing = agents.filter((name) => !personas.has(name) || fixed.includes(name));
155
+ if (missing.length > 0) {
156
+ return yield* ScriptUsage.make({
157
+ message: `unknown specialist(s): ${missing.join(", ")}; known: ${known.join(", ")} — add a card under .llm4ts/personas/<name>.md`
158
+ });
159
+ }
160
+ const chief = personas.get(chiefName);
161
+ const writer = personas.get(writerName);
162
+ if (chief === undefined || writer === undefined) {
163
+ return yield* ScriptUsage.make({ message: `no ${chiefName} or ${writerName} card` });
164
+ }
165
+ const names = new Set([chiefName, writerName, ...agents, ...(memory ? [memoryName] : [])]);
166
+ if (!memory)
167
+ names.delete(memoryName);
168
+ const all = [...names]
169
+ .flatMap((name) => {
170
+ const persona = personas.get(name);
171
+ return persona === undefined ? [] : [persona];
172
+ })
173
+ .sort((left, right) => left.order - right.order || left.name.localeCompare(right.name));
174
+ return { chief, writer, all };
175
+ });
176
+ /** Writes every bundled card the folder lacks; returns the paths written. */
177
+ export const ejectPersonas = Effect.fn("taskforce.ejectPersonas")(function* (files, workDir) {
178
+ const written = [];
179
+ for (const [name, text] of Object.entries(bundledSpecialistCards)) {
180
+ const path = join(personasDir(workDir), `${name}.md`);
181
+ if ((yield* files.read(path)) !== undefined)
182
+ continue;
183
+ yield* files.writeAtomic(path, text);
184
+ written.push(path);
185
+ }
186
+ return written;
187
+ });
188
+ export const describeCast = (cast) => cast
189
+ .map((persona) => ` ${persona.name} (${persona.tools ?? "none"}, ${persona.seat ?? "planner"}): ${persona.mandate.split(/[.!?]/)[0] ?? ""}.`)
190
+ .join("\n");
191
+ export const defaultAgents = selectableSpecialists;
192
+ // ---- Commands (decision 5) ------------------------------------------------------
193
+ /** A command line as argv: whitespace-separated, single and double quotes grouping. */
194
+ export const shellWords = (command) => {
195
+ const words = [];
196
+ let current = "";
197
+ let quoted = false;
198
+ let quote;
199
+ for (const char of command) {
200
+ if (quote !== undefined) {
201
+ if (char === quote)
202
+ quote = undefined;
203
+ else
204
+ current += char;
205
+ continue;
206
+ }
207
+ if (char === '"' || char === "'") {
208
+ quote = char;
209
+ quoted = true;
210
+ continue;
211
+ }
212
+ if (/\s/.test(char)) {
213
+ if (current.length > 0 || quoted)
214
+ words.push(current);
215
+ current = "";
216
+ quoted = false;
217
+ continue;
218
+ }
219
+ current += char;
220
+ }
221
+ if (current.length > 0 || quoted)
222
+ words.push(current);
223
+ return words;
224
+ };
225
+ /**
226
+ * What runs under `--no-pause`: the package's scripts through npm, pnpm or
227
+ * yarn, and every line of `.llm4ts/taskforce/commands.md` that is not blank
228
+ * or a comment.
229
+ */
230
+ export const declaredCommands = (packageJson, commandsMarkdown) => {
231
+ const scripts = new Set();
232
+ if (packageJson !== undefined) {
233
+ const parsed = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Struct({ scripts: Schema.optionalKey(Schema.Record(Schema.String, Schema.String)) })))(packageJson);
234
+ if (parsed._tag === "Some")
235
+ for (const name of Object.keys(parsed.value.scripts ?? {}))
236
+ scripts.add(name);
237
+ }
238
+ const lines = new Set((commandsMarkdown ?? "")
239
+ .split(/\r?\n/)
240
+ .map((line) => line
241
+ .trim()
242
+ .replace(/^-\s*/, "")
243
+ .replace(/^`(.*)`$/, "$1"))
244
+ .filter((line) => line.length > 0 && !line.startsWith("#"))
245
+ .map((line) => shellWords(line).join("\u0000")));
246
+ return (argv) => {
247
+ if (argv.length === 0)
248
+ return false;
249
+ if (lines.has(argv.join("\u0000")))
250
+ return true;
251
+ const [runner, second, third] = argv;
252
+ if (runner === "npm") {
253
+ return second === "test"
254
+ ? scripts.has("test")
255
+ : second === "run" && third !== undefined && scripts.has(third);
256
+ }
257
+ if (runner === "pnpm" || runner === "yarn") {
258
+ return second === "run"
259
+ ? third !== undefined && scripts.has(third)
260
+ : second !== undefined && scripts.has(second);
261
+ }
262
+ return false;
263
+ };
264
+ };
265
+ // ---- Prompts ------------------------------------------------------------------
266
+ const personaBrief = (persona) => [
267
+ `You are the ${persona.name} of a taskforce.`,
268
+ "",
269
+ `Mandate: ${persona.mandate}`,
270
+ ...(persona.caresAbout.length === 0 ? [] : [`You care about: ${persona.caresAbout}`]),
271
+ ...(persona.pushesBackOn.length === 0 ? [] : [`You push back on: ${persona.pushesBackOn}`]),
272
+ ...(persona.neverDecidesAlone.length === 0
273
+ ? []
274
+ : [`You never decide alone: ${persona.neverDecidesAlone}`]),
275
+ ...(persona.voice.length === 0 ? [] : [`Voice: ${persona.voice}`])
276
+ ].join("\n");
277
+ const castBrief = (cast) => [
278
+ "The cast (name, hands, mandate):",
279
+ ...cast.map((persona) => `- ${persona.name} — ${persona.tools ?? "none"}: ${persona.mandate.split(/(?<=[.!?])\s/)[0] ?? persona.mandate}`)
280
+ ].join("\n");
281
+ const contextBrief = (docs, budget) => {
282
+ if (docs.length === 0)
283
+ return [];
284
+ const each = Math.max(1_000, Math.floor(budget / 3 / docs.length));
285
+ return [
286
+ "",
287
+ "Context documents (standards and notes the work stays within):",
288
+ ...docs.flatMap((doc) => ["", `--- ${doc.path} ---`, cap(doc.text, each).text])
289
+ ];
290
+ };
291
+ const memoryBrief = (notes, budget) => {
292
+ if (notes.length === 0)
293
+ return [];
294
+ const each = Math.max(500, Math.floor(budget / 6 / notes.length));
295
+ return [
296
+ "",
297
+ "What we learned before (memory notes recalled for this goal):",
298
+ ...notes.flatMap((note) => ["", `--- ${note.name} ---`, cap(note.body, each).text])
299
+ ];
300
+ };
301
+ const briefTemplate = [
302
+ "A brief has eight fields: GOAL (one sentence, the outcome, executable by a stranger), SCOPE (paths it may touch; paths it may not), CONTEXT (pointers to files and reports; what it depends on, pasted in), ACCEPTANCE (checkable criteria, one per entry), VERIFY (exact commands, one per entry; only the Operator may run commands — name them anyway and they will be routed), TIMEBOX (a rough cap), FORBIDDEN (what it must not do), REPORT (what the report must hold and which deliverable it feeds)."
303
+ ].join("\n");
304
+ const planPrompt = (options) => [
305
+ personaBrief(options.chief),
306
+ "",
307
+ `Goal: ${options.goal}`,
308
+ "",
309
+ castBrief(options.cast),
310
+ ...contextBrief(options.docs, options.budget),
311
+ ...memoryBrief(options.notes, options.budget),
312
+ "",
313
+ `Propose the plan: the deliverables (file names; result.md is always one and holds the answer, its sources and the next steps) and between 2 and ${options.caps.briefs} briefs, numbered B1 upward in the order you list them. Name each brief's owner from the cast by name and the brief ids it depends on. Riskiest unknown first; independent briefs run together. Every deliverable must be named in some brief's REPORT.`,
314
+ "",
315
+ briefTemplate,
316
+ ...(options.violations.length === 0
317
+ ? []
318
+ : [
319
+ "",
320
+ "Your previous proposal was refused:",
321
+ ...options.violations.map((violation) => `- ${violation}`),
322
+ "Propose again without these faults."
323
+ ]),
324
+ "",
325
+ 'Reply with JSON: {"deliverables": ["result.md", ...], "briefs": [{"title": "...", "owner": "...", "dependsOn": ["B1"], "goal": "...", "scope": "...", "context": "...", "acceptance": ["..."], "verify": ["..."], "timebox": "...", "forbidden": "...", "report": "..."}]}'
326
+ ].join("\n");
327
+ const reportsBrief = (plan, reports, budget, only) => {
328
+ const chosen = plan.briefs.filter((brief) => only === undefined || only.includes(brief.id));
329
+ if (chosen.length === 0)
330
+ return ["(no reports yet)"];
331
+ const each = Math.max(800, Math.floor(budget / 2 / chosen.length));
332
+ return chosen.flatMap((brief) => {
333
+ const report = reportOf(reports, brief.id);
334
+ return report === undefined
335
+ ? [`--- ${brief.id} ${brief.title} (${brief.owner}): no report ---`]
336
+ : [
337
+ `--- ${brief.id} ${brief.title} (${brief.owner}): ${report.status}, ${report.summary} ---`,
338
+ ...(report.evidence.length === 0 ? [] : [`evidence: ${report.evidence.join(", ")}`]),
339
+ cap(report.body, each).text
340
+ ];
341
+ });
342
+ };
343
+ const checkPrompt = (options) => [
344
+ personaBrief(options.chief),
345
+ "",
346
+ `Goal: ${options.plan.goal}`,
347
+ `Deliverables: ${options.plan.deliverables.join(", ")}`,
348
+ "",
349
+ `Goal check after wave ${options.wave}. The reports:`,
350
+ "",
351
+ ...reportsBrief(options.plan, options.reports, options.budget),
352
+ "",
353
+ options.mayReplan
354
+ ? `Is the goal reached well enough for the Doc Writer to write the deliverables? If not, propose the second and last wave: up to ${Math.max(0, options.caps.briefs - options.plan.briefs.length)} more briefs, numbered from B${options.from}, that close the gap; they may depend on existing briefs by id. If yes, propose no briefs.`
355
+ : "Is the goal reached well enough for the Doc Writer to write the deliverables? No further wave is possible: say what is reached and what is not, and propose no briefs.",
356
+ "",
357
+ castBrief(options.cast),
358
+ "",
359
+ briefTemplate,
360
+ "",
361
+ 'Reply with JSON: {"reached": true, "note": "...", "briefs": []}'
362
+ ].join("\n");
363
+ const reportGuide = [
364
+ "Status: PASS when every acceptance criterion holds; ISSUES when the work is done but something named holds it back; BLOCKED when you could not do it (say what stopped you).",
365
+ "Evidence: paths of what proves the report (files, diffs, logs). Questions: what only the owner can answer, each with the assumption you proceeded on."
366
+ ].join("\n");
367
+ const briefPrompt = (options) => {
368
+ const { persona, plan, brief } = options;
369
+ return [
370
+ personaBrief(persona),
371
+ "",
372
+ `Goal of the taskforce: ${plan.goal}`,
373
+ "",
374
+ `Brief ${brief.id}: ${brief.title}${options.attempt > 1 ? ` (attempt ${options.attempt})` : ""}`,
375
+ `GOAL: ${brief.goal}`,
376
+ `SCOPE: ${brief.scope}`,
377
+ `CONTEXT: ${brief.context}`,
378
+ "ACCEPTANCE:",
379
+ ...acceptanceLines(brief).map((line) => `- ${line}`),
380
+ ...(verifyCommands(brief).length === 0
381
+ ? []
382
+ : ["VERIFY:", ...verifyCommands(brief).map((line) => `- ${line}`)]),
383
+ `TIMEBOX: ${brief.timebox}`,
384
+ `FORBIDDEN: ${brief.forbidden}`,
385
+ `REPORT: ${brief.report}`,
386
+ ...(brief.dependsOn.length === 0
387
+ ? []
388
+ : [
389
+ "",
390
+ "Reports this brief depends on:",
391
+ "",
392
+ ...reportsBrief(plan, options.reports, options.budget, brief.dependsOn)
393
+ ]),
394
+ ...(options.previous === undefined
395
+ ? []
396
+ : [
397
+ "",
398
+ `Your previous attempt was BLOCKED: ${options.previous.summary}`,
399
+ cap(options.previous.body, Math.floor(options.budget / 8)).text,
400
+ "Try once more; if it is still blocked, say exactly what is needed."
401
+ ]),
402
+ ...(options.commandOutput === undefined
403
+ ? []
404
+ : [
405
+ "",
406
+ "The commands were run for you; their output:",
407
+ "",
408
+ cap(options.commandOutput, Math.floor(options.budget / 2)).text
409
+ ]),
410
+ ...contextBrief(options.docs, options.budget),
411
+ ...memoryBrief(options.notes, options.budget),
412
+ "",
413
+ reportGuide,
414
+ "",
415
+ 'Reply with JSON: {"status": "PASS|ISSUES|BLOCKED", "evidence": ["..."], "summary": "one line", "questions": [{"question": "...", "assumption": "..."}], "body": "<the report, markdown>"}'
416
+ ].join("\n");
417
+ };
418
+ /** The Engineer's prompt: a coder with a worktree, asked to end with a REPORT line. */
419
+ const engineerPrompt = (options) => [
420
+ briefPrompt({ ...options, commandOutput: undefined }).split("\nReply with JSON:")[0] ?? "",
421
+ "",
422
+ "You are in a throwaway worktree of the repository: build, run and change what the brief needs. When you are done, write the report as your final message: what you built, what you ran, what it said, what is uncertain. End the message with one line exactly of the form",
423
+ "REPORT: PASS|ISSUES|BLOCKED — <one-line summary>"
424
+ ].join("\n");
425
+ export class DraftProposal extends Schema.Class("DraftProposal")({
426
+ documents: Schema.Array(Schema.Struct({ name: Schema.String, content: Schema.String }))
427
+ }) {
428
+ }
429
+ const draftProposalJsonSchema = {
430
+ type: "object",
431
+ properties: {
432
+ documents: {
433
+ type: "array",
434
+ items: {
435
+ type: "object",
436
+ properties: { name: { type: "string" }, content: { type: "string" } },
437
+ required: ["name", "content"]
438
+ }
439
+ }
440
+ },
441
+ required: ["documents"]
442
+ };
443
+ const draftPrompt = (options) => [
444
+ personaBrief(options.writer),
445
+ "",
446
+ `Goal: ${options.plan.goal}`,
447
+ `Deliverables to write: ${options.plan.deliverables.join(", ")}`,
448
+ ...contextBrief(options.docs, options.budget),
449
+ "",
450
+ options.previous.length === 0
451
+ ? "Write every deliverable from the reports below. Say what the taskforce established; cite the report or path behind each claim; where a question was parked for the owner, state the assumption the document rests on. Do not invent what no report supports."
452
+ : "Revise the deliverables below from the fix reports. Change nothing the fixes do not touch.",
453
+ ...(options.previous.length === 0
454
+ ? []
455
+ : [
456
+ "",
457
+ "Fix briefs that ran:",
458
+ ...options.fixes.map((brief) => `- ${brief.id} ${brief.title} (${brief.owner})`),
459
+ "",
460
+ "Current deliverables:",
461
+ ...options.previous.flatMap((doc) => [
462
+ "",
463
+ `--- ${doc.name} ---`,
464
+ cap(doc.content, Math.floor(options.budget / 6)).text
465
+ ])
466
+ ]),
467
+ "",
468
+ "Reports:",
469
+ "",
470
+ ...reportsBrief(options.plan, options.reports, options.budget),
471
+ "",
472
+ "Sections of result.md:",
473
+ options.writer.resultTemplate ??
474
+ "## Answer\n## Sources\n## Explanation\n## Assumptions and open questions\n## Next steps",
475
+ "",
476
+ 'Reply with JSON: {"documents": [{"name": "result.md", "content": "<complete markdown document>"}, ...]}'
477
+ ].join("\n");
478
+ const lensPrompt = (options) => [
479
+ `Review lens: ${options.lens.name}`,
480
+ "",
481
+ options.lens.systemPrompt,
482
+ "",
483
+ `Goal: ${options.plan.goal}`,
484
+ "Briefs:",
485
+ ...options.plan.briefs.map((brief) => `- ${brief.id} ${brief.title} (${brief.owner})`),
486
+ "",
487
+ "Deliverables:",
488
+ ...options.deliverables.flatMap((doc) => [
489
+ "",
490
+ `--- ${doc.name} ---`,
491
+ cap(doc.content, Math.floor(options.budget / 3 / Math.max(1, options.deliverables.length)))
492
+ .text
493
+ ]),
494
+ ...(options.diffs.length === 0
495
+ ? []
496
+ : [
497
+ "",
498
+ "Engineer diffs:",
499
+ ...options.diffs.flatMap(({ brief, diff }) => [
500
+ "",
501
+ `--- ${brief.id} ${brief.title} ---`,
502
+ cap(diff, Math.floor(options.budget / 3 / options.diffs.length)).text
503
+ ])
504
+ ]),
505
+ "",
506
+ "Report every concrete finding from this lens: what, where (a path, a section, a line), which brief's work it is about (its id, or empty when it is about a deliverable), and why it matters. No praise, no nitpicks. An empty list is a valid answer.",
507
+ "",
508
+ 'Reply with JSON: {"findings": [{"title": "...", "where": "...", "brief": "B2", "detail": "..."}]}'
509
+ ].join("\n");
510
+ const leadPrompt = (options) => [
511
+ personaBrief(options.reviewer),
512
+ "",
513
+ `You are the lead reviewer. Goal: ${options.plan.goal}`,
514
+ "",
515
+ "The Judgment service has already marked which findings block the goal (act-on). Sort the rest: consider (legitimate, worth the owner's attention), noted (valid but not actionable now), dismissed (wrong, nitpicky, or missing context — say why).",
516
+ "",
517
+ ...options.findings.map((finding) => `- ${finding.id}. [${finding.bucket}] ${finding.title} (${finding.lens}; ${finding.where}): ${finding.detail}`),
518
+ "",
519
+ 'Reply with JSON: {"verdicts": [{"id": 2, "bucket": "consider|noted|dismissed", "reason": "..."}]} — one verdict per finding not already act-on.'
520
+ ].join("\n");
521
+ const distillPrompt = (options) => [
522
+ personaBrief(options.memory),
523
+ "",
524
+ `Goal: ${options.plan.goal}`,
525
+ `Deliverables: ${options.plan.deliverables.join(", ")}`,
526
+ "",
527
+ "Write the run note for the next run on this repository. The owner's edits and answers are in the trail (phase owner) and under Answers.",
528
+ "",
529
+ "Answers and feedback the owner gave:",
530
+ ...(options.plan.answers.length === 0
531
+ ? ["- none"]
532
+ : options.plan.answers.map((point) => `- ${point.question}${point.answer === undefined ? "" : ` → ${point.answer}`}`)),
533
+ "",
534
+ "The trail:",
535
+ cap(options.trail, Math.floor(options.budget / 4)).text,
536
+ "",
537
+ "Reports:",
538
+ "",
539
+ ...reportsBrief(options.plan, options.reports, Math.floor(options.budget / 2)),
540
+ "",
541
+ 'Reply with JSON: {"decisions": ["..."], "preferences": ["..."], "failed": ["..."], "pointers": ["..."]}'
542
+ ].join("\n");
543
+ const firstLine = (text) => {
544
+ const line = terminalSafe(text.split(/\r?\n/)[0] ?? "")
545
+ // eslint-disable-next-line no-control-regex
546
+ .replace(/[\u0000-\u001f\u007f-\u009f]/g, "")
547
+ .replace(/\s+/g, " ")
548
+ .trim();
549
+ return line.length > 80 ? `${line.slice(0, 77)}...` : line;
550
+ };
551
+ const reportLine = /^REPORT:\s*(PASS|ISSUES|BLOCKED)\s*(?:[—:-]+\s*(.*))?$/m;
552
+ /** The Engineer's status and summary from the last REPORT line of its reply; none means the timebox or the model cut it. */
553
+ export const engineerReport = (reply) => {
554
+ const matches = [...reply.matchAll(new RegExp(reportLine.source, "gm"))];
555
+ const last = matches.at(-1);
556
+ if (last === undefined)
557
+ return undefined;
558
+ const status = last[1];
559
+ return status === "PASS" || status === "ISSUES" || status === "BLOCKED"
560
+ ? { status, summary: (last[2] ?? "").trim() }
561
+ : undefined;
562
+ };
563
+ /** The run, driven from its files until it halts for the person or is done. */
564
+ export const runTaskforce = Effect.fn("taskforce.run")(function* (deps) {
565
+ const { files, events, caps, cast } = deps;
566
+ const dir = runDir(deps.workDir, deps.runId);
567
+ const paths = runFiles(dir);
568
+ const say = (message) => events.publish(Info.make({ message }));
569
+ const save = (plan) => files.writeAtomic(paths.plan, renderPlan(plan));
570
+ const trail = (phase, decision, why, evidence, result) => Effect.gen(function* () {
571
+ const existing = yield* files.read(paths.trail);
572
+ const row = renderTrailRow({ ts: deps.now(), phase, decision, why, evidence, result });
573
+ yield* files.append(paths.trail, `${existing === undefined ? `${trailHeader}\n` : ""}${row}\n`);
574
+ });
575
+ const personaOf = (name) => cast.all.find((persona) => persona.name === name);
576
+ const seatOf = (persona) => {
577
+ const role = persona.seat ?? (persona.tools === "read-only" ? "reviewer" : "planner");
578
+ const fromRoster = deps.seats.forSeat?.(role);
579
+ if (fromRoster !== undefined)
580
+ return fromRoster;
581
+ return persona.tools === "read-only" ? deps.seats.readOnly : deps.seats.toolless;
582
+ };
583
+ const notesFor = (goal) => deps.memory ? recall(goal, deps.notes, 5) : [];
584
+ // ---- The plan ----
585
+ const loaded = yield* files.read(paths.plan);
586
+ let plan;
587
+ if (loaded === undefined) {
588
+ const goal = (deps.goal ?? "").trim();
589
+ if (goal.length === 0) {
590
+ return yield* ScriptUsage.make({
591
+ message: `no plan at ${paths.plan}: give the goal to start a run\n${taskforceUsage}`
592
+ });
593
+ }
594
+ plan = Plan.make({
595
+ id: deps.runId,
596
+ status: "planned",
597
+ goal,
598
+ deliverables: ["result.md"],
599
+ cast: cast.all.map((persona) => persona.name),
600
+ briefs: [],
601
+ checks: [],
602
+ answers: [],
603
+ feedback: "",
604
+ drafts: 0,
605
+ folded: []
606
+ });
607
+ yield* save(plan);
608
+ yield* say(`taskforce: ${paths.plan} opened — ${plan.cast.join(", ")}`);
609
+ }
610
+ else {
611
+ plan = yield* parsePlan(loaded, paths.plan);
612
+ }
613
+ for (const name of plan.cast) {
614
+ if (personaOf(name) === undefined) {
615
+ return yield* ScriptUsage.make({
616
+ message: `the plan lists ${name} but no such card is known; pass --agents with the plan's cast, or add .llm4ts/personas/${name}.md`
617
+ });
618
+ }
619
+ }
620
+ // Every specialist is a lane in the dashboard, from the first event of the run.
621
+ for (const name of plan.cast) {
622
+ yield* events.publish(StageStarted.make({ stage: `specialist ${name}`, lane: name }));
623
+ }
624
+ const notes = notesFor(plan.goal);
625
+ if (notes.length > 0)
626
+ yield* say(`memory: recalled ${notes.map((note) => note.name).join(", ")}`);
627
+ // ---- Reports ----
628
+ let reports = [];
629
+ for (const brief of plan.briefs) {
630
+ const text = yield* files.read(paths.report(brief.id));
631
+ if (text !== undefined)
632
+ reports.push(yield* parseReport(text, paths.report(brief.id)));
633
+ }
634
+ const workspaces = new Map();
635
+ const record = (report, brief) => Effect.gen(function* () {
636
+ reports = [...reports.filter((existing) => existing.brief !== report.brief), report];
637
+ yield* files.writeAtomic(paths.report(brief.id), renderReport(report, brief.title));
638
+ plan = syncAnswers(plan, [report]);
639
+ yield* save(plan);
640
+ yield* events.publish(BriefReported.make({
641
+ lane: brief.owner,
642
+ run: plan.id,
643
+ brief: brief.id,
644
+ title: brief.title,
645
+ wave: brief.wave,
646
+ attempt: report.attempt,
647
+ status: report.status,
648
+ summary: firstLine(report.summary)
649
+ }));
650
+ yield* trail(`wave ${brief.wave}`, `${brief.id} reported ${report.status} by ${brief.owner}`, report.summary, `reports/${brief.id}.md`, report.status === "BLOCKED" && !isFinal(report) ? "retry" : report.status.toLowerCase());
651
+ yield* say(`[${brief.id} ${brief.owner}] ${report.status}: ${firstLine(report.summary)}`);
652
+ });
653
+ const blocked = (brief, attempt, summary, body) => Report.make({
654
+ brief: brief.id,
655
+ status: "BLOCKED",
656
+ attempt,
657
+ evidence: [],
658
+ summary,
659
+ questions: [],
660
+ body
661
+ });
662
+ const fromProposal = (brief, attempt, proposal) => Report.make({
663
+ brief: brief.id,
664
+ status: proposal.status,
665
+ attempt,
666
+ evidence: proposal.evidence,
667
+ summary: proposal.summary,
668
+ questions: proposal.questions,
669
+ body: proposal.body
670
+ });
671
+ /** Runs the commands a brief names; the log, and a reason it could not. */
672
+ const runCommands = (brief, cwd) => Effect.gen(function* () {
673
+ const lines = [];
674
+ for (const command of verifyCommands(brief)) {
675
+ const argv = shellWords(command);
676
+ if (deps.noPause && !deps.allowedCommand(argv)) {
677
+ return { log: lines.join("\n"), refused: command };
678
+ }
679
+ const result = yield* deps.processes.run(argv, cwd, {}).pipe(Effect.map((done) => ({
680
+ exitCode: done.exitCode,
681
+ stdout: done.stdout,
682
+ stderr: done.stderr
683
+ })), Effect.catch((error) => Effect.succeed({ exitCode: 127, stdout: [], stderr: [error.message] })));
684
+ lines.push(`$ ${command}`, `exit ${result.exitCode}`, ...result.stdout, ...result.stderr, "");
685
+ }
686
+ return { log: lines.join("\n"), refused: undefined };
687
+ });
688
+ /** One brief, start to report: the seat by grade, the commands, the worktree. */
689
+ const runBrief = (brief, attempt) => Effect.gen(function* () {
690
+ const persona = personaOf(brief.owner);
691
+ if (persona === undefined) {
692
+ return yield* ScriptUsage.make({ message: `no card for ${brief.owner}` });
693
+ }
694
+ const previous = reportOf(reports, brief.id);
695
+ yield* events.publish(StageStarted.make({ stage: `${brief.id}: ${brief.title}`, lane: brief.owner }));
696
+ const prompts = {
697
+ persona,
698
+ plan,
699
+ brief,
700
+ attempt,
701
+ reports,
702
+ previous,
703
+ docs: deps.context,
704
+ notes,
705
+ budget: deps.budget
706
+ };
707
+ let report;
708
+ if (persona.tools === "workspace") {
709
+ report = yield* Effect.scoped(Effect.gen(function* () {
710
+ const workspace = yield* deps.workspaceFor(brief);
711
+ workspaces.set(brief.id, workspace.dir);
712
+ const reply = yield* completeAndPublish(workspace.coder, events, engineerPrompt(prompts)).pipe(Effect.map((text) => text), Effect.catch((error) => say(`[${brief.id}] the coder failed: ${error.message}`).pipe(Effect.as(undefined))));
713
+ const diff = yield* workspace.diff.pipe(Effect.catch(() => Effect.succeed("")));
714
+ const evidence = [];
715
+ if (diff.trim().length > 0) {
716
+ yield* files.writeAtomic(paths.diff(brief.id), diff);
717
+ evidence.push(`work/${brief.id}.diff`);
718
+ }
719
+ const parsed = reply === undefined ? undefined : engineerReport(reply);
720
+ return parsed === undefined
721
+ ? blocked(brief, attempt, reply === undefined
722
+ ? "the coder failed before reporting"
723
+ : "no REPORT line: the turn cap or the model cut the work short", reply ?? "")
724
+ : Report.make({
725
+ brief: brief.id,
726
+ status: parsed.status,
727
+ attempt,
728
+ evidence,
729
+ summary: parsed.summary,
730
+ questions: [],
731
+ body: reply ?? ""
732
+ });
733
+ }));
734
+ }
735
+ else {
736
+ let commandOutput;
737
+ if (persona.tools === "commands") {
738
+ const inWorkspace = brief.dependsOn
739
+ .map((id) => workspaces.get(id))
740
+ .find((dir) => dir !== undefined);
741
+ const ran = yield* runCommands(brief, inWorkspace ?? deps.workDir);
742
+ if (ran.log.length > 0)
743
+ yield* files.writeAtomic(paths.commandLog(brief.id), ran.log);
744
+ if (ran.refused !== undefined) {
745
+ return blocked(brief, attempt, `command not declared, not run under --no-pause: ${ran.refused}`, `Declare it in package.json scripts or ${commandsPath(deps.workDir)}, or run without --no-pause.\n\n${ran.log}`);
746
+ }
747
+ commandOutput = ran.log;
748
+ }
749
+ const proposal = yield* structuredAndPublish(seatOf(persona), events, briefPrompt({ ...prompts, commandOutput }), ReportProposal, reportProposalJsonSchema, persona.name).pipe(Effect.map((value) => value), Effect.catch((error) => say(`[${brief.id}] the seat failed: ${error.message}`).pipe(Effect.as(undefined))));
750
+ report =
751
+ proposal === undefined
752
+ ? blocked(brief, attempt, "the seat failed before reporting", "")
753
+ : fromProposal(brief, attempt, commandOutput === undefined
754
+ ? proposal
755
+ : ReportProposal.make({
756
+ ...proposal,
757
+ evidence: [...proposal.evidence, `reports/${brief.id}-commands.log`]
758
+ }));
759
+ }
760
+ yield* events.publish(StageCompleted.make({ stage: `${brief.id}: ${brief.title}`, lane: brief.owner }));
761
+ return report;
762
+ });
763
+ /** Worktrees whose dependents all ended are removed, unless kept. */
764
+ const sweepWorkspaces = (final) => Effect.gen(function* () {
765
+ if (deps.keepWork)
766
+ return;
767
+ for (const [id, workspaceDir] of [...workspaces]) {
768
+ const dependents = plan.briefs.filter((brief) => brief.dependsOn.includes(id));
769
+ const done = dependents.every((brief) => {
770
+ const report = reportOf(reports, brief.id);
771
+ return report !== undefined && isFinal(report);
772
+ });
773
+ if (final || done) {
774
+ yield* deps
775
+ .removeWorkspace(workspaceDir)
776
+ .pipe(Effect.catch((error) => say(`could not remove ${workspaceDir}: ${error.message}`)));
777
+ workspaces.delete(id);
778
+ }
779
+ }
780
+ });
781
+ const proposePlan = (violations) => structuredAndPublish(deps.seats.forSeat?.("planner") ?? deps.seats.toolless, events, planPrompt({
782
+ chief: cast.chief,
783
+ goal: plan.goal,
784
+ cast: cast.all,
785
+ docs: deps.context,
786
+ notes,
787
+ caps,
788
+ budget: deps.budget,
789
+ violations
790
+ }), PlanProposal, planProposalJsonSchema, cast.chief.name);
791
+ const readDeliverables = () => Effect.forEach(plan.deliverables, (name) => Effect.map(files.read(paths.deliverable(name)), (content) => ({
792
+ name,
793
+ content: content ?? ""
794
+ })));
795
+ let guard = 0;
796
+ for (;;) {
797
+ guard += 1;
798
+ if (guard > caps.briefs * 6 + 64) {
799
+ return yield* FlowAborted.make({
800
+ message: `taskforce ${deps.runId}: no end after ${guard} steps; the files under ${dir} are intact`
801
+ });
802
+ }
803
+ const action = nextAction(plan, reports, caps);
804
+ switch (action._tag) {
805
+ case "Refused":
806
+ return yield* ScriptUsage.make({ message: `taskforce ${deps.runId}: ${action.reason}` });
807
+ case "Done":
808
+ yield* sweepWorkspaces(true);
809
+ return {
810
+ _tag: "NothingToDo",
811
+ message: `taskforce ${deps.runId} is done; answer a question under '## Answers' or write '## Feedback' in ${paths.plan} to reopen it`
812
+ };
813
+ case "ProposePlan": {
814
+ let violations = [];
815
+ for (let round = 1; round <= 2; round += 1) {
816
+ const proposal = yield* proposePlan(violations);
817
+ const deliverables = [
818
+ ...new Set([
819
+ "result.md",
820
+ ...proposal.deliverables.map((name) => name.trim()).filter((name) => name.length > 0)
821
+ ])
822
+ ];
823
+ const assembled = assembleBriefs(proposal.briefs, { from: 1, wave: 1, cast: cast.all });
824
+ const candidate = Plan.make({ ...plan, deliverables, briefs: assembled.briefs });
825
+ violations = planViolations(candidate, caps);
826
+ for (const note of assembled.notes)
827
+ yield* say(`plan: ${note}`);
828
+ if (violations.length === 0) {
829
+ plan = candidate;
830
+ break;
831
+ }
832
+ yield* say(`plan: proposal ${round} refused:\n${violations.map((v) => ` - ${v}`).join("\n")}`);
833
+ }
834
+ if (violations.length > 0) {
835
+ yield* trail("plan", "plan refused twice", violations.join("; "), "plan.md", "stopped");
836
+ return yield* PlanInvalid.make({ path: paths.plan, violations });
837
+ }
838
+ yield* save(plan);
839
+ yield* trail("plan", `${cast.chief.name} proposed ${plan.briefs.length} briefs`, `deliverables ${plan.deliverables.join(", ")}`, "plan.md", deps.noPause ? "accepted" : "awaiting the owner");
840
+ yield* say(`taskforce: ${cast.chief.name} proposed ${plan.briefs.length} brief(s) for ${plan.deliverables.join(", ")}:\n${plan.briefs.map((brief) => ` ${brief.id}. ${brief.title} — ${brief.owner}${brief.dependsOn.length === 0 ? "" : ` (after ${brief.dependsOn.join(", ")})`}`).join("\n")}`);
841
+ if (!deps.noPause) {
842
+ return yield* PlanPending.make({ path: paths.plan, briefs: plan.briefs.length });
843
+ }
844
+ continue;
845
+ }
846
+ case "Open": {
847
+ const violations = planViolations(plan, caps);
848
+ if (violations.length > 0) {
849
+ return yield* PlanInvalid.make({ path: paths.plan, violations });
850
+ }
851
+ plan = Plan.make({ ...plan, status: "working" });
852
+ yield* save(plan);
853
+ yield* trail("plan", "plan opened", `${plan.briefs.length} briefs, ${plan.cast.length} in the cast`, "plan.md", "working");
854
+ yield* say(`taskforce: working ${plan.briefs.length} brief(s), up to ${deps.parallel} at once, ${caps.waves} wave(s) at most`);
855
+ continue;
856
+ }
857
+ case "RecordOwner": {
858
+ const recorded = recordOwner(plan, action, caps, cast.writer.name);
859
+ plan = Plan.make({
860
+ ...recorded.plan,
861
+ briefs: [...recorded.plan.briefs, ...recorded.briefs]
862
+ });
863
+ yield* save(plan);
864
+ for (const note of recorded.notes)
865
+ yield* say(`owner: ${note}`);
866
+ for (const answer of action.answers) {
867
+ yield* trail("owner", `answer ${answer.number} folded`, answer.answer, "plan.md", recorded.briefs.length === 0 ? "no rework" : "rework");
868
+ }
869
+ if (action.feedback.length > 0)
870
+ yield* trail("owner", "feedback folded", action.feedback, "plan.md", recorded.plan.status);
871
+ for (const brief of recorded.briefs) {
872
+ yield* say(`owner: ${brief.id} ${brief.title} — ${brief.owner} (wave ${brief.wave})`);
873
+ }
874
+ continue;
875
+ }
876
+ case "Skip": {
877
+ const report = blocked(action.brief, 2, `not run: ${action.reason}`, "A dependency ended blocked twice; the run went on without this brief.");
878
+ yield* record(report, action.brief);
879
+ continue;
880
+ }
881
+ case "Dispatch": {
882
+ const wave = action.briefs[0]?.wave ?? currentWave(plan);
883
+ yield* events.publish(StageStarted.make({ stage: `wave ${wave}` }));
884
+ for (const brief of action.briefs) {
885
+ yield* trail(`wave ${wave}`, `dispatched ${brief.id} to ${brief.owner}${action.attempt > 1 ? " again" : ""}`, brief.dependsOn.length === 0
886
+ ? "no dependencies"
887
+ : `after ${brief.dependsOn.join(", ")}`, "plan.md", "running");
888
+ }
889
+ const results = yield* Effect.forEach(action.briefs, (brief) => Effect.map(runBrief(brief, action.attempt), (report) => ({ brief, report })), { concurrency: Math.max(1, deps.parallel) });
890
+ for (const { brief, report } of results)
891
+ yield* record(report, brief);
892
+ yield* sweepWorkspaces(false);
893
+ yield* events.publish(StageCompleted.make({ stage: `wave ${wave}` }));
894
+ continue;
895
+ }
896
+ case "Check": {
897
+ const from = plan.briefs.length + 1;
898
+ const proposal = yield* structuredAndPublish(deps.seats.forSeat?.("planner") ?? deps.seats.toolless, events, checkPrompt({
899
+ chief: cast.chief,
900
+ plan,
901
+ reports,
902
+ wave: action.wave,
903
+ mayReplan: action.mayReplan,
904
+ from,
905
+ caps,
906
+ cast: cast.all,
907
+ budget: deps.budget
908
+ }), CheckProposal, checkProposalJsonSchema, cast.chief.name);
909
+ const check = GoalCheck.make({
910
+ wave: action.wave,
911
+ reached: proposal.reached || !action.mayReplan || proposal.briefs.length === 0,
912
+ note: proposal.note
913
+ });
914
+ let added = [];
915
+ if (!proposal.reached && action.mayReplan && proposal.briefs.length > 0) {
916
+ const room = Math.max(0, caps.briefs - plan.briefs.length);
917
+ const assembled = assembleBriefs(proposal.briefs.slice(0, room), { from, wave: action.wave + 1, cast: cast.all }, plan.briefs.map((brief) => brief.id));
918
+ added = assembled.briefs.slice(0, room);
919
+ for (const note of assembled.notes)
920
+ yield* say(`check: ${note}`);
921
+ if (proposal.briefs.length > room)
922
+ yield* say(`check: ${proposal.briefs.length - room} proposed brief(s) dropped at the cap of ${caps.briefs}`);
923
+ }
924
+ const candidate = Plan.make({
925
+ ...plan,
926
+ checks: [...plan.checks, check],
927
+ briefs: [...plan.briefs, ...added],
928
+ status: added.length === 0 ? "drafting" : "working"
929
+ });
930
+ const violations = added.length === 0 ? [] : planViolations(candidate, caps);
931
+ if (violations.length > 0) {
932
+ yield* say(`check: the second wave was refused and dropped:\n${violations.map((v) => ` - ${v}`).join("\n")}`);
933
+ plan = Plan.make({
934
+ ...plan,
935
+ checks: [...plan.checks, GoalCheck.make({ ...check, reached: true })],
936
+ status: "drafting"
937
+ });
938
+ }
939
+ else {
940
+ plan = candidate;
941
+ }
942
+ yield* save(plan);
943
+ yield* trail("check", `wave ${action.wave}: ${check.reached ? "reached" : "not reached"}`, proposal.note, "plan.md", added.length === 0 ? "drafting" : `wave ${action.wave + 1}: ${added.length} briefs`);
944
+ yield* say(`${cast.chief.name}: wave ${action.wave} ${check.reached ? "reached the goal" : "did not reach the goal"} — ${firstLine(proposal.note)}${added.length === 0 ? "" : `; ${added.length} more brief(s)`}`);
945
+ continue;
946
+ }
947
+ case "Draft": {
948
+ if (plan.status !== "drafting") {
949
+ plan = Plan.make({ ...plan, status: "drafting" });
950
+ yield* save(plan);
951
+ }
952
+ const previous = action.redraft ? yield* readDeliverables() : [];
953
+ const fixes = plan.briefs.filter((brief) => brief.wave === currentWave(plan) && action.redraft);
954
+ const proposal = yield* structuredAndPublish(seatOf(cast.writer), events, draftPrompt({
955
+ writer: cast.writer,
956
+ plan,
957
+ reports,
958
+ docs: deps.context,
959
+ budget: deps.budget,
960
+ previous,
961
+ fixes
962
+ }), DraftProposal, draftProposalJsonSchema, cast.writer.name);
963
+ const written = [];
964
+ for (const document of proposal.documents) {
965
+ const name = document.name.trim();
966
+ if (!plan.deliverables.includes(name))
967
+ continue;
968
+ yield* files.writeAtomic(paths.deliverable(name), `${document.content.trim()}\n`);
969
+ written.push(name);
970
+ }
971
+ const missing = plan.deliverables.filter((name) => !written.includes(name));
972
+ if (missing.length > 0)
973
+ yield* say(`${cast.writer.name}: did not write ${missing.join(", ")}`);
974
+ yield* files.writeAtomic(paths.openQuestions, renderOpenQuestions(plan, reports));
975
+ plan = Plan.make({
976
+ ...plan,
977
+ drafts: plan.drafts + 1,
978
+ status: plan.drafts === 0 ? "reviewing" : "distilling"
979
+ });
980
+ yield* save(plan);
981
+ yield* trail("draft", `${cast.writer.name} wrote draft ${plan.drafts}`, written.join(", "), written.map((name) => name).join(", "), plan.status);
982
+ yield* say(`${cast.writer.name}: draft ${plan.drafts} — ${written.map((name) => paths.deliverable(name)).join(", ")}`);
983
+ continue;
984
+ }
985
+ case "Review": {
986
+ const deliverables = yield* readDeliverables();
987
+ const diffs = [];
988
+ for (const brief of plan.briefs) {
989
+ if (personaOf(brief.owner)?.tools !== "workspace")
990
+ continue;
991
+ const diff = yield* files.read(paths.diff(brief.id));
992
+ if (diff !== undefined && diff.trim().length > 0)
993
+ diffs.push({ brief, diff });
994
+ }
995
+ const reviewer = cast.all.find((persona) => persona.name === "Reviewer");
996
+ const reviewSeat = reviewer === undefined ? deps.seats.readOnly : seatOf(reviewer);
997
+ const findings = [];
998
+ for (const lens of deps.lenses) {
999
+ const found = yield* structuredAndPublish(reviewSeat, events, lensPrompt({ lens, plan, deliverables, diffs, budget: deps.budget }), LensFindings, lensFindingsJsonSchema, `lens ${lens.name}`);
1000
+ for (const finding of found.findings) {
1001
+ const id = findings.length + 1;
1002
+ const result = yield* judgeOrEscalate({
1003
+ judgment: deps.judgment,
1004
+ reasoning: deps.seats.toolless,
1005
+ events,
1006
+ request: {
1007
+ state: {
1008
+ goal: plan.goal,
1009
+ finding: `${finding.title} (${finding.where}): ${finding.detail}`
1010
+ },
1011
+ questions: {
1012
+ blocks: truth("This finding, left unaddressed, stops the deliverables from reaching the goal.")
1013
+ }
1014
+ }
1015
+ });
1016
+ const answer = yield* truthOf(result, "blocks").pipe(Effect.option);
1017
+ const blocks = answer._tag === "Some" && decide(answer.value) !== "hold" && answer.value.truth >= 0.5;
1018
+ const probability = answer._tag === "Some" ? answer.value.truth.toFixed(2) : "n/a";
1019
+ findings.push(Finding.make({
1020
+ id,
1021
+ lens: lens.name,
1022
+ title: finding.title,
1023
+ where: finding.where,
1024
+ brief: plan.briefs.some((brief) => brief.id === finding.brief.trim())
1025
+ ? finding.brief.trim()
1026
+ : "",
1027
+ detail: finding.detail,
1028
+ bucket: blocks ? "act-on" : "consider",
1029
+ reason: blocks
1030
+ ? `judged blocking (p=${probability})`
1031
+ : `judged not blocking (p=${probability})`
1032
+ }));
1033
+ yield* trail("review", `finding ${id} ${blocks ? "act-on" : "consider"}: ${finding.title}`, `${lens.name}; p=${probability}`, finding.where, blocks ? "fix" : "lead");
1034
+ }
1035
+ }
1036
+ const pending = findings.filter((finding) => finding.bucket === "consider");
1037
+ if (reviewer !== undefined && pending.length > 0) {
1038
+ const lead = yield* structuredAndPublish(seatOf(reviewer), events, leadPrompt({ reviewer, plan, findings }), LeadProposal, leadProposalJsonSchema, `${reviewer.name} lead`);
1039
+ for (const verdict of lead.verdicts) {
1040
+ const index = findings.findIndex((finding) => finding.id === verdict.id && finding.bucket === "consider");
1041
+ if (index < 0)
1042
+ continue;
1043
+ findings[index] = Finding.make({
1044
+ ...findings[index],
1045
+ bucket: verdict.bucket,
1046
+ reason: verdict.reason
1047
+ });
1048
+ }
1049
+ }
1050
+ yield* files.writeAtomic(paths.review, renderReview(findings));
1051
+ const fix = fixBriefs(plan, findings, caps, cast.writer.name);
1052
+ for (const dropped of fix.dropped)
1053
+ yield* say(`review: finding ${dropped.id} dropped at the brief cap: ${dropped.title}`);
1054
+ plan = Plan.make({
1055
+ ...plan,
1056
+ briefs: [...plan.briefs, ...fix.briefs],
1057
+ status: fix.briefs.length === 0 ? "distilling" : "fixing"
1058
+ });
1059
+ yield* save(plan);
1060
+ yield* trail("review", `${findings.length} finding(s): ${findings.filter((f) => f.bucket === "act-on").length} act-on`, deps.lenses.map((lens) => lens.name).join(", "), "review.md", fix.briefs.length === 0
1061
+ ? "no fix wave"
1062
+ : `fix wave: ${fix.briefs.map((brief) => brief.id).join(", ")}`);
1063
+ yield* say(`review: ${findings.length} finding(s) — ${paths.review}${fix.briefs.length === 0 ? "" : `; fix wave of ${fix.briefs.length}`}`);
1064
+ continue;
1065
+ }
1066
+ case "Distill": {
1067
+ yield* files.writeAtomic(paths.openQuestions, renderOpenQuestions(plan, reports));
1068
+ const memory = cast.all.find((persona) => persona.name === memoryName);
1069
+ if (deps.memory && memory !== undefined) {
1070
+ const trailText = (yield* files.read(paths.trail)) ?? "";
1071
+ const note = yield* structuredAndPublish(seatOf(memory), events, distillPrompt({ memory, plan, reports, trail: trailText, budget: deps.budget }), RunNote, runNoteJsonSchema, memory.name);
1072
+ const path = join(deps.workDir, ".llm4ts", "memory", "runs", `${plan.id}.md`);
1073
+ yield* files.writeAtomic(path, renderRunNote(plan.id, plan.goal, note));
1074
+ yield* trail("distill", `${memory.name} wrote the run note`, `${note.decisions.length} decisions, ${note.failed.length} failures`, `.llm4ts/memory/runs/${plan.id}.md`, "done");
1075
+ yield* say(`${memory.name}: ${path}`);
1076
+ }
1077
+ plan = Plan.make({ ...plan, status: "done" });
1078
+ yield* save(plan);
1079
+ yield* sweepWorkspaces(true);
1080
+ const unanswered = plan.answers.filter((point) => (point.answer ?? "").trim().length === 0);
1081
+ const blockedTwice = plan.briefs.filter((brief) => {
1082
+ const report = reportOf(reports, brief.id);
1083
+ return report?.status === "BLOCKED" && isFinal(report);
1084
+ });
1085
+ const summary = [
1086
+ `taskforce ${deps.runId} done after ${plan.briefs.length} brief(s), ${currentWave(plan)} wave(s) and ${plan.drafts} draft(s)`,
1087
+ ...plan.deliverables.map((name) => `${name}: ${paths.deliverable(name)}`),
1088
+ `review: ${paths.review}`,
1089
+ `trail: ${paths.trail}`,
1090
+ `open questions: ${paths.openQuestions}${blockedTwice.length === 0 ? "" : ` (${blockedTwice.length} brief(s) blocked)`}`,
1091
+ ...(unanswered.length === 0
1092
+ ? []
1093
+ : [
1094
+ `${unanswered.length} question(s) for you under '## Answers' in ${paths.plan}; answer and rerun to fold them in`
1095
+ ])
1096
+ ];
1097
+ for (const line of summary)
1098
+ yield* say(line);
1099
+ for (const name of plan.cast) {
1100
+ yield* events.publish(StageCompleted.make({ stage: `specialist ${name}`, lane: name }));
1101
+ }
1102
+ return { _tag: "Finished", summary };
1103
+ }
1104
+ }
1105
+ }
1106
+ });
1107
+ /** The two lenses a repository without `.llm4ts/lenses/` reviews with. */
1108
+ export const bundledLenses = [
1109
+ {
1110
+ name: "evidence",
1111
+ systemPrompt: "Check every claim in the deliverables against the reports and the diffs. A claim no report supports, a number no log shows, a source that does not exist, an assumption presented as a fact: each is a finding."
1112
+ },
1113
+ {
1114
+ name: "risk",
1115
+ systemPrompt: "Ask what breaks if the deliverables are wrong and acted on. A recommendation with an unexamined failure mode, a next step that is irreversible, a change in a diff that touches more than its brief, a security or data concern nobody raised: each is a finding."
1116
+ }
1117
+ ];