@ngockhoale/ckit 0.3.0 → 0.4.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.
- package/README.md +14 -2
- package/dist/src/gui/server.d.ts +3 -1
- package/dist/src/gui/server.js +41 -15
- package/dist/src/team/bus.d.ts +60 -0
- package/dist/src/team/bus.js +172 -0
- package/dist/src/team/config.js +5 -4
- package/dist/src/team/engine.d.ts +33 -1
- package/dist/src/team/engine.js +1095 -170
- package/dist/src/team/mcp/hub.d.ts +16 -0
- package/dist/src/team/mcp/hub.js +99 -0
- package/dist/src/team/mcp/stdio-server.d.ts +2 -0
- package/dist/src/team/mcp/stdio-server.js +103 -0
- package/dist/src/team/runners.d.ts +4 -0
- package/dist/src/team/runners.js +8 -2
- package/dist/src/team/scheduler.d.ts +20 -0
- package/dist/src/team/scheduler.js +73 -0
- package/dist/src/team/sessions/claude.d.ts +16 -5
- package/dist/src/team/sessions/claude.js +127 -13
- package/dist/src/team/sessions/codex.d.ts +3 -2
- package/dist/src/team/sessions/codex.js +21 -3
- package/dist/src/team/sessions/fallback.js +6 -2
- package/dist/src/team/sessions/index.d.ts +1 -1
- package/dist/src/team/sessions/index.js +3 -3
- package/dist/src/team/sessions/omp.d.ts +12 -3
- package/dist/src/team/sessions/omp.js +95 -8
- package/dist/src/team/sessions/proc.d.ts +20 -2
- package/dist/src/team/sessions/proc.js +64 -18
- package/dist/src/team/sessions/types.d.ts +23 -2
- package/dist/src/team/telemetry.d.ts +32 -0
- package/dist/src/team/telemetry.js +135 -0
- package/dist/src/team/types.d.ts +173 -1
- package/dist/src/tui/team/model.js +10 -0
- package/gui/app.css +23 -0
- package/gui/app.js +208 -6
- package/gui/comic/comic.css +86 -0
- package/gui/comic/engine.js +44 -0
- package/gui/comic/render.js +73 -16
- package/gui/index.html +1 -1
- package/package.json +1 -1
package/dist/src/team/engine.js
CHANGED
|
@@ -5,6 +5,9 @@ import { readSecret } from './secrets.js';
|
|
|
5
5
|
import { createCappedSink, createTeamJournal } from './journal.js';
|
|
6
6
|
import { readTeamJournal } from './journal.js';
|
|
7
7
|
import { openSession as defaultOpenSession, sessionsEnabled } from './sessions/index.js';
|
|
8
|
+
import { createRunBus } from './bus.js';
|
|
9
|
+
import { startToolHub } from './mcp/hub.js';
|
|
10
|
+
import { globalAgentScheduler } from './scheduler.js';
|
|
8
11
|
import { otherRunsNote, workspaceLeaseFor } from './workspace-lease.js';
|
|
9
12
|
import { advisorKeyOf, createSimulatedRunner, dispatchRunner, simHeader } from './runners.js';
|
|
10
13
|
import { DEFAULT_MISSIONS, allAgentsOf, effectiveOrder } from './types.js';
|
|
@@ -23,7 +26,14 @@ function knownSecretValues(config, projectRoot) {
|
|
|
23
26
|
class Redirect extends Error {
|
|
24
27
|
}
|
|
25
28
|
class Halt extends Error {
|
|
26
|
-
}
|
|
29
|
+
}
|
|
30
|
+
const sessionRegistries = new WeakMap();
|
|
31
|
+
const sessionRegistry = (sch) => { let r = sessionRegistries.get(sch); if (!r) {
|
|
32
|
+
r = new Set();
|
|
33
|
+
sessionRegistries.set(sch, r);
|
|
34
|
+
} return r; };
|
|
35
|
+
class NodeCancelled extends Error {
|
|
36
|
+
} // a PARALLEL_EXECUTE node stopped because a sibling node redirected or halted the flow // run already finished (stop) or failed; unwinds the pipeline
|
|
27
37
|
const oneLine = (s, max = 200) => { const t = s.replace(/\s+/g, ' ').trim(); return t.length > max ? `${t.slice(0, max - 1)}…` : t; };
|
|
28
38
|
const clip = (s, max) => s.length > max ? `${s.slice(0, max)}\n[...truncated]` : s;
|
|
29
39
|
const STOP_RE = /^\s*(stop|dừng)/i, REDIRECT_RE = /^\s*(redirect|đổi hướng)[:\s]\s*/i;
|
|
@@ -102,9 +112,143 @@ export function parseCheckpoint(text) {
|
|
|
102
112
|
const dispatch = d.split('\n').filter(l => !/^[ \t>*_#-]*(CONSULT[ \t]+\S+|CHECKPOINT)\b/i.test(l)).join('\n').trim();
|
|
103
113
|
return { decision, dispatch, reason, consults };
|
|
104
114
|
}
|
|
105
|
-
|
|
115
|
+
const FIND_RE = /^[ \t>*_-]*FINDING[ \t]*(?:[\[(]?[ \t]*(critical|high|medium|low|info)[ \t]*[\])]?)?[ \t]*[:\-–][ \t]*(.+)$/gim;
|
|
116
|
+
const listOf = (text, label) => [...text.matchAll(new RegExp(`^[ \\t>*_-]*(?:${label})[ \\t]*\\**[ \\t]*:\\**[ \\t]*(.+)$`, 'gim'))].map(m => oneLine(m[1], 400)).slice(0, 20);
|
|
117
|
+
const NOTHING_RE = /^\(?(nothing|none|n\/a|no open (questions|items|issues))\.?\)?$/i;
|
|
118
|
+
/** Deterministic AgentContribution content from an agent message (FINDING/RISK/RECOMMEND/PROPOSE/EVIDENCE/QUESTION lines + the handoff OPEN section). A failed QC verdict without a high finding adds one. Never throws. */
|
|
119
|
+
export function contributionFrom(text, verdictFail = false) {
|
|
120
|
+
const findings = [...text.matchAll(FIND_RE)].slice(0, 50).map(m => {
|
|
121
|
+
const raw = m[2].trim(), loc = /\s*(?:\[at ([^\]]+)\]|\bat ([^\s\]]*[/.:][^\s\]]*))\s*$/.exec(raw);
|
|
122
|
+
return { summary: oneLine(loc ? raw.slice(0, loc.index) : raw, 400), severity: (m[1] ?? 'medium').toLowerCase(), ...(loc ? { location: oneLine((loc[1] ?? loc[2]), 200) } : {}) };
|
|
123
|
+
});
|
|
124
|
+
if (verdictFail && !findings.some(f => f.severity === 'critical' || f.severity === 'high'))
|
|
125
|
+
findings.push({ summary: oneLine(text.split('\n').find(l => l.trim() && !/VERDICT/i.test(l)) ?? 'the review failed', 300), severity: 'high' });
|
|
126
|
+
const sec = parseHandoff(text), open = sec && !NOTHING_RE.test(sec.OPEN.trim()) ? [oneLine(sec.OPEN, 600)] : [];
|
|
127
|
+
return { findings, recommendations: listOf(text, 'RECOMMEND(?:ATION)?S?'), risks: listOf(text, 'RISK'), proposedDecisions: listOf(text, 'PROPOSE(?:D DECISION)?'), evidenceRefs: listOf(text, 'EVIDENCE'), unresolvedQuestions: [...listOf(text, 'QUESTION'), ...open].slice(0, 20), status: 'complete' };
|
|
128
|
+
}
|
|
129
|
+
const SEV_RANK = { critical: 4, high: 3, medium: 2, low: 1, info: 0 };
|
|
130
|
+
const normKey = (t) => t.toLowerCase().replace(/[^\p{L}\p{N} ]/gu, ' ').replace(/\s+/g, ' ').trim();
|
|
131
|
+
/** PF-BOARD reducer (research 8.5): latest revision per agent+task only, superseded dropped; findings with the same requirement + location + normalized summary merge (highest severity, all agents kept). Deterministic: input order independent, sorted by severity then key. */
|
|
132
|
+
export function mergeFindings(cs) {
|
|
133
|
+
const latest = new Map();
|
|
134
|
+
for (const c of cs) {
|
|
135
|
+
if (c.status === 'superseded')
|
|
136
|
+
continue;
|
|
137
|
+
const k = `${c.agentId} ${c.taskId}`, p = latest.get(k);
|
|
138
|
+
if (!p || (c.revision ?? 0) >= (p.revision ?? 0))
|
|
139
|
+
latest.set(k, c);
|
|
140
|
+
}
|
|
141
|
+
const out = new Map();
|
|
142
|
+
for (const c of latest.values())
|
|
143
|
+
for (const f of c.findings) {
|
|
144
|
+
const key = `${normKey(f.requirement ?? '')}|${normKey(f.location ?? '')}|${normKey(f.summary)}`;
|
|
145
|
+
const m = out.get(key), rank = `${c.agentId}\u0000${f.summary}\u0000${f.location ?? ''}\u0000${f.requirement ?? ''}`;
|
|
146
|
+
if (!m) {
|
|
147
|
+
out.set(key, { key, summary: f.summary, severity: f.severity, ...(f.location ? { location: f.location } : {}), ...(f.requirement ? { requirement: f.requirement } : {}), agents: new Set([c.agentId]), ids: [f.id], rep: { sev: SEV_RANK[f.severity], rank } });
|
|
148
|
+
continue;
|
|
149
|
+
}
|
|
150
|
+
m.agents.add(c.agentId);
|
|
151
|
+
m.ids.push(f.id);
|
|
152
|
+
if (SEV_RANK[f.severity] > SEV_RANK[m.severity])
|
|
153
|
+
m.severity = f.severity;
|
|
154
|
+
// representative wording/location: the most severe report, ties broken by agent id then text (never by arrival order)
|
|
155
|
+
if (SEV_RANK[f.severity] > m.rep.sev || (SEV_RANK[f.severity] === m.rep.sev && rank < m.rep.rank)) {
|
|
156
|
+
m.rep = { sev: SEV_RANK[f.severity], rank };
|
|
157
|
+
m.summary = f.summary;
|
|
158
|
+
if (f.location)
|
|
159
|
+
m.location = f.location;
|
|
160
|
+
else
|
|
161
|
+
delete m.location;
|
|
162
|
+
if (f.requirement)
|
|
163
|
+
m.requirement = f.requirement;
|
|
164
|
+
else
|
|
165
|
+
delete m.requirement;
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
return [...out.values()].map(m => ({ key: m.key, summary: m.summary, severity: m.severity, ...(m.location ? { location: m.location } : {}), ...(m.requirement ? { requirement: m.requirement } : {}), agents: [...m.agents].sort(), findingIds: [...m.ids].sort() }))
|
|
169
|
+
.sort((a, b) => SEV_RANK[b.severity] - SEV_RANK[a.severity] || (a.key < b.key ? -1 : a.key > b.key ? 1 : 0));
|
|
170
|
+
}
|
|
171
|
+
/** Streaming redaction (review item 5): returns the redacted text that is safe to emit now and the raw tail to keep.
|
|
172
|
+
* The tail (at least `overlap` chars, cut at whitespace) is held back so a secret split across chunks is redacted as a whole; the prefix is emitted
|
|
173
|
+
* only when redacting the whole buffer ends exactly with the redacted tail (no match spans the cut). `final` = the turn ended: emit everything. */
|
|
174
|
+
export function splitRedacted(pending, redact, overlap, final) {
|
|
175
|
+
if (final)
|
|
176
|
+
return { emit: redact(pending), keep: '' };
|
|
177
|
+
for (let lim = pending.length - overlap; lim > 0;) {
|
|
178
|
+
let cut = lim;
|
|
179
|
+
while (cut > 0 && !/\s/.test(pending[cut - 1]))
|
|
180
|
+
cut--;
|
|
181
|
+
if (cut <= 0)
|
|
182
|
+
break;
|
|
183
|
+
const all = redact(pending), tail = redact(pending.slice(cut));
|
|
184
|
+
if (all.endsWith(tail))
|
|
185
|
+
return { emit: all.slice(0, all.length - tail.length), keep: pending.slice(cut) };
|
|
186
|
+
lim = cut - 1; // a match spans this cut: try an earlier whitespace
|
|
187
|
+
}
|
|
188
|
+
return { emit: '', keep: pending };
|
|
189
|
+
}
|
|
190
|
+
const URGENT_RE = /(^|[^\p{L}])(urgent|asap|immediately|khẩn|gấp|ngay lập tức)([^\p{L}]|$)/iu;
|
|
191
|
+
const MODE_RE = /^[ \t>*_#-]*MODE[ \t]*\**[ \t]*:\**[ \t]*\**[ \t]*(DIRECT|DELEGATE|PARALLEL[ _-]?MERGE|PARALLEL[ _-]?EXECUTE|TARGETED[ _-]?DISCUSSION)\b[^\n]*$/im;
|
|
192
|
+
const READ_ONLY_RE = /(?<![\p{L}])read[ -]?only(?![\p{L}])|(?<![\p{L}])(?:review|analy[sz]e|analysis|explain|inspect) only(?![\p{L}])|(?<![\p{L}])(?:do not|don't|dont|never|without) (?:change|changing|modify|modifying|edit|editing|touch|touching|write|writing)(?![\p{L}])[^.\n]{0,20}(?<![\p{L}])(?:files?|code|anything|the repo|the project)(?![\p{L}])|(?<![\p{L}])no (?:code |file )?changes(?![\p{L}])|chỉ đọc|không (?:được )?(?:sửa|thay đổi|chỉnh sửa)/giu;
|
|
193
|
+
/** A request to change something (EN + VI): a goal that asks for it is never read-only, whatever scope words it also contains. */
|
|
194
|
+
const CHANGE_RE = /(?<![\p{L}])(?:fix|implement|add|change|modify|edit|update|create|write|refactor|rename|delete|remove|build|patch|apply|install|sửa|thêm|đổi|thay đổi|tạo|xóa|xoá|viết|cài)(?![\p{L}])/iu;
|
|
195
|
+
/** PF-MODES: the owner asked for a read-only result (question, analysis, review) - no team may change files.
|
|
196
|
+
* The scope phrase must open the goal (first 25 chars) and the rest of the goal (after removing the scope phrases and [bracket tags]) must not ask for a change. */
|
|
197
|
+
export const isReadOnlyGoal = (goal) => {
|
|
198
|
+
const g = goal.replace(/\[[^\]]*\]/g, ' ').trim(), first = [...g.matchAll(READ_ONLY_RE)][0];
|
|
199
|
+
if (!first || (first.index ?? 0) > 25)
|
|
200
|
+
return false;
|
|
201
|
+
return !CHANGE_RE.test(g.replace(READ_ONLY_RE, ' '));
|
|
202
|
+
};
|
|
203
|
+
/** The Director's "TEAMS: a, b" line: the configured teams it activates (lowercased ids), or null when absent. */
|
|
204
|
+
export function parseTeams(text) {
|
|
205
|
+
const m = /^[ \t>*_#-]*TEAMS[ \t]*\**[ \t]*:\**[ \t]*(.*)$/im.exec(text);
|
|
206
|
+
if (!m)
|
|
207
|
+
return null;
|
|
208
|
+
return m[1].replace(/[*`"'_]/g, ' ').split(/[,;\s]+/).map(x => x.trim().toLowerCase()).filter(Boolean);
|
|
209
|
+
}
|
|
210
|
+
/** PF-PROG / PARALLEL_EXECUTE: the Director's "DEPENDS: implement <- ba; test <- ba; qc <- implement, test" line -> team -> its dependencies (lowercased), or null when absent. "x <- none" = no dependency. */
|
|
211
|
+
export function parseDepends(text) {
|
|
212
|
+
const m = /^[ \t>*_#-]*DEPENDS[ \t]*\**[ \t]*:\**[ \t]*(.*)$/im.exec(text);
|
|
213
|
+
if (!m)
|
|
214
|
+
return null;
|
|
215
|
+
const out = new Map();
|
|
216
|
+
for (const part of m[1].replace(/[*`"']/g, '').split(';')) {
|
|
217
|
+
const [lhs, rhs] = part.split(/<-|←|\bafter\b/i);
|
|
218
|
+
const id = lhs?.trim().toLowerCase();
|
|
219
|
+
if (!id || rhs === undefined)
|
|
220
|
+
continue;
|
|
221
|
+
out.set(id, rhs.split(/[,\s]+/).map(x => x.trim().toLowerCase()).filter(x => x && x !== 'none' && x !== '-'));
|
|
222
|
+
}
|
|
223
|
+
return out.size ? out : null;
|
|
224
|
+
}
|
|
225
|
+
/** Owner order + the Director's DEPENDS -> a safe task graph: a team may only depend on teams before it in the owner order (acyclic, owner order kept);
|
|
226
|
+
* a team the Director did not mention depends on the team right before it; QC depends on every team before it that nothing else depends on (it verifies the whole result). */
|
|
227
|
+
export function buildGraph(order, deps) {
|
|
228
|
+
const g = new Map();
|
|
229
|
+
order.forEach((id, k) => {
|
|
230
|
+
const said = deps?.get(id);
|
|
231
|
+
g.set(id, said ? [...new Set(said.filter(d => order.indexOf(d) >= 0 && order.indexOf(d) < k))] : k > 0 ? [order[k - 1]] : []);
|
|
232
|
+
});
|
|
233
|
+
const qk = order.indexOf('qc');
|
|
234
|
+
if (qk > 0) {
|
|
235
|
+
const before = order.slice(0, qk), used = new Set(before.flatMap(id => g.get(id) ?? []));
|
|
236
|
+
g.set('qc', [...new Set([...(g.get('qc') ?? []), ...before.filter(id => !used.has(id))])].sort((a, b) => order.indexOf(a) - order.indexOf(b)));
|
|
237
|
+
}
|
|
238
|
+
return g;
|
|
239
|
+
}
|
|
240
|
+
/** The Director's collaboration mode line (PF-MODES), or null when absent. */
|
|
241
|
+
export function parseMode(text) {
|
|
242
|
+
const m = MODE_RE.exec(text);
|
|
243
|
+
if (!m)
|
|
244
|
+
return null;
|
|
245
|
+
const mode = m[1].toUpperCase().replace(/[ -]/g, '_').replace(/^PARALLEL(?=[A-Z])/, 'PARALLEL_').replace(/^TARGETED(?=[A-Z])/, 'TARGETED_');
|
|
246
|
+
const reason = /^[ \t>*_#-]*MODE REASON\**[ \t]*:\**[ \t]*(.+)$/im.exec(text)?.[1]?.trim() ?? '';
|
|
247
|
+
return { mode, reason: oneLine(reason, 300) };
|
|
248
|
+
}
|
|
249
|
+
function makeHandle(runId, runDir, history, listeners, done, sendToDirector, stop, extras = {}) {
|
|
106
250
|
return {
|
|
107
|
-
runId, runDir, done, sendToDirector, stop, ...
|
|
251
|
+
runId, runDir, done, sendToDirector, stop, ...extras,
|
|
108
252
|
subscribe(listener) {
|
|
109
253
|
for (const e of [...history]) {
|
|
110
254
|
try {
|
|
@@ -127,11 +271,14 @@ export function startTeamRun(opts) {
|
|
|
127
271
|
const inbox = [], notes = [], convo = [];
|
|
128
272
|
const lanes = config.lanes ?? [], ownerLane = lanes.find(l => l.id === opts.lane) ?? null;
|
|
129
273
|
let order = ownerLane ? [...ownerLane.order] : lanes.length ? [...lanes[0].order] : effectiveOrder(config); // with lanes: the chosen lane's teams (set at intake)
|
|
274
|
+
let earlyTest = null; // PF-TEST / PF-PROG: the Tester team's early test plan, written while Implement works
|
|
130
275
|
const outs = new Map(); // flow order; each team's latest output
|
|
131
276
|
const passes = new Map(), sentBack = new Map(), asks = new Map(), backs = new Map();
|
|
277
|
+
const retReasons = new Map(); // per team: its pending RETURN TO PREVIOUS reason (per team, so concurrent PARALLEL_EXECUTE nodes never see each other's)
|
|
278
|
+
let graph = null; // PARALLEL_EXECUTE task graph: team -> the teams it depends on (null = the linear owner-order flow)
|
|
132
279
|
const limit = config.limits.qcLoops; // max send-backs per team boundary, and as many ask-backs
|
|
133
280
|
const briefs = new Map(); // team id -> the Director's section for that team
|
|
134
|
-
let assumptions = '', laneNote = '',
|
|
281
|
+
let assumptions = '', laneNote = '', finished = false, handoff = '', qcReport = '', qcPassed = false, deliverable = '', resolveDone, intakeBrief = '', intakeIntro = '';
|
|
135
282
|
const done = new Promise(r => { resolveDone = r; });
|
|
136
283
|
// Owner attachments: stored once in the run folder, then named in every agent prompt (Director, BA, Implement, QC) and in the BA handoff.
|
|
137
284
|
const atts = [], excerpts = new Map();
|
|
@@ -185,11 +332,119 @@ export function startTeamRun(opts) {
|
|
|
185
332
|
emit({ type: 'run.completed', outcome, report }); // emitted while !finished (guard allows run.completed anyway)
|
|
186
333
|
finished = true;
|
|
187
334
|
closeSessions();
|
|
335
|
+
try {
|
|
336
|
+
hub?.close();
|
|
337
|
+
}
|
|
338
|
+
catch { /* already closed */ }
|
|
339
|
+
hub = null;
|
|
340
|
+
paused = false;
|
|
341
|
+
wakeAll();
|
|
342
|
+
wakeNow?.();
|
|
188
343
|
journal.writeArtifact('report.md', report);
|
|
189
344
|
resolveDone(outcome);
|
|
190
345
|
};
|
|
191
346
|
const halted = () => { if (finished)
|
|
192
347
|
throw new Halt(); };
|
|
348
|
+
/** Live-only event (never journaled): deltas, native tool calls. */
|
|
349
|
+
const liveEmit = (ev) => {
|
|
350
|
+
if (finished)
|
|
351
|
+
return;
|
|
352
|
+
const e = { seq: history.length ? history[history.length - 1].seq : 0, at: new Date().toISOString(), runId: journal.runId, ...ev };
|
|
353
|
+
for (const l of [...listeners]) {
|
|
354
|
+
try {
|
|
355
|
+
l(e);
|
|
356
|
+
}
|
|
357
|
+
catch { /* ignore */ }
|
|
358
|
+
}
|
|
359
|
+
};
|
|
360
|
+
// ---- PF-WAIT: why an agent is not producing output (journaled on change only; heartbeats are never progress) ----
|
|
361
|
+
const waits = new Map();
|
|
362
|
+
const setWait = (agentId, reason, detail) => { if (waits.get(agentId) === reason)
|
|
363
|
+
return; waits.set(agentId, reason); emit({ type: 'agent.wait', agentId, reason, ...(detail ? { detail: oneLine(detail, 160) } : {}) }); };
|
|
364
|
+
// ---- B8 owner pause / resume / interrupt ----
|
|
365
|
+
let paused = false, resumeWaiters = [];
|
|
366
|
+
const wakeAll = () => { const w = resumeWaiters; resumeWaiters = []; for (const f of w)
|
|
367
|
+
f(); };
|
|
368
|
+
const gate = async (agentId) => { while (paused && !finished) {
|
|
369
|
+
setWait(agentId, 'paused');
|
|
370
|
+
await new Promise(r => resumeWaiters.push(r));
|
|
371
|
+
} halted(); };
|
|
372
|
+
const turnCtl = new Map(), interrupted = new Set();
|
|
373
|
+
// ---- PF-CONTRIB / PF-BOARD: typed contributions and decision records (deterministic core; the Director decides semantics) ----
|
|
374
|
+
let goalRevision = 0, cSeq = 0;
|
|
375
|
+
const contribs = [], contribSigs = new Set(), decisionRevs = new Map();
|
|
376
|
+
const curTask = new Map(); // team id -> its running task id
|
|
377
|
+
const createdTasks = new Set(); // task ids already announced (graph mode announces every node up front as pending)
|
|
378
|
+
let criticalSince = false, wakeNow = null; // PF-WAKE: a critical finding arrived since the Director last woke (bypasses the coalescing window)
|
|
379
|
+
const contribRevs = new Map(), lastTokens = new Map();
|
|
380
|
+
/** Turn context captured when an agent turn starts: its goal revision and task. A contribution is stamped with these, never with the values at publish time. */
|
|
381
|
+
const turnCtx = new Map();
|
|
382
|
+
/** `rev` = the goal revision the agent's turn started under; older than the current one = the contribution is stale (status superseded, ignored by the board). */
|
|
383
|
+
const publish = (agentId, c, taskId, runtimeStatus = 'ok', rev = goalRevision) => {
|
|
384
|
+
const stale = rev < goalRevision;
|
|
385
|
+
const sig = JSON.stringify([agentId, taskId, rev, c]);
|
|
386
|
+
if (contribSigs.has(sig))
|
|
387
|
+
return null; // exact duplicate: dropped
|
|
388
|
+
contribSigs.add(sig);
|
|
389
|
+
const now = new Date().toISOString(), id = ++cSeq, rk = `${agentId} ${taskId}`, revision = (contribRevs.get(rk) ?? 0) + 1;
|
|
390
|
+
contribRevs.set(rk, revision);
|
|
391
|
+
const findings = c.findings.map((f, i) => ({ ...f, id: `f-${id}-${i + 1}` }));
|
|
392
|
+
const team = allAgentsOf(config).find(a => a.id === agentId)?.team ?? 'agent';
|
|
393
|
+
const k = { contributionId: `c-${id}`, runId: journal.runId, agentId, taskId, goalRevision: rev, status: stale ? 'superseded' : c.status, findings, recommendations: c.recommendations, risks: c.risks, proposedDecisions: c.proposedDecisions, evidenceRefs: c.evidenceRefs, unresolvedQuestions: c.unresolvedQuestions, createdAt: now, updatedAt: now,
|
|
394
|
+
ns: `${team}/${agentId}`, revision, runtimeStatus, usage: { tokens: lastTokens.get(agentId) ?? null } };
|
|
395
|
+
contribs.push(k);
|
|
396
|
+
if (!stale && findings.some(f => f.severity === 'critical')) {
|
|
397
|
+
criticalSince = true;
|
|
398
|
+
wakeNow?.();
|
|
399
|
+
}
|
|
400
|
+
emit({ type: 'contribution.published', contribution: k });
|
|
401
|
+
return k;
|
|
402
|
+
};
|
|
403
|
+
const record = (id, d) => {
|
|
404
|
+
const revision = (decisionRevs.get(id) ?? 0) + 1;
|
|
405
|
+
decisionRevs.set(id, revision);
|
|
406
|
+
emit({ type: 'decision.recorded', decision: { id, runId: journal.runId, goalRevision, title: oneLine(d.title, 200), requirements: [], contributions: d.contributions ?? [], selected: oneLine(d.selected, 600), rejected: d.rejected ?? [], evidence: d.evidence ?? [], rationale: oneLine(d.rationale, 600), affectedTasks: d.affectedTasks ?? [], requiredVerification: d.requiredVerification ?? [], authority: d.authority ?? 'director', status: d.status, revision } });
|
|
407
|
+
};
|
|
408
|
+
const highIn = (cs) => cs.some(c => c.findings.some(f => f.severity === 'critical' || f.severity === 'high'));
|
|
409
|
+
// ---- PF-LOOP: a repeated send-back / question / rejection without new evidence is stopped ----
|
|
410
|
+
const lastBack = new Map(), stalls = new Map();
|
|
411
|
+
const LOOP_STALL_MAX = 2;
|
|
412
|
+
const norm = (t) => oneLine(t, 600).toLowerCase().replace(/[^\p{L}\p{N} ]/gu, '').replace(/\s+/g, ' ').trim();
|
|
413
|
+
/** Progress ledger (research 8.4): the same normalized reason again = no new evidence -> stall +1; at LOOP_STALL_MAX the exchange is stopped. */
|
|
414
|
+
const repeated = (key, reason) => {
|
|
415
|
+
const v = norm(reason), prev = lastBack.get(key);
|
|
416
|
+
lastBack.set(key, v);
|
|
417
|
+
const n = prev !== undefined && prev === v && v.length > 0 ? (stalls.get(key) ?? 0) + 1 : 0;
|
|
418
|
+
stalls.set(key, n);
|
|
419
|
+
return n >= LOOP_STALL_MAX;
|
|
420
|
+
};
|
|
421
|
+
// ---- B6 A2A bus (always) + CKit MCP tool hub (real native sessions only) ----
|
|
422
|
+
let lastInboxAt = 0;
|
|
423
|
+
let collabMode = 'PARALLEL_MERGE', delegateTo = null;
|
|
424
|
+
const agentIds = new Set(allAgentsOf(config).map(a => a.id));
|
|
425
|
+
let dirLock = Promise.resolve();
|
|
426
|
+
const bus = createRunBus({
|
|
427
|
+
runId: journal.runId, emit: ev => emit(ev), redact: t => journal.redact(t),
|
|
428
|
+
isAddress: id => id === 'all' || id === 'director' || agentIds.has(id) || id === 'ba' || id === 'implement' || id === 'qc' || !!extraOf(id),
|
|
429
|
+
teamOf: aid => allAgentsOf(config).find(a => a.id === aid)?.team ?? null,
|
|
430
|
+
onAsk: async (from, question) => {
|
|
431
|
+
if (finished)
|
|
432
|
+
return 'The run has finished.';
|
|
433
|
+
const asker = allAgentsOf(config).find(a => a.id === from);
|
|
434
|
+
emit({ type: 'flow.back', kind: 'ask', from: asker?.team ?? from, to: 'director', reason: oneLine(question, 300) });
|
|
435
|
+
if (!modelDirector())
|
|
436
|
+
return `Use your brief: ${clip(briefOf(asker?.team ?? '') || intakeIntro || goal, 1500)}`;
|
|
437
|
+
const t = await directorAsk(`answer ${asker?.name ?? from}`, `${role(config.director, 'An agent asks you a blocking question through the CKit tools. Answer in one short message; decide on evidence. Do not change any file.', true)}\n${common()}\nQUESTION from ${asker?.name ?? from}: ${question}`, 'clarification');
|
|
438
|
+
return t?.trim() ? directorSay(from, t) : 'The Director could not answer; state your assumption and continue.';
|
|
439
|
+
},
|
|
440
|
+
onProgress: (aid, text) => emit({ type: 'agent.activity', agentId: aid, text: oneLine(text, 160) }),
|
|
441
|
+
onContribution: (aid, c) => {
|
|
442
|
+
const ctx = turnCtx.get(aid), team = allAgentsOf(config).find(a => a.id === aid)?.team ?? '';
|
|
443
|
+
publish(aid, c, ctx?.taskId || curTask.get(team) || `t-${team || 'agent'}-adhoc`, 'ok', ctx?.rev ?? goalRevision);
|
|
444
|
+
},
|
|
445
|
+
});
|
|
446
|
+
let hub = null;
|
|
447
|
+
const toolsOn = opts.tools ?? (!simulated && !opts.runner && !opts.openSession && sessionsEnabled() && process.env['CKIT_MCP'] !== '0');
|
|
193
448
|
// ---- prompts ----
|
|
194
449
|
const header = (agent, stage, loop, turn = 1, turns = 1, final = false) => simulated || agent.cli === 'simulated' ? `${simHeader({ stage, loop, turn, turns, final })}\n` : '';
|
|
195
450
|
const recent = (n = 8) => convo.slice(-n).map(c => `${c.who}: ${clip(c.text, 1500)}`).join('\n\n') || '(nothing yet)';
|
|
@@ -198,7 +453,9 @@ export function startTeamRun(opts) {
|
|
|
198
453
|
: '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.';
|
|
199
454
|
const extraOf = (id) => config.extraTeams?.find(t => t.id === id);
|
|
200
455
|
const teamName = (id) => id === 'director' ? 'Director' : extraOf(id)?.name ?? (id === 'ba' ? 'BA' : id === 'implement' ? 'Implement' : id === 'qc' ? 'QC' : id);
|
|
201
|
-
const prevId = (k) => k <= 0 ? 'director' : order[k - 1];
|
|
456
|
+
const prevId = (k) => k <= 0 ? 'director' : graph ? graph.get(order[k])?.[0] ?? 'director' : order[k - 1];
|
|
457
|
+
/** A security review team: the default "security" team, or any team named Security. Its critical findings block Delivery. */
|
|
458
|
+
const isSecurityTeam = (id) => id === 'security' || /\bsecurity\b/i.test(extraOf(id)?.name ?? '');
|
|
202
459
|
const agentsOf = (id) => id === 'ba' || id === 'implement' || id === 'qc' ? config.teams[id] : extraOf(id)?.agents ?? [];
|
|
203
460
|
const teamLabel = (agent) => teamName(agent.team).toUpperCase();
|
|
204
461
|
const missionOf = (teamId) => extraOf(teamId)?.mission ?? config.missions?.[teamId] ?? DEFAULT_MISSIONS[teamId] ?? '';
|
|
@@ -215,7 +472,8 @@ export function startTeamRun(opts) {
|
|
|
215
472
|
};
|
|
216
473
|
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` : '';
|
|
217
474
|
const WORKER_NOTE = 'You run inside CKit as a worker process: ignore any message from host hooks, completion gates or status checks of the CLI tool itself (they are not your task and not from the owner); never answer about them - just do what this prompt asks.';
|
|
218
|
-
const
|
|
475
|
+
const toolsNote = (agent) => hub && agent.team !== 'director' ? '\nCKit tools (MCP server "ckit") are available: ckit_publish_contribution (publish findings as soon as you have them), ckit_report_progress, ckit_send_message / ckit_read_inbox (talk to another agent directly), ckit_ask_director (blocking question). Use them when useful; your final message is still your result.' : '';
|
|
476
|
+
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.\n${WORKER_NOTE}${toolsNote(agent)}`;
|
|
219
477
|
/** Pulls the flow markers out of an agent message (first of each, anywhere in the text, optional bullet/bold). Never throws. */
|
|
220
478
|
const markers = (text) => {
|
|
221
479
|
let ask = null, ret = null;
|
|
@@ -246,43 +504,81 @@ export function startTeamRun(opts) {
|
|
|
246
504
|
// ---- persistent sessions: one per agent per run, created lazily, closed when the run ends ----
|
|
247
505
|
const useSessions = !simulated && (opts.openSession !== undefined || (!opts.runner && sessionsEnabled()));
|
|
248
506
|
const sessions = new Map(), running = new Map();
|
|
249
|
-
|
|
507
|
+
/** R2-5: open persistent sessions are live CLI processes. Per scheduler (process-wide) we track them and keep their number within the cap: opening one while
|
|
508
|
+
* `cap` are open first closes an idle one (any run). A busy session holds a slot, so with this turn's slot held an idle one always exists. */
|
|
509
|
+
const myEntries = new Map();
|
|
510
|
+
/** A read-only turn of a write agent (early test plan, Director consult) gets its own session: a session's sandbox is fixed at spawn. */
|
|
511
|
+
const sessKey = (agent) => { const base = allAgentsOf(config).find(a => a.id === agent.id); return base && base.access === 'write' && agent.access === 'read' ? `${agent.id}#ro` : agent.id; };
|
|
512
|
+
const sessionFor = (agent, slotHeld = false) => {
|
|
250
513
|
if (!useSessions || simAgent(agent) || agent.cli === 'api' || agent.cli === 'auto')
|
|
251
514
|
return null;
|
|
252
|
-
|
|
515
|
+
const sk = sessKey(agent);
|
|
516
|
+
let s = sessions.get(sk);
|
|
253
517
|
if (!s) {
|
|
518
|
+
const tools = hub && agent.team !== 'director' ? { mcp: hub.mcpServer(agent.id), specs: bus.toolSpecs(), call: (n, a) => bus.callTool(agent.id, n, a) } : null; // the Director gets no bus tools (it would wait on itself)
|
|
519
|
+
const reg = scheduler && slotHeld ? sessionRegistry(scheduler) : null;
|
|
520
|
+
if (reg)
|
|
521
|
+
for (const e of [...reg]) {
|
|
522
|
+
if (reg.size < scheduler.cap)
|
|
523
|
+
break;
|
|
524
|
+
if (!e.busy) {
|
|
525
|
+
reg.delete(e);
|
|
526
|
+
e.evict();
|
|
527
|
+
}
|
|
528
|
+
}
|
|
254
529
|
try {
|
|
255
|
-
s = (opts.openSession ?? defaultOpenSession)(agent, { cwd: opts.projectRoot });
|
|
530
|
+
s = (opts.openSession ?? defaultOpenSession)(agent, { cwd: opts.projectRoot, ...(tools ? { tools } : {}) });
|
|
256
531
|
}
|
|
257
532
|
catch {
|
|
258
533
|
return null;
|
|
259
534
|
}
|
|
260
|
-
sessions.set(
|
|
535
|
+
sessions.set(sk, s);
|
|
536
|
+
if (reg) {
|
|
537
|
+
const ent = { busy: false, evict: () => { if (sessions.get(sk) === s)
|
|
538
|
+
sessions.delete(sk); myEntries.delete(sk); closeOne(s); } };
|
|
539
|
+
reg.add(ent);
|
|
540
|
+
myEntries.set(sk, ent);
|
|
541
|
+
}
|
|
261
542
|
}
|
|
262
543
|
return s;
|
|
263
544
|
};
|
|
264
|
-
const
|
|
265
|
-
|
|
545
|
+
const unregister = (sk) => { const e = myEntries.get(sk); if (e && scheduler)
|
|
546
|
+
sessionRegistry(scheduler).delete(e); myEntries.delete(sk); };
|
|
547
|
+
const exits = []; // every session close: whenClosed waits for all owned processes to exit
|
|
548
|
+
const closeOne = (s) => { if (!s)
|
|
549
|
+
return; try {
|
|
550
|
+
const r = s.close();
|
|
551
|
+
if (r)
|
|
552
|
+
exits.push(r.catch(() => undefined));
|
|
266
553
|
}
|
|
267
554
|
catch { /* already gone */ } };
|
|
268
|
-
const
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
}
|
|
272
|
-
catch { /* already gone */ }
|
|
273
|
-
} sessions.clear(); running.clear(); };
|
|
555
|
+
const dropSession = (agent) => { const s = sessions.get(sessKey(agent)); unregister(sessKey(agent)); sessions.delete(sessKey(agent)); running.delete(agent.id); closeOne(s); };
|
|
556
|
+
const closeSessions = () => { for (const k of [...myEntries.keys()])
|
|
557
|
+
unregister(k); for (const s of sessions.values())
|
|
558
|
+
closeOne(s); sessions.clear(); running.clear(); };
|
|
274
559
|
/** Live-only partial text (never written to events.jsonl: too chatty). Coalesced to ~250 ms per agent. */
|
|
275
560
|
const deltaBuf = new Map();
|
|
276
|
-
const
|
|
561
|
+
const OVERLAP = Math.max(256, ...known.map(k => k.length + 8)); // held-back tail: longer than any known secret
|
|
562
|
+
/** final = the turn ended (emit the held-back tail too); otherwise only the part that cannot be the start of a split secret. */
|
|
563
|
+
const flushDelta = (agentId, final = true) => {
|
|
277
564
|
const b = deltaBuf.get(agentId);
|
|
278
565
|
if (!b)
|
|
279
566
|
return;
|
|
280
|
-
if (b.timer)
|
|
567
|
+
if (b.timer) {
|
|
281
568
|
clearTimeout(b.timer);
|
|
282
|
-
|
|
283
|
-
|
|
569
|
+
b.timer = null;
|
|
570
|
+
}
|
|
571
|
+
if (finished) {
|
|
572
|
+
deltaBuf.delete(agentId);
|
|
573
|
+
return;
|
|
574
|
+
}
|
|
575
|
+
const { emit: text, keep } = splitRedacted(b.text, t => journal.redact(t), OVERLAP, final);
|
|
576
|
+
b.text = keep;
|
|
577
|
+
if (!keep)
|
|
578
|
+
deltaBuf.delete(agentId);
|
|
579
|
+
if (!text)
|
|
284
580
|
return;
|
|
285
|
-
const e = { seq: history.length ? history[history.length - 1].seq : 0, at: new Date().toISOString(), runId: journal.runId, type: 'agent.delta', agentId, text
|
|
581
|
+
const e = { seq: history.length ? history[history.length - 1].seq : 0, at: new Date().toISOString(), runId: journal.runId, type: 'agent.delta', agentId, text };
|
|
286
582
|
for (const l of [...listeners]) {
|
|
287
583
|
try {
|
|
288
584
|
l(e);
|
|
@@ -298,7 +594,7 @@ export function startTeamRun(opts) {
|
|
|
298
594
|
}
|
|
299
595
|
b.text += text;
|
|
300
596
|
if (!b.timer) {
|
|
301
|
-
b.timer = setTimeout(() => flushDelta(agentId), 250);
|
|
597
|
+
b.timer = setTimeout(() => flushDelta(agentId, false), 250);
|
|
302
598
|
b.timer.unref?.();
|
|
303
599
|
}
|
|
304
600
|
};
|
|
@@ -322,13 +618,29 @@ export function startTeamRun(opts) {
|
|
|
322
618
|
const logPath = (agent) => `.ckit/team/runs/${journal.runId}/agents/${agent.id}.log`;
|
|
323
619
|
/** Runs one agent turn through the runner, wiring activity/step/subagent events. Never throws. */
|
|
324
620
|
const lease = opts.lease ?? workspaceLeaseFor(opts.projectRoot), startedMs = Date.now();
|
|
621
|
+
const scheduler = opts.scheduler !== undefined ? opts.scheduler : simulated ? null : globalAgentScheduler();
|
|
325
622
|
/** Write turns hold the workspace lease (FIFO across runs); every turn is told when other runs changed files meanwhile. */
|
|
326
|
-
|
|
623
|
+
const ctxBudget = () => { const v = Number(process.env['CKIT_CTX_MAX_CHARS']); return Number.isFinite(v) && v >= 4000 ? v : 200000; };
|
|
624
|
+
let ctxSeq = 0;
|
|
625
|
+
/** B9: a prompt over the context budget keeps its head (role, goal, brief, handoff) and its newest tail; the middle (older history) is cut and the full prompt saved as an artifact. */
|
|
626
|
+
const fitContext = (agent, prompt) => {
|
|
627
|
+
const max = ctxBudget();
|
|
628
|
+
if (prompt.length <= max)
|
|
629
|
+
return prompt;
|
|
630
|
+
const art = journal.writeArtifact(`context/${agent.id}-${++ctxSeq}.md`, prompt), head = Math.floor(max * 0.55), tail = Math.floor(max * 0.4);
|
|
631
|
+
const out = `${prompt.slice(0, head)}\n\n[... CKit compacted ${prompt.length - head - tail} characters of older context here; the full prompt is in ${art} ...]\n\n${prompt.slice(prompt.length - tail)}`;
|
|
632
|
+
emit({ type: 'context.compacted', agentId: agent.id, before: prompt.length, after: out.length, artifact: art });
|
|
633
|
+
return out;
|
|
634
|
+
};
|
|
635
|
+
async function callRunner(agent, prompt, first, last, noLease = false, signal) {
|
|
327
636
|
let release = null, waitedNoted = false;
|
|
328
|
-
if (
|
|
637
|
+
if (signal?.aborted)
|
|
638
|
+
return { ok: false, reason: 'cancelled' };
|
|
639
|
+
if (agent.access === 'write' && !noLease) {
|
|
329
640
|
try {
|
|
330
|
-
release = await lease.acquire(journal.runId, agent.id, abort.signal, h => { if (!waitedNoted) {
|
|
641
|
+
release = await lease.acquire(journal.runId, agent.id, signal ? AbortSignal.any([abort.signal, signal]) : abort.signal, h => { if (!waitedNoted) {
|
|
331
642
|
waitedNoted = true;
|
|
643
|
+
setWait(agent.id, 'waiting-resource', `waiting resource: workspace held by run ${h.runId} (${h.agentId})`);
|
|
332
644
|
emit({ type: 'agent.activity', agentId: agent.id, text: oneLine(`Waiting for the workspace: run ${h.runId} (${h.agentId}) is changing files`, 160) });
|
|
333
645
|
} });
|
|
334
646
|
}
|
|
@@ -336,15 +648,30 @@ export function startTeamRun(opts) {
|
|
|
336
648
|
return { ok: false, reason: 'cancelled' };
|
|
337
649
|
}
|
|
338
650
|
}
|
|
651
|
+
// PF-RES-SCHED: team agents take a global process slot (after the lease, never before: no lock-order inversion). The Director is exempt: an agent
|
|
652
|
+
// holding a slot can block on ckit_ask_director, so a counted Director could deadlock a full scheduler. One Director per run keeps this bounded.
|
|
653
|
+
let slot = null;
|
|
654
|
+
if (scheduler && agent.team !== 'director') {
|
|
655
|
+
try {
|
|
656
|
+
slot = await scheduler.acquire(journal.runId, agent.id, signal ? AbortSignal.any([abort.signal, signal]) : abort.signal, st => setWait(agent.id, 'waiting-resource', `waiting resource: ${st.running}/${st.cap} agent processes busy, ${st.queued} queued`));
|
|
657
|
+
}
|
|
658
|
+
catch {
|
|
659
|
+
release?.();
|
|
660
|
+
setWait(agent.id, 'idle');
|
|
661
|
+
return { ok: false, reason: 'cancelled' };
|
|
662
|
+
}
|
|
663
|
+
}
|
|
339
664
|
try {
|
|
340
665
|
const others = lease.othersSince(journal.runId, startedMs);
|
|
341
|
-
return await callRunnerLeased(agent, others.length ? `${otherRunsNote(others)}\n\n${prompt}` : prompt, first, last);
|
|
666
|
+
return await callRunnerLeased(agent, fitContext(agent, others.length ? `${otherRunsNote(others)}\n\n${prompt}` : prompt), first, last, signal);
|
|
342
667
|
}
|
|
343
668
|
finally {
|
|
669
|
+
slot?.();
|
|
344
670
|
release?.();
|
|
671
|
+
setWait(agent.id, 'idle');
|
|
345
672
|
}
|
|
346
673
|
}
|
|
347
|
-
async function callRunnerLeased(agent, prompt, first, last) {
|
|
674
|
+
async function callRunnerLeased(agent, prompt, first, last, signal) {
|
|
348
675
|
const t0 = Date.now(), stamp = () => new Date().toISOString();
|
|
349
676
|
agentLog(agent, `===== ${stamp()} agent ${agent.id} (${agent.name}) =====\ncli: ${agent.cli}\nmodel: ${agent.model ?? '(default)'}\naccess: ${agent.access}\ntask: ${first}\n----- PROMPT -----\n${prompt}\n----- EVENTS -----\n`);
|
|
350
677
|
const done = (res) => {
|
|
@@ -363,12 +690,21 @@ export function startTeamRun(opts) {
|
|
|
363
690
|
const own = simAgent(agent);
|
|
364
691
|
if (!own)
|
|
365
692
|
step(first);
|
|
693
|
+
const ctl = new AbortController(), onAbort = () => ctl.abort();
|
|
694
|
+
abort.signal.addEventListener('abort', onAbort, { once: true });
|
|
695
|
+
signal?.addEventListener('abort', onAbort, { once: true }); // the pass this turn belongs to was cancelled (a sibling redirected/halted)
|
|
696
|
+
if (signal?.aborted)
|
|
697
|
+
ctl.abort();
|
|
698
|
+
turnCtl.set(agent.id, ctl);
|
|
699
|
+
setWait(agent.id, 'waiting-first-output');
|
|
700
|
+
const firstOut = () => { if (waits.get(agent.id) === 'waiting-first-output')
|
|
701
|
+
setWait(agent.id, 'generating'); };
|
|
366
702
|
try {
|
|
367
703
|
const raw = rawSink(agent);
|
|
368
704
|
const runOpts = {
|
|
369
|
-
cwd: opts.projectRoot, timeoutMs: config.limits.agentTimeoutMs, signal:
|
|
705
|
+
cwd: opts.projectRoot, timeoutMs: config.limits.agentTimeoutMs, signal: ctl.signal, ...(atts.length ? { images: images() } : {}),
|
|
370
706
|
onRaw: (stream, line) => raw(`[${stamp()}] ${stream}: ${line.endsWith('\n') ? line : `${line}\n`}`),
|
|
371
|
-
onActivity: text => { agentLog(agent, `[${stamp()}] activity: ${oneLine(text, 400)}\n`); emit({ type: 'agent.activity', agentId: agent.id, text: oneLine(text, 160) }); const l = own ? null : stepOf(text); if (l)
|
|
707
|
+
onActivity: text => { firstOut(); agentLog(agent, `[${stamp()}] activity: ${oneLine(text, 400)}\n`); emit({ type: 'agent.activity', agentId: agent.id, text: oneLine(text, 160) }); const l = own ? null : stepOf(text); if (l)
|
|
372
708
|
step(l); },
|
|
373
709
|
onStep: (label, k, total) => step(oneLine(label, 80), k, total),
|
|
374
710
|
onSubagent: e => {
|
|
@@ -378,20 +714,26 @@ export function startTeamRun(opts) {
|
|
|
378
714
|
: { type: 'subagent.finished', agentId: agent.id, childId: e.childId, ok: e.ok, summary: oneLine(e.summary, 200) });
|
|
379
715
|
},
|
|
380
716
|
};
|
|
381
|
-
const sess = sessionFor(agent);
|
|
717
|
+
const sess = sessionFor(agent, scheduler !== null && agent.team !== 'director' ? true : false);
|
|
382
718
|
let res;
|
|
383
719
|
if (!sess)
|
|
384
720
|
res = await runner(agent, prompt, runOpts);
|
|
385
721
|
else {
|
|
386
722
|
running.set(agent.id, sess);
|
|
723
|
+
const ent = myEntries.get(sessKey(agent));
|
|
724
|
+
if (ent)
|
|
725
|
+
ent.busy = true;
|
|
387
726
|
try {
|
|
388
|
-
res = await sess.send(prompt, { ...runOpts, onDelta: t => pushDelta(agent.id, t) }
|
|
727
|
+
res = await sess.send(prompt, { ...runOpts, onDelta: t => { firstOut(); pushDelta(agent.id, t); }, onFirstOutput: firstOut,
|
|
728
|
+
onTool: (phase, name, text) => { firstOut(); setWait(agent.id, phase === 'call' ? 'executing-tool' : 'generating', phase === 'call' ? name : undefined); liveEmit({ type: 'agent.tool', agentId: agent.id, phase, name: oneLine(name, 80), text: oneLine(journal.redact(text), phase === 'call' ? 300 : 400) }); } }); // redact the whole text first, then shorten
|
|
389
729
|
}
|
|
390
730
|
finally {
|
|
391
731
|
flushDelta(agent.id);
|
|
392
732
|
running.delete(agent.id);
|
|
733
|
+
if (ent)
|
|
734
|
+
ent.busy = false;
|
|
393
735
|
}
|
|
394
|
-
if (!res.ok && res.transport && !abort.signal.aborted) {
|
|
736
|
+
if (!res.ok && res.transport && !abort.signal.aborted && !ctl.signal.aborted) {
|
|
395
737
|
dropSession(agent);
|
|
396
738
|
runOpts.onActivity?.(`Persistent session failed (${oneLine(res.reason, 100)}); retrying this turn with a fresh one-shot process`);
|
|
397
739
|
res = await runner(agent, prompt, runOpts);
|
|
@@ -404,18 +746,53 @@ export function startTeamRun(opts) {
|
|
|
404
746
|
catch (e) {
|
|
405
747
|
return done({ ok: false, reason: withArgsNote(agent, e instanceof Error ? e.message : 'runner threw') });
|
|
406
748
|
}
|
|
749
|
+
finally {
|
|
750
|
+
abort.signal.removeEventListener('abort', onAbort);
|
|
751
|
+
signal?.removeEventListener('abort', onAbort);
|
|
752
|
+
if (turnCtl.get(agent.id) === ctl)
|
|
753
|
+
turnCtl.delete(agent.id);
|
|
754
|
+
}
|
|
407
755
|
}
|
|
408
|
-
|
|
756
|
+
/** PF-CALLS turn class of a team turn. */
|
|
757
|
+
const classOf = (agent, phase = '') => agent.team === 'director' ? 'director-synthesis' : phase === 'discuss' ? 'discussion' : phase === 'clarify' ? 'clarification' : sentBack.has(agent.team) ? 'retry' : agent.team === 'implement' ? 'implementation' : agent.team === 'qc' ? 'review' : agent.team === 'ba' ? 'research' : agent.team === 'test' ? 'test' : 'execution';
|
|
758
|
+
/** One agent turn with the pause gate, unread mail delivered in the prompt, and redo after an owner interrupt. */
|
|
759
|
+
async function runTurn(agent, task, prompt, first, last, o = {}) {
|
|
760
|
+
let p = prompt;
|
|
761
|
+
for (;;) {
|
|
762
|
+
await gate(agent.id);
|
|
763
|
+
const mail = bus.unread(agent.id);
|
|
764
|
+
if (mail.length) {
|
|
765
|
+
bus.markRead(agent.id, mail.map(m => m.mailId), 'prompt');
|
|
766
|
+
p += `\n\nMESSAGES FOR YOU (CKit mail, oldest first):\n${mail.map(m => `- from ${m.from}${m.kind !== 'mail' ? ` (${m.kind})` : ''}: ${m.subject}: ${clip(m.text, 2000)}`).join('\n')}`;
|
|
767
|
+
}
|
|
768
|
+
const taskId = o.taskId ?? curTask.get(agent.team);
|
|
769
|
+
turnCtx.set(agent.id, { rev: goalRevision, taskId: taskId ?? '' });
|
|
770
|
+
setWait(agent.id, 'starting');
|
|
771
|
+
emit({ type: 'agent.started', agentId: agent.id, task, turnClass: o.cls ?? classOf(agent), ...(taskId && agent.team !== 'director' ? { taskId } : {}) });
|
|
772
|
+
const res = await callRunner(agent, p, first, last, o.noLease === true, o.signal);
|
|
773
|
+
halted();
|
|
774
|
+
if (res.ok)
|
|
775
|
+
interrupted.delete(agent.id); // an interrupt the turn finished through anyway must not redo a later, unrelated failure
|
|
776
|
+
if (!res.ok && interrupted.delete(agent.id)) {
|
|
777
|
+
emit({ type: 'agent.interrupted', agentId: agent.id });
|
|
778
|
+
await gate(agent.id);
|
|
779
|
+
const guidance = [...inbox, ...notes.slice(-3)];
|
|
780
|
+
p = `${prompt}\n\nYOUR PREVIOUS ATTEMPT AT THIS TURN WAS INTERRUPTED BY THE OWNER. Start this turn again${guidance.length ? ` and follow the owner's newest guidance:\n${guidance.map(g => `- ${clip(g, 1500)}`).join('\n')}` : '.'}`;
|
|
781
|
+
continue;
|
|
782
|
+
}
|
|
783
|
+
return res;
|
|
784
|
+
}
|
|
785
|
+
}
|
|
786
|
+
async function turn(agent, task, to, prompt, o = {}) {
|
|
409
787
|
halted();
|
|
410
|
-
emit({ type: 'agent.started', agentId: agent.id, task });
|
|
411
788
|
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'];
|
|
412
|
-
const res = await
|
|
413
|
-
halted();
|
|
789
|
+
const res = await runTurn(agent, task, prompt, labels[0], labels[1], o);
|
|
414
790
|
if (!res.ok) {
|
|
415
791
|
emit({ type: 'agent.failed', agentId: agent.id, reason: res.reason });
|
|
416
792
|
return null;
|
|
417
793
|
}
|
|
418
|
-
|
|
794
|
+
lastTokens.set(agent.id, res.tokens);
|
|
795
|
+
emit({ type: 'agent.message', agentId: agent.id, to, text: res.text, tokens: res.tokens, ...(o.round ? { round: o.round } : {}) });
|
|
419
796
|
const safe = journal.redact(res.text);
|
|
420
797
|
convo.push({ who: agent.name, text: safe });
|
|
421
798
|
return safe;
|
|
@@ -427,15 +804,24 @@ export function startTeamRun(opts) {
|
|
|
427
804
|
};
|
|
428
805
|
// ---- director ----
|
|
429
806
|
const modelDirector = () => !simulated && config.director.cli !== 'auto' && config.director.cli !== 'simulated';
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
const
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
807
|
+
/** One Director model turn. Director turns are serialized (one persistent session), e.g. a bus question while a checkpoint runs. */
|
|
808
|
+
async function directorAsk(task, prompt, cls = 'director-synthesis') {
|
|
809
|
+
const prev = dirLock;
|
|
810
|
+
let release;
|
|
811
|
+
dirLock = new Promise(r => { release = r; });
|
|
812
|
+
try {
|
|
813
|
+
await prev;
|
|
814
|
+
halted();
|
|
815
|
+
const res = await runTurn(config.director, task, prompt, 'Reading the request', 'Writing the answer', { cls });
|
|
816
|
+
if (!res.ok) {
|
|
817
|
+
emit({ type: 'agent.failed', agentId: config.director.id, reason: res.reason });
|
|
818
|
+
return null;
|
|
819
|
+
}
|
|
820
|
+
return res.text;
|
|
821
|
+
}
|
|
822
|
+
finally {
|
|
823
|
+
release();
|
|
437
824
|
}
|
|
438
|
-
return res.text;
|
|
439
825
|
}
|
|
440
826
|
function directorSay(to, text, tokens = null) {
|
|
441
827
|
emit({ type: 'agent.message', agentId: config.director.id, to, text, tokens });
|
|
@@ -472,7 +858,7 @@ export function startTeamRun(opts) {
|
|
|
472
858
|
if (modelDirector()) {
|
|
473
859
|
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` : '';
|
|
474
860
|
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.' : '';
|
|
475
|
-
const ask = () => 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}`);
|
|
861
|
+
const ask = () => 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.\nOn PROCEED also add a line "MODE: <mode>" and a line "MODE REASON: <one sentence>". Modes: DIRECT = you answer it yourself right now (a question answerable from the request, the project files or a small lookup): put the complete answer for the owner in your reply and write no team sections; DELEGATE <agent id> = one best-fit agent does it alone (single-scope investigation or small fix); PARALLEL_MERGE = several agents give independent views at the same time and their team leads merge (options, reviews, risk); PARALLEL_EXECUTE = multi-part implementation through the teams. Never activate an agent just because it is configured; choose the cheapest mode that is good enough.\nWith DELEGATE, PARALLEL_MERGE, PARALLEL_EXECUTE or TARGETED_DISCUSSION also add a line "TEAMS: <team ids, comma separated>" naming ONLY the teams that must run (the pipeline order is kept); every other team is skipped. A read-only goal (a question, analysis or review where no file may change) activates no team with a write agent and no Test or QC team: those exist to change and verify files.\nWith PARALLEL_EXECUTE also add a line "DEPENDS: <team> <- <team>, <team>; <team> <- none; ..." saying which teams need which other teams' results first; teams with no dependency between them run at the same time (a team may only depend on teams earlier in the pipeline order; writes to the workspace are still serialized by CKit).${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}`);
|
|
476
862
|
for (let attempt = 0; attempt < 2; attempt++) {
|
|
477
863
|
const t = await ask();
|
|
478
864
|
if (t?.trim())
|
|
@@ -493,8 +879,93 @@ export function startTeamRun(opts) {
|
|
|
493
879
|
const m = /\[lane:([a-z0-9-]+)\]/i.exec(goal), l = lanes.find(x => x.id === m?.[1]?.toLowerCase()) ?? lanes[0];
|
|
494
880
|
return `DECISION: PROCEED\nLANE: ${l.id}\nLANE REASON: (simulated) ${m ? 'the goal names this lane' : 'first lane'}`;
|
|
495
881
|
}
|
|
496
|
-
|
|
882
|
+
const st = /\[sim-teams:([a-z0-9,-]+)\]/i.exec(goal), sx = /\[sim-execute(?::([^\]]*))?\]/i.exec(goal);
|
|
883
|
+
const stl = (st ? `\nTEAMS: ${st[1]}` : '') + (sx ? `\nMODE: PARALLEL_EXECUTE\nMODE REASON: (simulated) independent parts run as a task graph${sx[1] ? `\nDEPENDS: ${sx[1]}` : ''}` : '');
|
|
884
|
+
const sm = stl + (/\[sim-targeted\]/i.test(goal) ? '\nMODE: TARGETED_DISCUSSION\nMODE REASON: (simulated) a real trade-off to settle' : /\[sim-direct\]/i.test(goal) ? '\nMODE: DIRECT\nMODE REASON: (simulated) answerable without the teams\n(simulated) Direct answer from the Director: done.' : /\[sim-delegate:([a-z0-9-]+)\]/i.exec(goal) ? `\nMODE: DELEGATE ${/\[sim-delegate:([a-z0-9-]+)\]/i.exec(goal)[1]}\nMODE REASON: (simulated) one agent is enough` : '');
|
|
885
|
+
if (sm.includes('DIRECT'))
|
|
886
|
+
return `DECISION: PROCEED${sm}`;
|
|
887
|
+
return lanes.length ? `DECISION: PROCEED${sm}` : `DECISION: PROCEED${sm}\n${ruleBrief()}`;
|
|
497
888
|
}
|
|
889
|
+
/** PF-MODES: DIRECT = no team runs; DELEGATE = only the named agent's team, with only that agent; otherwise the flow (default PARALLEL_MERGE). Recorded as a decision. */
|
|
890
|
+
const chooseMode = (text) => {
|
|
891
|
+
const m = parseMode(text), before = [...order], why = new Map();
|
|
892
|
+
let mode = !order.length ? 'DIRECT' : m?.mode ?? 'PARALLEL_MERGE', reason = !order.length ? 'no team in this flow' : m?.reason || (m ? '' : 'default: no MODE line');
|
|
893
|
+
if (mode === 'DELEGATE') {
|
|
894
|
+
const id = /DELEGATE[ \t]*[:\-]?[ \t]*["'`*]*([A-Za-z0-9_-]+)/i.exec(MODE_RE.exec(text)?.[0] ?? '')?.[1]?.toLowerCase();
|
|
895
|
+
const a = allAgentsOf(config).find(x => x.id === id && x.team !== 'director' && order.includes(x.team));
|
|
896
|
+
if (a) {
|
|
897
|
+
delegateTo = a;
|
|
898
|
+
order = [a.team];
|
|
899
|
+
reason = `${a.name}: ${reason}`;
|
|
900
|
+
}
|
|
901
|
+
else {
|
|
902
|
+
mode = 'PARALLEL_MERGE';
|
|
903
|
+
reason = `DELEGATE named no agent of this flow (${id ?? 'none'}); fell back to PARALLEL_MERGE`;
|
|
904
|
+
}
|
|
905
|
+
}
|
|
906
|
+
if (mode === 'DIRECT') {
|
|
907
|
+
for (const t of order)
|
|
908
|
+
why.set(t, 'DIRECT: the Director answers the owner itself');
|
|
909
|
+
order = [];
|
|
910
|
+
}
|
|
911
|
+
else if (delegateTo) {
|
|
912
|
+
for (const t of before)
|
|
913
|
+
if (t !== delegateTo.team)
|
|
914
|
+
why.set(t, `DELEGATE: only ${delegateTo.name} works on this goal`);
|
|
915
|
+
}
|
|
916
|
+
else {
|
|
917
|
+
const want = parseTeams(text)?.filter(t => order.includes(t));
|
|
918
|
+
if (want?.length) {
|
|
919
|
+
for (const t of order)
|
|
920
|
+
if (!want.includes(t))
|
|
921
|
+
why.set(t, `the Director did not activate this team (TEAMS: ${want.join(', ')})`);
|
|
922
|
+
order = order.filter(t => want.includes(t));
|
|
923
|
+
}
|
|
924
|
+
}
|
|
925
|
+
const writes = (t) => delegateTo?.team === t ? delegateTo.access === 'write' : agentsOf(t).some(a => a.access === 'write');
|
|
926
|
+
if (isReadOnlyGoal(goal) && order.length) {
|
|
927
|
+
// Core guard, independent of the model: a read-only goal never runs a team that writes files, tests or verifies changes - and never falls back to one.
|
|
928
|
+
const drop = (t) => delegateTo?.team === t && delegateTo.access !== 'write' ? null : t === 'qc' || t === 'test' ? 'read-only goal: nothing changes, so there is nothing to test or verify' : isSecurityTeam(t) ? 'read-only goal: no code changes, so there is no change to security-review' : writes(t) ? 'read-only goal: this team has a write agent and no file may change' : null;
|
|
929
|
+
for (const t of order) {
|
|
930
|
+
const r = drop(t);
|
|
931
|
+
if (r)
|
|
932
|
+
why.set(t, r);
|
|
933
|
+
}
|
|
934
|
+
order = order.filter(t => drop(t) === null);
|
|
935
|
+
if (!order.length) {
|
|
936
|
+
mode = 'DIRECT';
|
|
937
|
+
delegateTo = null;
|
|
938
|
+
reason = 'read-only goal and no read-only team in this flow: the Director answers it itself';
|
|
939
|
+
}
|
|
940
|
+
}
|
|
941
|
+
else if (mode !== 'DIRECT' && order.some(writes)) {
|
|
942
|
+
// Core rule: a flow that can change files always gets its Security review and QC, in owner order, whatever mode or TEAMS line the Director chose.
|
|
943
|
+
const forced = before.filter(t => !order.includes(t) && (isSecurityTeam(t) || t === 'qc') && agentsOf(t).length > 0);
|
|
944
|
+
if (forced.length) {
|
|
945
|
+
order = before.filter(t => order.includes(t) || forced.includes(t));
|
|
946
|
+
for (const t of forced)
|
|
947
|
+
why.delete(t);
|
|
948
|
+
reason = `${reason ? `${reason}; ` : ''}Core rule added ${forced.map(teamName).join(', ')} because this flow changes files`;
|
|
949
|
+
}
|
|
950
|
+
}
|
|
951
|
+
if (mode === 'DIRECT') {
|
|
952
|
+
for (const t of before)
|
|
953
|
+
if (!order.includes(t) || order.length === 0)
|
|
954
|
+
why.set(t, why.get(t) ?? 'DIRECT: the Director answers the owner itself');
|
|
955
|
+
order = [];
|
|
956
|
+
}
|
|
957
|
+
collabMode = mode;
|
|
958
|
+
graph = mode === 'PARALLEL_EXECUTE' && order.length > 1 ? buildGraph(order, parseDepends(text)) : null;
|
|
959
|
+
emit({ type: 'mode.chosen', mode, reason: oneLine(reason, 300) });
|
|
960
|
+
for (const t of before)
|
|
961
|
+
if (!order.includes(t))
|
|
962
|
+
emit({ type: 'team.skipped', team: t, reason: oneLine(why.get(t) ?? 'not needed for this goal', 300) });
|
|
963
|
+
record('d-mode', { title: 'Collaboration mode', selected: mode, status: 'committed', rationale: reason || mode, affectedTasks: [...order] });
|
|
964
|
+
if (graph)
|
|
965
|
+
record('d-graph', { title: 'Task graph', selected: [...graph].map(([t, d]) => `${t} <- ${d.join(', ') || 'none'}`).join('; '), status: 'committed', rationale: 'PARALLEL_EXECUTE: teams without a dependency between them run at the same time', affectedTasks: [...order] });
|
|
966
|
+
if (order.length < before.length)
|
|
967
|
+
record('d-teams', { title: 'Teams activated', selected: order.join(', ') || 'none (Director only)', status: 'committed', rationale: before.filter(t => !order.includes(t)).map(t => `${teamName(t)} skipped: ${why.get(t) ?? 'not needed'}`).join('; '), rejected: before.filter(t => !order.includes(t)) });
|
|
968
|
+
};
|
|
498
969
|
const parseLane = (text) => {
|
|
499
970
|
const m = /^[ \t>*_#-]*LANE[ \t]*\**[ \t]*:\**[ \t]*(.+)$/im.exec(text);
|
|
500
971
|
const v = (m?.[1] ?? '').replace(/[*`"'_]/g, '').trim().toLowerCase();
|
|
@@ -553,7 +1024,9 @@ export function startTeamRun(opts) {
|
|
|
553
1024
|
if (modelDirector() && !parseBriefs(body).size)
|
|
554
1025
|
body = `${body}\n\n${ruleBrief()}`;
|
|
555
1026
|
}
|
|
556
|
-
|
|
1027
|
+
chooseMode(text);
|
|
1028
|
+
body = body.split('\n').filter(l => !/^[ \t>*_#-]*(MODE( REASON)?|TEAMS|DEPENDS)\**[ \t]*:/i.test(l)).join('\n').trim();
|
|
1029
|
+
intakeBrief = directorSay(order[0] ?? 'all', body || (collabMode === 'DIRECT' ? '(the Director gave no answer text)' : ruleBrief()));
|
|
557
1030
|
break;
|
|
558
1031
|
}
|
|
559
1032
|
briefs.clear();
|
|
@@ -578,9 +1051,24 @@ export function startTeamRun(opts) {
|
|
|
578
1051
|
}
|
|
579
1052
|
return ruleDecision(text);
|
|
580
1053
|
}
|
|
1054
|
+
/** PF-WAKE window sleep: cut short by an urgent owner message, a critical finding or the run ending. */
|
|
1055
|
+
const wakeSleep = (ms) => new Promise(r => {
|
|
1056
|
+
const t = setTimeout(() => { wakeNow = null; r(); }, ms);
|
|
1057
|
+
wakeNow = () => { clearTimeout(t); wakeNow = null; r(); };
|
|
1058
|
+
});
|
|
581
1059
|
/** Processes owner messages between agent turns. Throws Redirect / Halt. */
|
|
582
1060
|
async function drain() {
|
|
583
1061
|
let redirect = false;
|
|
1062
|
+
if (inbox.length && modelDirector()) { // PF-WAKE coalescing: messages that arrive within the window share one Director turn (STOP never waits: it is handled on arrival)
|
|
1063
|
+
const win = Number(process.env['CKIT_WAKE_WINDOW_MS'] ?? 1500), left = lastInboxAt + (Number.isFinite(win) ? Math.max(0, win) : 1500) - Date.now();
|
|
1064
|
+
const bypass = criticalSince || inbox.some(t => URGENT_RE.test(t)); // urgent steer / critical finding: wake now (STOP is handled on arrival)
|
|
1065
|
+
if (left > 0 && !bypass)
|
|
1066
|
+
await wakeSleep(left);
|
|
1067
|
+
halted();
|
|
1068
|
+
criticalSince = false;
|
|
1069
|
+
if (inbox.length > 1)
|
|
1070
|
+
inbox.splice(0, inbox.length, inbox.join('\n\n'));
|
|
1071
|
+
}
|
|
584
1072
|
while (inbox.length) {
|
|
585
1073
|
const text = inbox.shift();
|
|
586
1074
|
const d = await decide(text);
|
|
@@ -591,6 +1079,8 @@ export function startTeamRun(opts) {
|
|
|
591
1079
|
throw new Halt();
|
|
592
1080
|
}
|
|
593
1081
|
notes.push(d.note);
|
|
1082
|
+
goalRevision++;
|
|
1083
|
+
record('d-owner', { title: 'Owner instruction', selected: d.decision, status: 'committed', authority: 'owner', rationale: d.note });
|
|
594
1084
|
if (d.decision === 'redirect')
|
|
595
1085
|
redirect = true;
|
|
596
1086
|
}
|
|
@@ -606,7 +1096,7 @@ export function startTeamRun(opts) {
|
|
|
606
1096
|
finish('stopped', `Run stopped. ${why}\n\nGoal: ${goal}\n${handoff ? `\nLast handoff: handoff-ba.md\n` : ''}`);
|
|
607
1097
|
}
|
|
608
1098
|
const nextOf = (k) => order[k + 1] ?? 'director';
|
|
609
|
-
const backOf = () => { const r =
|
|
1099
|
+
const backOf = (id) => { const r = retReasons.get(id) ?? null; retReasons.delete(id); return r === null ? null : { full: r, short: oneLine(r, 300) }; };
|
|
610
1100
|
const handoffs = new Map(); // per team: its latest handoff in short form (for the trail)
|
|
611
1101
|
const cap = (s, n) => { const t = oneLine(s, 100000); return t.length > n ? `${t.slice(0, n - 1)}... (shortened)` : t; };
|
|
612
1102
|
/** Compact trail of the handoffs of the first `upTo` teams: DONE and OPEN only, capped, explicitly marked as shortened. */
|
|
@@ -616,18 +1106,46 @@ export function startTeamRun(opts) {
|
|
|
616
1106
|
};
|
|
617
1107
|
const hdr = (agent, stage, loop, turn, turns, phase, round) => simAgent(agent) ? `${simHeader({ stage, loop, turn, turns, final: phase === 'handoff' || phase === 'single', phase, round })}\n` : '';
|
|
618
1108
|
const hdrS = (agent, stage, loop) => simAgent(agent) ? `${simHeader({ stage, loop, turn: 1, turns: 1, final: true })}\n` : '';
|
|
1109
|
+
const earlyPlans = new Map();
|
|
1110
|
+
/** PF-TEST: once the contract (the team right before Implement) is accepted, a later Tester team starts deriving test scenarios in parallel with Implement, read-only. It blocks nothing; only the Tester's own pass waits for it. */
|
|
1111
|
+
const startEarlyTest = (k) => {
|
|
1112
|
+
if (earlyTest || graph || collabMode === 'DIRECT' || collabMode === 'DELEGATE' || process.env['CKIT_EARLY_TEST'] === '0')
|
|
1113
|
+
return;
|
|
1114
|
+
const impl = order.indexOf('implement'), tid = order.find((x, i) => i > impl && x !== 'qc' && /\btesters?\b/i.test(teamName(x))); // a team named "Tester" (the default Tester team)
|
|
1115
|
+
if (impl < 0 || k !== impl - 1 || !tid)
|
|
1116
|
+
return;
|
|
1117
|
+
const agents = agentsOf(tid);
|
|
1118
|
+
if (!agents.length)
|
|
1119
|
+
return;
|
|
1120
|
+
const taskId = `t-${tid}-early`, dep = curTask.get(order[k]);
|
|
1121
|
+
emit({ type: 'task.created', taskId, team: tid, title: `${teamName(tid)} early test plan`, deps: dep ? [dep] : [] });
|
|
1122
|
+
emit({ type: 'task.updated', taskId, status: 'running', note: 'parallel with Implement' });
|
|
1123
|
+
const contract = clip(outs.get(order[k]) ?? '', 8000), rev = goalRevision, ctl = new AbortController();
|
|
1124
|
+
const p = Promise.all(agents.map(a => {
|
|
1125
|
+
const ro = { ...a, access: 'read' }; // never competes with the writer for the workspace
|
|
1126
|
+
return turn(ro, `${teamName(tid)} early test plan`, tid, `${hdr(ro, 'extra-team', 1, 1, 1, 'contribute', 1)}${role(ro, `EARLY TEST DESIGN (in parallel with the implementation, which is not done yet). From the contract below derive the test scenarios you will run later: one per line as "FINDING [severity]: <scenario / risk> [at <requirement or file>]". ${a.access === 'write' ? 'Focus on acceptance-criteria and contract tests.' : 'Focus on edge cases, invalid input, regressions and security.'} Do not change any file yet.`, true)}\n${common()}\nCONTRACT (handoff of the ${teamName(order[k])} team):\n${contract}\n`, { cls: 'test', noLease: true, taskId, signal: ctl.signal })
|
|
1127
|
+
.then(t => { if (t && !ctl.signal.aborted)
|
|
1128
|
+
publish(a.id, contributionFrom(t), taskId, 'ok', rev); return t && !ctl.signal.aborted ? `[${a.name}]: ${clip(t, 3000)}` : ''; })
|
|
1129
|
+
.catch(() => '');
|
|
1130
|
+
})).then(xs => { const plan = xs.filter(Boolean).join('\n\n'); emit({ type: 'task.updated', taskId, status: ctl.signal.aborted ? 'failed' : plan ? 'done' : 'failed', ...(ctl.signal.aborted ? { note: 'cancelled: the flow restarted' } : {}) }); return plan; });
|
|
1131
|
+
earlyTest = { id: tid, taskId, p, ctl };
|
|
1132
|
+
};
|
|
619
1133
|
const dispatches = new Map(); // Director's dispatch text per team (model Director only)
|
|
620
1134
|
const dirBacks = new Map(); // Director send-backs per team at a checkpoint
|
|
621
1135
|
const inputBlock = (k, id) => {
|
|
622
|
-
const
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
1136
|
+
const parts = [];
|
|
1137
|
+
for (const p of graph ? graph.get(id) ?? [] : [prevId(k)])
|
|
1138
|
+
if (p !== 'director')
|
|
1139
|
+
parts.push(`HANDOFF FROM THE ${teamName(p).toUpperCase()} TEAM (in full):\n${clip(outs.get(p) ?? '', 8000)}`);
|
|
1140
|
+
const trail = graph ? '' : trailBlock(k - 1);
|
|
626
1141
|
if (trail)
|
|
627
1142
|
parts.push(trail.trimEnd());
|
|
628
1143
|
const dp = dispatches.get(id);
|
|
629
1144
|
if (dp)
|
|
630
1145
|
parts.push(`DIRECTOR'S DISPATCH FOR YOUR TEAM:\n${clip(dp, 3000)}`);
|
|
1146
|
+
const et = earlyPlans.get(id);
|
|
1147
|
+
if (et)
|
|
1148
|
+
parts.push(`EARLY TEST PLAN (your team wrote it in parallel with the implementation, from the contract only; now verify it against the real change):\n${clip(et, 6000)}`);
|
|
631
1149
|
const sb = sentBack.get(id);
|
|
632
1150
|
if (sb)
|
|
633
1151
|
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)}`);
|
|
@@ -667,19 +1185,23 @@ export function startTeamRun(opts) {
|
|
|
667
1185
|
return t ?? '(the previous team could not answer)';
|
|
668
1186
|
}
|
|
669
1187
|
/** 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. */
|
|
670
|
-
async function teamTurn(k, agent, task, to, prompt,
|
|
1188
|
+
async function teamTurn(k, agent, task, to, prompt, o = {}) {
|
|
671
1189
|
let extra = '';
|
|
672
1190
|
for (;;) {
|
|
673
|
-
const text = await turn(agent, task, to, prompt + extra,
|
|
1191
|
+
const text = await turn(agent, task, to, prompt + extra, o);
|
|
674
1192
|
if (text === null)
|
|
675
1193
|
return null;
|
|
676
1194
|
const m = markers(text);
|
|
677
1195
|
if (m.ret !== null) {
|
|
678
|
-
|
|
1196
|
+
retReasons.set(order[k] ?? agent.team, m.ret || 'no reason given');
|
|
679
1197
|
return m.clean;
|
|
680
1198
|
}
|
|
681
1199
|
if (m.ask === null || (asks.get(k) ?? 0) >= limit)
|
|
682
1200
|
return m.clean;
|
|
1201
|
+
if (repeated(`ask:${agent.id}`, m.ask)) {
|
|
1202
|
+
emit({ type: 'loop.detected', kind: 'ask', from: agent.team, reason: oneLine(`the same question again without new evidence: ${m.ask}`, 300) });
|
|
1203
|
+
return m.clean;
|
|
1204
|
+
}
|
|
683
1205
|
asks.set(k, (asks.get(k) ?? 0) + 1);
|
|
684
1206
|
const answer = await askPrevious(k, agent, m.ask || 'please clarify');
|
|
685
1207
|
await drain();
|
|
@@ -694,113 +1216,212 @@ export function startTeamRun(opts) {
|
|
|
694
1216
|
const to = nextOf(k), toName = to === 'director' ? 'Director' : teamName(to);
|
|
695
1217
|
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:".' : ''}`;
|
|
696
1218
|
};
|
|
1219
|
+
/** Parallel members of one pass share an AbortController: when one rejects (Redirect / Halt) the siblings are cancelled (so none keeps the write lease)
|
|
1220
|
+
* and every member has settled before the first rejection is rethrown. */
|
|
1221
|
+
async function parallelAll(start) {
|
|
1222
|
+
const ctl = new AbortController();
|
|
1223
|
+
const ps = start(ctl.signal).map(p => p.catch((e) => { ctl.abort(); throw e; }));
|
|
1224
|
+
const rs = await Promise.allSettled(ps);
|
|
1225
|
+
const bad = rs.find((r) => r.status === 'rejected');
|
|
1226
|
+
if (bad)
|
|
1227
|
+
throw bad.reason;
|
|
1228
|
+
return rs.map(r => r.value);
|
|
1229
|
+
}
|
|
697
1230
|
/** 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. */
|
|
698
|
-
async function teamPass(k, id, pass) {
|
|
1231
|
+
async function teamPass(k, id, pass, nodeSig) {
|
|
699
1232
|
const agents = agentsOf(id), lead = agents[0], name = teamName(id), isQc = id === 'qc', to = nextOf(k), toName = to === 'director' ? 'Director' : teamName(to);
|
|
700
1233
|
const stageName = id === 'ba' ? 'ba-discussion' : id === 'implement' || id === 'qc' ? id : 'extra-team';
|
|
701
1234
|
emit({ type: 'stage.changed', stage: stageName, loop: pass, ...(stageName === 'extra-team' ? { team: id } : {}) });
|
|
702
|
-
const
|
|
1235
|
+
const rounds = config.limits.baRounds, active = delegateTo && delegateTo.team === id ? [delegateTo] : agents, multi = active.length > 1;
|
|
1236
|
+
const parallel = multi && (rounds === 0 || collabMode === 'PARALLEL_MERGE' && rounds === 0);
|
|
703
1237
|
const writer = isQc ? undefined : agents.find(a => a.access === 'write'); // QC reviews; it never changes files
|
|
704
|
-
const turns = !multi ? 1 : agents.length * rounds + (writer ? 1 : 0) + (writer === lead ? 0 : 1);
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
if (!isQc)
|
|
712
|
-
return fail(agent, `the ${name} stage`);
|
|
713
|
-
const f = history.filter(e => e.type === 'agent.failed').at(-1); // a QC reviewer that cannot run counts as FAIL
|
|
714
|
-
verdicts.set(agent.id, 'FAIL');
|
|
715
|
-
failNote = `QC agent could not run: ${f && f.type === 'agent.failed' ? f.reason : 'unknown'}`;
|
|
716
|
-
return '';
|
|
717
|
-
}
|
|
718
|
-
lastMsg.set(agent.id, text);
|
|
719
|
-
if (isQc && /VERDICT/i.test(text))
|
|
720
|
-
verdicts.set(agent.id, parseVerdict(text));
|
|
721
|
-
await drain();
|
|
722
|
-
return text;
|
|
723
|
-
};
|
|
724
|
-
const early = () => retReason !== null;
|
|
725
|
-
const returnedEarly = () => {
|
|
726
|
-
if (!early())
|
|
727
|
-
return null;
|
|
728
|
-
if (isQc) {
|
|
729
|
-
qcReturn = retReason;
|
|
730
|
-
retReason = null;
|
|
731
|
-
return null;
|
|
732
|
-
}
|
|
733
|
-
return { out: [...lastMsg.values()].at(-1) ?? '', back: backOf() };
|
|
734
|
-
};
|
|
735
|
-
if (!multi) {
|
|
736
|
-
raw = await run(lead, 'single', 1, `${workWhat(id)}\n${handoffInstr(id, k)}`, name, 'director', false); // the team's result goes to the Director, never straight to the next team
|
|
737
|
-
const r = returnedEarly();
|
|
738
|
-
if (r)
|
|
739
|
-
return r;
|
|
1238
|
+
const turns = !multi ? 1 : parallel ? agents.length * (collabMode === 'TARGETED_DISCUSSION' ? 2 : 1) + 1 : agents.length * rounds + (writer ? 1 : 0) + (writer === lead ? 0 : 1);
|
|
1239
|
+
// B7 task graph: one task per team pass; it depends on the previous team's latest task
|
|
1240
|
+
const taskId = `t-${id}-${pass}`, depTasks = (graph ? graph.get(id) ?? [] : k > 0 ? [order[k - 1]] : []).flatMap(d => curTask.get(d) ?? []);
|
|
1241
|
+
curTask.set(id, taskId);
|
|
1242
|
+
if (!createdTasks.has(taskId)) {
|
|
1243
|
+
createdTasks.add(taskId);
|
|
1244
|
+
emit({ type: 'task.created', taskId, team: id, title: `${name} pass ${pass}`, deps: depTasks });
|
|
740
1245
|
}
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
1246
|
+
emit({ type: 'task.updated', taskId, status: 'running' });
|
|
1247
|
+
let taskDone = false;
|
|
1248
|
+
const endTask = (status, note) => { if (taskDone)
|
|
1249
|
+
return; taskDone = true; emit({ type: 'task.updated', taskId, status, ...(note ? { note: oneLine(note, 200) } : {}) }); };
|
|
1250
|
+
try {
|
|
1251
|
+
return await teamPassBody();
|
|
1252
|
+
}
|
|
1253
|
+
catch (e) {
|
|
1254
|
+
endTask('failed', e instanceof Halt && !finished ? 'halted' : 'the run ended');
|
|
1255
|
+
throw e;
|
|
1256
|
+
}
|
|
1257
|
+
async function teamPassBody() {
|
|
1258
|
+
const verdicts = new Map(), lastMsg = new Map(), log = [];
|
|
1259
|
+
let n = 0, qcReturn = null, raw = null, failNote = '';
|
|
1260
|
+
const run = async (agent, phase, round, what, task, toId, readOnly, sig0) => {
|
|
1261
|
+
if (nodeSig?.aborted)
|
|
1262
|
+
throw new NodeCancelled();
|
|
1263
|
+
const signal = sig0 && nodeSig ? AbortSignal.any([sig0, nodeSig]) : sig0 ?? nodeSig;
|
|
1264
|
+
n++;
|
|
1265
|
+
const rev = goalRevision; // captured at turn start: an owner instruction that lands meanwhile makes this contribution stale
|
|
1266
|
+
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 ? `\n${phase === 'handoff' && parallel ? 'INDEPENDENT CONTRIBUTIONS OF YOUR TEAM (written in parallel, none saw the others)' : 'TEAM DISCUSSION SO FAR (your own team only)'}:\n${log.join('\n\n')}\n` : ''}`, { ...(phase === 'discuss' ? { round } : {}), cls: phase === 'handoff' ? 'coordination' : classOf(agent, phase), taskId, ...(signal ? { signal } : {}) });
|
|
1267
|
+
if (nodeSig?.aborted)
|
|
1268
|
+
throw new NodeCancelled(); // a sibling graph node redirected / halted: this node stops without publishing
|
|
1269
|
+
if (signal?.aborted)
|
|
1270
|
+
return null; // the parallel pass was cancelled because a sibling redirected / halted: no publish, no failure
|
|
1271
|
+
if (text === null) {
|
|
1272
|
+
if (!isQc && phase === 'contribute' && readOnly) {
|
|
1273
|
+
// PF-RES slow/failed agent: a read-only parallel contributor that times out or fails only loses its own contribution; teammates and the merge go on
|
|
1274
|
+
const f = history.filter(e => e.type === 'agent.failed').at(-1);
|
|
1275
|
+
publish(agent.id, { findings: [], recommendations: [], risks: [`${agent.name} could not contribute: ${oneLine(f && f.type === 'agent.failed' ? f.reason : 'unknown', 200)}`], proposedDecisions: [], evidenceRefs: [], unresolvedQuestions: [], status: 'complete' }, taskId, 'failed', rev);
|
|
1276
|
+
return null;
|
|
1277
|
+
}
|
|
1278
|
+
if (!isQc)
|
|
1279
|
+
return fail(agent, `the ${name} stage`);
|
|
1280
|
+
const f = history.filter(e => e.type === 'agent.failed').at(-1); // a QC reviewer that cannot run counts as FAIL
|
|
1281
|
+
verdicts.set(agent.id, 'FAIL');
|
|
1282
|
+
failNote = `QC agent could not run: ${f && f.type === 'agent.failed' ? f.reason : 'unknown'}`;
|
|
1283
|
+
publish(agent.id, { findings: [{ summary: oneLine(failNote, 300), severity: 'high' }], recommendations: [], risks: [], proposedDecisions: [], evidenceRefs: [], unresolvedQuestions: [], status: 'complete' }, taskId, 'failed', rev);
|
|
1284
|
+
return '';
|
|
1285
|
+
}
|
|
1286
|
+
lastMsg.set(agent.id, text);
|
|
1287
|
+
if (isQc && /VERDICT/i.test(text))
|
|
1288
|
+
verdicts.set(agent.id, parseVerdict(text));
|
|
1289
|
+
if (phase !== 'discuss')
|
|
1290
|
+
publish(agent.id, contributionFrom(text, isQc && /VERDICT/i.test(text) && parseVerdict(text) === 'FAIL'), taskId, 'ok', rev);
|
|
1291
|
+
if (!parallel || phase === 'handoff')
|
|
1292
|
+
await drain();
|
|
1293
|
+
return text;
|
|
1294
|
+
};
|
|
1295
|
+
const early = () => retReasons.has(id);
|
|
1296
|
+
const returnedEarly = () => {
|
|
1297
|
+
if (!early())
|
|
1298
|
+
return null;
|
|
1299
|
+
if (isQc) {
|
|
1300
|
+
qcReturn = retReasons.get(id) ?? null;
|
|
1301
|
+
retReasons.delete(id);
|
|
1302
|
+
return null;
|
|
1303
|
+
}
|
|
1304
|
+
return { out: [...lastMsg.values()].at(-1) ?? '', back: backOf(id) };
|
|
1305
|
+
};
|
|
1306
|
+
if (!multi) {
|
|
1307
|
+
const solo = active[0];
|
|
1308
|
+
raw = await run(solo, 'single', 1, `${workWhat(id)}\n${handoffInstr(id, k)}`, name, 'director', false); // the team's result goes to the Director, never straight to the next team
|
|
1309
|
+
const r = returnedEarly();
|
|
1310
|
+
if (r) {
|
|
1311
|
+
endTask('done', 'sent back');
|
|
1312
|
+
return r;
|
|
756
1313
|
}
|
|
757
|
-
if (r >= 2 && agreed === agents.length)
|
|
758
|
-
break;
|
|
759
1314
|
}
|
|
760
|
-
if (
|
|
761
|
-
|
|
1315
|
+
else if (parallel) {
|
|
1316
|
+
// PF-COLLAB: every member works independently and at the same time (no discussion rounds, nobody waits for a teammate); then the lead merges.
|
|
1317
|
+
const others = (a) => agents.filter(x => x.id !== a.id).map(x => x.name).join(', ');
|
|
1318
|
+
const outsP = await parallelAll(sig => agents.map((a, i) => {
|
|
1319
|
+
const writes = a === writer;
|
|
1320
|
+
const what = writes
|
|
1321
|
+
? `You are the ONLY member of the ${name} team who changes files in this pass. ${workWhat(id)}\nYour teammates (${others(a)}) work at the same time on their own independent contribution; do not wait for them.`
|
|
1322
|
+
: `INDEPENDENT CONTRIBUTION. ${workWhat(id)}\nWork on your own, now; your teammates (${others(a)}) do the same in parallel and nobody waits for anybody. Report concrete findings, each on its own line as "FINDING [critical|high|medium|low|info]: <summary> [at <file:line>]", plus optional lines "RISK: ...", "RECOMMEND: ...", "QUESTION: ...". Do not change any file.`;
|
|
1323
|
+
return run(a, 'contribute', 1, what, `${name} contribution (${i + 1}/${agents.length})`, lead.id, !writes, sig).then(t => ({ a, t }));
|
|
1324
|
+
}));
|
|
1325
|
+
if (qcReturn === null && !retReasons.has(id)) {
|
|
1326
|
+
log.length = 0;
|
|
1327
|
+
const alive = outsP.filter(o => o.t !== null);
|
|
1328
|
+
if (!alive.length)
|
|
1329
|
+
return fail(lead, `the ${name} stage`); // every member failed: nothing to merge
|
|
1330
|
+
for (const { a, t } of outsP)
|
|
1331
|
+
log.push(t === null ? `[${a.name}]: (no contribution: this agent failed or timed out; merge without it and say so)` : `[${a.name}${a === writer ? ', the writer' : ''}]: ${clip(t, 3000)}`);
|
|
1332
|
+
n = agents.length;
|
|
1333
|
+
if (collabMode === 'TARGETED_DISCUSSION') {
|
|
1334
|
+
// exactly ONE clarification round (research 8.6): each member reads the others' contributions once and answers only disagreements; no further rounds, no reviewer-of-reviewer
|
|
1335
|
+
const snapshot = log.join('\n\n');
|
|
1336
|
+
const outsC = await parallelAll(sig => agents.map(a => run(a, 'clarify', 1, `TARGETED CLARIFICATION (one round only). Read your teammates' independent contributions below. Reply ONLY where you disagree or have new evidence: "CONFIRM: <finding>", "DISPUTE: <finding> because <evidence>" or "NEW EVIDENCE: ...". No new work, no file changes.\nCONTRIBUTIONS:\n${snapshot}`, `${name} clarification`, lead.id, true, sig).then(t => ({ a, t }))));
|
|
1337
|
+
for (const { a, t } of outsC)
|
|
1338
|
+
if (t?.trim())
|
|
1339
|
+
log.push(`[${a.name}, clarification]: ${clip(t, 1500)}`);
|
|
1340
|
+
n += agents.length;
|
|
1341
|
+
}
|
|
1342
|
+
const merged = mergeFindings(contribs.filter(c => c.taskId === taskId));
|
|
1343
|
+
if (merged.length)
|
|
1344
|
+
log.push(`MERGED FINDINGS (deduplicated by CKit; severity = highest reported):\n${merged.slice(0, 40).map(f => `- [${f.severity}] ${f.summary}${f.location ? ` at ${f.location}` : ''} (${f.agents.join(', ')})`).join('\n')}`);
|
|
1345
|
+
const merger = outsP.find(o => o.a === lead && o.t !== null)?.a ?? alive[0].a; // a lead that failed is replaced by a teammate that delivered
|
|
1346
|
+
raw = await run(merger, 'handoff', 1, `Your team's members contributed independently (below). You are the team lead: merge them into the team's single result. Decide on evidence, not majority; keep every critical/high finding unless the evidence disproves it, and say why. ${isQc ? 'State the merged result: "VERDICT: FAIL" when any reviewer failed it with evidence, else "VERDICT: PASS". ' : ''}Do not change any file.\n${handoffInstr(id, k)}`, `${name} merge`, 'director', true);
|
|
1347
|
+
}
|
|
762
1348
|
const rr = returnedEarly();
|
|
763
|
-
if (rr)
|
|
1349
|
+
if (rr) {
|
|
1350
|
+
endTask('done', 'sent back');
|
|
764
1351
|
return rr;
|
|
765
|
-
|
|
766
|
-
raw = t;
|
|
767
|
-
else
|
|
768
|
-
log.push(`[work] ${writer.name}: ${clip(t ?? '', 2500)}`);
|
|
1352
|
+
}
|
|
769
1353
|
}
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
1354
|
+
else {
|
|
1355
|
+
discussion: for (let r = 1; r <= rounds; r++) {
|
|
1356
|
+
let agreed = 0;
|
|
1357
|
+
for (let i = 0; i < agents.length; i++) {
|
|
1358
|
+
const a = agents[i], peer = agents[(i + 1) % agents.length];
|
|
1359
|
+
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(', ')}).`;
|
|
1360
|
+
const t = await run(a, 'discuss', r, what, `${name} discussion ${r}/${rounds} (${i + 1}/${agents.length})`, peer.id, true);
|
|
1361
|
+
const rr = returnedEarly();
|
|
1362
|
+
if (rr) {
|
|
1363
|
+
endTask('done', 'sent back');
|
|
1364
|
+
return rr;
|
|
1365
|
+
}
|
|
1366
|
+
if (qcReturn !== null)
|
|
1367
|
+
break discussion;
|
|
1368
|
+
log.push(`[round ${r}] ${a.name}: ${clip(t ?? '', 1500)}`);
|
|
1369
|
+
if (r >= 2 && t && AGREED_RE.test(t))
|
|
1370
|
+
agreed++;
|
|
1371
|
+
}
|
|
1372
|
+
if (r >= 2 && agreed === agents.length)
|
|
1373
|
+
break;
|
|
1374
|
+
}
|
|
1375
|
+
if (qcReturn === null && writer) {
|
|
1376
|
+
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`, writer === lead ? 'director' : lead.id, false); // a non-lead writer reports inside the team; the lead's handoff is what reaches the Director
|
|
1377
|
+
const rr = returnedEarly();
|
|
1378
|
+
if (rr) {
|
|
1379
|
+
endTask('done', 'sent back');
|
|
1380
|
+
return rr;
|
|
1381
|
+
}
|
|
1382
|
+
if (writer === lead)
|
|
1383
|
+
raw = t;
|
|
1384
|
+
else
|
|
1385
|
+
log.push(`[work] ${writer.name}: ${clip(t ?? '', 2500)}`);
|
|
1386
|
+
}
|
|
1387
|
+
if (qcReturn === null && raw === null) {
|
|
1388
|
+
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`, 'director', true);
|
|
1389
|
+
const rr = returnedEarly();
|
|
1390
|
+
if (rr) {
|
|
1391
|
+
endTask('done', 'sent back');
|
|
1392
|
+
return rr;
|
|
1393
|
+
}
|
|
1394
|
+
}
|
|
775
1395
|
}
|
|
1396
|
+
const rawText = raw ?? '';
|
|
1397
|
+
const sec = parseHandoff(rawText);
|
|
1398
|
+
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)}`;
|
|
1399
|
+
let back = null;
|
|
1400
|
+
if (isQc) {
|
|
1401
|
+
const failed = qcReturn !== null || [...verdicts.values()].some(v => v === 'FAIL') || (!verdicts.size);
|
|
1402
|
+
const verdict = failed ? 'FAIL' : 'PASS';
|
|
1403
|
+
const firstFailId = [...verdicts].find(([, v]) => v === 'FAIL')?.[0];
|
|
1404
|
+
const firstFail = qcReturn !== null ? `Returned to the previous team: ${qcReturn}` : failNote || (firstFailId ? (lastMsg.get(firstFailId) ?? '').replace(/\n?.*VERDICT.*$/i, '') : 'no reviewer gave a verdict');
|
|
1405
|
+
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`;
|
|
1406
|
+
const art = journal.writeArtifact(`qc-report-${pass}.md`, qcReport);
|
|
1407
|
+
emit({ type: 'qc.verdict', verdict, loop: pass, summary: oneLine(verdict === 'PASS' ? 'All QC reviewers passed the deliverable.' : firstFail, 300) });
|
|
1408
|
+
qcPassed = verdict === 'PASS';
|
|
1409
|
+
void art;
|
|
1410
|
+
text += `\n\nVERDICT: ${verdict}`;
|
|
1411
|
+
back = failed ? { full: qcReport, short: oneLine(firstFail, 300) } : null;
|
|
1412
|
+
}
|
|
1413
|
+
else
|
|
1414
|
+
back = backOf(id);
|
|
1415
|
+
if (id === 'ba' && atts.length)
|
|
1416
|
+
text += `\n\n## Attachments from the owner\nPart of this handoff. Read them together with the document above.\n${attachmentLines(atts)}\n`;
|
|
1417
|
+
handoffs.set(id, { done: sec ? sec.DONE : rawText, open: sec ? sec.OPEN : '(handoff not structured)' });
|
|
1418
|
+
const art = journal.writeArtifact(`handoff-${id}.md`, text);
|
|
1419
|
+
if (id === 'ba')
|
|
1420
|
+
journal.writeArtifact('handoff-ba.md', text);
|
|
1421
|
+
emit({ type: 'handoff.created', from: id, to: 'director', title: `${name} -> Director`, artifact: art, text: clip(text, 8000) }); // every team reports to the Director; the Director dispatches the next team
|
|
1422
|
+
endTask(back ? 'failed' : 'done', back ? back.short : undefined);
|
|
1423
|
+
return { out: text, back, art };
|
|
776
1424
|
}
|
|
777
|
-
const rawText = raw ?? '';
|
|
778
|
-
const sec = parseHandoff(rawText);
|
|
779
|
-
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)}`;
|
|
780
|
-
let back = null;
|
|
781
|
-
if (isQc) {
|
|
782
|
-
const failed = qcReturn !== null || [...verdicts.values()].some(v => v === 'FAIL') || (!verdicts.size);
|
|
783
|
-
const verdict = failed ? 'FAIL' : 'PASS';
|
|
784
|
-
const firstFailId = [...verdicts].find(([, v]) => v === 'FAIL')?.[0];
|
|
785
|
-
const firstFail = qcReturn !== null ? `Returned to the previous team: ${qcReturn}` : failNote || (firstFailId ? (lastMsg.get(firstFailId) ?? '').replace(/\n?.*VERDICT.*$/i, '') : 'no reviewer gave a verdict');
|
|
786
|
-
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`;
|
|
787
|
-
const art = journal.writeArtifact(`qc-report-${pass}.md`, qcReport);
|
|
788
|
-
emit({ type: 'qc.verdict', verdict, loop: pass, summary: oneLine(verdict === 'PASS' ? 'All QC reviewers passed the deliverable.' : firstFail, 300) });
|
|
789
|
-
qcPassed = verdict === 'PASS';
|
|
790
|
-
void art;
|
|
791
|
-
text += `\n\nVERDICT: ${verdict}`;
|
|
792
|
-
back = failed ? { full: qcReport, short: oneLine(firstFail, 300) } : null;
|
|
793
|
-
}
|
|
794
|
-
else
|
|
795
|
-
back = backOf();
|
|
796
|
-
if (id === 'ba' && atts.length)
|
|
797
|
-
text += `\n\n## Attachments from the owner\nPart of this handoff. Read them together with the document above.\n${attachmentLines(atts)}\n`;
|
|
798
|
-
handoffs.set(id, { done: sec ? sec.DONE : rawText, open: sec ? sec.OPEN : '(handoff not structured)' });
|
|
799
|
-
const art = journal.writeArtifact(`handoff-${id}.md`, text);
|
|
800
|
-
if (id === 'ba')
|
|
801
|
-
journal.writeArtifact('handoff-ba.md', text);
|
|
802
|
-
emit({ type: 'handoff.created', from: id, to: 'director', title: `${name} -> Director`, artifact: art, text: clip(text, 8000) }); // every team reports to the Director; the Director dispatches the next team
|
|
803
|
-
return { out: text, back, art };
|
|
804
1425
|
}
|
|
805
1426
|
/** Director rewrites the brief for team 1 after it sent the work back. */
|
|
806
1427
|
async function directorRewrite(id, reason) {
|
|
@@ -819,9 +1440,12 @@ export function startTeamRun(opts) {
|
|
|
819
1440
|
if (!modelDirector())
|
|
820
1441
|
return dflt;
|
|
821
1442
|
const ho = handoffs.get(id), ids = new Set(agentsOf(id).map(x => x.id));
|
|
822
|
-
const
|
|
1443
|
+
const tid = curTask.get(id), high = highIn(contribs.filter(c => c.taskId === tid && c.goalRevision === goalRevision));
|
|
1444
|
+
// PF-WAKE: the Director is woken only for open questions, a critical/high finding, a failed agent or a pending owner message
|
|
1445
|
+
const clean = !!ho && /^\(?(nothing|none|n\/a|no open (questions|items|issues))\.?\)?$/i.test(ho.open.trim()) && !inbox.length && !high && !history.some(e => e.type === 'agent.failed' && ids.has(e.agentId));
|
|
823
1446
|
if (clean) {
|
|
824
1447
|
emit({ type: 'director.decision', decision: 'continue', note: 'auto: clean handoff' });
|
|
1448
|
+
record(`d-cp-${id}`, { title: `${teamName(id)} result accepted`, selected: 'accept', status: 'committed', authority: 'core', rationale: 'clean handoff: nothing open, no critical/high finding', affectedTasks: tid ? [tid] : [] });
|
|
825
1449
|
return dflt;
|
|
826
1450
|
} // nothing open: skip the Director model call
|
|
827
1451
|
const ask = (extra, again) => directorAsk(`checkpoint ${teamName(id)}`, `${role(config.director, `You are the Director. The ${teamName(id)} team reported to you. Check the report against the owner goal and your brief, then decide. Reply with a line exactly "CHECKPOINT: ACCEPT" followed by a section "DISPATCH:" with the instructions for the ${teamName(nextId)} team, or a line exactly "CHECKPOINT: RETURN" and a line "RETURN REASON: <what the ${teamName(id)} team must fix>".${again ? '' : ' You may first gather context from a teammate agent (read-only) with up to 2 lines "CONSULT <agent id>: <question>"; then you are asked again.'} Do not change any file.`, true)}\nTEAM ROSTER (flow order):\n${rosterText()}\nORIGINAL GOAL: ${oneLine(goal, 2000)}\n${common()}\nYOUR BRIEF FOR ${teamName(id).toUpperCase()}:\n${briefOf(id)}\n\nREPORT OF THE ${teamName(id).toUpperCase()} TEAM:\n${clip(report, 6000)}\n\nYOUR BRIEF FOR ${teamName(nextId).toUpperCase()} (next team):\n${briefOf(nextId)}${extra}`);
|
|
@@ -848,7 +1472,9 @@ export function startTeamRun(opts) {
|
|
|
848
1472
|
cp = parseCheckpoint(t2);
|
|
849
1473
|
}
|
|
850
1474
|
}
|
|
851
|
-
|
|
1475
|
+
const decision = cp.decision === 'return' ? 'return' : 'accept';
|
|
1476
|
+
record(`d-cp-${id}`, { title: `${teamName(id)} result ${decision === 'return' ? 'returned' : 'accepted'}`, selected: decision, status: 'committed', rationale: decision === 'return' ? cp.reason || 'rework requested' : oneLine(cp.dispatch || 'accepted', 400), contributions: contribs.filter(c => c.taskId === tid).map(c => c.contributionId), affectedTasks: tid ? [tid] : [] });
|
|
1477
|
+
return { decision, dispatch: cp.dispatch, said: cp.dispatch || t.trim(), reason: cp.reason };
|
|
852
1478
|
}
|
|
853
1479
|
/** 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. */
|
|
854
1480
|
async function flow(from = 0) {
|
|
@@ -856,14 +1482,23 @@ export function startTeamRun(opts) {
|
|
|
856
1482
|
while (k < order.length) {
|
|
857
1483
|
const id = order[k], pass = (passes.get(id) ?? 0) + 1;
|
|
858
1484
|
passes.set(id, pass);
|
|
859
|
-
|
|
1485
|
+
retReasons.delete(id);
|
|
1486
|
+
if (earlyTest && earlyTest.id === id && !earlyPlans.has(id)) {
|
|
1487
|
+
setWait(agentsOf(id)[0]?.id ?? id, 'waiting-dependency', earlyTest.taskId);
|
|
1488
|
+
const plan = await earlyTest.p;
|
|
1489
|
+
halted();
|
|
1490
|
+
if (plan)
|
|
1491
|
+
earlyPlans.set(id, plan);
|
|
1492
|
+
}
|
|
860
1493
|
const res = await teamPass(k, id, pass);
|
|
861
1494
|
let note = '';
|
|
862
1495
|
sentBack.delete(id);
|
|
863
1496
|
outs.set(id, res.out);
|
|
864
1497
|
if (res.back) {
|
|
865
|
-
const used = backs.get(k) ?? 0;
|
|
866
|
-
if (
|
|
1498
|
+
const used = backs.get(k) ?? 0, loop = repeated(`ret:${id}`, res.back.short);
|
|
1499
|
+
if (loop)
|
|
1500
|
+
emit({ type: 'loop.detected', kind: 'return', from: id, reason: oneLine(`the same send-back again without new evidence: ${res.back.short}`, 300) });
|
|
1501
|
+
if (used < limit && !loop) {
|
|
867
1502
|
backs.set(k, used + 1);
|
|
868
1503
|
emit({ type: 'flow.back', kind: 'return', from: id, to: prevId(k), reason: res.back.short });
|
|
869
1504
|
if (k === 0)
|
|
@@ -880,9 +1515,13 @@ export function startTeamRun(opts) {
|
|
|
880
1515
|
}
|
|
881
1516
|
else if (k < order.length - 1) {
|
|
882
1517
|
const nextId = order[k + 1], cp = await checkpoint(id, nextId, res.out);
|
|
1518
|
+
if (cp.decision !== 'return')
|
|
1519
|
+
startEarlyTest(k);
|
|
883
1520
|
if (cp.decision === 'return') {
|
|
884
|
-
const used = dirBacks.get(id) ?? 0;
|
|
885
|
-
if (
|
|
1521
|
+
const used = dirBacks.get(id) ?? 0, loop = repeated(`dret:${id}`, cp.reason);
|
|
1522
|
+
if (loop)
|
|
1523
|
+
emit({ type: 'loop.detected', kind: 'return', from: 'director', reason: oneLine(`the Director returned the same thing again: ${cp.reason}`, 300) });
|
|
1524
|
+
if (used < limit && !loop) {
|
|
886
1525
|
dirBacks.set(id, used + 1);
|
|
887
1526
|
const reason = cp.reason || 'the Director asked for a rework';
|
|
888
1527
|
emit({ type: 'flow.back', kind: 'return', from: 'director', to: id, reason: oneLine(reason, 300) });
|
|
@@ -910,6 +1549,176 @@ export function startTeamRun(opts) {
|
|
|
910
1549
|
const lastId = order.at(-1);
|
|
911
1550
|
deliverable = lastId ? outs.get(lastId) ?? '' : '';
|
|
912
1551
|
}
|
|
1552
|
+
/** PF-PROG / PARALLEL_EXECUTE: every team starts as soon as the teams it depends on are done, so a slow team blocks only its dependents.
|
|
1553
|
+
* Write turns are still serialized by the workspace lease and capped by the global scheduler. A send-back re-runs the first dependency, then the team (bounded by limits.qcLoops).
|
|
1554
|
+
* When one node redirects / halts / fails, the sibling nodes are cancelled and every node settles before the error is rethrown. */
|
|
1555
|
+
async function flowGraph(only) {
|
|
1556
|
+
const g = graph, ctl = new AbortController();
|
|
1557
|
+
const dependents = (id) => order.filter(x => (g.get(x) ?? []).includes(id));
|
|
1558
|
+
const closure = (start) => { const out = new Set(), q = [start]; while (q.length)
|
|
1559
|
+
for (const d of dependents(q.pop()))
|
|
1560
|
+
if (!out.has(d)) {
|
|
1561
|
+
out.add(d);
|
|
1562
|
+
q.push(d);
|
|
1563
|
+
} return out; };
|
|
1564
|
+
const mine = (id) => !only || only.has(id);
|
|
1565
|
+
for (const id of order)
|
|
1566
|
+
if (mine(id)) {
|
|
1567
|
+
const p = (passes.get(id) ?? 0) + 1, tid = `t-${id}-${p}`;
|
|
1568
|
+
if (!createdTasks.has(tid)) {
|
|
1569
|
+
createdTasks.add(tid);
|
|
1570
|
+
emit({ type: 'task.created', taskId: tid, team: id, title: `${teamName(id)} pass ${p}`, deps: (g.get(id) ?? []).map(d => `t-${d}-${(passes.get(d) ?? 0) + 1}`) });
|
|
1571
|
+
emit({ type: 'task.updated', taskId: tid, status: 'pending', note: (g.get(id) ?? []).length ? `waiting for: ${(g.get(id) ?? []).map(teamName).join(', ')}` : 'ready' });
|
|
1572
|
+
}
|
|
1573
|
+
}
|
|
1574
|
+
// Every node has a "ready" gate dependents wait on. A send-back that re-runs a dependency closes that gate again and invalidates its dependents (R2-6).
|
|
1575
|
+
const ready = new Map(), nctl = new Map(), live = new Set(), errs = [];
|
|
1576
|
+
const fresh = (id) => { ready.get(id)?.res(); /* wake waiters on the old gate: they see it was replaced and wait on the new one (else a dependent already awaiting it never wakes) */ /* wake waiters on the old gate: they see it was replaced and wait on the new one (else a dependent already awaiting it never wakes) */ let res; const p = new Promise(r => { res = r; }); ready.set(id, { p, res }); };
|
|
1577
|
+
const settleAll = () => { for (const r of ready.values())
|
|
1578
|
+
r.res(); };
|
|
1579
|
+
for (const id of order) {
|
|
1580
|
+
fresh(id);
|
|
1581
|
+
if (!mine(id))
|
|
1582
|
+
ready.get(id)?.res();
|
|
1583
|
+
}
|
|
1584
|
+
const pass1 = async (id, sig) => { const k = order.indexOf(id), p = (passes.get(id) ?? 0) + 1; passes.set(id, p); retReasons.delete(id); const r = await teamPass(k, id, p, sig); sentBack.delete(id); outs.set(id, r.out); return r; };
|
|
1585
|
+
/** The dependency `to` is being re-run for `id`: everything else built on its old output (done, running, or waiting) is invalidated and runs again on the new one. */
|
|
1586
|
+
const active = new Set(), started = new Set();
|
|
1587
|
+
const invalidate = (to, id) => {
|
|
1588
|
+
const own = closure(id);
|
|
1589
|
+
own.add(id);
|
|
1590
|
+
for (const d of order) {
|
|
1591
|
+
if (!closure(to).has(d) || own.has(d) || !mine(d))
|
|
1592
|
+
continue;
|
|
1593
|
+
if (!active.has(d)) {
|
|
1594
|
+
fresh(d);
|
|
1595
|
+
spawn(d);
|
|
1596
|
+
} // already finished on the old output: run again
|
|
1597
|
+
else if (started.has(d)) {
|
|
1598
|
+
fresh(d);
|
|
1599
|
+
nctl.get(d)?.abort();
|
|
1600
|
+
} // running on the old output: cancel and restart
|
|
1601
|
+
} // still waiting: it re-checks its dependencies' gates, so it picks up the new output
|
|
1602
|
+
};
|
|
1603
|
+
const node = async (id) => {
|
|
1604
|
+
const deps = g.get(id) ?? [], k = order.indexOf(id);
|
|
1605
|
+
for (;;) {
|
|
1606
|
+
started.delete(id);
|
|
1607
|
+
if (deps.length) {
|
|
1608
|
+
for (const a of agentsOf(id))
|
|
1609
|
+
setWait(a.id, 'waiting-dependency', `waiting for: ${deps.map(teamName).join(', ')}`);
|
|
1610
|
+
for (;;) {
|
|
1611
|
+
const ps = deps.map(d => ready.get(d).p);
|
|
1612
|
+
await Promise.all(ps);
|
|
1613
|
+
if (ctl.signal.aborted)
|
|
1614
|
+
throw new NodeCancelled();
|
|
1615
|
+
if (deps.every((d, i) => ready.get(d).p === ps[i]))
|
|
1616
|
+
break;
|
|
1617
|
+
}
|
|
1618
|
+
}
|
|
1619
|
+
if (ctl.signal.aborted)
|
|
1620
|
+
throw new NodeCancelled();
|
|
1621
|
+
halted();
|
|
1622
|
+
const my = new AbortController();
|
|
1623
|
+
nctl.set(id, my);
|
|
1624
|
+
started.add(id);
|
|
1625
|
+
const sig = AbortSignal.any([ctl.signal, my.signal]);
|
|
1626
|
+
try {
|
|
1627
|
+
for (;;) {
|
|
1628
|
+
const res = await pass1(id, sig);
|
|
1629
|
+
if (res.back) {
|
|
1630
|
+
const used = backs.get(k) ?? 0, loop = repeated(`ret:${id}`, res.back.short), to = deps[0] ?? 'director';
|
|
1631
|
+
if (loop)
|
|
1632
|
+
emit({ type: 'loop.detected', kind: 'return', from: id, reason: oneLine(`the same send-back again without new evidence: ${res.back.short}`, 300) });
|
|
1633
|
+
if (used < limit && !loop) {
|
|
1634
|
+
backs.set(k, used + 1);
|
|
1635
|
+
emit({ type: 'flow.back', kind: 'return', from: id, to, reason: res.back.short });
|
|
1636
|
+
if (to === 'director')
|
|
1637
|
+
await directorRewrite(id, res.back.full);
|
|
1638
|
+
else {
|
|
1639
|
+
sentBack.set(to, { from: id, reason: res.back.full });
|
|
1640
|
+
fresh(to);
|
|
1641
|
+
invalidate(to, id); // the dependency's output changes: its other dependents must not keep the old one
|
|
1642
|
+
try {
|
|
1643
|
+
await pass1(to, sig);
|
|
1644
|
+
}
|
|
1645
|
+
finally {
|
|
1646
|
+
ready.get(to)?.res();
|
|
1647
|
+
}
|
|
1648
|
+
}
|
|
1649
|
+
continue;
|
|
1650
|
+
}
|
|
1651
|
+
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.]`);
|
|
1652
|
+
if (id === 'qc')
|
|
1653
|
+
qcPassed = false;
|
|
1654
|
+
}
|
|
1655
|
+
else {
|
|
1656
|
+
const next = dependents(id)[0];
|
|
1657
|
+
if (next) {
|
|
1658
|
+
const cp = await checkpoint(id, next, res.out);
|
|
1659
|
+
if (cp.decision === 'return') {
|
|
1660
|
+
const used = dirBacks.get(id) ?? 0, loop = repeated(`dret:${id}`, cp.reason);
|
|
1661
|
+
if (loop)
|
|
1662
|
+
emit({ type: 'loop.detected', kind: 'return', from: 'director', reason: oneLine(`the Director returned the same thing again: ${cp.reason}`, 300) });
|
|
1663
|
+
if (used < limit && !loop) {
|
|
1664
|
+
dirBacks.set(id, used + 1);
|
|
1665
|
+
emit({ type: 'flow.back', kind: 'return', from: 'director', to: id, reason: oneLine(cp.reason || 'the Director asked for a rework', 300) });
|
|
1666
|
+
sentBack.set(id, { from: 'director', reason: cp.reason || 'the Director asked for a rework' });
|
|
1667
|
+
continue;
|
|
1668
|
+
}
|
|
1669
|
+
}
|
|
1670
|
+
for (const d of dependents(id)) {
|
|
1671
|
+
if (cp.dispatch)
|
|
1672
|
+
dispatches.set(d, cp.dispatch);
|
|
1673
|
+
emit({ type: 'handoff.created', from: 'director', to: d, title: `Director -> ${teamName(d)}`, artifact: res.art ?? `handoff-${id}.md`, text: clip(`### HANDOFF Director -> ${teamName(d)}\n${dispatches.get(d) ?? `Proceed with your brief. The ${teamName(id)} team's report is attached in full.`}`, 8000) });
|
|
1674
|
+
}
|
|
1675
|
+
}
|
|
1676
|
+
}
|
|
1677
|
+
break;
|
|
1678
|
+
}
|
|
1679
|
+
ready.get(id)?.res();
|
|
1680
|
+
return;
|
|
1681
|
+
}
|
|
1682
|
+
catch (e) {
|
|
1683
|
+
if (e instanceof NodeCancelled && !ctl.signal.aborted && my.signal.aborted)
|
|
1684
|
+
continue; // invalidated by a send-back upstream: run again on the new output
|
|
1685
|
+
throw e;
|
|
1686
|
+
}
|
|
1687
|
+
}
|
|
1688
|
+
};
|
|
1689
|
+
function spawn(id) {
|
|
1690
|
+
active.add(id);
|
|
1691
|
+
const p = node(id).catch((e) => { errs.push(e); ctl.abort(); settleAll(); }).finally(() => { active.delete(id); live.delete(p); });
|
|
1692
|
+
live.add(p);
|
|
1693
|
+
}
|
|
1694
|
+
for (const id of order)
|
|
1695
|
+
if (mine(id))
|
|
1696
|
+
spawn(id);
|
|
1697
|
+
while (live.size)
|
|
1698
|
+
await Promise.all([...live]);
|
|
1699
|
+
const bad = errs.find(e => !(e instanceof NodeCancelled)) ?? errs[0];
|
|
1700
|
+
if (bad)
|
|
1701
|
+
throw bad instanceof NodeCancelled ? new Halt() : bad;
|
|
1702
|
+
const lastId = order.at(-1);
|
|
1703
|
+
deliverable = lastId ? outs.get(lastId) ?? '' : '';
|
|
1704
|
+
}
|
|
1705
|
+
/** Re-runs team `id` after a send-back: linear flow from its position, or in graph mode only that node and the teams built on it (everything upstream keeps its output). */
|
|
1706
|
+
async function rerun(id) {
|
|
1707
|
+
if (!graph) {
|
|
1708
|
+
await flow(order.indexOf(id));
|
|
1709
|
+
return;
|
|
1710
|
+
}
|
|
1711
|
+
const g = graph, set = new Set([id]);
|
|
1712
|
+
for (let grew = true; grew;) {
|
|
1713
|
+
grew = false;
|
|
1714
|
+
for (const x of order)
|
|
1715
|
+
if (!set.has(x) && (g.get(x) ?? []).some(d => set.has(d))) {
|
|
1716
|
+
set.add(x);
|
|
1717
|
+
grew = true;
|
|
1718
|
+
}
|
|
1719
|
+
}
|
|
1720
|
+
await flowGraph(set);
|
|
1721
|
+
}
|
|
913
1722
|
/** 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. */
|
|
914
1723
|
function finalOutputs() {
|
|
915
1724
|
const lastId = order.at(-1), last = lastId ? outs.get(lastId) ?? '' : '';
|
|
@@ -943,26 +1752,94 @@ export function startTeamRun(opts) {
|
|
|
943
1752
|
reviewChecklist = v === null ? 'review verdict not readable' : clip(said, 3000);
|
|
944
1753
|
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) });
|
|
945
1754
|
reviewUnmet = verdict === 'FAIL';
|
|
946
|
-
if (verdict === 'PASS')
|
|
1755
|
+
if (verdict === 'PASS') {
|
|
1756
|
+
record('d-review', { title: 'Director review', selected: 'PASS', status: 'verified', rationale: 'every requirement met' });
|
|
947
1757
|
return;
|
|
948
|
-
|
|
1758
|
+
}
|
|
1759
|
+
const rloop = repeated('review', ret);
|
|
1760
|
+
if (rloop)
|
|
1761
|
+
emit({ type: 'loop.detected', kind: 'review', from: 'director', reason: oneLine(`the review rejected the same thing again: ${ret}`, 300) });
|
|
1762
|
+
record('d-review', { title: 'Director review', selected: 'FAIL', status: 'rejected', rationale: ret });
|
|
1763
|
+
if (used >= limit || rloop) {
|
|
949
1764
|
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]`;
|
|
950
1765
|
return;
|
|
951
1766
|
}
|
|
952
1767
|
used++;
|
|
953
1768
|
emit({ type: 'flow.back', kind: 'return', from: 'director', to: lastId, reason: oneLine(ret, 300) });
|
|
954
1769
|
sentBack.set(lastId, { from: 'director', reason: `${ret}\n\nDirector's checklist:\n${clip(said, 2500)}` });
|
|
955
|
-
await
|
|
1770
|
+
await rerun(lastId);
|
|
956
1771
|
await drain();
|
|
957
1772
|
}
|
|
958
1773
|
}
|
|
1774
|
+
/** Critical findings of the security team(s) still open: those in the latest current contribution of each security agent. */
|
|
1775
|
+
const openCriticals = () => {
|
|
1776
|
+
const latest = new Map();
|
|
1777
|
+
for (const c of contribs) {
|
|
1778
|
+
const t = allAgentsOf(config).find(a => a.id === c.agentId)?.team ?? '';
|
|
1779
|
+
if (isSecurityTeam(t) && c.status !== 'superseded')
|
|
1780
|
+
latest.set(c.agentId, c);
|
|
1781
|
+
} // any revision: an owner steer does not hide a finding, only a newer security review replaces it
|
|
1782
|
+
return [...latest.values()].flatMap(c => c.findings.filter(f => f.severity === 'critical'));
|
|
1783
|
+
};
|
|
1784
|
+
let securityAccepted = '';
|
|
1785
|
+
/** Delivery gate: an open critical security finding blocks Delivery. The work goes back to Implement (bounded by the send-back limit),
|
|
1786
|
+
* then the owner decides: "ACCEPT: <reason>" delivers with the findings recorded as accepted; anything else is guidance for one more rework. */
|
|
1787
|
+
async function securityGate() {
|
|
1788
|
+
let reworks = 0, asks = 0;
|
|
1789
|
+
for (;;) {
|
|
1790
|
+
const open = openCriticals();
|
|
1791
|
+
if (!open.length) {
|
|
1792
|
+
if (reworks || asks)
|
|
1793
|
+
record('d-security', { title: 'Critical security findings', selected: 'resolved', status: 'verified', authority: 'core', rationale: 'the latest security review has no critical finding' });
|
|
1794
|
+
return;
|
|
1795
|
+
}
|
|
1796
|
+
const list = open.map(f => `- ${oneLine(f.summary, 300)}${f.location ? ` (at ${f.location})` : ''}`).join('\n');
|
|
1797
|
+
const sec = order.find(isSecurityTeam) ?? 'security', impl = order.indexOf('implement');
|
|
1798
|
+
record('d-security', { title: 'Critical security findings', selected: 'block delivery', status: 'committed', authority: 'core', rationale: oneLine(`Delivery is blocked: ${open.length} critical security finding(s) open`, 400), evidence: open.map(f => f.id) });
|
|
1799
|
+
if (impl >= 0 && reworks < limit) {
|
|
1800
|
+
reworks++;
|
|
1801
|
+
const reason = `Critical security finding(s) must be fixed before delivery:\n${list}`;
|
|
1802
|
+
emit({ type: 'flow.back', kind: 'return', from: sec, to: 'implement', reason: oneLine(reason, 300) });
|
|
1803
|
+
sentBack.set('implement', { from: sec, reason });
|
|
1804
|
+
await rerun('implement');
|
|
1805
|
+
await drain();
|
|
1806
|
+
halted();
|
|
1807
|
+
continue;
|
|
1808
|
+
}
|
|
1809
|
+
if (asks >= 3) {
|
|
1810
|
+
finish('failed', journal.redact(`Run failed: critical security finding(s) are still open and were not accepted, so the work is not delivered.\n${list}`));
|
|
1811
|
+
throw new Halt();
|
|
1812
|
+
}
|
|
1813
|
+
asks++;
|
|
1814
|
+
const q = `Critical security finding(s) are still open after ${reworks} rework(s), so Delivery is blocked:\n${list}\n\nReply "ACCEPT: <reason>" to deliver anyway (the findings are recorded as accepted with your reason), give guidance for another fix, or stop the run.`;
|
|
1815
|
+
directorSay('all', q);
|
|
1816
|
+
emit({ type: 'run.waiting', round: asks, questions: q, assumptions: null, team: sec });
|
|
1817
|
+
const w = await waitForOwner('');
|
|
1818
|
+
halted();
|
|
1819
|
+
const acc = /^\s*ACCEPT(?:ED)?\b\s*[:\-–]?\s*(.*)$/is.exec(w.text);
|
|
1820
|
+
if (acc && (acc[1] ?? '').trim()) {
|
|
1821
|
+
securityAccepted = `${list}\nAccepted by the owner: ${oneLine(acc[1], 400)}`;
|
|
1822
|
+
record('d-security', { title: 'Critical security findings', selected: 'accepted by the owner', status: 'committed', authority: 'owner', rationale: oneLine(acc[1], 600), evidence: open.map(f => f.id) });
|
|
1823
|
+
return;
|
|
1824
|
+
}
|
|
1825
|
+
notes.push(`Owner's guidance on the critical security findings: ${w.text}`);
|
|
1826
|
+
if (impl >= 0) {
|
|
1827
|
+
sentBack.set('implement', { from: sec, reason: `Critical security finding(s):\n${list}\n\nOwner's guidance: ${w.text}` });
|
|
1828
|
+
await rerun('implement');
|
|
1829
|
+
await drain();
|
|
1830
|
+
halted();
|
|
1831
|
+
}
|
|
1832
|
+
}
|
|
1833
|
+
}
|
|
959
1834
|
async function delivery() {
|
|
960
1835
|
emit({ type: 'stage.changed', stage: 'delivery', loop: 1 });
|
|
961
1836
|
const arts = [...order.map(id => `handoff-${id}.md`), ...history.filter(e => e.type === 'qc.verdict').map(e => `qc-report-${e.loop}.md`), 'transcript.md'];
|
|
962
|
-
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`;
|
|
1837
|
+
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}` : ''}${securityAccepted ? `\n\n## Accepted critical security findings\n${securityAccepted}` : ''}${assumptions ? `\n\n## Assumptions made\n${assumptions}` : ''}\n\n## Artifacts\n${arts.map(a => `- ${a}`).join('\n')}\n`;
|
|
963
1838
|
let report = rules;
|
|
964
|
-
if (
|
|
965
|
-
|
|
1839
|
+
if (collabMode === 'DIRECT' && !order.length)
|
|
1840
|
+
report = intakeBrief || rules;
|
|
1841
|
+
else if (modelDirector()) {
|
|
1842
|
+
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${securityAccepted ? `ACCEPTED CRITICAL SECURITY FINDINGS (list them in the report):\n${securityAccepted}\n` : ''}${finalOutputs()}${reviewOn() && reviewChecklist ? `\nDIRECTOR REVIEW CHECKLIST${reviewUnmet ? ' (NOT MET items remain open)' : ''}:\n${reviewChecklist}\n` : ''}`);
|
|
966
1843
|
if (t?.trim())
|
|
967
1844
|
report = t;
|
|
968
1845
|
}
|
|
@@ -974,6 +1851,18 @@ export function startTeamRun(opts) {
|
|
|
974
1851
|
}
|
|
975
1852
|
async function pipeline() {
|
|
976
1853
|
try {
|
|
1854
|
+
if (toolsOn) {
|
|
1855
|
+
try {
|
|
1856
|
+
hub = await startToolHub(bus, { runId: journal.runId });
|
|
1857
|
+
if (finished) {
|
|
1858
|
+
hub.close();
|
|
1859
|
+
hub = null;
|
|
1860
|
+
}
|
|
1861
|
+
}
|
|
1862
|
+
catch (e) {
|
|
1863
|
+
emit({ type: 'agent.activity', agentId: config.director.id, text: oneLine(`CKit tools unavailable (${e instanceof Error ? e.message : String(e)}); agents run without them`, 160) });
|
|
1864
|
+
}
|
|
1865
|
+
}
|
|
977
1866
|
await intake();
|
|
978
1867
|
if (finished)
|
|
979
1868
|
return;
|
|
@@ -981,8 +1870,12 @@ export function startTeamRun(opts) {
|
|
|
981
1870
|
try {
|
|
982
1871
|
handoff = '';
|
|
983
1872
|
handoffs.clear();
|
|
1873
|
+
earlyTest?.ctl.abort();
|
|
1874
|
+
earlyTest = null; // a redirect cancels the early test of the previous flow
|
|
1875
|
+
earlyPlans.clear();
|
|
984
1876
|
reviewChecklist = '';
|
|
985
1877
|
reviewUnmet = false;
|
|
1878
|
+
securityAccepted = '';
|
|
986
1879
|
qcReport = '';
|
|
987
1880
|
deliverable = '';
|
|
988
1881
|
qcPassed = !order.includes('qc');
|
|
@@ -993,12 +1886,17 @@ export function startTeamRun(opts) {
|
|
|
993
1886
|
sentBack.clear();
|
|
994
1887
|
asks.clear();
|
|
995
1888
|
backs.clear();
|
|
996
|
-
|
|
1889
|
+
retReasons.clear();
|
|
1890
|
+
createdTasks.clear();
|
|
997
1891
|
convo.length = 0;
|
|
998
1892
|
if (intakeIntro)
|
|
999
1893
|
convo.push({ who: config.director.name, text: intakeIntro });
|
|
1000
|
-
|
|
1894
|
+
if (graph)
|
|
1895
|
+
await flowGraph();
|
|
1896
|
+
else
|
|
1897
|
+
await flow();
|
|
1001
1898
|
await reviewStage();
|
|
1899
|
+
await securityGate();
|
|
1002
1900
|
await delivery();
|
|
1003
1901
|
break;
|
|
1004
1902
|
}
|
|
@@ -1041,9 +1939,36 @@ export function startTeamRun(opts) {
|
|
|
1041
1939
|
}
|
|
1042
1940
|
catch { /* steering is best effort */ }
|
|
1043
1941
|
}
|
|
1942
|
+
lastInboxAt = Date.now();
|
|
1044
1943
|
inbox.push(added.length ? `${text} [owner attached: ${added.map(a => a.path).join(', ')}]` : text);
|
|
1045
|
-
|
|
1046
|
-
|
|
1944
|
+
if (URGENT_RE.test(text))
|
|
1945
|
+
wakeNow?.(); // an urgent steer is not held by the coalescing window
|
|
1946
|
+
}, () => doStop('Stopped from the console.'), {
|
|
1947
|
+
proceedWithAssumptions: () => { const w = waiting; if (w && w.assumptions)
|
|
1948
|
+
w.wake({ how: 'proceed', text: '' }); },
|
|
1949
|
+
pause: () => { if (finished || paused)
|
|
1950
|
+
return; paused = true; emit({ type: 'run.paused', by: 'owner' }); },
|
|
1951
|
+
resume: () => { if (finished || !paused)
|
|
1952
|
+
return; paused = false; emit({ type: 'run.resumed' }); wakeAll(); },
|
|
1953
|
+
interrupt: () => {
|
|
1954
|
+
if (finished)
|
|
1955
|
+
return;
|
|
1956
|
+
if (!paused) {
|
|
1957
|
+
paused = true;
|
|
1958
|
+
emit({ type: 'run.paused', by: 'interrupt' });
|
|
1959
|
+
}
|
|
1960
|
+
for (const [aid, ctl] of turnCtl) {
|
|
1961
|
+
interrupted.add(aid);
|
|
1962
|
+
const sess = running.get(aid);
|
|
1963
|
+
try {
|
|
1964
|
+
sess?.interrupt();
|
|
1965
|
+
}
|
|
1966
|
+
catch { /* best effort */ }
|
|
1967
|
+
ctl.abort();
|
|
1968
|
+
}
|
|
1969
|
+
},
|
|
1970
|
+
whenClosed: () => done.then(() => Promise.all(exits)).then(() => undefined), // resolves only after every owned child process has exited
|
|
1971
|
+
});
|
|
1047
1972
|
}
|
|
1048
1973
|
/** Re-emits a journal with original relative timing / speed (gaps capped at 1.5s/speed). */
|
|
1049
1974
|
export function replayTeamRun(runDir, opts = {}) {
|
|
@@ -1081,6 +2006,6 @@ export function replayTeamRun(runDir, opts = {}) {
|
|
|
1081
2006
|
end('failed');
|
|
1082
2007
|
else
|
|
1083
2008
|
timer = setTimeout(step, 0);
|
|
1084
|
-
return makeHandle(events[0]?.runId ?? basename(runDir), runDir, history, listeners, done, () => { }, () => end('stopped'));
|
|
2009
|
+
return makeHandle(events[0]?.runId ?? basename(runDir), runDir, history, listeners, done, () => { }, () => end('stopped'), {});
|
|
1085
2010
|
}
|
|
1086
2011
|
//# sourceMappingURL=engine.js.map
|