@ngockhoale/ckit 0.1.1 → 0.2.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.
@@ -1,16 +1,17 @@
1
- // Agent Company engine: Director -> BA -> Implement -> QC (loop) -> BA review -> delivery. Journals every event; the TUI only subscribes.
1
+ // Agent Company engine: Director -> the teams in config order (default BA -> Implement -> QC; send-backs and ask-backs between neighbours) -> delivery. Journals every event; the TUI only subscribes.
2
2
  import { basename, join } from 'node:path';
3
3
  import { attachmentLines, attachmentPromptBlock, storeAttachments } from './attachments.js';
4
4
  import { readSecret } from './secrets.js';
5
5
  import { createTeamJournal } from './journal.js';
6
6
  import { readTeamJournal } from './journal.js';
7
7
  import { advisorKeyOf, createSimulatedRunner, dispatchRunner, simHeader } from './runners.js';
8
+ import { DEFAULT_MISSIONS, allAgentsOf, effectiveOrder } from './types.js';
8
9
  /** Every secret value the agents may touch (stored apiKeyRefs + CKit advisor key): always redacted from journal/artifacts. */
9
10
  function knownSecretValues(config, projectRoot) {
10
11
  const out = [], key = advisorKeyOf(projectRoot);
11
12
  if (key)
12
13
  out.push(key);
13
- for (const a of [config.director, ...config.teams.ba, ...config.teams.implement, ...config.teams.qc]) {
14
+ for (const a of allAgentsOf(config)) {
14
15
  const v = readSecret(a.apiKeyRef);
15
16
  if (v)
16
17
  out.push(v);
@@ -38,9 +39,60 @@ export function parseVerdict(text) {
38
39
  const last = all[all.length - 1]?.[1];
39
40
  return last && last.toUpperCase() === 'PASS' ? 'PASS' : 'FAIL';
40
41
  }
41
- function makeHandle(runId, runDir, history, listeners, done, sendToDirector, stop) {
42
+ /** The Director's first-turn decision line (lenient: case, bullets, bold, dashes). No decision line = PROCEED. Never throws. */
43
+ export function parseDirectorDecision(text) {
44
+ const re = /^[ \t>*_#-]*DECISION[ \t]*[:\-–]?[ \t]*(?:\*\*|__)?[ \t]*(PROCEED|NEED[ _-]*INFO|CANNOT[ _-]*DO|CAN'?T[ _-]*DO)\b[^\n]*$/gim;
45
+ const all = [...text.matchAll(re)], m = all[all.length - 1];
46
+ const kind = !m ? 'proceed' : /^NEED/i.test(m[1]) ? 'need' : /^CAN/i.test(m[1]) ? 'cannot' : 'proceed';
47
+ const body = m ? text.replace(m[0], '').trim() : text.trim();
48
+ const after = (src, label) => { const x = label.exec(src); return x ? [src.slice(0, x.index).trim(), src.slice(x.index + x[0].length).trim()] : [src.trim(), '']; };
49
+ if (kind === 'need') {
50
+ const [q, a] = after(body, /^[ \t>*_#-]*ASSUMPTIONS[ \t]+IF[ \t]+NO[ \t]+ANSWER[ \t]*\**[ \t]*:\**/im);
51
+ return { kind, body, questions: clip(q, 3000), assumptions: clip(a, 1500), reason: '', alternatives: '' };
52
+ }
53
+ if (kind === 'cannot') {
54
+ const [head, alt] = after(body, /^[ \t>*_#-]*WHAT[ \t]+WOULD[ \t]+WORK[ \t]*\**[ \t]*:\**/im);
55
+ return { kind, body, questions: '', assumptions: '', reason: clip(head.replace(/^[ \t>*_#-]*REASON[ \t]*\**[ \t]*:\**[ \t]*/im, '').trim(), 2000), alternatives: clip(alt, 2000) };
56
+ }
57
+ const a = /^[ \t>*_#-]*ASSUMPTIONS[ \t]*\**[ \t]*:\**[ \t]*([\s\S]*?)(?=^[ \t]*#{2,4}[ \t]*TEAM\b|$(?![\s\S]))/im.exec(body);
58
+ return { kind, body, questions: '', assumptions: a ? clip(a[1].trim(), 1500) : '', reason: '', alternatives: '' };
59
+ }
60
+ export const HANDOFF_SECTIONS = ['DONE', 'DECISIONS', 'OPEN', 'FOR YOU'];
61
+ /** Reads the four handoff sections out of a team lead's message. null when any is missing (callers fall back to the raw message). Never throws. */
62
+ export function parseHandoff(text) {
63
+ const head = /^[ \t>*_#-]*HANDOFF\b[^\n]*$/im.exec(text), lines = (head ? text.slice(head.index + head[0].length) : text).split('\n');
64
+ const rx = /^[ \t>]*(#{1,6}[ \t]*)?(\*\*|__)?(DONE|DECISIONS|OPEN|FOR YOU)[ \t]*(\*\*|__)?[ \t]*(:?)[ \t]*(?:\*\*|__)?[ \t]*(.*)$/i;
65
+ const out = {};
66
+ let cur = null;
67
+ for (const line of lines) {
68
+ const m = rx.exec(line);
69
+ if (m && (m[1] || m[2] || m[5] || !(m[6] ?? '').trim())) {
70
+ cur = m[3].toUpperCase();
71
+ if (out[cur]) {
72
+ cur = null;
73
+ continue;
74
+ }
75
+ out[cur] = (m[6] ?? '').trim() ? [m[6].trim()] : [];
76
+ }
77
+ else if (cur)
78
+ out[cur].push(line);
79
+ }
80
+ if (!HANDOFF_SECTIONS.every(s => out[s]))
81
+ return null;
82
+ const r = {};
83
+ for (const s of HANDOFF_SECTIONS)
84
+ r[s] = out[s].join('\n').trim() || '(nothing)';
85
+ return r;
86
+ }
87
+ const AGREED_RE = /^[ \t>*_#-]*AGREED\b[^\n]*$/im;
88
+ /** Last `REVIEW: PASS|FAIL` wins; null when no verdict line exists. */
89
+ export function parseReview(text) {
90
+ const all = [...text.matchAll(/REVIEW\s*[:\-]?\s*\**\s*(PASS|FAIL)/gi)], last = all[all.length - 1]?.[1];
91
+ return last ? last.toUpperCase() : null;
92
+ }
93
+ function makeHandle(runId, runDir, history, listeners, done, sendToDirector, stop, proceedWithAssumptions) {
42
94
  return {
43
- runId, runDir, done, sendToDirector, stop,
95
+ runId, runDir, done, sendToDirector, stop, ...(proceedWithAssumptions ? { proceedWithAssumptions } : {}),
44
96
  subscribe(listener) {
45
97
  for (const e of [...history]) {
46
98
  try {
@@ -61,7 +113,13 @@ export function startTeamRun(opts) {
61
113
  const history = [], listeners = new Set();
62
114
  const abort = new AbortController();
63
115
  const inbox = [], notes = [], convo = [];
64
- let finished = false, handoff = '', qcReport = '', qcPassed = false, deliverable = '', resolveDone, intakeBrief = '';
116
+ const lanes = config.lanes ?? [], ownerLane = lanes.find(l => l.id === opts.lane) ?? null;
117
+ let order = ownerLane ? [...ownerLane.order] : lanes.length ? [...lanes[0].order] : effectiveOrder(config); // with lanes: the chosen lane's teams (set at intake)
118
+ const outs = new Map(); // flow order; each team's latest output
119
+ const passes = new Map(), sentBack = new Map(), asks = new Map(), backs = new Map();
120
+ const limit = config.limits.qcLoops; // max send-backs per team boundary, and as many ask-backs
121
+ const briefs = new Map(); // team id -> the Director's section for that team
122
+ let assumptions = '', laneNote = '', retReason = null, finished = false, handoff = '', qcReport = '', qcPassed = false, deliverable = '', resolveDone, intakeBrief = '', intakeIntro = '';
65
123
  const done = new Promise(r => { resolveDone = r; });
66
124
  // Owner attachments: stored once in the run folder, then named in every agent prompt (Director, BA, Implement, QC) and in the BA handoff.
67
125
  const atts = [], excerpts = new Map();
@@ -88,12 +146,12 @@ export function startTeamRun(opts) {
88
146
  catch { /* ignore */ }
89
147
  }
90
148
  };
91
- const nameOf = (id) => [config.director, ...config.teams.ba, ...config.teams.implement, ...config.teams.qc].find(a => a.id === id)?.name ?? id;
149
+ const nameOf = (id) => allAgentsOf(config).find(a => a.id === id)?.name ?? id;
92
150
  function transcript(e) {
93
151
  if (e.type === 'run.started')
94
152
  journal.appendArtifact('transcript.md', `# Team run ${e.runId}\n\nGoal: ${e.goal}\n\n${e.attachments?.length ? `Attachments:\n${attachmentLines(e.attachments)}\n\n` : ''}`);
95
153
  else if (e.type === 'stage.changed')
96
- journal.appendArtifact('transcript.md', `\n## Stage: ${e.stage} (loop ${e.loop})\n\n`);
154
+ journal.appendArtifact('transcript.md', `\n## Stage: ${e.team ? `extra team ${config.extraTeams?.find(t => t.id === e.team)?.name ?? e.team}` : e.stage} (loop ${e.loop})\n\n`);
97
155
  else if (e.type === 'agent.message')
98
156
  journal.appendArtifact('transcript.md', `### ${nameOf(e.agentId)} -> ${nameOf(e.to)}\n\n${e.text}\n\n`);
99
157
  else if (e.type === 'agent.failed')
@@ -102,6 +160,8 @@ export function startTeamRun(opts) {
102
160
  journal.appendArtifact('transcript.md', `### Owner\n\n${e.text}\n\n${e.attachments?.length ? `Attachments:\n${attachmentLines(e.attachments)}\n\n` : ''}`);
103
161
  else if (e.type === 'director.decision')
104
162
  journal.appendArtifact('transcript.md', `### Director decision: ${e.decision}\n\n${e.note}\n\n`);
163
+ else if (e.type === 'flow.back')
164
+ journal.appendArtifact('transcript.md', `### ${e.kind === 'ask' ? '? ASK-BACK' : '↩ RETURN'}: ${teamName(e.from)} -> ${teamName(e.to)}\n\n${e.reason}\n\n`);
105
165
  else if (e.type === 'qc.verdict')
106
166
  journal.appendArtifact('transcript.md', `### QC verdict: ${e.verdict} (loop ${e.loop})\n\n${e.summary}\n\n`);
107
167
  else if (e.type === 'run.completed')
@@ -120,15 +180,54 @@ export function startTeamRun(opts) {
120
180
  // ---- prompts ----
121
181
  const header = (agent, stage, loop, turn = 1, turns = 1, final = false) => simulated || agent.cli === 'simulated' ? `${simHeader({ stage, loop, turn, turns, final })}\n` : '';
122
182
  const recent = (n = 8) => convo.slice(-n).map(c => `${c.who}: ${clip(c.text, 1500)}`).join('\n\n') || '(nothing yet)';
123
- const accessLine = (agent) => agent.access === 'write'
183
+ const accessLine = (agent, readOnly = false) => agent.access === 'write' && !readOnly
124
184
  ? 'ACCESS: read + write. Read any file in the project folder to understand the request and the existing code, and change files there when your task needs it.'
125
185
  : 'ACCESS: read only. Read any file in the project folder to understand the request and the existing code. Do not create, change or delete files.';
126
- const role = (agent, what) => `You are ${agent.name}, member of the ${agent.team.toUpperCase()} team in a software "agent company" (Director -> BA -> Implement -> QC). ${agent.persona ?? ''}\n${what}\n${accessLine(agent)}\nAnswer concisely.`;
127
- const common = () => `GOAL: ${oneLine(goal, 2000)}\n${notes.length ? `\nOWNER NOTES (follow them):\n${notes.map(n => `- ${n}`).join('\n')}\n` : ''}${intakeBrief ? `\nDIRECTOR BRIEF:\n${intakeBrief}\n` : ''}${attachmentPromptBlock(atts, excerpts)}`;
186
+ const extraOf = (id) => config.extraTeams?.find(t => t.id === id);
187
+ const teamName = (id) => id === 'director' ? 'Director' : extraOf(id)?.name ?? (id === 'ba' ? 'BA' : id === 'implement' ? 'Implement' : id === 'qc' ? 'QC' : id);
188
+ const prevId = (k) => k <= 0 ? 'director' : order[k - 1];
189
+ const agentsOf = (id) => id === 'ba' || id === 'implement' || id === 'qc' ? config.teams[id] : extraOf(id)?.agents ?? [];
190
+ const teamLabel = (agent) => teamName(agent.team).toUpperCase();
191
+ const missionOf = (teamId) => extraOf(teamId)?.mission ?? config.missions?.[teamId] ?? DEFAULT_MISSIONS[teamId] ?? '';
192
+ /** The Director's own section for a team; with none parsed, the mission plus the whole Director message. Never empty after intake. */
193
+ const briefOf = (teamId) => briefs.get(teamId) ?? (intakeBrief ? `(no section for your team in the Director's message; read all of it)\n${clip(intakeBrief, 2500)}` : '');
194
+ const teamBlock = (agent) => agent.team === 'director' ? '' : `TEAM MISSION: ${missionOf(agent.team)}\n${briefOf(agent.team) ? `DIRECTOR'S BRIEF FOR YOUR TEAM:\n${briefOf(agent.team)}\n` : ''}`;
195
+ /** Position line + the backward rules, stated in every team prompt. */
196
+ const flowBlock = (agent) => {
197
+ const k = order.indexOf(agent.team);
198
+ if (k < 0)
199
+ return '';
200
+ const before = teamName(prevId(k)), after = order[k + 1] ? teamName(order[k + 1]) : 'the Director (final report)';
201
+ return `FLOW: You are team ${k + 1} of ${order.length}; before you: ${before}; after you: ${after}. Work goes Director -> ${order.map(teamName).join(' -> ')}.\nIf something from ${before} is unclear, end your message with a line "ASK PREVIOUS: <your question>" and ${before} will answer. If the work you received is not good enough to continue, end your message with a line "RETURN TO PREVIOUS: <reason>" and ${before} will redo it. Use these only when really needed.\n`;
202
+ };
203
+ const sysBlock = () => config.systemPrompt ? `PROJECT INSTRUCTIONS FROM THE OWNER (they apply to everything you do here, but they do not override the flow markers, the handoff format or your read/write access):\n${config.systemPrompt}\n\n` : '';
204
+ const role = (agent, what, readOnly = false) => `${sysBlock()}You are ${agent.name}, member of the ${teamLabel(agent)} team in a software "agent company" (Director -> ${order.map(teamName).join(' -> ') || 'teams'}). ${agent.persona ?? ''}\n${what}\n${teamBlock(agent)}${flowBlock(agent)}${accessLine(agent, readOnly)}\nAnswer concisely.`;
205
+ /** Pulls the flow markers out of an agent message (first of each, anywhere in the text, optional bullet/bold). Never throws. */
206
+ const markers = (text) => {
207
+ let ask = null, ret = null;
208
+ const keep = text.split('\n').filter(line => {
209
+ const m = /^[\s>*_\-#]*(ASK PREVIOUS|RETURN TO PREVIOUS)\**\s*:\**\s*(.*)$/i.exec(line);
210
+ if (!m)
211
+ return true;
212
+ const v = (m[2] ?? '').replace(/\*+$/, '').trim();
213
+ if (m[1].toUpperCase().startsWith('ASK')) {
214
+ if (ask === null)
215
+ ask = v;
216
+ }
217
+ else if (ret === null)
218
+ ret = v;
219
+ return false;
220
+ });
221
+ return { ask, ret, clean: keep.join('\n').trim() || text };
222
+ };
223
+ const assumptionsBlock = () => assumptions ? `\nASSUMPTIONS MADE (the owner did not confirm them; the Director decided to proceed with these):\n${assumptions}\n` : '';
224
+ const common = () => `GOAL: ${oneLine(goal, 2000)}\n${assumptionsBlock()}${notes.length ? `\nOWNER NOTES (follow them):\n${notes.map(n => `- ${n}`).join('\n')}\n` : ''}${intakeIntro ? `\nDIRECTOR BRIEF:\n${intakeIntro}\n` : ''}${attachmentPromptBlock(atts, excerpts)}`;
128
225
  // ---- one agent turn ----
129
226
  /** Heuristic step label for real runners' activity lines (null = not a step boundary). */
130
227
  const stepOf = (text) => /^\$ /.test(text) ? 'Running commands' : /^edited |^tool: (Edit|Write|MultiEdit|NotebookEdit)/.test(text) ? 'Editing files' : /^tool: (Read|Grep|Glob|LS)/.test(text) ? 'Reading code' : /^thinking/.test(text) ? 'Thinking' : /^tool: /.test(text) ? 'Using tools' : null;
131
228
  const simAgent = (a) => simulated || a.cli === 'simulated';
229
+ /** Failure text for an agent with extra CLI arguments: name them, so a typo is easy to find. */
230
+ const withArgsNote = (agent, reason) => agent.cliArgs && reason !== 'cancelled' && agent.cli !== 'api' && agent.cli !== 'auto' && agent.cli !== 'simulated' ? `${reason}\nExtra CLI arguments are set for this agent: ${agent.cliArgs}. If the CLI rejected an option, fix or clear them in Config (Extra CLI arguments).` : reason;
132
231
  /** Runs one agent turn through the runner, wiring activity/step/subagent events. Never throws. */
133
232
  async function callRunner(agent, prompt, first, last) {
134
233
  let n = 0, lastLabel = '';
@@ -154,23 +253,23 @@ export function startTeamRun(opts) {
154
253
  });
155
254
  if (res.ok && !own)
156
255
  step(last);
157
- return res;
256
+ return res.ok ? res : { ok: false, reason: withArgsNote(agent, res.reason) };
158
257
  }
159
258
  catch (e) {
160
- return { ok: false, reason: e instanceof Error ? e.message : 'runner threw' };
259
+ return { ok: false, reason: withArgsNote(agent, e instanceof Error ? e.message : 'runner threw') };
161
260
  }
162
261
  }
163
- async function turn(agent, task, to, prompt) {
262
+ async function turn(agent, task, to, prompt, round) {
164
263
  halted();
165
264
  emit({ type: 'agent.started', agentId: agent.id, task });
166
- const labels = agent.team === 'ba' ? ['Reading the goal', `Replying to ${nameOf(to)}`] : agent.team === 'implement' ? ['Planning', 'Reporting'] : ['Reviewing diff', 'Writing verdict'];
265
+ const labels = agent.team === 'ba' ? ['Reading the goal', `Replying to ${nameOf(to)}`] : agent.team === 'implement' ? ['Planning', 'Reporting'] : agent.team === 'qc' ? ['Reviewing diff', 'Writing verdict'] : ['Reading the context', 'Reporting'];
167
266
  const res = await callRunner(agent, prompt, labels[0], labels[1]);
168
267
  halted();
169
268
  if (!res.ok) {
170
269
  emit({ type: 'agent.failed', agentId: agent.id, reason: res.reason });
171
270
  return null;
172
271
  }
173
- emit({ type: 'agent.message', agentId: agent.id, to, text: res.text, tokens: res.tokens });
272
+ emit({ type: 'agent.message', agentId: agent.id, to, text: res.text, tokens: res.tokens, ...(round ? { round } : {}) });
174
273
  const safe = journal.redact(res.text);
175
274
  convo.push({ who: agent.name, text: safe });
176
275
  return safe;
@@ -196,19 +295,117 @@ export function startTeamRun(opts) {
196
295
  emit({ type: 'agent.message', agentId: config.director.id, to, text, tokens });
197
296
  return journal.redact(text);
198
297
  }
199
- async function intake() {
200
- emit({ type: 'stage.changed', stage: 'director-intake', loop: 1 });
201
- const rule = () => `Brief: deliver "${oneLine(goal, 300)}".${atts.length ? ` The owner attached ${atts.length} file(s): ${atts.map(a => a.name).join(', ')}. Every team reads them as part of the request.` : ''} Pipeline: BA agrees one handoff -> Implement builds it -> QC verifies (up to ${config.limits.qcLoops} return loops) -> BA checks against the handoff -> final report to the owner.`;
202
- let brief = rule();
298
+ /** Teams that exist, in flow order. Built from the actual config; empty built-in teams are absent. */
299
+ const roster = (ids = order) => ids.map((id, k) => ({ id, name: teamName(id), mission: missionOf(id), when: `as step ${k + 1} of ${ids.length}, after ${k === 0 ? 'Director' : teamName(ids[k - 1])}`, agents: agentsOf(id) }));
300
+ const rosterText = (ids = order) => roster(ids).map(t => `- team id "${t.id}" (${t.name}), runs ${t.when}\n mission: ${t.mission}\n agents: ${t.agents.map(a => `${a.name} [${a.cli}${a.model ? `/${a.model}` : ''}, ${a.access}]`).join('; ')}`).join('\n') || '(no teams: you answer the goal yourself)';
301
+ const laneRosterText = () => lanes.map(l => `LANE id "${l.id}" (${l.name}) - use it for: ${l.when}\n${rosterText(l.order).split('\n').map(x => ` ${x}`).join('\n')}`).join('\n\n');
302
+ /** Splits a Director message into per-team sections (`### TEAM <id>`). Unknown ids and an unparsable message simply yield fewer sections; never throws. */
303
+ const parseBriefs = (text) => {
304
+ const out = new Map(), ids = new Set(roster().map(t => t.id));
305
+ const parts = text.split(/^[ \t]*#{2,4}[ \t]*TEAM[ \t]+["']?([A-Za-z0-9-]+)["']?[^\n]*$/gim);
306
+ for (let i = 1; i + 1 < parts.length; i += 2) {
307
+ const id = parts[i].toLowerCase(), body = parts[i + 1].trim();
308
+ if (ids.has(id) && body && !out.has(id))
309
+ out.set(id, clip(body, 2500));
310
+ }
311
+ return out;
312
+ };
313
+ // ---- intake triage: the Director decides PROCEED / NEED INFO / CANNOT DO before any team starts ----
314
+ const accessFacts = () => {
315
+ const r = roster(), w = r.filter(t => t.agents.some(a => a.access === 'write')).map(t => t.name), ro = r.filter(t => !t.agents.some(a => a.access === 'write')).map(t => t.name);
316
+ return `ACCESS FACTS (from the configuration): teams with a write agent, which can change files: ${w.join(', ') || 'none'}; read-only teams: ${ro.join(', ') || 'none'}.`;
317
+ };
318
+ const ruleBrief = () => `Brief: deliver "${oneLine(goal, 300)}".${atts.length ? ` The owner attached ${atts.length} file(s): ${atts.map(a => a.name).join(', ')}. Every team reads them as part of the request.` : ''} Pipeline: ${roster().map(t => t.name).join(' -> ') || 'Director only'} -> final report to the owner.${roster().map(t => `\n\n### TEAM ${t.id}\nDo: ${t.mission} (for "${oneLine(goal, 200)}")\nDeliverable: your report on your part of the goal.\nOut of scope: anything another team owns.`).join('')}`;
319
+ const qaRounds = [];
320
+ let needRounds = 0, forced = false, waiting = null;
321
+ const waitForOwner = (assume) => new Promise(res => { waiting = { assumptions: assume, wake: r => { waiting = null; res(r); } }; });
322
+ /** One Director triage turn; the text always ends up parsed by parseDirectorDecision. Simulated / rule-based directors answer from the goal flags. */
323
+ async function intakeTurn() {
203
324
  if (modelDirector()) {
204
- const t = await directorAsk('intake brief', `${role(config.director, 'You are the Director. Write a short intake brief (scope, assumptions, what BA should clarify) for the owner request.')}\n${common()}`);
325
+ const answered = qaRounds.length ? `\nYOUR EARLIER QUESTIONS AND THE OWNER'S ANSWERS:\n${qaRounds.map((q, i) => `Round ${i + 1} questions:\n${q.questions}\nOwner's answer:\n${q.answer}`).join('\n\n')}\n` : '';
326
+ const limitNote = forced ? '\nThe owner chose to proceed with your stated assumptions: answer "DECISION: PROCEED" now.' : needRounds >= 3 ? '\nYou already asked 3 times: you must not use NEED INFO again. Choose PROCEED with stated assumptions, or CANNOT DO.' : '';
327
+ const t = await directorAsk('intake brief', `${role(config.director, `You are the Director. First triage the owner request, then (only on PROCEED) split it between your teams.\nYour reply must contain exactly one decision line on its own line: "DECISION: PROCEED", "DECISION: NEED INFO" or "DECISION: CANNOT DO".\n- PROCEED: write a short overall summary (scope), an "ASSUMPTIONS:" list when you assumed anything, then one section per listed team, each starting with a line exactly "### TEAM <team id>" followed by: what this team must do for this goal, the expected deliverable, and what is out of scope for it. Assign every part of the goal to exactly one listed team and assign nothing to a team that is not listed.\n- NEED INFO: no team starts. Write a numbered list of at most 5 specific questions, each with why you need it; when sensible add a line "ASSUMPTIONS IF NO ANSWER:" followed by what you would assume.\n- CANNOT DO: write "REASON:" and then "WHAT WOULD WORK:" with 1 to 3 alternatives.\nRules: prefer PROCEED with stated assumptions when the gap is small and a wrong guess is cheap. Use NEED INFO only when a wrong guess wastes work or risks damage. Use CANNOT DO only when no reasonable reading of the request can be achieved with the configured teams, their access and this workspace. Never invent requirements. Never start teams on a request you do not understand. Answer in the owner's language. You may read project files (read only) to decide. Check the work is assignable: changing files needs a team with a write agent.${limitNote}`, true)}\n${accessFacts()}\n${lanes.length ? `LANES (choose exactly one; you may not invent lanes or teams):\n${laneRosterText()}\n${ownerLane ? `The owner FIXED the lane: "${ownerLane.id}". Brief only its teams. You may still answer NEED INFO or CANNOT DO.` : 'On PROCEED you MUST include a line "LANE: <lane id>" and a line "LANE REASON: <one sentence>", and write sections only for the teams of that lane. If no lane fits, answer DECISION: CANNOT DO with the reason "no lane fits" and say which lane would be needed; if the request is unclear between lanes, use NEED INFO.'}` : `TEAM ROSTER (pipeline order):\n${rosterText()}`}\n${common()}${answered}`);
205
328
  if (t?.trim())
206
- brief = t;
329
+ return t;
330
+ return `DECISION: PROCEED\n${ruleBrief()}`; // the Director could not answer: carry on with the rule-based brief
207
331
  }
208
- else
209
- emit({ type: 'agent.started', agentId: config.director.id, task: 'intake brief' });
210
- intakeBrief = directorSay('ba', brief);
211
- convo.push({ who: config.director.name, text: intakeBrief });
332
+ emit({ type: 'agent.started', agentId: config.director.id, task: 'intake brief' });
333
+ if (/\[sim-cannot\]/i.test(goal))
334
+ return 'DECISION: CANNOT DO\nREASON: (simulated) this request cannot be done with the configured teams in this workspace.\nWHAT WOULD WORK:\n1. Ask for something the configured teams can do.\n2. Add a team that can do this work.';
335
+ if (/\[sim-need-info\]/i.test(goal) && !qaRounds.length)
336
+ return 'DECISION: NEED INFO\n1. Which file or area should change? (a wrong guess would edit the wrong place)\n2. What should happen on invalid input? (it decides the acceptance criteria)\nASSUMPTIONS IF NO ANSWER:\n- Change the main module only.\n- Invalid input fails with a clear error.';
337
+ if (lanes.length && !ownerLane) {
338
+ const m = /\[lane:([a-z0-9-]+)\]/i.exec(goal), l = lanes.find(x => x.id === m?.[1]?.toLowerCase()) ?? lanes[0];
339
+ return `DECISION: PROCEED\nLANE: ${l.id}\nLANE REASON: (simulated) ${m ? 'the goal names this lane' : 'first lane'}`;
340
+ }
341
+ return lanes.length ? 'DECISION: PROCEED' : `DECISION: PROCEED\n${ruleBrief()}`;
342
+ }
343
+ const parseLane = (text) => {
344
+ const m = /^[ \t>*_#-]*LANE[ \t]*\**[ \t]*:\**[ \t]*(.+)$/im.exec(text);
345
+ const v = (m?.[1] ?? '').replace(/[*`"'_]/g, '').trim().toLowerCase();
346
+ return v ? lanes.find(l => l.id === v || l.name.toLowerCase() === v) ?? lanes.find(l => v.startsWith(l.id + ' ') || v.startsWith(l.name.toLowerCase() + ' ')) ?? null : null;
347
+ };
348
+ async function intake() {
349
+ emit({ type: 'stage.changed', stage: 'director-intake', loop: 1 });
350
+ for (;;) {
351
+ const text = await intakeTurn();
352
+ let d = parseDirectorDecision(text);
353
+ if (d.kind === 'need' && (needRounds >= 3 || forced))
354
+ d = d.assumptions ? { ...d, kind: 'proceed', body: '' } : { ...d, kind: 'cannot', reason: 'The request is still unclear after the allowed rounds of questions and no assumption was offered.', alternatives: 'Restate the request with the missing details and start a new run.' };
355
+ if (d.kind === 'cannot') {
356
+ const msg = `The Director could not take this request.\n\n${d.reason ? `REASON: ${d.reason}` : d.body}${d.alternatives ? `\n\nWHAT WOULD WORK:\n${d.alternatives}` : ''}`;
357
+ directorSay('all', msg);
358
+ finish('declined', journal.redact(msg));
359
+ throw new Halt();
360
+ }
361
+ if (d.kind === 'need') {
362
+ needRounds++;
363
+ directorSay('all', `${d.questions}${d.assumptions ? `\n\nASSUMPTIONS IF NO ANSWER:\n${d.assumptions}` : ''}`);
364
+ emit({ type: 'run.waiting', round: needRounds, questions: d.questions, assumptions: d.assumptions || null });
365
+ const w = await waitForOwner(d.assumptions);
366
+ halted();
367
+ if (w.how === 'proceed') {
368
+ assumptions = d.assumptions;
369
+ forced = true;
370
+ qaRounds.push({ questions: d.questions, answer: 'The owner chose to proceed with your stated assumptions.' });
371
+ }
372
+ else {
373
+ qaRounds.push({ questions: d.questions, answer: w.text });
374
+ notes.push(`Owner's answer to the Director: ${w.text}`);
375
+ }
376
+ continue;
377
+ }
378
+ if (d.assumptions)
379
+ assumptions = d.assumptions;
380
+ let body = d.body;
381
+ if (lanes.length) {
382
+ let lane = ownerLane ?? parseLane(text), by = ownerLane ? 'owner' : 'director';
383
+ if (!lane && modelDirector()) {
384
+ const t2 = await directorAsk('choose the lane', `${role(config.director, `Your answer did not contain a readable lane. Choose exactly one of: ${lanes.map(l => `"${l.id}" (${l.name})`).join(', ')}. Reply with ONLY two lines: "LANE: <lane id>" and "LANE REASON: <one sentence>".`, true)}\n${laneRosterText()}\n${common()}`);
385
+ lane = t2 ? parseLane(t2) : null;
386
+ if (lane && t2)
387
+ body = `${body}\n${t2}`;
388
+ }
389
+ if (!lane) {
390
+ lane = lanes[0];
391
+ by = 'fallback';
392
+ laneNote = `lane chosen by fallback: the Director gave no readable LANE line, so the first lane (${lane.name}) was used`;
393
+ }
394
+ order = [...lane.order];
395
+ const reason = by === 'owner' ? 'the owner fixed the lane' : by === 'fallback' ? laneNote : oneLine(/^[ \t>*_#-]*LANE REASON\**[ \t]*:\**[ \t]*(.+)$/im.exec(body)?.[1] ?? /^[ \t>*_#-]*LANE REASON\**[ \t]*:\**[ \t]*(.+)$/im.exec(text)?.[1] ?? 'no reason given', 200);
396
+ body = body.split('\n').filter(l => !/^[ \t>*_#-]*LANE( REASON)?\**[ \t]*:/i.test(l)).join('\n').trim();
397
+ emit({ type: 'lane.chosen', laneId: lane.id, name: lane.name, by, reason });
398
+ if (modelDirector() && !parseBriefs(body).size)
399
+ body = `${body}\n\n${ruleBrief()}`;
400
+ }
401
+ intakeBrief = directorSay(order[0] ?? 'all', body || ruleBrief());
402
+ break;
403
+ }
404
+ briefs.clear();
405
+ for (const [k, v] of parseBriefs(intakeBrief))
406
+ briefs.set(k, v);
407
+ intakeIntro = briefs.size ? (intakeBrief.split(/^[ \t]*#{2,4}[ \t]*TEAM[ \t]/im)[0] ?? '').trim() || intakeBrief : intakeBrief;
408
+ convo.push({ who: config.director.name, text: intakeIntro });
212
409
  await drain();
213
410
  }
214
411
  async function decide(text) {
@@ -249,95 +446,282 @@ export function startTeamRun(opts) {
249
446
  if (finished)
250
447
  return;
251
448
  abort.abort();
449
+ if (waiting)
450
+ waiting.wake({ how: 'stop', text: '' });
252
451
  finish('stopped', `Run stopped. ${why}\n\nGoal: ${goal}\n${handoff ? `\nLast handoff: handoff-ba.md\n` : ''}`);
253
452
  }
254
- // ---- stages ----
255
- async function baDiscussion() {
256
- const ba = config.teams.ba, total = config.limits.baRounds * ba.length;
257
- emit({ type: 'stage.changed', stage: 'ba-discussion', loop: 1 });
258
- let last = '';
259
- for (let i = 0; i < total; i++) {
260
- const agent = ba[i % ba.length], peer = ba.length > 1 ? ba[(i + 1) % ba.length] : null, final = i === total - 1;
261
- const what = final
262
- ? `This is the final BA turn. Produce the ONE final HANDOFF document in markdown with sections: # HANDOFF, ## Goal, ## Scope, ## Acceptance criteria (checklist "- [ ]"), ## Out of scope, ## Risks. Reconcile the discussion; output only the document.`
263
- : `Discuss the request with your BA partner${peer ? ` (${peer.name})` : ''}: clarify scope, propose acceptance criteria, challenge weak points. Address your partner directly.`;
264
- const text = await turn(agent, final ? 'finalize handoff' : `BA discussion ${i + 1}/${total}`, final ? 'implement' : peer?.id ?? 'all', `${header(agent, 'ba-discussion', 1, i + 1, total, final)}${role(agent, what)}\n${common()}\nCONVERSATION SO FAR:\n${recent()}`);
453
+ const nextOf = (k) => order[k + 1] ?? 'director';
454
+ const backOf = () => { const r = retReason; retReason = null; return r === null ? null : { full: r, short: oneLine(r, 300) }; };
455
+ const handoffs = new Map(); // per team: its latest handoff in short form (for the trail)
456
+ const cap = (s, n) => { const t = oneLine(s, 100000); return t.length > n ? `${t.slice(0, n - 1)}... (shortened)` : t; };
457
+ /** Compact trail of the handoffs of the first `upTo` teams: DONE and OPEN only, capped, explicitly marked as shortened. */
458
+ const trailBlock = (upTo) => {
459
+ const t = order.slice(0, Math.max(0, upTo)).map(id => { const h = handoffs.get(id); return h ? `- ${teamName(id)}: DONE: ${cap(h.done, 300)} | OPEN: ${cap(h.open, 300)}` : ''; }).filter(Boolean).join('\n');
460
+ return t ? `EARLIER TEAMS (shortened trail: DONE and OPEN only, not the full handoffs):\n${t}\n` : '';
461
+ };
462
+ const hdr = (agent, stage, loop, turn, turns, phase, round) => simAgent(agent) ? `${simHeader({ stage, loop, turn, turns, final: phase === 'handoff' || phase === 'single', phase, round })}\n` : '';
463
+ const hdrS = (agent, stage, loop) => simAgent(agent) ? `${simHeader({ stage, loop, turn: 1, turns: 1, final: true })}\n` : '';
464
+ const inputBlock = (k, id) => {
465
+ const p = prevId(k), parts = [];
466
+ if (p !== 'director')
467
+ parts.push(`HANDOFF FROM THE ${teamName(p).toUpperCase()} TEAM (in full):\n${clip(outs.get(p) ?? '', 8000)}`);
468
+ const trail = trailBlock(k - 1);
469
+ if (trail)
470
+ parts.push(trail.trimEnd());
471
+ const sb = sentBack.get(id);
472
+ if (sb)
473
+ parts.push(`YOUR PREVIOUS HANDOFF:\n${clip(outs.get(id) ?? '', 4000)}\n\nSENT BACK TO YOU by the ${teamName(sb.from)} team (redo your work and fix this):\n${clip(sb.reason, 4000)}`);
474
+ return parts.length ? `${parts.join('\n\n')}\n` : '';
475
+ };
476
+ /** The previous team (the Director for team 1) answers one question from a later team. Never fails the run. */
477
+ async function askPrevious(k, asker, question) {
478
+ const pid = prevId(k);
479
+ emit({ type: 'flow.back', kind: 'ask', from: asker.team, to: pid, reason: oneLine(question, 300) });
480
+ if (pid === 'director') {
481
+ let ans = `Re "${oneLine(question, 200)}": everything I know is in the brief for your team:\n${briefOf(asker.team)}`;
482
+ if (modelDirector()) {
483
+ const t = await directorAsk(`answer ${teamName(asker.team)}`, `${role(config.director, 'A team asks you a question about its brief. Answer in one short message; do not restate the whole brief.')}\nTEAM ROSTER (flow order):\n${rosterText()}\n${common()}\nYOUR EARLIER BRIEF FOR THAT TEAM:\n${briefOf(asker.team)}\nQUESTION from ${asker.name} (${teamName(asker.team)}): ${question}`);
484
+ if (t?.trim())
485
+ ans = t;
486
+ }
487
+ return directorSay(asker.id, ans);
488
+ }
489
+ const lead = agentsOf(pid)[0];
490
+ const t = await turn(lead, `answer ${asker.name}`, asker.id, `${hdrS(lead, 'ask-answer', passes.get(pid) ?? 1)}${role(lead, `A later team (${teamName(asker.team)}, ${asker.name}) asks you a question about your work. Answer in one short message; do not redo your work.`, true)}\n${common()}\nYOUR OWN HANDOFF:\n${clip(outs.get(pid) ?? '', 4000)}\nQUESTION: ${question}`);
491
+ return t ?? '(the previous team could not answer)';
492
+ }
493
+ /** One turn of a team agent with the backward rules. RETURN TO PREVIOUS sets retReason; ASK PREVIOUS is answered (up to the limit) and the agent continues. null = agent failed. */
494
+ async function teamTurn(k, agent, task, to, prompt, round) {
495
+ let extra = '';
496
+ for (;;) {
497
+ const text = await turn(agent, task, to, prompt + extra, round);
265
498
  if (text === null)
266
- return fail(agent, 'the BA discussion');
267
- last = text;
499
+ return null;
500
+ const m = markers(text);
501
+ if (m.ret !== null) {
502
+ retReason = m.ret || 'no reason given';
503
+ return m.clean;
504
+ }
505
+ if (m.ask === null || (asks.get(k) ?? 0) >= limit)
506
+ return m.clean;
507
+ asks.set(k, (asks.get(k) ?? 0) + 1);
508
+ const answer = await askPrevious(k, agent, m.ask || 'please clarify');
268
509
  await drain();
510
+ extra += `\n\nYOUR QUESTION TO ${teamName(prevId(k)).toUpperCase()}: ${m.ask}\nANSWER FROM ${teamName(prevId(k)).toUpperCase()} (the team before you):\n${clip(answer, 3000)}\nContinue your work using this answer.`;
269
511
  }
270
- handoff = atts.length ? `${last}\n\n## Attachments from the owner\nPart of this handoff. Read them together with the document above.\n${attachmentLines(atts)}\n` : last;
271
- const art = journal.writeArtifact('handoff-ba.md', handoff);
272
- emit({ type: 'handoff.created', from: 'ba', to: 'implement', title: 'BA handoff', artifact: art });
273
512
  }
274
- async function implement(loop) {
275
- emit({ type: 'stage.changed', stage: 'implement', loop });
276
- const [lead, ...helpers] = config.teams.implement;
277
- const base = `HANDOFF (your spec):\n${clip(handoff, 6000)}\n${loop > 1 ? `\nQC REPORT TO FIX (loop ${loop - 1}):\n${clip(qcReport, 4000)}\n` : ''}`;
278
- const leadText = await turn(lead, loop > 1 ? 'fix QC findings' : 'implement handoff', 'qc', `${header(lead, 'implement', loop)}${role(lead, 'Implement the handoff in the project (edit files, run tests). Finish with: what changed (files) and how to verify.')}\n${common()}\n${base}`);
279
- if (leadText === null)
280
- return fail(lead, 'the implementation');
281
- deliverable = leadText;
282
- await drain();
283
- for (const h of helpers) {
284
- const t = await turn(h, 'help implement', 'qc', `${header(h, 'implement', loop)}${role(h, 'You are a helper developer. Review the lead developer\'s work and complete or fix anything missing. Report what you changed.')}\n${common()}\n${base}\nLEAD REPORT:\n${leadText}`);
285
- if (t === null)
286
- return fail(h, 'helping with the implementation');
287
- deliverable += `\n\n${h.name}: ${t}`;
513
+ const workWhat = (id) => id === 'ba' ? 'Clarify the request and produce the spec: scope, acceptance criteria as a checklist "- [ ]", out of scope, risks.'
514
+ : id === 'implement' ? 'Implement the work received (edit files, run tests); report what changed (files) and how to verify.'
515
+ : id === 'qc' ? 'Review and test the deliverable against the acceptance criteria received (read the diff, run tests/commands as needed). Put a line exactly "VERDICT: PASS" or "VERDICT: FAIL" at the end of your message.'
516
+ : `Do your part as the ${teamName(id)} team, then report what you did and found.`;
517
+ const handoffInstr = (id, k) => {
518
+ const to = nextOf(k), toName = to === 'director' ? 'Director' : teamName(to);
519
+ return `HANDOFF: end your message with ONE structured handoff for ${toName}. Start it with the line "### HANDOFF ${teamName(id)} -> ${toName}" and then four sections, each heading on its own line: "DONE:" (what is finished, concretely), "DECISIONS:" (what was decided and why), "OPEN:" (what is unresolved or not verified, or "nothing"), "FOR YOU:" (what ${toName} must do or check next).${sentBack.has(id) ? ' You were sent back: begin DONE with "Changes since my previous handoff:".' : ''}`;
520
+ };
521
+ /** One pass of one team. 1 agent = one turn (work + handoff). 2+ agents = discussion rounds (bounded by limits.baRounds, early stop on AGREED), then ONE writer does the work (never two writers), then the lead writes the handoff. */
522
+ async function teamPass(k, id, pass) {
523
+ const agents = agentsOf(id), lead = agents[0], name = teamName(id), isQc = id === 'qc', to = nextOf(k), toName = to === 'director' ? 'Director' : teamName(to);
524
+ const stageName = id === 'ba' ? 'ba-discussion' : id === 'implement' || id === 'qc' ? id : 'extra-team';
525
+ emit({ type: 'stage.changed', stage: stageName, loop: pass, ...(stageName === 'extra-team' ? { team: id } : {}) });
526
+ const multi = agents.length > 1, rounds = config.limits.baRounds;
527
+ const writer = isQc ? undefined : agents.find(a => a.access === 'write'); // QC reviews; it never changes files
528
+ const turns = !multi ? 1 : agents.length * rounds + (writer ? 1 : 0) + (writer === lead ? 0 : 1);
529
+ const verdicts = new Map(), lastMsg = new Map(), log = [];
530
+ let n = 0, qcReturn = null, raw = null, failNote = '';
531
+ const run = async (agent, phase, round, what, task, toId, readOnly) => {
532
+ n++;
533
+ const text = await teamTurn(k, agent, task, toId, `${hdr(agent, stageName, pass, n, turns, phase, round)}${role(agent, what, readOnly)}\n${common()}\n${inputBlock(k, id)}${log.length ? `\nTEAM DISCUSSION SO FAR (your own team only):\n${log.join('\n\n')}\n` : ''}`, phase === 'discuss' ? round : undefined);
534
+ if (text === null) {
535
+ if (!isQc)
536
+ return fail(agent, `the ${name} stage`);
537
+ const f = history.filter(e => e.type === 'agent.failed').at(-1); // a QC reviewer that cannot run counts as FAIL
538
+ verdicts.set(agent.id, 'FAIL');
539
+ failNote = `QC agent could not run: ${f && f.type === 'agent.failed' ? f.reason : 'unknown'}`;
540
+ return '';
541
+ }
542
+ lastMsg.set(agent.id, text);
543
+ if (isQc && /VERDICT/i.test(text))
544
+ verdicts.set(agent.id, parseVerdict(text));
288
545
  await drain();
546
+ return text;
547
+ };
548
+ const early = () => retReason !== null;
549
+ const returnedEarly = () => {
550
+ if (!early())
551
+ return null;
552
+ if (isQc) {
553
+ qcReturn = retReason;
554
+ retReason = null;
555
+ return null;
556
+ }
557
+ return { out: [...lastMsg.values()].at(-1) ?? '', back: backOf() };
558
+ };
559
+ if (!multi) {
560
+ raw = await run(lead, 'single', 1, `${workWhat(id)}\n${handoffInstr(id, k)}`, name, to, false);
561
+ const r = returnedEarly();
562
+ if (r)
563
+ return r;
564
+ }
565
+ else {
566
+ discussion: for (let r = 1; r <= rounds; r++) {
567
+ let agreed = 0;
568
+ for (let i = 0; i < agents.length; i++) {
569
+ const a = agents[i], peer = agents[(i + 1) % agents.length];
570
+ const what = `TEAM DISCUSSION, round ${r} of ${rounds}. ${workWhat(id)}\n${r === 1 ? 'Round 1: give your own take; do not wait for your teammates.' : 'Read your teammates\' messages below. Challenge weak points and merge the good ones; if you now agree with the team position, include a line "AGREED".'}\nDo not change any file during the discussion; speak to your teammates (${agents.filter(x => x.id !== a.id).map(x => x.name).join(', ')}).`;
571
+ const t = await run(a, 'discuss', r, what, `${name} discussion ${r}/${rounds} (${i + 1}/${agents.length})`, peer.id, true);
572
+ const rr = returnedEarly();
573
+ if (rr)
574
+ return rr;
575
+ if (qcReturn !== null)
576
+ break discussion;
577
+ log.push(`[round ${r}] ${a.name}: ${clip(t ?? '', 1500)}`);
578
+ if (r >= 2 && t && AGREED_RE.test(t))
579
+ agreed++;
580
+ }
581
+ if (r >= 2 && agreed === agents.length)
582
+ break;
583
+ }
584
+ if (qcReturn === null && writer) {
585
+ const t = await run(writer, 'work', 1, `The discussion is over. You are the ONLY member of the ${name} team who changes files in this pass: do the work following the team discussion. ${workWhat(id)}${writer === lead ? `\n${handoffInstr(id, k)}` : ''}`, `${name} work`, to, false);
586
+ const rr = returnedEarly();
587
+ if (rr)
588
+ return rr;
589
+ if (writer === lead)
590
+ raw = t;
591
+ else
592
+ log.push(`[work] ${writer.name}: ${clip(t ?? '', 2500)}`);
593
+ }
594
+ if (qcReturn === null && raw === null) {
595
+ raw = await run(lead, 'handoff', 1, `The discussion is over. You are the team lead: write the team's single result. ${isQc ? 'State the merged result: "VERDICT: FAIL" when any reviewer failed it, else "VERDICT: PASS". ' : ''}${handoffInstr(id, k)}`, `${name} handoff`, to, true);
596
+ const rr = returnedEarly();
597
+ if (rr)
598
+ return rr;
599
+ }
600
+ }
601
+ const rawText = raw ?? '';
602
+ const sec = parseHandoff(rawText);
603
+ let text = sec ? `### HANDOFF ${name} -> ${toName}\n${HANDOFF_SECTIONS.map(s => `#### ${s}\n${sec[s]}`).join('\n\n')}` : `### HANDOFF ${name} -> ${toName}\n(the team lead did not use the four sections; this is its final message)\n${clip(rawText, 6000)}`;
604
+ let back = null;
605
+ if (isQc) {
606
+ const failed = qcReturn !== null || [...verdicts.values()].some(v => v === 'FAIL') || (!verdicts.size);
607
+ const verdict = failed ? 'FAIL' : 'PASS';
608
+ const firstFailId = [...verdicts].find(([, v]) => v === 'FAIL')?.[0];
609
+ const firstFail = qcReturn !== null ? `Returned to the previous team: ${qcReturn}` : failNote || (firstFailId ? (lastMsg.get(firstFailId) ?? '').replace(/\n?.*VERDICT.*$/i, '') : 'no reviewer gave a verdict');
610
+ qcReport = `# QC report (loop ${pass}) - ${verdict}\n\n${agents.map(a => `## ${a.name} - ${verdicts.get(a.id) ?? 'no verdict'}\n\n${lastMsg.get(a.id) ?? '(no message)'}`).join('\n\n')}\n\n## Team handoff\n\n${text}\n`;
611
+ const art = journal.writeArtifact(`qc-report-${pass}.md`, qcReport);
612
+ emit({ type: 'qc.verdict', verdict, loop: pass, summary: oneLine(verdict === 'PASS' ? 'All QC reviewers passed the deliverable.' : firstFail, 300) });
613
+ qcPassed = verdict === 'PASS';
614
+ void art;
615
+ text += `\n\nVERDICT: ${verdict}`;
616
+ back = failed ? { full: qcReport, short: oneLine(firstFail, 300) } : null;
617
+ }
618
+ else
619
+ back = backOf();
620
+ if (id === 'ba' && atts.length)
621
+ text += `\n\n## Attachments from the owner\nPart of this handoff. Read them together with the document above.\n${attachmentLines(atts)}\n`;
622
+ handoffs.set(id, { done: sec ? sec.DONE : rawText, open: sec ? sec.OPEN : '(handoff not structured)' });
623
+ const art = journal.writeArtifact(`handoff-${id}.md`, text);
624
+ if (id === 'ba')
625
+ journal.writeArtifact('handoff-ba.md', text);
626
+ emit({ type: 'handoff.created', from: id, to, title: `${name} -> ${toName}`, artifact: art, text: clip(text, 8000) });
627
+ return { out: text, back };
628
+ }
629
+ /** Director rewrites the brief for team 1 after it sent the work back. */
630
+ async function directorRewrite(id, reason) {
631
+ let text = `${briefOf(id)}\n\nDIRECTOR REVISION (the ${teamName(id)} team sent the brief back: ${oneLine(reason, 300)}). Address this point first.`;
632
+ if (modelDirector()) {
633
+ const t = await directorAsk(`rewrite brief for ${teamName(id)}`, `${role(config.director, `The first team sent your brief back with a reason. Rewrite the brief for that team only: answer the reason, keep it short. Start with a line exactly "### TEAM ${id}".`)}\nTEAM ROSTER (flow order):\n${rosterText()}\n${common()}\nYOUR EARLIER BRIEF FOR THAT TEAM:\n${briefOf(id)}\nREASON: ${reason}`);
634
+ if (t?.trim())
635
+ text = t;
289
636
  }
637
+ const said = directorSay(id, text);
638
+ briefs.set(id, parseBriefs(said).get(id) ?? clip(said, 2500));
290
639
  }
291
- /** Returns true when QC passed. */
292
- async function qc(loop) {
293
- emit({ type: 'stage.changed', stage: 'qc', loop });
294
- const agents = config.teams.qc, notesThisLoop = [];
295
- let fails = 0, firstFail = '';
296
- for (let i = 0; i < agents.length; i++) {
297
- const agent = agents[i], peer = agents[(i + 1) % agents.length];
298
- const text = await turn(agent, `QC review ${i + 1}/${agents.length}`, agents.length > 1 ? (i === agents.length - 1 ? 'implement' : peer.id) : 'implement', `${header(agent, 'qc', loop, i + 1, agents.length, i === agents.length - 1)}${role(agent, 'Review and test the deliverable against the handoff acceptance criteria (read the diff, run tests/commands as needed). Discuss with other QC reviewers: agree or disagree with their notes. End with a last line exactly "VERDICT: PASS" or "VERDICT: FAIL".')}\n${common()}\nHANDOFF:\n${clip(handoff, 6000)}\nDELIVERABLE REPORT:\n${clip(deliverable, 4000)}\n${notesThisLoop.length ? `\nOTHER QC NOTES:\n${notesThisLoop.join('\n\n')}\n` : ''}`);
299
- let verdict, body;
300
- if (text === null) { // QC failure = FAIL with reason (the agent.failed event already carries it)
301
- const f = history.filter(e => e.type === 'agent.failed').at(-1);
302
- verdict = 'FAIL';
303
- body = `QC agent could not run: ${f && f.type === 'agent.failed' ? f.reason : 'unknown'}`;
640
+ /** Runs the teams strictly in order from team index `from`. A return from team k re-runs team k-1 with the reason, then moves forward again; bounded per boundary by limits.qcLoops. */
641
+ async function flow(from = 0) {
642
+ let k = from;
643
+ while (k < order.length) {
644
+ const id = order[k], pass = (passes.get(id) ?? 0) + 1;
645
+ passes.set(id, pass);
646
+ retReason = null;
647
+ const res = await teamPass(k, id, pass);
648
+ sentBack.delete(id);
649
+ outs.set(id, res.out);
650
+ if (res.back) {
651
+ const used = backs.get(k) ?? 0;
652
+ if (used < limit) {
653
+ backs.set(k, used + 1);
654
+ emit({ type: 'flow.back', kind: 'return', from: id, to: prevId(k), reason: res.back.short });
655
+ if (k === 0)
656
+ await directorRewrite(id, res.back.full);
657
+ else {
658
+ sentBack.set(order[k - 1], { from: id, reason: res.back.full });
659
+ k--;
660
+ }
661
+ continue;
662
+ }
663
+ outs.set(id, `${res.out}\n\n[NOTE: this team sent the work back but the limit of ${limit} send-back(s) at this step was reached; the flow moved on.]`);
664
+ if (id === 'qc')
665
+ qcPassed = false;
666
+ }
667
+ k++;
668
+ }
669
+ const lastId = order.at(-1);
670
+ deliverable = lastId ? outs.get(lastId) ?? '' : '';
671
+ }
672
+ /** What the Director's delivery sees from the flow: the last team's output, the QC report (when a QC team exists) and every send-back-limit note. */
673
+ function finalOutputs() {
674
+ const lastId = order.at(-1), last = lastId ? outs.get(lastId) ?? '' : '';
675
+ const notes = order.filter(id => /send-back\(s\) at this step was reached/.test(outs.get(id) ?? '')).map(id => `- ${teamName(id)}: send-back limit reached, the flow moved on with open problems.`);
676
+ return [laneNote ? `NOTE: ${laneNote}` : '', lastId ? `LAST TEAM (${teamName(lastId)}) OUTPUT:\n${clip(last, 3000)}` : '', order.includes('qc') && qcReport ? `QC: ${qcPassed ? 'PASSED' : 'FAIL - DID NOT PASS (send-back limit reached)'}\n${clip(qcReport, 3000)}` : '', notes.length ? `UNRESOLVED:\n${notes.join('\n')}` : ''].filter(Boolean).join('\n\n');
677
+ }
678
+ // ---- Director review: the Director checks the finished work against the ORIGINAL request before delivery ----
679
+ const reviewOn = () => config.directorReview !== false && order.length > 0;
680
+ let reviewChecklist = '', reviewUnmet = false;
681
+ async function reviewStage() {
682
+ if (!reviewOn())
683
+ return;
684
+ const lastId = order[order.length - 1];
685
+ let used = 0;
686
+ for (let loop = 1;; loop++) {
687
+ emit({ type: 'stage.changed', stage: 'review', loop });
688
+ let text;
689
+ if (modelDirector()) {
690
+ const t = await directorAsk('review the result', `${role(config.director, 'You are the Director doing the final review. Compare the finished work with the ORIGINAL owner request (not with your own brief). List every requirement of the request one by one as "- <requirement>: MET" or "- <requirement>: NOT MET" with the evidence (what the teams reported, what was verified and by whom). Do not change any file. End with a last line exactly "REVIEW: PASS" or "REVIEW: FAIL"; on FAIL add a line "RETURN TO PREVIOUS: <what is missing>".', true)}\nORIGINAL REQUEST (the owner's words): ${goal}\n${common()}${assumptionsBlock()}\nFINAL HANDOFF (${teamName(lastId)} -> Director):\n${clip(outs.get(lastId) ?? '', 6000)}\n${trailBlock(order.length - 1)}${finalOutputs()}\n${laneNote ? `NOTE: ${laneNote}\n` : ''}`);
691
+ text = t ?? '';
304
692
  }
305
693
  else {
306
- verdict = parseVerdict(text);
307
- body = text;
694
+ emit({ type: 'agent.started', agentId: config.director.id, task: 'review the result' });
695
+ const failIt = /\[sim-review-fail\]/i.test(goal) && loop === 1;
696
+ text = failIt ? `- The request as written: NOT MET (no regression test mentioned in the final handoff)\nREVIEW: FAIL\nRETURN TO PREVIOUS: add a regression test that proves the requested behaviour` : `- The request as written: MET (see the final handoff and the QC verdict)\nREVIEW: PASS`;
308
697
  }
309
- notesThisLoop.push(`## ${agent.name} — ${verdict}\n\n${body}`);
310
- if (verdict === 'FAIL') {
311
- fails++;
312
- if (!firstFail)
313
- firstFail = body.replace(/\n?.*VERDICT.*$/i, '');
698
+ const said = directorSay('all', text || '(no review text)');
699
+ const v = parseReview(said);
700
+ const ret = /^[ \t>*_#-]*RETURN TO PREVIOUS\**\s*:\**\s*(.*)$/im.exec(said)?.[1]?.trim() || 'the review found requirements that are not met';
701
+ const verdict = v ?? 'PASS';
702
+ reviewChecklist = v === null ? 'review verdict not readable' : clip(said, 3000);
703
+ emit({ type: 'review.verdict', verdict, loop, summary: v === null ? 'review verdict not readable' : oneLine(verdict === 'PASS' ? 'Every requirement is met.' : ret, 300), checklist: clip(said, 3000) });
704
+ reviewUnmet = verdict === 'FAIL';
705
+ if (verdict === 'PASS')
706
+ return;
707
+ if (used >= limit) {
708
+ reviewChecklist = `${clip(said, 3000)}\n[the send-back limit of ${limit} for the Director review was reached; the items marked NOT MET are still open]`;
709
+ return;
314
710
  }
711
+ used++;
712
+ emit({ type: 'flow.back', kind: 'return', from: 'director', to: lastId, reason: oneLine(ret, 300) });
713
+ sentBack.set(lastId, { from: 'director', reason: `${ret}\n\nDirector's checklist:\n${clip(said, 2500)}` });
714
+ await flow(order.length - 1);
315
715
  await drain();
316
716
  }
317
- const verdict = fails ? 'FAIL' : 'PASS';
318
- qcReport = `# QC report (loop ${loop}) — ${verdict}\n\n${notesThisLoop.join('\n\n')}\n`;
319
- const art = journal.writeArtifact(`qc-report-${loop}.md`, qcReport);
320
- emit({ type: 'qc.verdict', verdict, loop, summary: oneLine(verdict === 'PASS' ? 'All QC reviewers passed the deliverable.' : firstFail, 300) });
321
- if (verdict === 'FAIL' && loop <= config.limits.qcLoops)
322
- emit({ type: 'handoff.created', from: 'qc', to: 'implement', title: `QC report ${loop}`, artifact: art });
323
- return verdict === 'PASS';
324
717
  }
325
- async function baReview() {
326
- emit({ type: 'stage.changed', stage: 'ba-review', loop: 1 });
327
- const lead = config.teams.ba[0];
328
- const text = await turn(lead, 'review deliverable vs handoff', 'director', `${header(lead, 'ba-review', 1)}${role(lead, 'Check the deliverable against the handoff acceptance criteria, one by one. State approved or not, with reasons.')}\n${common()}\nHANDOFF:\n${clip(handoff, 6000)}\nDELIVERABLE REPORT:\n${clip(deliverable, 4000)}\nQC: ${qcPassed ? 'PASSED' : 'DID NOT PASS (QC loops exhausted)'}\n${qcReport ? clip(qcReport, 3000) : ''}`);
329
- if (text === null)
330
- return fail(lead, 'the BA review');
331
- await drain();
332
- return text;
333
- }
334
- async function delivery(review) {
718
+ async function delivery() {
335
719
  emit({ type: 'stage.changed', stage: 'delivery', loop: 1 });
336
- const arts = ['handoff-ba.md', ...history.filter(e => e.type === 'qc.verdict').map(e => `qc-report-${e.loop}.md`), 'transcript.md'];
337
- const rules = `# Delivery report\n\n**Goal:** ${oneLine(goal, 400)}\n\n**QC:** ${qcPassed ? 'PASSED' : 'DID NOT PASS within the loop limit — review the QC reports before relying on this'}\n\n## What was built\n${clip(deliverable, 3000)}\n\n## BA review\n${clip(review, 2000)}\n\n## Artifacts\n${arts.map(a => `- ${a}`).join('\n')}\n`;
720
+ const arts = [...order.map(id => `handoff-${id}.md`), ...history.filter(e => e.type === 'qc.verdict').map(e => `qc-report-${e.loop}.md`), 'transcript.md'];
721
+ const rules = `# Delivery report\n\n**Goal:** ${oneLine(goal, 400)}\n\n**QC:** ${!order.includes('qc') ? 'not part of this company (no QC team)' : qcPassed ? 'PASSED' : 'DID NOT PASS within the loop limit — review the QC reports before relying on this'}\n\n## What was built\n${clip(deliverable || (roster().length ? '' : intakeBrief), 3000)}\n\n## Final team outputs\n${clip(finalOutputs(), 3000)}${reviewOn() && reviewChecklist ? `\n\n## Director review\n${reviewUnmet ? 'Some requirements are NOT MET; do not describe the work as complete.\n' : ''}${reviewChecklist}` : ''}${assumptions ? `\n\n## Assumptions made\n${assumptions}` : ''}\n\n## Artifacts\n${arts.map(a => `- ${a}`).join('\n')}\n`;
338
722
  let report = rules;
339
723
  if (modelDirector()) {
340
- const t = await directorAsk('delivery report', `${role(config.director, 'Write the final report to the owner in markdown: what was delivered, QC outcome, caveats, artifacts.')}\n${common()}\nHANDOFF:\n${clip(handoff, 4000)}\nDELIVERABLE:\n${clip(deliverable, 3000)}\nQC PASSED: ${qcPassed}\nBA REVIEW:\n${clip(review, 2000)}`);
724
+ const t = await directorAsk('delivery report', `${role(config.director, 'Write the final report to the owner in markdown. Say plainly what was done, what was verified and by whom, and what remains open. List every unmet requirement under "Not met" and never claim the work is complete while any remains. Include a section "Assumptions made" when assumptions were made.', true)}\n${common()}\nFINAL HANDOFF (to the Director):\n${clip(order.length ? outs.get(order[order.length - 1]) ?? '' : '', 6000)}\n${trailBlock(order.length - 1)}QC PASSED: ${qcPassed}\n${finalOutputs()}${reviewOn() && reviewChecklist ? `\nDIRECTOR REVIEW CHECKLIST${reviewUnmet ? ' (NOT MET items remain open)' : ''}:\n${reviewChecklist}\n` : ''}`);
341
725
  if (t?.trim())
342
726
  report = t;
343
727
  }
@@ -350,25 +734,29 @@ export function startTeamRun(opts) {
350
734
  async function pipeline() {
351
735
  try {
352
736
  await intake();
353
- let review = '';
737
+ if (finished)
738
+ return;
354
739
  for (;;) {
355
740
  try {
356
741
  handoff = '';
742
+ handoffs.clear();
743
+ reviewChecklist = '';
744
+ reviewUnmet = false;
357
745
  qcReport = '';
358
746
  deliverable = '';
359
- qcPassed = false;
747
+ qcPassed = !order.includes('qc');
748
+ outs.clear();
749
+ passes.clear();
750
+ sentBack.clear();
751
+ asks.clear();
752
+ backs.clear();
753
+ retReason = null;
360
754
  convo.length = 0;
361
- if (intakeBrief)
362
- convo.push({ who: config.director.name, text: intakeBrief });
363
- await baDiscussion();
364
- for (let loop = 1;; loop++) {
365
- await implement(loop);
366
- qcPassed = await qc(loop);
367
- if (qcPassed || loop > config.limits.qcLoops)
368
- break;
369
- }
370
- review = await baReview();
371
- await delivery(review);
755
+ if (intakeIntro)
756
+ convo.push({ who: config.director.name, text: intakeIntro });
757
+ await flow();
758
+ await reviewStage();
759
+ await delivery();
372
760
  break;
373
761
  }
374
762
  catch (e) {
@@ -399,8 +787,14 @@ export function startTeamRun(opts) {
399
787
  doStop('Owner asked the Director to stop.');
400
788
  return;
401
789
  }
790
+ if (waiting) {
791
+ const w = waiting;
792
+ w.wake({ how: 'answer', text: added.length ? `${text} [owner attached: ${added.map(a => a.path).join(', ')}]` : text });
793
+ return;
794
+ }
402
795
  inbox.push(added.length ? `${text} [owner attached: ${added.map(a => a.path).join(', ')}]` : text);
403
- }, () => doStop('Stopped from the console.'));
796
+ }, () => doStop('Stopped from the console.'), () => { const w = waiting; if (w && w.assumptions)
797
+ w.wake({ how: 'proceed', text: '' }); });
404
798
  }
405
799
  /** Re-emits a journal with original relative timing / speed (gaps capped at 1.5s/speed). */
406
800
  export function replayTeamRun(runDir, opts = {}) {