@ngockhoale/ckit 0.3.1 → 0.4.1
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/cli/ckit.js +0 -0
- 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 +1151 -176
- 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/engine.js +44 -0
- 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);
|
|
284
573
|
return;
|
|
285
|
-
|
|
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)
|
|
580
|
+
return;
|
|
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,40 +690,82 @@ 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'); };
|
|
702
|
+
// Stall watchdog: a provider stream can go silent mid-turn (seen on a real run: the stream abandoned a tool_use block and then sent only pings,
|
|
703
|
+
// so the CLI hung until agentTimeoutMs). No model output for stallMs while waiting for or generating output (never while a tool runs) aborts
|
|
704
|
+
// this attempt; the turn is retried once on a fresh process, then fails with a clear reason instead of hanging.
|
|
705
|
+
const stallMs = Math.min(Math.max(1000, Number(process.env['CKIT_STALL_MS']) || 240000), Math.max(1000, config.limits.agentTimeoutMs - 1000));
|
|
706
|
+
// Per-turn runners do not report tool calls, so a quiet long command looks like 'generating' there: only sessions (which report executing-tool) watch 'generating'.
|
|
707
|
+
let lastOut = Date.now(), stalled = false, att = new AbortController(), watch = null, inSession = false;
|
|
708
|
+
const bump = () => { lastOut = Date.now(); };
|
|
709
|
+
if (!own) {
|
|
710
|
+
watch = setInterval(() => { const w = waits.get(agent.id); if ((w === 'waiting-first-output' || (inSession && w === 'generating')) && Date.now() - lastOut > stallMs && !att.signal.aborted) {
|
|
711
|
+
stalled = true;
|
|
712
|
+
att.abort();
|
|
713
|
+
} }, Math.max(200, Math.min(5000, stallMs / 4)));
|
|
714
|
+
watch.unref?.();
|
|
715
|
+
}
|
|
366
716
|
try {
|
|
367
717
|
const raw = rawSink(agent);
|
|
368
|
-
const runOpts = {
|
|
369
|
-
cwd: opts.projectRoot, timeoutMs: config.limits.agentTimeoutMs, signal:
|
|
718
|
+
const runOpts = () => ({
|
|
719
|
+
cwd: opts.projectRoot, timeoutMs: config.limits.agentTimeoutMs, signal: AbortSignal.any([ctl.signal, att.signal]), ...(atts.length ? { images: images() } : {}),
|
|
370
720
|
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)
|
|
721
|
+
onActivity: text => { bump(); 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
722
|
step(l); },
|
|
373
|
-
onStep: (label, k, total) => step(oneLine(label, 80), k, total),
|
|
723
|
+
onStep: (label, k, total) => { bump(); step(oneLine(label, 80), k, total); },
|
|
374
724
|
onSubagent: e => {
|
|
725
|
+
bump();
|
|
375
726
|
agentLog(agent, `[${stamp()}] subagent ${e.type} ${e.childId}: ${e.type === 'started' ? e.task : e.type === 'activity' ? e.text : e.summary}\n`);
|
|
376
727
|
emit(e.type === 'started' ? { type: 'subagent.started', agentId: agent.id, childId: e.childId, kind: e.kind, task: oneLine(e.task, 160) }
|
|
377
728
|
: e.type === 'activity' ? { type: 'subagent.activity', agentId: agent.id, childId: e.childId, text: oneLine(e.text, 160) }
|
|
378
729
|
: { type: 'subagent.finished', agentId: agent.id, childId: e.childId, ok: e.ok, summary: oneLine(e.summary, 200) });
|
|
379
730
|
},
|
|
380
|
-
};
|
|
381
|
-
const
|
|
731
|
+
});
|
|
732
|
+
const fresh = () => { stalled = false; att = new AbortController(); bump(); setWait(agent.id, 'waiting-first-output'); };
|
|
733
|
+
const sess = sessionFor(agent, scheduler !== null && agent.team !== 'director' ? true : false);
|
|
382
734
|
let res;
|
|
383
735
|
if (!sess)
|
|
384
|
-
res = await runner(agent, prompt, runOpts);
|
|
736
|
+
res = await runner(agent, prompt, runOpts());
|
|
385
737
|
else {
|
|
386
738
|
running.set(agent.id, sess);
|
|
739
|
+
const ent = myEntries.get(sessKey(agent));
|
|
740
|
+
if (ent)
|
|
741
|
+
ent.busy = true;
|
|
742
|
+
inSession = true;
|
|
387
743
|
try {
|
|
388
|
-
res = await sess.send(prompt, { ...runOpts, onDelta: t => pushDelta(agent.id, t) });
|
|
744
|
+
res = await sess.send(prompt, { ...runOpts(), onDelta: t => { bump(); firstOut(); pushDelta(agent.id, t); }, onFirstOutput: () => { bump(); firstOut(); },
|
|
745
|
+
onTool: (phase, name, text) => { bump(); 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
746
|
}
|
|
390
747
|
finally {
|
|
391
748
|
flushDelta(agent.id);
|
|
392
749
|
running.delete(agent.id);
|
|
750
|
+
if (ent)
|
|
751
|
+
ent.busy = false;
|
|
752
|
+
inSession = false;
|
|
393
753
|
}
|
|
394
|
-
if (!res.ok && res.transport && !abort.signal.aborted) {
|
|
754
|
+
if (!res.ok && (res.transport || stalled) && !abort.signal.aborted && !ctl.signal.aborted) {
|
|
395
755
|
dropSession(agent);
|
|
396
|
-
|
|
397
|
-
|
|
756
|
+
const why = stalled ? `no model output for ${Math.round(stallMs / 1000)} s (stalled stream)` : oneLine(res.reason, 100);
|
|
757
|
+
runOpts().onActivity?.(`Persistent session failed (${why}); retrying this turn with a fresh one-shot process`);
|
|
758
|
+
fresh(); // after the notice: the notice counts as output (firstOut) and must not mark the new attempt as already generating
|
|
759
|
+
res = await runner(agent, prompt, runOpts());
|
|
398
760
|
}
|
|
399
761
|
}
|
|
762
|
+
if (!res.ok && stalled && !sess && !abort.signal.aborted && !ctl.signal.aborted) {
|
|
763
|
+
runOpts().onActivity?.(`No model output for ${Math.round(stallMs / 1000)} s (stalled stream); retrying this turn with a fresh process`);
|
|
764
|
+
fresh();
|
|
765
|
+
res = await runner(agent, prompt, runOpts());
|
|
766
|
+
}
|
|
767
|
+
if (!res.ok && stalled && !abort.signal.aborted && !ctl.signal.aborted)
|
|
768
|
+
res = { ok: false, reason: `no model output for ${Math.round(stallMs / 1000)} s, twice (the provider stream stalled); check the CLI/provider connection` };
|
|
400
769
|
if (res.ok && !own)
|
|
401
770
|
step(last);
|
|
402
771
|
return done(res.ok ? res : { ok: false, reason: withArgsNote(agent, res.reason) });
|
|
@@ -404,18 +773,55 @@ export function startTeamRun(opts) {
|
|
|
404
773
|
catch (e) {
|
|
405
774
|
return done({ ok: false, reason: withArgsNote(agent, e instanceof Error ? e.message : 'runner threw') });
|
|
406
775
|
}
|
|
776
|
+
finally {
|
|
777
|
+
if (watch)
|
|
778
|
+
clearInterval(watch);
|
|
779
|
+
abort.signal.removeEventListener('abort', onAbort);
|
|
780
|
+
signal?.removeEventListener('abort', onAbort);
|
|
781
|
+
if (turnCtl.get(agent.id) === ctl)
|
|
782
|
+
turnCtl.delete(agent.id);
|
|
783
|
+
}
|
|
784
|
+
}
|
|
785
|
+
/** PF-CALLS turn class of a team turn. */
|
|
786
|
+
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';
|
|
787
|
+
/** One agent turn with the pause gate, unread mail delivered in the prompt, and redo after an owner interrupt. */
|
|
788
|
+
async function runTurn(agent, task, prompt, first, last, o = {}) {
|
|
789
|
+
let p = prompt;
|
|
790
|
+
for (;;) {
|
|
791
|
+
await gate(agent.id);
|
|
792
|
+
const mail = bus.unread(agent.id);
|
|
793
|
+
if (mail.length) {
|
|
794
|
+
bus.markRead(agent.id, mail.map(m => m.mailId), 'prompt');
|
|
795
|
+
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')}`;
|
|
796
|
+
}
|
|
797
|
+
const taskId = o.taskId ?? curTask.get(agent.team);
|
|
798
|
+
turnCtx.set(agent.id, { rev: goalRevision, taskId: taskId ?? '' });
|
|
799
|
+
setWait(agent.id, 'starting');
|
|
800
|
+
emit({ type: 'agent.started', agentId: agent.id, task, turnClass: o.cls ?? classOf(agent), ...(taskId && agent.team !== 'director' ? { taskId } : {}) });
|
|
801
|
+
const res = await callRunner(agent, p, first, last, o.noLease === true, o.signal);
|
|
802
|
+
halted();
|
|
803
|
+
if (res.ok)
|
|
804
|
+
interrupted.delete(agent.id); // an interrupt the turn finished through anyway must not redo a later, unrelated failure
|
|
805
|
+
if (!res.ok && interrupted.delete(agent.id)) {
|
|
806
|
+
emit({ type: 'agent.interrupted', agentId: agent.id });
|
|
807
|
+
await gate(agent.id);
|
|
808
|
+
const guidance = [...inbox, ...notes.slice(-3)];
|
|
809
|
+
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')}` : '.'}`;
|
|
810
|
+
continue;
|
|
811
|
+
}
|
|
812
|
+
return res;
|
|
813
|
+
}
|
|
407
814
|
}
|
|
408
|
-
async function turn(agent, task, to, prompt,
|
|
815
|
+
async function turn(agent, task, to, prompt, o = {}) {
|
|
409
816
|
halted();
|
|
410
|
-
emit({ type: 'agent.started', agentId: agent.id, task });
|
|
411
817
|
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();
|
|
818
|
+
const res = await runTurn(agent, task, prompt, labels[0], labels[1], o);
|
|
414
819
|
if (!res.ok) {
|
|
415
820
|
emit({ type: 'agent.failed', agentId: agent.id, reason: res.reason });
|
|
416
821
|
return null;
|
|
417
822
|
}
|
|
418
|
-
|
|
823
|
+
lastTokens.set(agent.id, res.tokens);
|
|
824
|
+
emit({ type: 'agent.message', agentId: agent.id, to, text: res.text, tokens: res.tokens, ...(o.round ? { round: o.round } : {}) });
|
|
419
825
|
const safe = journal.redact(res.text);
|
|
420
826
|
convo.push({ who: agent.name, text: safe });
|
|
421
827
|
return safe;
|
|
@@ -427,15 +833,24 @@ export function startTeamRun(opts) {
|
|
|
427
833
|
};
|
|
428
834
|
// ---- director ----
|
|
429
835
|
const modelDirector = () => !simulated && config.director.cli !== 'auto' && config.director.cli !== 'simulated';
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
const
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
836
|
+
/** One Director model turn. Director turns are serialized (one persistent session), e.g. a bus question while a checkpoint runs. */
|
|
837
|
+
async function directorAsk(task, prompt, cls = 'director-synthesis') {
|
|
838
|
+
const prev = dirLock;
|
|
839
|
+
let release;
|
|
840
|
+
dirLock = new Promise(r => { release = r; });
|
|
841
|
+
try {
|
|
842
|
+
await prev;
|
|
843
|
+
halted();
|
|
844
|
+
const res = await runTurn(config.director, task, prompt, 'Reading the request', 'Writing the answer', { cls });
|
|
845
|
+
if (!res.ok) {
|
|
846
|
+
emit({ type: 'agent.failed', agentId: config.director.id, reason: res.reason });
|
|
847
|
+
return null;
|
|
848
|
+
}
|
|
849
|
+
return res.text;
|
|
850
|
+
}
|
|
851
|
+
finally {
|
|
852
|
+
release();
|
|
437
853
|
}
|
|
438
|
-
return res.text;
|
|
439
854
|
}
|
|
440
855
|
function directorSay(to, text, tokens = null) {
|
|
441
856
|
emit({ type: 'agent.message', agentId: config.director.id, to, text, tokens });
|
|
@@ -472,7 +887,7 @@ export function startTeamRun(opts) {
|
|
|
472
887
|
if (modelDirector()) {
|
|
473
888
|
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
889
|
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}`);
|
|
890
|
+
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. Do not chain every team after the previous one: list only real data dependencies (example for ba, implement, test, security, qc: "DEPENDS: implement <- ba; test <- implement; security <- implement; qc <- test, security" — Test and Security both only need the implementation, so they review it 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
891
|
for (let attempt = 0; attempt < 2; attempt++) {
|
|
477
892
|
const t = await ask();
|
|
478
893
|
if (t?.trim())
|
|
@@ -493,8 +908,93 @@ export function startTeamRun(opts) {
|
|
|
493
908
|
const m = /\[lane:([a-z0-9-]+)\]/i.exec(goal), l = lanes.find(x => x.id === m?.[1]?.toLowerCase()) ?? lanes[0];
|
|
494
909
|
return `DECISION: PROCEED\nLANE: ${l.id}\nLANE REASON: (simulated) ${m ? 'the goal names this lane' : 'first lane'}`;
|
|
495
910
|
}
|
|
496
|
-
|
|
911
|
+
const st = /\[sim-teams:([a-z0-9,-]+)\]/i.exec(goal), sx = /\[sim-execute(?::([^\]]*))?\]/i.exec(goal);
|
|
912
|
+
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]}` : ''}` : '');
|
|
913
|
+
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` : '');
|
|
914
|
+
if (sm.includes('DIRECT'))
|
|
915
|
+
return `DECISION: PROCEED${sm}`;
|
|
916
|
+
return lanes.length ? `DECISION: PROCEED${sm}` : `DECISION: PROCEED${sm}\n${ruleBrief()}`;
|
|
497
917
|
}
|
|
918
|
+
/** 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. */
|
|
919
|
+
const chooseMode = (text) => {
|
|
920
|
+
const m = parseMode(text), before = [...order], why = new Map();
|
|
921
|
+
let mode = !order.length ? 'DIRECT' : m?.mode ?? 'PARALLEL_MERGE', reason = !order.length ? 'no team in this flow' : m?.reason || (m ? '' : 'default: no MODE line');
|
|
922
|
+
if (mode === 'DELEGATE') {
|
|
923
|
+
const id = /DELEGATE[ \t]*[:\-]?[ \t]*["'`*]*([A-Za-z0-9_-]+)/i.exec(MODE_RE.exec(text)?.[0] ?? '')?.[1]?.toLowerCase();
|
|
924
|
+
const a = allAgentsOf(config).find(x => x.id === id && x.team !== 'director' && order.includes(x.team));
|
|
925
|
+
if (a) {
|
|
926
|
+
delegateTo = a;
|
|
927
|
+
order = [a.team];
|
|
928
|
+
reason = `${a.name}: ${reason}`;
|
|
929
|
+
}
|
|
930
|
+
else {
|
|
931
|
+
mode = 'PARALLEL_MERGE';
|
|
932
|
+
reason = `DELEGATE named no agent of this flow (${id ?? 'none'}); fell back to PARALLEL_MERGE`;
|
|
933
|
+
}
|
|
934
|
+
}
|
|
935
|
+
if (mode === 'DIRECT') {
|
|
936
|
+
for (const t of order)
|
|
937
|
+
why.set(t, 'DIRECT: the Director answers the owner itself');
|
|
938
|
+
order = [];
|
|
939
|
+
}
|
|
940
|
+
else if (delegateTo) {
|
|
941
|
+
for (const t of before)
|
|
942
|
+
if (t !== delegateTo.team)
|
|
943
|
+
why.set(t, `DELEGATE: only ${delegateTo.name} works on this goal`);
|
|
944
|
+
}
|
|
945
|
+
else {
|
|
946
|
+
const want = parseTeams(text)?.filter(t => order.includes(t));
|
|
947
|
+
if (want?.length) {
|
|
948
|
+
for (const t of order)
|
|
949
|
+
if (!want.includes(t))
|
|
950
|
+
why.set(t, `the Director did not activate this team (TEAMS: ${want.join(', ')})`);
|
|
951
|
+
order = order.filter(t => want.includes(t));
|
|
952
|
+
}
|
|
953
|
+
}
|
|
954
|
+
const writes = (t) => delegateTo?.team === t ? delegateTo.access === 'write' : agentsOf(t).some(a => a.access === 'write');
|
|
955
|
+
if (isReadOnlyGoal(goal) && order.length) {
|
|
956
|
+
// 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.
|
|
957
|
+
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;
|
|
958
|
+
for (const t of order) {
|
|
959
|
+
const r = drop(t);
|
|
960
|
+
if (r)
|
|
961
|
+
why.set(t, r);
|
|
962
|
+
}
|
|
963
|
+
order = order.filter(t => drop(t) === null);
|
|
964
|
+
if (!order.length) {
|
|
965
|
+
mode = 'DIRECT';
|
|
966
|
+
delegateTo = null;
|
|
967
|
+
reason = 'read-only goal and no read-only team in this flow: the Director answers it itself';
|
|
968
|
+
}
|
|
969
|
+
}
|
|
970
|
+
else if (mode !== 'DIRECT' && order.some(writes)) {
|
|
971
|
+
// 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.
|
|
972
|
+
const forced = before.filter(t => !order.includes(t) && (isSecurityTeam(t) || t === 'qc') && agentsOf(t).length > 0);
|
|
973
|
+
if (forced.length) {
|
|
974
|
+
order = before.filter(t => order.includes(t) || forced.includes(t));
|
|
975
|
+
for (const t of forced)
|
|
976
|
+
why.delete(t);
|
|
977
|
+
reason = `${reason ? `${reason}; ` : ''}Core rule added ${forced.map(teamName).join(', ')} because this flow changes files`;
|
|
978
|
+
}
|
|
979
|
+
}
|
|
980
|
+
if (mode === 'DIRECT') {
|
|
981
|
+
for (const t of before)
|
|
982
|
+
if (!order.includes(t) || order.length === 0)
|
|
983
|
+
why.set(t, why.get(t) ?? 'DIRECT: the Director answers the owner itself');
|
|
984
|
+
order = [];
|
|
985
|
+
}
|
|
986
|
+
collabMode = mode;
|
|
987
|
+
graph = mode === 'PARALLEL_EXECUTE' && order.length > 1 ? buildGraph(order, parseDepends(text)) : null;
|
|
988
|
+
emit({ type: 'mode.chosen', mode, reason: oneLine(reason, 300) });
|
|
989
|
+
for (const t of before)
|
|
990
|
+
if (!order.includes(t))
|
|
991
|
+
emit({ type: 'team.skipped', team: t, reason: oneLine(why.get(t) ?? 'not needed for this goal', 300) });
|
|
992
|
+
record('d-mode', { title: 'Collaboration mode', selected: mode, status: 'committed', rationale: reason || mode, affectedTasks: [...order] });
|
|
993
|
+
if (graph)
|
|
994
|
+
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] });
|
|
995
|
+
if (order.length < before.length)
|
|
996
|
+
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)) });
|
|
997
|
+
};
|
|
498
998
|
const parseLane = (text) => {
|
|
499
999
|
const m = /^[ \t>*_#-]*LANE[ \t]*\**[ \t]*:\**[ \t]*(.+)$/im.exec(text);
|
|
500
1000
|
const v = (m?.[1] ?? '').replace(/[*`"'_]/g, '').trim().toLowerCase();
|
|
@@ -553,7 +1053,9 @@ export function startTeamRun(opts) {
|
|
|
553
1053
|
if (modelDirector() && !parseBriefs(body).size)
|
|
554
1054
|
body = `${body}\n\n${ruleBrief()}`;
|
|
555
1055
|
}
|
|
556
|
-
|
|
1056
|
+
chooseMode(text);
|
|
1057
|
+
body = body.split('\n').filter(l => !/^[ \t>*_#-]*(MODE( REASON)?|TEAMS|DEPENDS)\**[ \t]*:/i.test(l)).join('\n').trim();
|
|
1058
|
+
intakeBrief = directorSay(order[0] ?? 'all', body || (collabMode === 'DIRECT' ? '(the Director gave no answer text)' : ruleBrief()));
|
|
557
1059
|
break;
|
|
558
1060
|
}
|
|
559
1061
|
briefs.clear();
|
|
@@ -578,9 +1080,24 @@ export function startTeamRun(opts) {
|
|
|
578
1080
|
}
|
|
579
1081
|
return ruleDecision(text);
|
|
580
1082
|
}
|
|
1083
|
+
/** PF-WAKE window sleep: cut short by an urgent owner message, a critical finding or the run ending. */
|
|
1084
|
+
const wakeSleep = (ms) => new Promise(r => {
|
|
1085
|
+
const t = setTimeout(() => { wakeNow = null; r(); }, ms);
|
|
1086
|
+
wakeNow = () => { clearTimeout(t); wakeNow = null; r(); };
|
|
1087
|
+
});
|
|
581
1088
|
/** Processes owner messages between agent turns. Throws Redirect / Halt. */
|
|
582
1089
|
async function drain() {
|
|
583
1090
|
let redirect = false;
|
|
1091
|
+
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)
|
|
1092
|
+
const win = Number(process.env['CKIT_WAKE_WINDOW_MS'] ?? 1500), left = lastInboxAt + (Number.isFinite(win) ? Math.max(0, win) : 1500) - Date.now();
|
|
1093
|
+
const bypass = criticalSince || inbox.some(t => URGENT_RE.test(t)); // urgent steer / critical finding: wake now (STOP is handled on arrival)
|
|
1094
|
+
if (left > 0 && !bypass)
|
|
1095
|
+
await wakeSleep(left);
|
|
1096
|
+
halted();
|
|
1097
|
+
criticalSince = false;
|
|
1098
|
+
if (inbox.length > 1)
|
|
1099
|
+
inbox.splice(0, inbox.length, inbox.join('\n\n'));
|
|
1100
|
+
}
|
|
584
1101
|
while (inbox.length) {
|
|
585
1102
|
const text = inbox.shift();
|
|
586
1103
|
const d = await decide(text);
|
|
@@ -591,6 +1108,8 @@ export function startTeamRun(opts) {
|
|
|
591
1108
|
throw new Halt();
|
|
592
1109
|
}
|
|
593
1110
|
notes.push(d.note);
|
|
1111
|
+
goalRevision++;
|
|
1112
|
+
record('d-owner', { title: 'Owner instruction', selected: d.decision, status: 'committed', authority: 'owner', rationale: d.note });
|
|
594
1113
|
if (d.decision === 'redirect')
|
|
595
1114
|
redirect = true;
|
|
596
1115
|
}
|
|
@@ -606,7 +1125,7 @@ export function startTeamRun(opts) {
|
|
|
606
1125
|
finish('stopped', `Run stopped. ${why}\n\nGoal: ${goal}\n${handoff ? `\nLast handoff: handoff-ba.md\n` : ''}`);
|
|
607
1126
|
}
|
|
608
1127
|
const nextOf = (k) => order[k + 1] ?? 'director';
|
|
609
|
-
const backOf = () => { const r =
|
|
1128
|
+
const backOf = (id) => { const r = retReasons.get(id) ?? null; retReasons.delete(id); return r === null ? null : { full: r, short: oneLine(r, 300) }; };
|
|
610
1129
|
const handoffs = new Map(); // per team: its latest handoff in short form (for the trail)
|
|
611
1130
|
const cap = (s, n) => { const t = oneLine(s, 100000); return t.length > n ? `${t.slice(0, n - 1)}... (shortened)` : t; };
|
|
612
1131
|
/** Compact trail of the handoffs of the first `upTo` teams: DONE and OPEN only, capped, explicitly marked as shortened. */
|
|
@@ -616,18 +1135,58 @@ export function startTeamRun(opts) {
|
|
|
616
1135
|
};
|
|
617
1136
|
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
1137
|
const hdrS = (agent, stage, loop) => simAgent(agent) ? `${simHeader({ stage, loop, turn: 1, turns: 1, final: true })}\n` : '';
|
|
1138
|
+
const earlyPlans = new Map();
|
|
1139
|
+
/** 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. */
|
|
1140
|
+
const startEarlyTest = (k) => {
|
|
1141
|
+
if (earlyTest || collabMode === 'DIRECT' || collabMode === 'DELEGATE' || process.env['CKIT_EARLY_TEST'] === '0')
|
|
1142
|
+
return;
|
|
1143
|
+
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)
|
|
1144
|
+
if (impl < 0 || k !== impl - 1 || !tid)
|
|
1145
|
+
return;
|
|
1146
|
+
if (graph) {
|
|
1147
|
+
const seen = new Set(), q = [...(graph.get(tid) ?? [])];
|
|
1148
|
+
while (q.length) {
|
|
1149
|
+
const d = q.pop();
|
|
1150
|
+
if (!seen.has(d)) {
|
|
1151
|
+
seen.add(d);
|
|
1152
|
+
q.push(...(graph.get(d) ?? []));
|
|
1153
|
+
}
|
|
1154
|
+
}
|
|
1155
|
+
if (!seen.has('implement'))
|
|
1156
|
+
return;
|
|
1157
|
+
} // the Tester does not wait for Implement: its own pass starts now, no early plan needed
|
|
1158
|
+
const agents = agentsOf(tid);
|
|
1159
|
+
if (!agents.length)
|
|
1160
|
+
return;
|
|
1161
|
+
const taskId = `t-${tid}-early`, dep = curTask.get(order[k]);
|
|
1162
|
+
emit({ type: 'task.created', taskId, team: tid, title: `${teamName(tid)} early test plan`, deps: dep ? [dep] : [] });
|
|
1163
|
+
emit({ type: 'task.updated', taskId, status: 'running', note: 'parallel with Implement' });
|
|
1164
|
+
const contract = clip(outs.get(order[k]) ?? '', 8000), rev = goalRevision, ctl = new AbortController();
|
|
1165
|
+
const p = Promise.all(agents.map(a => {
|
|
1166
|
+
const ro = { ...a, access: 'read' }; // never competes with the writer for the workspace
|
|
1167
|
+
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 })
|
|
1168
|
+
.then(t => { if (t && !ctl.signal.aborted)
|
|
1169
|
+
publish(a.id, contributionFrom(t), taskId, 'ok', rev); return t && !ctl.signal.aborted ? `[${a.name}]: ${clip(t, 3000)}` : ''; })
|
|
1170
|
+
.catch(() => '');
|
|
1171
|
+
})).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; });
|
|
1172
|
+
earlyTest = { id: tid, taskId, p, ctl };
|
|
1173
|
+
};
|
|
619
1174
|
const dispatches = new Map(); // Director's dispatch text per team (model Director only)
|
|
620
1175
|
const dirBacks = new Map(); // Director send-backs per team at a checkpoint
|
|
621
1176
|
const inputBlock = (k, id) => {
|
|
622
|
-
const
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
1177
|
+
const parts = [];
|
|
1178
|
+
for (const p of graph ? graph.get(id) ?? [] : [prevId(k)])
|
|
1179
|
+
if (p !== 'director')
|
|
1180
|
+
parts.push(`HANDOFF FROM THE ${teamName(p).toUpperCase()} TEAM (in full):\n${clip(outs.get(p) ?? '', 8000)}`);
|
|
1181
|
+
const trail = graph ? '' : trailBlock(k - 1);
|
|
626
1182
|
if (trail)
|
|
627
1183
|
parts.push(trail.trimEnd());
|
|
628
1184
|
const dp = dispatches.get(id);
|
|
629
1185
|
if (dp)
|
|
630
1186
|
parts.push(`DIRECTOR'S DISPATCH FOR YOUR TEAM:\n${clip(dp, 3000)}`);
|
|
1187
|
+
const et = earlyPlans.get(id);
|
|
1188
|
+
if (et)
|
|
1189
|
+
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
1190
|
const sb = sentBack.get(id);
|
|
632
1191
|
if (sb)
|
|
633
1192
|
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 +1226,23 @@ export function startTeamRun(opts) {
|
|
|
667
1226
|
return t ?? '(the previous team could not answer)';
|
|
668
1227
|
}
|
|
669
1228
|
/** 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,
|
|
1229
|
+
async function teamTurn(k, agent, task, to, prompt, o = {}) {
|
|
671
1230
|
let extra = '';
|
|
672
1231
|
for (;;) {
|
|
673
|
-
const text = await turn(agent, task, to, prompt + extra,
|
|
1232
|
+
const text = await turn(agent, task, to, prompt + extra, o);
|
|
674
1233
|
if (text === null)
|
|
675
1234
|
return null;
|
|
676
1235
|
const m = markers(text);
|
|
677
1236
|
if (m.ret !== null) {
|
|
678
|
-
|
|
1237
|
+
retReasons.set(order[k] ?? agent.team, m.ret || 'no reason given');
|
|
679
1238
|
return m.clean;
|
|
680
1239
|
}
|
|
681
1240
|
if (m.ask === null || (asks.get(k) ?? 0) >= limit)
|
|
682
1241
|
return m.clean;
|
|
1242
|
+
if (repeated(`ask:${agent.id}`, m.ask)) {
|
|
1243
|
+
emit({ type: 'loop.detected', kind: 'ask', from: agent.team, reason: oneLine(`the same question again without new evidence: ${m.ask}`, 300) });
|
|
1244
|
+
return m.clean;
|
|
1245
|
+
}
|
|
683
1246
|
asks.set(k, (asks.get(k) ?? 0) + 1);
|
|
684
1247
|
const answer = await askPrevious(k, agent, m.ask || 'please clarify');
|
|
685
1248
|
await drain();
|
|
@@ -694,113 +1257,212 @@ export function startTeamRun(opts) {
|
|
|
694
1257
|
const to = nextOf(k), toName = to === 'director' ? 'Director' : teamName(to);
|
|
695
1258
|
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
1259
|
};
|
|
1260
|
+
/** Parallel members of one pass share an AbortController: when one rejects (Redirect / Halt) the siblings are cancelled (so none keeps the write lease)
|
|
1261
|
+
* and every member has settled before the first rejection is rethrown. */
|
|
1262
|
+
async function parallelAll(start) {
|
|
1263
|
+
const ctl = new AbortController();
|
|
1264
|
+
const ps = start(ctl.signal).map(p => p.catch((e) => { ctl.abort(); throw e; }));
|
|
1265
|
+
const rs = await Promise.allSettled(ps);
|
|
1266
|
+
const bad = rs.find((r) => r.status === 'rejected');
|
|
1267
|
+
if (bad)
|
|
1268
|
+
throw bad.reason;
|
|
1269
|
+
return rs.map(r => r.value);
|
|
1270
|
+
}
|
|
697
1271
|
/** 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) {
|
|
1272
|
+
async function teamPass(k, id, pass, nodeSig) {
|
|
699
1273
|
const agents = agentsOf(id), lead = agents[0], name = teamName(id), isQc = id === 'qc', to = nextOf(k), toName = to === 'director' ? 'Director' : teamName(to);
|
|
700
1274
|
const stageName = id === 'ba' ? 'ba-discussion' : id === 'implement' || id === 'qc' ? id : 'extra-team';
|
|
701
1275
|
emit({ type: 'stage.changed', stage: stageName, loop: pass, ...(stageName === 'extra-team' ? { team: id } : {}) });
|
|
702
|
-
const
|
|
1276
|
+
const rounds = config.limits.baRounds, active = delegateTo && delegateTo.team === id ? [delegateTo] : agents, multi = active.length > 1;
|
|
1277
|
+
const parallel = multi && (rounds === 0 || collabMode === 'PARALLEL_MERGE' && rounds === 0);
|
|
703
1278
|
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;
|
|
1279
|
+
const turns = !multi ? 1 : parallel ? agents.length * (collabMode === 'TARGETED_DISCUSSION' ? 2 : 1) + 1 : agents.length * rounds + (writer ? 1 : 0) + (writer === lead ? 0 : 1);
|
|
1280
|
+
// B7 task graph: one task per team pass; it depends on the previous team's latest task
|
|
1281
|
+
const taskId = `t-${id}-${pass}`, depTasks = (graph ? graph.get(id) ?? [] : k > 0 ? [order[k - 1]] : []).flatMap(d => curTask.get(d) ?? []);
|
|
1282
|
+
curTask.set(id, taskId);
|
|
1283
|
+
if (!createdTasks.has(taskId)) {
|
|
1284
|
+
createdTasks.add(taskId);
|
|
1285
|
+
emit({ type: 'task.created', taskId, team: id, title: `${name} pass ${pass}`, deps: depTasks });
|
|
740
1286
|
}
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
1287
|
+
emit({ type: 'task.updated', taskId, status: 'running' });
|
|
1288
|
+
let taskDone = false;
|
|
1289
|
+
const endTask = (status, note) => { if (taskDone)
|
|
1290
|
+
return; taskDone = true; emit({ type: 'task.updated', taskId, status, ...(note ? { note: oneLine(note, 200) } : {}) }); };
|
|
1291
|
+
try {
|
|
1292
|
+
return await teamPassBody();
|
|
1293
|
+
}
|
|
1294
|
+
catch (e) {
|
|
1295
|
+
endTask('failed', e instanceof Halt && !finished ? 'halted' : 'the run ended');
|
|
1296
|
+
throw e;
|
|
1297
|
+
}
|
|
1298
|
+
async function teamPassBody() {
|
|
1299
|
+
const verdicts = new Map(), lastMsg = new Map(), log = [];
|
|
1300
|
+
let n = 0, qcReturn = null, raw = null, failNote = '';
|
|
1301
|
+
const run = async (agent, phase, round, what, task, toId, readOnly, sig0) => {
|
|
1302
|
+
if (nodeSig?.aborted)
|
|
1303
|
+
throw new NodeCancelled();
|
|
1304
|
+
const signal = sig0 && nodeSig ? AbortSignal.any([sig0, nodeSig]) : sig0 ?? nodeSig;
|
|
1305
|
+
n++;
|
|
1306
|
+
const rev = goalRevision; // captured at turn start: an owner instruction that lands meanwhile makes this contribution stale
|
|
1307
|
+
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 } : {}) });
|
|
1308
|
+
if (nodeSig?.aborted)
|
|
1309
|
+
throw new NodeCancelled(); // a sibling graph node redirected / halted: this node stops without publishing
|
|
1310
|
+
if (signal?.aborted)
|
|
1311
|
+
return null; // the parallel pass was cancelled because a sibling redirected / halted: no publish, no failure
|
|
1312
|
+
if (text === null) {
|
|
1313
|
+
if (!isQc && phase === 'contribute' && readOnly) {
|
|
1314
|
+
// 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
|
|
1315
|
+
const f = history.filter(e => e.type === 'agent.failed').at(-1);
|
|
1316
|
+
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);
|
|
1317
|
+
return null;
|
|
1318
|
+
}
|
|
1319
|
+
if (!isQc)
|
|
1320
|
+
return fail(agent, `the ${name} stage`);
|
|
1321
|
+
const f = history.filter(e => e.type === 'agent.failed').at(-1); // a QC reviewer that cannot run counts as FAIL
|
|
1322
|
+
verdicts.set(agent.id, 'FAIL');
|
|
1323
|
+
failNote = `QC agent could not run: ${f && f.type === 'agent.failed' ? f.reason : 'unknown'}`;
|
|
1324
|
+
publish(agent.id, { findings: [{ summary: oneLine(failNote, 300), severity: 'high' }], recommendations: [], risks: [], proposedDecisions: [], evidenceRefs: [], unresolvedQuestions: [], status: 'complete' }, taskId, 'failed', rev);
|
|
1325
|
+
return '';
|
|
1326
|
+
}
|
|
1327
|
+
lastMsg.set(agent.id, text);
|
|
1328
|
+
if (isQc && /VERDICT/i.test(text))
|
|
1329
|
+
verdicts.set(agent.id, parseVerdict(text));
|
|
1330
|
+
if (phase !== 'discuss')
|
|
1331
|
+
publish(agent.id, contributionFrom(text, isQc && /VERDICT/i.test(text) && parseVerdict(text) === 'FAIL'), taskId, 'ok', rev);
|
|
1332
|
+
if (!parallel || phase === 'handoff')
|
|
1333
|
+
await drain();
|
|
1334
|
+
return text;
|
|
1335
|
+
};
|
|
1336
|
+
const early = () => retReasons.has(id);
|
|
1337
|
+
const returnedEarly = () => {
|
|
1338
|
+
if (!early())
|
|
1339
|
+
return null;
|
|
1340
|
+
if (isQc) {
|
|
1341
|
+
qcReturn = retReasons.get(id) ?? null;
|
|
1342
|
+
retReasons.delete(id);
|
|
1343
|
+
return null;
|
|
1344
|
+
}
|
|
1345
|
+
return { out: [...lastMsg.values()].at(-1) ?? '', back: backOf(id) };
|
|
1346
|
+
};
|
|
1347
|
+
if (!multi) {
|
|
1348
|
+
const solo = active[0];
|
|
1349
|
+
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
|
|
1350
|
+
const r = returnedEarly();
|
|
1351
|
+
if (r) {
|
|
1352
|
+
endTask('done', 'sent back');
|
|
1353
|
+
return r;
|
|
756
1354
|
}
|
|
757
|
-
if (r >= 2 && agreed === agents.length)
|
|
758
|
-
break;
|
|
759
1355
|
}
|
|
760
|
-
if (
|
|
761
|
-
|
|
1356
|
+
else if (parallel) {
|
|
1357
|
+
// PF-COLLAB: every member works independently and at the same time (no discussion rounds, nobody waits for a teammate); then the lead merges.
|
|
1358
|
+
const others = (a) => agents.filter(x => x.id !== a.id).map(x => x.name).join(', ');
|
|
1359
|
+
const outsP = await parallelAll(sig => agents.map((a, i) => {
|
|
1360
|
+
const writes = a === writer;
|
|
1361
|
+
const what = writes
|
|
1362
|
+
? `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.`
|
|
1363
|
+
: `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.`;
|
|
1364
|
+
return run(a, 'contribute', 1, what, `${name} contribution (${i + 1}/${agents.length})`, lead.id, !writes, sig).then(t => ({ a, t }));
|
|
1365
|
+
}));
|
|
1366
|
+
if (qcReturn === null && !retReasons.has(id)) {
|
|
1367
|
+
log.length = 0;
|
|
1368
|
+
const alive = outsP.filter(o => o.t !== null);
|
|
1369
|
+
if (!alive.length)
|
|
1370
|
+
return fail(lead, `the ${name} stage`); // every member failed: nothing to merge
|
|
1371
|
+
for (const { a, t } of outsP)
|
|
1372
|
+
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)}`);
|
|
1373
|
+
n = agents.length;
|
|
1374
|
+
if (collabMode === 'TARGETED_DISCUSSION') {
|
|
1375
|
+
// 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
|
|
1376
|
+
const snapshot = log.join('\n\n');
|
|
1377
|
+
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 }))));
|
|
1378
|
+
for (const { a, t } of outsC)
|
|
1379
|
+
if (t?.trim())
|
|
1380
|
+
log.push(`[${a.name}, clarification]: ${clip(t, 1500)}`);
|
|
1381
|
+
n += agents.length;
|
|
1382
|
+
}
|
|
1383
|
+
const merged = mergeFindings(contribs.filter(c => c.taskId === taskId));
|
|
1384
|
+
if (merged.length)
|
|
1385
|
+
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')}`);
|
|
1386
|
+
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
|
|
1387
|
+
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);
|
|
1388
|
+
}
|
|
762
1389
|
const rr = returnedEarly();
|
|
763
|
-
if (rr)
|
|
1390
|
+
if (rr) {
|
|
1391
|
+
endTask('done', 'sent back');
|
|
764
1392
|
return rr;
|
|
765
|
-
|
|
766
|
-
raw = t;
|
|
767
|
-
else
|
|
768
|
-
log.push(`[work] ${writer.name}: ${clip(t ?? '', 2500)}`);
|
|
1393
|
+
}
|
|
769
1394
|
}
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
1395
|
+
else {
|
|
1396
|
+
discussion: for (let r = 1; r <= rounds; r++) {
|
|
1397
|
+
let agreed = 0;
|
|
1398
|
+
for (let i = 0; i < agents.length; i++) {
|
|
1399
|
+
const a = agents[i], peer = agents[(i + 1) % agents.length];
|
|
1400
|
+
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(', ')}).`;
|
|
1401
|
+
const t = await run(a, 'discuss', r, what, `${name} discussion ${r}/${rounds} (${i + 1}/${agents.length})`, peer.id, true);
|
|
1402
|
+
const rr = returnedEarly();
|
|
1403
|
+
if (rr) {
|
|
1404
|
+
endTask('done', 'sent back');
|
|
1405
|
+
return rr;
|
|
1406
|
+
}
|
|
1407
|
+
if (qcReturn !== null)
|
|
1408
|
+
break discussion;
|
|
1409
|
+
log.push(`[round ${r}] ${a.name}: ${clip(t ?? '', 1500)}`);
|
|
1410
|
+
if (r >= 2 && t && AGREED_RE.test(t))
|
|
1411
|
+
agreed++;
|
|
1412
|
+
}
|
|
1413
|
+
if (r >= 2 && agreed === agents.length)
|
|
1414
|
+
break;
|
|
1415
|
+
}
|
|
1416
|
+
if (qcReturn === null && writer) {
|
|
1417
|
+
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
|
|
1418
|
+
const rr = returnedEarly();
|
|
1419
|
+
if (rr) {
|
|
1420
|
+
endTask('done', 'sent back');
|
|
1421
|
+
return rr;
|
|
1422
|
+
}
|
|
1423
|
+
if (writer === lead)
|
|
1424
|
+
raw = t;
|
|
1425
|
+
else
|
|
1426
|
+
log.push(`[work] ${writer.name}: ${clip(t ?? '', 2500)}`);
|
|
1427
|
+
}
|
|
1428
|
+
if (qcReturn === null && raw === null) {
|
|
1429
|
+
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);
|
|
1430
|
+
const rr = returnedEarly();
|
|
1431
|
+
if (rr) {
|
|
1432
|
+
endTask('done', 'sent back');
|
|
1433
|
+
return rr;
|
|
1434
|
+
}
|
|
1435
|
+
}
|
|
775
1436
|
}
|
|
1437
|
+
const rawText = raw ?? '';
|
|
1438
|
+
const sec = parseHandoff(rawText);
|
|
1439
|
+
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)}`;
|
|
1440
|
+
let back = null;
|
|
1441
|
+
if (isQc) {
|
|
1442
|
+
const failed = qcReturn !== null || [...verdicts.values()].some(v => v === 'FAIL') || (!verdicts.size);
|
|
1443
|
+
const verdict = failed ? 'FAIL' : 'PASS';
|
|
1444
|
+
const firstFailId = [...verdicts].find(([, v]) => v === 'FAIL')?.[0];
|
|
1445
|
+
const firstFail = qcReturn !== null ? `Returned to the previous team: ${qcReturn}` : failNote || (firstFailId ? (lastMsg.get(firstFailId) ?? '').replace(/\n?.*VERDICT.*$/i, '') : 'no reviewer gave a verdict');
|
|
1446
|
+
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`;
|
|
1447
|
+
const art = journal.writeArtifact(`qc-report-${pass}.md`, qcReport);
|
|
1448
|
+
emit({ type: 'qc.verdict', verdict, loop: pass, summary: oneLine(verdict === 'PASS' ? 'All QC reviewers passed the deliverable.' : firstFail, 300) });
|
|
1449
|
+
qcPassed = verdict === 'PASS';
|
|
1450
|
+
void art;
|
|
1451
|
+
text += `\n\nVERDICT: ${verdict}`;
|
|
1452
|
+
back = failed ? { full: qcReport, short: oneLine(firstFail, 300) } : null;
|
|
1453
|
+
}
|
|
1454
|
+
else
|
|
1455
|
+
back = backOf(id);
|
|
1456
|
+
if (id === 'ba' && atts.length)
|
|
1457
|
+
text += `\n\n## Attachments from the owner\nPart of this handoff. Read them together with the document above.\n${attachmentLines(atts)}\n`;
|
|
1458
|
+
handoffs.set(id, { done: sec ? sec.DONE : rawText, open: sec ? sec.OPEN : '(handoff not structured)' });
|
|
1459
|
+
const art = journal.writeArtifact(`handoff-${id}.md`, text);
|
|
1460
|
+
if (id === 'ba')
|
|
1461
|
+
journal.writeArtifact('handoff-ba.md', text);
|
|
1462
|
+
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
|
|
1463
|
+
endTask(back ? 'failed' : 'done', back ? back.short : undefined);
|
|
1464
|
+
return { out: text, back, art };
|
|
776
1465
|
}
|
|
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
1466
|
}
|
|
805
1467
|
/** Director rewrites the brief for team 1 after it sent the work back. */
|
|
806
1468
|
async function directorRewrite(id, reason) {
|
|
@@ -819,9 +1481,12 @@ export function startTeamRun(opts) {
|
|
|
819
1481
|
if (!modelDirector())
|
|
820
1482
|
return dflt;
|
|
821
1483
|
const ho = handoffs.get(id), ids = new Set(agentsOf(id).map(x => x.id));
|
|
822
|
-
const
|
|
1484
|
+
const tid = curTask.get(id), high = highIn(contribs.filter(c => c.taskId === tid && c.goalRevision === goalRevision));
|
|
1485
|
+
// PF-WAKE: the Director is woken only for open questions, a critical/high finding, a failed agent or a pending owner message
|
|
1486
|
+
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
1487
|
if (clean) {
|
|
824
1488
|
emit({ type: 'director.decision', decision: 'continue', note: 'auto: clean handoff' });
|
|
1489
|
+
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
1490
|
return dflt;
|
|
826
1491
|
} // nothing open: skip the Director model call
|
|
827
1492
|
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 +1513,9 @@ export function startTeamRun(opts) {
|
|
|
848
1513
|
cp = parseCheckpoint(t2);
|
|
849
1514
|
}
|
|
850
1515
|
}
|
|
851
|
-
|
|
1516
|
+
const decision = cp.decision === 'return' ? 'return' : 'accept';
|
|
1517
|
+
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] : [] });
|
|
1518
|
+
return { decision, dispatch: cp.dispatch, said: cp.dispatch || t.trim(), reason: cp.reason };
|
|
852
1519
|
}
|
|
853
1520
|
/** 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
1521
|
async function flow(from = 0) {
|
|
@@ -856,14 +1523,23 @@ export function startTeamRun(opts) {
|
|
|
856
1523
|
while (k < order.length) {
|
|
857
1524
|
const id = order[k], pass = (passes.get(id) ?? 0) + 1;
|
|
858
1525
|
passes.set(id, pass);
|
|
859
|
-
|
|
1526
|
+
retReasons.delete(id);
|
|
1527
|
+
if (earlyTest && earlyTest.id === id && !earlyPlans.has(id)) {
|
|
1528
|
+
setWait(agentsOf(id)[0]?.id ?? id, 'waiting-dependency', earlyTest.taskId);
|
|
1529
|
+
const plan = await earlyTest.p;
|
|
1530
|
+
halted();
|
|
1531
|
+
if (plan)
|
|
1532
|
+
earlyPlans.set(id, plan);
|
|
1533
|
+
}
|
|
860
1534
|
const res = await teamPass(k, id, pass);
|
|
861
1535
|
let note = '';
|
|
862
1536
|
sentBack.delete(id);
|
|
863
1537
|
outs.set(id, res.out);
|
|
864
1538
|
if (res.back) {
|
|
865
|
-
const used = backs.get(k) ?? 0;
|
|
866
|
-
if (
|
|
1539
|
+
const used = backs.get(k) ?? 0, loop = repeated(`ret:${id}`, res.back.short);
|
|
1540
|
+
if (loop)
|
|
1541
|
+
emit({ type: 'loop.detected', kind: 'return', from: id, reason: oneLine(`the same send-back again without new evidence: ${res.back.short}`, 300) });
|
|
1542
|
+
if (used < limit && !loop) {
|
|
867
1543
|
backs.set(k, used + 1);
|
|
868
1544
|
emit({ type: 'flow.back', kind: 'return', from: id, to: prevId(k), reason: res.back.short });
|
|
869
1545
|
if (k === 0)
|
|
@@ -880,9 +1556,13 @@ export function startTeamRun(opts) {
|
|
|
880
1556
|
}
|
|
881
1557
|
else if (k < order.length - 1) {
|
|
882
1558
|
const nextId = order[k + 1], cp = await checkpoint(id, nextId, res.out);
|
|
1559
|
+
if (cp.decision !== 'return')
|
|
1560
|
+
startEarlyTest(k);
|
|
883
1561
|
if (cp.decision === 'return') {
|
|
884
|
-
const used = dirBacks.get(id) ?? 0;
|
|
885
|
-
if (
|
|
1562
|
+
const used = dirBacks.get(id) ?? 0, loop = repeated(`dret:${id}`, cp.reason);
|
|
1563
|
+
if (loop)
|
|
1564
|
+
emit({ type: 'loop.detected', kind: 'return', from: 'director', reason: oneLine(`the Director returned the same thing again: ${cp.reason}`, 300) });
|
|
1565
|
+
if (used < limit && !loop) {
|
|
886
1566
|
dirBacks.set(id, used + 1);
|
|
887
1567
|
const reason = cp.reason || 'the Director asked for a rework';
|
|
888
1568
|
emit({ type: 'flow.back', kind: 'return', from: 'director', to: id, reason: oneLine(reason, 300) });
|
|
@@ -910,6 +1590,185 @@ export function startTeamRun(opts) {
|
|
|
910
1590
|
const lastId = order.at(-1);
|
|
911
1591
|
deliverable = lastId ? outs.get(lastId) ?? '' : '';
|
|
912
1592
|
}
|
|
1593
|
+
/** 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.
|
|
1594
|
+
* 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).
|
|
1595
|
+
* When one node redirects / halts / fails, the sibling nodes are cancelled and every node settles before the error is rethrown. */
|
|
1596
|
+
async function flowGraph(only) {
|
|
1597
|
+
const g = graph, ctl = new AbortController();
|
|
1598
|
+
const dependents = (id) => order.filter(x => (g.get(x) ?? []).includes(id));
|
|
1599
|
+
const closure = (start) => { const out = new Set(), q = [start]; while (q.length)
|
|
1600
|
+
for (const d of dependents(q.pop()))
|
|
1601
|
+
if (!out.has(d)) {
|
|
1602
|
+
out.add(d);
|
|
1603
|
+
q.push(d);
|
|
1604
|
+
} return out; };
|
|
1605
|
+
const mine = (id) => !only || only.has(id);
|
|
1606
|
+
for (const id of order)
|
|
1607
|
+
if (mine(id)) {
|
|
1608
|
+
const p = (passes.get(id) ?? 0) + 1, tid = `t-${id}-${p}`;
|
|
1609
|
+
if (!createdTasks.has(tid)) {
|
|
1610
|
+
createdTasks.add(tid);
|
|
1611
|
+
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}`) });
|
|
1612
|
+
emit({ type: 'task.updated', taskId: tid, status: 'pending', note: (g.get(id) ?? []).length ? `waiting for: ${(g.get(id) ?? []).map(teamName).join(', ')}` : 'ready' });
|
|
1613
|
+
}
|
|
1614
|
+
}
|
|
1615
|
+
// 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).
|
|
1616
|
+
const ready = new Map(), nctl = new Map(), live = new Set(), errs = [];
|
|
1617
|
+
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 }); };
|
|
1618
|
+
const settleAll = () => { for (const r of ready.values())
|
|
1619
|
+
r.res(); };
|
|
1620
|
+
for (const id of order) {
|
|
1621
|
+
fresh(id);
|
|
1622
|
+
if (!mine(id))
|
|
1623
|
+
ready.get(id)?.res();
|
|
1624
|
+
}
|
|
1625
|
+
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; };
|
|
1626
|
+
/** 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. */
|
|
1627
|
+
const active = new Set(), started = new Set();
|
|
1628
|
+
const invalidate = (to, id) => {
|
|
1629
|
+
const own = closure(id);
|
|
1630
|
+
own.add(id);
|
|
1631
|
+
for (const d of order) {
|
|
1632
|
+
if (!closure(to).has(d) || own.has(d) || !mine(d))
|
|
1633
|
+
continue;
|
|
1634
|
+
if (!active.has(d)) {
|
|
1635
|
+
fresh(d);
|
|
1636
|
+
spawn(d);
|
|
1637
|
+
} // already finished on the old output: run again
|
|
1638
|
+
else if (started.has(d)) {
|
|
1639
|
+
fresh(d);
|
|
1640
|
+
nctl.get(d)?.abort();
|
|
1641
|
+
} // running on the old output: cancel and restart
|
|
1642
|
+
} // still waiting: it re-checks its dependencies' gates, so it picks up the new output
|
|
1643
|
+
};
|
|
1644
|
+
const node = async (id) => {
|
|
1645
|
+
const deps = g.get(id) ?? [], k = order.indexOf(id);
|
|
1646
|
+
for (;;) {
|
|
1647
|
+
started.delete(id);
|
|
1648
|
+
if (deps.length) {
|
|
1649
|
+
for (const a of agentsOf(id))
|
|
1650
|
+
setWait(a.id, 'waiting-dependency', `waiting for: ${deps.map(teamName).join(', ')}`);
|
|
1651
|
+
for (;;) {
|
|
1652
|
+
const ps = deps.map(d => ready.get(d).p);
|
|
1653
|
+
await Promise.all(ps);
|
|
1654
|
+
if (ctl.signal.aborted)
|
|
1655
|
+
throw new NodeCancelled();
|
|
1656
|
+
if (deps.every((d, i) => ready.get(d).p === ps[i]))
|
|
1657
|
+
break;
|
|
1658
|
+
}
|
|
1659
|
+
}
|
|
1660
|
+
if (ctl.signal.aborted)
|
|
1661
|
+
throw new NodeCancelled();
|
|
1662
|
+
halted();
|
|
1663
|
+
if (earlyTest && earlyTest.id === id && !earlyPlans.has(id)) {
|
|
1664
|
+
setWait(agentsOf(id)[0]?.id ?? id, 'waiting-dependency', earlyTest.taskId);
|
|
1665
|
+
const plan = await earlyTest.p;
|
|
1666
|
+
halted();
|
|
1667
|
+
if (plan)
|
|
1668
|
+
earlyPlans.set(id, plan);
|
|
1669
|
+
}
|
|
1670
|
+
const my = new AbortController();
|
|
1671
|
+
nctl.set(id, my);
|
|
1672
|
+
started.add(id);
|
|
1673
|
+
const sig = AbortSignal.any([ctl.signal, my.signal]);
|
|
1674
|
+
try {
|
|
1675
|
+
for (;;) {
|
|
1676
|
+
const res = await pass1(id, sig);
|
|
1677
|
+
if (res.back) {
|
|
1678
|
+
const used = backs.get(k) ?? 0, loop = repeated(`ret:${id}`, res.back.short), to = deps[0] ?? 'director';
|
|
1679
|
+
if (loop)
|
|
1680
|
+
emit({ type: 'loop.detected', kind: 'return', from: id, reason: oneLine(`the same send-back again without new evidence: ${res.back.short}`, 300) });
|
|
1681
|
+
if (used < limit && !loop) {
|
|
1682
|
+
backs.set(k, used + 1);
|
|
1683
|
+
emit({ type: 'flow.back', kind: 'return', from: id, to, reason: res.back.short });
|
|
1684
|
+
if (to === 'director')
|
|
1685
|
+
await directorRewrite(id, res.back.full);
|
|
1686
|
+
else {
|
|
1687
|
+
sentBack.set(to, { from: id, reason: res.back.full });
|
|
1688
|
+
fresh(to);
|
|
1689
|
+
invalidate(to, id); // the dependency's output changes: its other dependents must not keep the old one
|
|
1690
|
+
try {
|
|
1691
|
+
await pass1(to, sig);
|
|
1692
|
+
}
|
|
1693
|
+
finally {
|
|
1694
|
+
ready.get(to)?.res();
|
|
1695
|
+
}
|
|
1696
|
+
}
|
|
1697
|
+
continue;
|
|
1698
|
+
}
|
|
1699
|
+
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.]`);
|
|
1700
|
+
if (id === 'qc')
|
|
1701
|
+
qcPassed = false;
|
|
1702
|
+
}
|
|
1703
|
+
else {
|
|
1704
|
+
const next = dependents(id)[0];
|
|
1705
|
+
if (next) {
|
|
1706
|
+
const cp = await checkpoint(id, next, res.out);
|
|
1707
|
+
if (cp.decision === 'return') {
|
|
1708
|
+
const used = dirBacks.get(id) ?? 0, loop = repeated(`dret:${id}`, cp.reason);
|
|
1709
|
+
if (loop)
|
|
1710
|
+
emit({ type: 'loop.detected', kind: 'return', from: 'director', reason: oneLine(`the Director returned the same thing again: ${cp.reason}`, 300) });
|
|
1711
|
+
if (used < limit && !loop) {
|
|
1712
|
+
dirBacks.set(id, used + 1);
|
|
1713
|
+
emit({ type: 'flow.back', kind: 'return', from: 'director', to: id, reason: oneLine(cp.reason || 'the Director asked for a rework', 300) });
|
|
1714
|
+
sentBack.set(id, { from: 'director', reason: cp.reason || 'the Director asked for a rework' });
|
|
1715
|
+
continue;
|
|
1716
|
+
}
|
|
1717
|
+
}
|
|
1718
|
+
if (cp.decision !== 'return')
|
|
1719
|
+
startEarlyTest(k); // PF-TEST in the task graph too: the Tester designs tests from the contract while Implement works
|
|
1720
|
+
for (const d of dependents(id)) {
|
|
1721
|
+
if (cp.dispatch)
|
|
1722
|
+
dispatches.set(d, cp.dispatch);
|
|
1723
|
+
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) });
|
|
1724
|
+
}
|
|
1725
|
+
}
|
|
1726
|
+
}
|
|
1727
|
+
break;
|
|
1728
|
+
}
|
|
1729
|
+
ready.get(id)?.res();
|
|
1730
|
+
return;
|
|
1731
|
+
}
|
|
1732
|
+
catch (e) {
|
|
1733
|
+
if (e instanceof NodeCancelled && !ctl.signal.aborted && my.signal.aborted)
|
|
1734
|
+
continue; // invalidated by a send-back upstream: run again on the new output
|
|
1735
|
+
throw e;
|
|
1736
|
+
}
|
|
1737
|
+
}
|
|
1738
|
+
};
|
|
1739
|
+
function spawn(id) {
|
|
1740
|
+
active.add(id);
|
|
1741
|
+
const p = node(id).catch((e) => { errs.push(e); ctl.abort(); settleAll(); }).finally(() => { active.delete(id); live.delete(p); });
|
|
1742
|
+
live.add(p);
|
|
1743
|
+
}
|
|
1744
|
+
for (const id of order)
|
|
1745
|
+
if (mine(id))
|
|
1746
|
+
spawn(id);
|
|
1747
|
+
while (live.size)
|
|
1748
|
+
await Promise.all([...live]);
|
|
1749
|
+
const bad = errs.find(e => !(e instanceof NodeCancelled)) ?? errs[0];
|
|
1750
|
+
if (bad)
|
|
1751
|
+
throw bad instanceof NodeCancelled ? new Halt() : bad;
|
|
1752
|
+
const lastId = order.at(-1);
|
|
1753
|
+
deliverable = lastId ? outs.get(lastId) ?? '' : '';
|
|
1754
|
+
}
|
|
1755
|
+
/** 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). */
|
|
1756
|
+
async function rerun(id) {
|
|
1757
|
+
if (!graph) {
|
|
1758
|
+
await flow(order.indexOf(id));
|
|
1759
|
+
return;
|
|
1760
|
+
}
|
|
1761
|
+
const g = graph, set = new Set([id]);
|
|
1762
|
+
for (let grew = true; grew;) {
|
|
1763
|
+
grew = false;
|
|
1764
|
+
for (const x of order)
|
|
1765
|
+
if (!set.has(x) && (g.get(x) ?? []).some(d => set.has(d))) {
|
|
1766
|
+
set.add(x);
|
|
1767
|
+
grew = true;
|
|
1768
|
+
}
|
|
1769
|
+
}
|
|
1770
|
+
await flowGraph(set);
|
|
1771
|
+
}
|
|
913
1772
|
/** 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
1773
|
function finalOutputs() {
|
|
915
1774
|
const lastId = order.at(-1), last = lastId ? outs.get(lastId) ?? '' : '';
|
|
@@ -943,26 +1802,94 @@ export function startTeamRun(opts) {
|
|
|
943
1802
|
reviewChecklist = v === null ? 'review verdict not readable' : clip(said, 3000);
|
|
944
1803
|
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
1804
|
reviewUnmet = verdict === 'FAIL';
|
|
946
|
-
if (verdict === 'PASS')
|
|
1805
|
+
if (verdict === 'PASS') {
|
|
1806
|
+
record('d-review', { title: 'Director review', selected: 'PASS', status: 'verified', rationale: 'every requirement met' });
|
|
947
1807
|
return;
|
|
948
|
-
|
|
1808
|
+
}
|
|
1809
|
+
const rloop = repeated('review', ret);
|
|
1810
|
+
if (rloop)
|
|
1811
|
+
emit({ type: 'loop.detected', kind: 'review', from: 'director', reason: oneLine(`the review rejected the same thing again: ${ret}`, 300) });
|
|
1812
|
+
record('d-review', { title: 'Director review', selected: 'FAIL', status: 'rejected', rationale: ret });
|
|
1813
|
+
if (used >= limit || rloop) {
|
|
949
1814
|
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
1815
|
return;
|
|
951
1816
|
}
|
|
952
1817
|
used++;
|
|
953
1818
|
emit({ type: 'flow.back', kind: 'return', from: 'director', to: lastId, reason: oneLine(ret, 300) });
|
|
954
1819
|
sentBack.set(lastId, { from: 'director', reason: `${ret}\n\nDirector's checklist:\n${clip(said, 2500)}` });
|
|
955
|
-
await
|
|
1820
|
+
await rerun(lastId);
|
|
956
1821
|
await drain();
|
|
957
1822
|
}
|
|
958
1823
|
}
|
|
1824
|
+
/** Critical findings of the security team(s) still open: those in the latest current contribution of each security agent. */
|
|
1825
|
+
const openCriticals = () => {
|
|
1826
|
+
const latest = new Map();
|
|
1827
|
+
for (const c of contribs) {
|
|
1828
|
+
const t = allAgentsOf(config).find(a => a.id === c.agentId)?.team ?? '';
|
|
1829
|
+
if (isSecurityTeam(t) && c.status !== 'superseded')
|
|
1830
|
+
latest.set(c.agentId, c);
|
|
1831
|
+
} // any revision: an owner steer does not hide a finding, only a newer security review replaces it
|
|
1832
|
+
return [...latest.values()].flatMap(c => c.findings.filter(f => f.severity === 'critical'));
|
|
1833
|
+
};
|
|
1834
|
+
let securityAccepted = '';
|
|
1835
|
+
/** Delivery gate: an open critical security finding blocks Delivery. The work goes back to Implement (bounded by the send-back limit),
|
|
1836
|
+
* then the owner decides: "ACCEPT: <reason>" delivers with the findings recorded as accepted; anything else is guidance for one more rework. */
|
|
1837
|
+
async function securityGate() {
|
|
1838
|
+
let reworks = 0, asks = 0;
|
|
1839
|
+
for (;;) {
|
|
1840
|
+
const open = openCriticals();
|
|
1841
|
+
if (!open.length) {
|
|
1842
|
+
if (reworks || asks)
|
|
1843
|
+
record('d-security', { title: 'Critical security findings', selected: 'resolved', status: 'verified', authority: 'core', rationale: 'the latest security review has no critical finding' });
|
|
1844
|
+
return;
|
|
1845
|
+
}
|
|
1846
|
+
const list = open.map(f => `- ${oneLine(f.summary, 300)}${f.location ? ` (at ${f.location})` : ''}`).join('\n');
|
|
1847
|
+
const sec = order.find(isSecurityTeam) ?? 'security', impl = order.indexOf('implement');
|
|
1848
|
+
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) });
|
|
1849
|
+
if (impl >= 0 && reworks < limit) {
|
|
1850
|
+
reworks++;
|
|
1851
|
+
const reason = `Critical security finding(s) must be fixed before delivery:\n${list}`;
|
|
1852
|
+
emit({ type: 'flow.back', kind: 'return', from: sec, to: 'implement', reason: oneLine(reason, 300) });
|
|
1853
|
+
sentBack.set('implement', { from: sec, reason });
|
|
1854
|
+
await rerun('implement');
|
|
1855
|
+
await drain();
|
|
1856
|
+
halted();
|
|
1857
|
+
continue;
|
|
1858
|
+
}
|
|
1859
|
+
if (asks >= 3) {
|
|
1860
|
+
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}`));
|
|
1861
|
+
throw new Halt();
|
|
1862
|
+
}
|
|
1863
|
+
asks++;
|
|
1864
|
+
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.`;
|
|
1865
|
+
directorSay('all', q);
|
|
1866
|
+
emit({ type: 'run.waiting', round: asks, questions: q, assumptions: null, team: sec });
|
|
1867
|
+
const w = await waitForOwner('');
|
|
1868
|
+
halted();
|
|
1869
|
+
const acc = /^\s*ACCEPT(?:ED)?\b\s*[:\-–]?\s*(.*)$/is.exec(w.text);
|
|
1870
|
+
if (acc && (acc[1] ?? '').trim()) {
|
|
1871
|
+
securityAccepted = `${list}\nAccepted by the owner: ${oneLine(acc[1], 400)}`;
|
|
1872
|
+
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) });
|
|
1873
|
+
return;
|
|
1874
|
+
}
|
|
1875
|
+
notes.push(`Owner's guidance on the critical security findings: ${w.text}`);
|
|
1876
|
+
if (impl >= 0) {
|
|
1877
|
+
sentBack.set('implement', { from: sec, reason: `Critical security finding(s):\n${list}\n\nOwner's guidance: ${w.text}` });
|
|
1878
|
+
await rerun('implement');
|
|
1879
|
+
await drain();
|
|
1880
|
+
halted();
|
|
1881
|
+
}
|
|
1882
|
+
}
|
|
1883
|
+
}
|
|
959
1884
|
async function delivery() {
|
|
960
1885
|
emit({ type: 'stage.changed', stage: 'delivery', loop: 1 });
|
|
961
1886
|
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`;
|
|
1887
|
+
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
1888
|
let report = rules;
|
|
964
|
-
if (
|
|
965
|
-
|
|
1889
|
+
if (collabMode === 'DIRECT' && !order.length)
|
|
1890
|
+
report = intakeBrief || rules;
|
|
1891
|
+
else if (modelDirector()) {
|
|
1892
|
+
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
1893
|
if (t?.trim())
|
|
967
1894
|
report = t;
|
|
968
1895
|
}
|
|
@@ -974,6 +1901,18 @@ export function startTeamRun(opts) {
|
|
|
974
1901
|
}
|
|
975
1902
|
async function pipeline() {
|
|
976
1903
|
try {
|
|
1904
|
+
if (toolsOn) {
|
|
1905
|
+
try {
|
|
1906
|
+
hub = await startToolHub(bus, { runId: journal.runId });
|
|
1907
|
+
if (finished) {
|
|
1908
|
+
hub.close();
|
|
1909
|
+
hub = null;
|
|
1910
|
+
}
|
|
1911
|
+
}
|
|
1912
|
+
catch (e) {
|
|
1913
|
+
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) });
|
|
1914
|
+
}
|
|
1915
|
+
}
|
|
977
1916
|
await intake();
|
|
978
1917
|
if (finished)
|
|
979
1918
|
return;
|
|
@@ -981,8 +1920,12 @@ export function startTeamRun(opts) {
|
|
|
981
1920
|
try {
|
|
982
1921
|
handoff = '';
|
|
983
1922
|
handoffs.clear();
|
|
1923
|
+
earlyTest?.ctl.abort();
|
|
1924
|
+
earlyTest = null; // a redirect cancels the early test of the previous flow
|
|
1925
|
+
earlyPlans.clear();
|
|
984
1926
|
reviewChecklist = '';
|
|
985
1927
|
reviewUnmet = false;
|
|
1928
|
+
securityAccepted = '';
|
|
986
1929
|
qcReport = '';
|
|
987
1930
|
deliverable = '';
|
|
988
1931
|
qcPassed = !order.includes('qc');
|
|
@@ -993,12 +1936,17 @@ export function startTeamRun(opts) {
|
|
|
993
1936
|
sentBack.clear();
|
|
994
1937
|
asks.clear();
|
|
995
1938
|
backs.clear();
|
|
996
|
-
|
|
1939
|
+
retReasons.clear();
|
|
1940
|
+
createdTasks.clear();
|
|
997
1941
|
convo.length = 0;
|
|
998
1942
|
if (intakeIntro)
|
|
999
1943
|
convo.push({ who: config.director.name, text: intakeIntro });
|
|
1000
|
-
|
|
1944
|
+
if (graph)
|
|
1945
|
+
await flowGraph();
|
|
1946
|
+
else
|
|
1947
|
+
await flow();
|
|
1001
1948
|
await reviewStage();
|
|
1949
|
+
await securityGate();
|
|
1002
1950
|
await delivery();
|
|
1003
1951
|
break;
|
|
1004
1952
|
}
|
|
@@ -1041,9 +1989,36 @@ export function startTeamRun(opts) {
|
|
|
1041
1989
|
}
|
|
1042
1990
|
catch { /* steering is best effort */ }
|
|
1043
1991
|
}
|
|
1992
|
+
lastInboxAt = Date.now();
|
|
1044
1993
|
inbox.push(added.length ? `${text} [owner attached: ${added.map(a => a.path).join(', ')}]` : text);
|
|
1045
|
-
|
|
1046
|
-
|
|
1994
|
+
if (URGENT_RE.test(text))
|
|
1995
|
+
wakeNow?.(); // an urgent steer is not held by the coalescing window
|
|
1996
|
+
}, () => doStop('Stopped from the console.'), {
|
|
1997
|
+
proceedWithAssumptions: () => { const w = waiting; if (w && w.assumptions)
|
|
1998
|
+
w.wake({ how: 'proceed', text: '' }); },
|
|
1999
|
+
pause: () => { if (finished || paused)
|
|
2000
|
+
return; paused = true; emit({ type: 'run.paused', by: 'owner' }); },
|
|
2001
|
+
resume: () => { if (finished || !paused)
|
|
2002
|
+
return; paused = false; emit({ type: 'run.resumed' }); wakeAll(); },
|
|
2003
|
+
interrupt: () => {
|
|
2004
|
+
if (finished)
|
|
2005
|
+
return;
|
|
2006
|
+
if (!paused) {
|
|
2007
|
+
paused = true;
|
|
2008
|
+
emit({ type: 'run.paused', by: 'interrupt' });
|
|
2009
|
+
}
|
|
2010
|
+
for (const [aid, ctl] of turnCtl) {
|
|
2011
|
+
interrupted.add(aid);
|
|
2012
|
+
const sess = running.get(aid);
|
|
2013
|
+
try {
|
|
2014
|
+
sess?.interrupt();
|
|
2015
|
+
}
|
|
2016
|
+
catch { /* best effort */ }
|
|
2017
|
+
ctl.abort();
|
|
2018
|
+
}
|
|
2019
|
+
},
|
|
2020
|
+
whenClosed: () => done.then(() => Promise.all(exits)).then(() => undefined), // resolves only after every owned child process has exited
|
|
2021
|
+
});
|
|
1047
2022
|
}
|
|
1048
2023
|
/** Re-emits a journal with original relative timing / speed (gaps capped at 1.5s/speed). */
|
|
1049
2024
|
export function replayTeamRun(runDir, opts = {}) {
|
|
@@ -1081,6 +2056,6 @@ export function replayTeamRun(runDir, opts = {}) {
|
|
|
1081
2056
|
end('failed');
|
|
1082
2057
|
else
|
|
1083
2058
|
timer = setTimeout(step, 0);
|
|
1084
|
-
return makeHandle(events[0]?.runId ?? basename(runDir), runDir, history, listeners, done, () => { }, () => end('stopped'));
|
|
2059
|
+
return makeHandle(events[0]?.runId ?? basename(runDir), runDir, history, listeners, done, () => { }, () => end('stopped'), {});
|
|
1085
2060
|
}
|
|
1086
2061
|
//# sourceMappingURL=engine.js.map
|