@ngockhoale/ckit 0.1.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/gui/app.js CHANGED
@@ -7,10 +7,8 @@
7
7
  var SHOT = Q.get('shot') || '', CLIS = [], CHECK = {};
8
8
  var TC = {director: '#A36BFF', ba: '#21D6E8', implement: '#F3A544', qc: '#4AD69A'};
9
9
  var TL = {director: 'DIRECTOR', ba: 'TEAM BA', implement: 'TEAM IMPLEMENT', qc: 'TEAM QC'};
10
- var STAGES = ['director-intake', 'ba-discussion', 'implement', 'qc', 'ba-review', 'delivery'];
11
- var STAGE_LABEL = ['Director', 'BA', 'Implement', 'QC', 'BA Review', 'Delivery'];
12
- var PHASE = {'director-intake': 'Director intake', 'ba-discussion': 'BA internal discussion', 'implement': 'Implement team at work', 'qc': 'QC inspection', 'ba-review': 'BA review', 'delivery': 'Delivery'};
13
- var STAGE_TEAM = {'director-intake': 'director', 'ba-discussion': 'ba', 'implement': 'implement', 'qc': 'qc', 'ba-review': 'ba', 'delivery': 'director'};
10
+ var PHASE = {'director-intake': 'Director intake', 'ba-discussion': 'BA internal discussion', 'implement': 'Implement team at work', 'qc': 'QC inspection', 'review': 'Director review', 'delivery': 'Delivery'};
11
+ var STAGE_TEAM = {'director-intake': 'director', 'ba-discussion': 'ba', 'implement': 'implement', 'qc': 'qc', 'review': 'director', 'delivery': 'director'};
14
12
  var $ = function (id) { return document.getElementById(id); };
15
13
  function h(tag, attrs, kids) {
16
14
  var e = document.createElement(tag);
@@ -32,45 +30,76 @@
32
30
  function clock(iso) { var d = new Date(iso); return isNaN(d) ? '' : d.toTimeString().slice(0, 8); }
33
31
 
34
32
  var S = {config: null, view: 'live', comic: false, run: null, agents: {}, order: [], events: [], msgs: 0, tokens: 0, stageIdx: -1, loop: 1, stageTimes: {}, selected: null,
35
- started: 0, ended: 0, outcome: null, replay: false, history: true, buckets: [], tokBuckets: [], handoffs: [], verdicts: [], lastStageAt: 0, dirty: true, bubbles: {}, narr: '', lastPanelSub: {}, lastAt: 0};
33
+ started: 0, ended: 0, outcome: null, replay: false, history: true, buckets: [], tokBuckets: [], handoffs: [], flowBacks: [], verdicts: [], lastStageAt: 0, dirty: true, bubbles: {}, narr: '', lastPanelSub: {}, lastAt: 0};
36
34
  var net = window.CKNet.create($('net'));
37
35
  window.__ck = {S: S, net: net};
38
36
 
39
- function cfgAgents(cfg) { return [cfg.director].concat(cfg.teams.ba, cfg.teams.implement, cfg.teams.qc); }
37
+ var XPAL = ['#FF6B8A', '#8BE04E', '#4F9DFF', '#FF8A4C', '#E0C341', '#B58CFF'], BUILTIN = {director: 1, ba: 1, implement: 1, qc: 1};
38
+ var DEFAULT_MISSION = {ba: 'Turn the goal into one clear handoff: scope, testable acceptance criteria, out of scope, risks. Afterwards check the finished work against it.', implement: 'Build what the handoff asks for in the project: change the code, run the checks, report what changed and how to verify.', qc: 'Independently review and test the deliverable against the acceptance criteria and give a PASS or FAIL verdict with reasons.'};
39
+ function extrasOf(cfg) { return (cfg && cfg.extraTeams) || []; }
40
+ function cfgAgents(cfg) { var x = []; extrasOf(cfg).forEach(function (t) { x = x.concat(t.agents); }); return [cfg.director].concat(cfg.teams.ba || [], cfg.teams.implement || [], cfg.teams.qc || [], x); }
41
+ /* extra teams get a colour from the palette (index = position in extraTeams) and a label; shared with the canvas through the CKNet colour table */
42
+ function registerTeams(cfg) {
43
+ Object.keys(TC).forEach(function (k) { if (!BUILTIN[k]) { delete TC[k]; delete TL[k]; delete window.CKNet.TEAM_COLOR[k]; delete window.CKNet.TEAM_LABEL[k]; } });
44
+ extrasOf(cfg).forEach(function (t, i) { TC[t.id] = XPAL[i % XPAL.length]; TL[t.id] = 'TEAM ' + String(t.name).toUpperCase(); window.CKNet.TEAM_COLOR[t.id] = TC[t.id]; window.CKNet.TEAM_LABEL[t.id] = TL[t.id]; });
45
+ }
46
+ /* flow order: cfg.order wins, else ba, implement, qc with extra teams after the stage named by their legacy runAfter (mirrors effectiveOrder in src/team/types.ts) */
47
+ function orderOf(cfg) {
48
+ var has = function (id) { return BUILTIN[id] ? id !== 'director' && (cfg.teams[id] || []).length > 0 : extrasOf(cfg).some(function (t) { return t.id === id && t.agents.length > 0; }); };
49
+ var ids = (cfg.order || null);
50
+ if (ids) { var seen = {}, out = ids.filter(function (id) { if (seen[id] || !has(id)) return false; seen[id] = 1; return true; }); ['ba', 'implement', 'qc'].concat(extrasOf(cfg).map(function (t) { return t.id; })).forEach(function (id) { if (has(id) && !seen[id]) out.push(id); }); return out; }
51
+ var xs = function (after) { return extrasOf(cfg).filter(function (t) { return (t.runAfter || 'implement') === after; }).map(function (t) { return t.id; }); };
52
+ return ['ba'].concat(xs('ba'), ['implement'], xs('implement'), ['qc'], xs('qc')).filter(has);
53
+ }
54
+ /* strip stages in flow order; only teams that have agents (built-ins) appear, extra teams sit after the stage they run after */
55
+ function stageList(cfg) {
56
+ var out = [{key: 'director-intake', label: 'Director', team: 'director'}];
57
+ var chip = {ba: {key: 'ba-discussion', label: 'BA', team: 'ba'}, implement: {key: 'implement', label: 'Implement', team: 'implement'}, qc: {key: 'qc', label: 'QC', team: 'qc'}};
58
+ var lanes = (cfg && cfg.lanes) || [], ids = S.lane ? S.lane.order : lanes.length ? null : cfg ? orderOf(cfg) : ['ba', 'implement', 'qc'];
59
+ if (ids === null) out.push({key: 'lane?', label: '…', team: 'director'}); /* lanes exist and the Director has not chosen yet */
60
+ else ids.forEach(function (id) { if (chip[id]) out.push(chip[id]); else { var t = extrasOf(cfg).filter(function (x) { return x.id === id; })[0]; if (t) out.push({key: 'x:' + t.id, label: t.name, team: t.id}); } });
61
+ if (!cfg || cfg.directorReview !== false) out.push({key: 'review', label: 'Review', team: 'director'});
62
+ out.push({key: 'delivery', label: 'Delivery', team: 'director'});
63
+ return out;
64
+ }
40
65
  function setupAgents(cfg) {
66
+ registerTeams(cfg); window.CKNet.TEAM_ORDER = orderOf(cfg);
41
67
  S.agents = {}; S.order = [];
42
68
  cfgAgents(cfg).forEach(function (a) { S.order.push(a.id); S.agents[a.id] = {cfg: a, state: 'idle', task: '', activity: '', step: 0, total: null, label: '', tokens: 0, t0: 0, spark: [], outputs: [], subs: {}, msgs: 0}; });
43
69
  net.setAgents(cfgAgents(cfg));
44
70
  }
45
71
  function resetRun() {
46
- S.events = []; S.atts = []; S.fails = []; S.msgs = 0; S.tokens = 0; S.stageIdx = -1; S.loop = 1; S.stageTimes = {}; S.started = 0; S.ended = 0; S.outcome = null; S.handoffs = []; S.verdicts = []; S.buckets = []; S.tokBuckets = []; S.lastStageAt = 0; S.narr = '';
72
+ S.events = []; S.atts = []; S.fails = []; S.msgs = 0; S.tokens = 0; S.stageIdx = -1; S.stageKey = ''; S.loop = 1; S.stageTimes = {}; S.started = 0; S.ended = 0; S.outcome = null; S.handoffs = []; S.flowBacks = []; S.verdicts = []; S.buckets = []; S.tokBuckets = []; S.lastStageAt = 0; S.narr = '';
47
73
  $('feed').innerHTML = ''; $('comicpanels').innerHTML = ''; $('bubbles').innerHTML = ''; S.bubbles = {}; S.lastPanelSub = {};
48
74
  $('overlay').hidden = true; $('hobanner').classList.remove('on');
75
+ S.lane = null; S.laneBy = ''; S.waiting = null; net.setActiveTeams(null);
49
76
  if (S.config) setupAgents(S.config);
50
77
  net.reset(); setNarr('Waiting for a mission…'); S.dirty = true;
51
78
  }
52
79
  function A(id) { return S.agents[id]; }
53
80
  function nm(id) { return A(id) ? A(id).cfg.name : id === 'all' ? 'everyone' : TL[id] || id; }
54
- function tcol(id) { return A(id) ? TC[A(id).cfg.team] : TC[id] || '#8A9AAF'; }
81
+ function tcol(id) { return A(id) ? TC[A(id).cfg.team] || '#8A9AAF' : TC[id] || '#8A9AAF'; }
55
82
  function ini(id) { return A(id) ? net.initials(A(id).cfg) : '?'; }
56
- function setNarr(t) { S.narr = t; $('nowtext').textContent = t; }
83
+ function setNarr(t) { S.narr = t; $('nowtext').textContent = t; $('now').classList.toggle('ask', !!S.waiting); }
57
84
 
58
85
  function activeSubs() { var n = 0; S.order.forEach(function (id) { Object.keys(A(id).subs).forEach(function (k) { if (A(id).subs[k].state === 'run') n++; }); }); return n; }
59
86
  function caption() {
60
- var st = STAGES[S.stageIdx], n = activeSubs(), c;
61
- if (S.outcome) c = S.outcome === 'delivered' ? '<b>Mission delivered</b> — báo cáo đã sẵn sàng' : '<b>Run ' + S.outcome + '</b>';
87
+ var st = S.stageKey && S.stageKey.slice(0, 2) === 'x:' ? 'x' : S.stageKey, n = activeSubs(), c;
88
+ if (S.outcome) c = S.outcome === 'delivered' ? '<b>Mission delivered</b> — báo cáo đã sẵn sàng' : S.outcome === 'declined' ? '<b>Director could not take this request</b> — no team started' : '<b>Run ' + S.outcome + '</b>';
89
+ else if (S.waiting) c = '<b>Director</b> is waiting for your answer — nothing is running';
62
90
  else if (!st) c = 'Chờ nhiệm vụ…';
63
91
  else if (st === 'director-intake') c = '<b>Director</b> đang tiếp nhận và phân tích yêu cầu';
64
92
  else if (st === 'ba-discussion') c = '<b>Team BA</b> đang thảo luận yêu cầu (các BA tranh luận → HANDOFF)';
65
93
  else if (st === 'implement') c = '<b>Implement</b> đang viết code' + (n ? ' — <b>' + n + ' subagent</b> đang hỗ trợ' : '') + (S.loop > 1 ? ' (sửa lỗi vòng ' + S.loop + ')' : '');
94
+ else if (S.stageKey && S.stageKey.slice(0, 2) === 'x:') c = '<b>' + (extrasOf(S.config).filter(function (t) { return 'x:' + t.id === S.stageKey; })[0] || {name: 'Team'}).name + '</b> đang làm việc';
66
95
  else if (st === 'qc') c = '<b>QC</b> đang kiểm thử' + (n ? ' — ' + n + ' subagent hỗ trợ' : '') + (S.loop > 1 ? ' (QC loop ' + S.loop + ')' : '');
67
- else if (st === 'ba-review') c = '<b>Team BA</b> đang review kết quả so với yêu cầu';
96
+ else if (st === 'review') c = '<b>Director</b> đối chiếu kết quả với yêu cầu gốc';
68
97
  else c = '<b>Director</b> đang tổng hợp báo cáo giao khách';
69
98
  $('caption').innerHTML = c;
70
99
  }
71
100
  function narrate(st) {
72
101
  var m = {'director-intake': 'Director nhận yêu cầu từ chủ dự án và giao cho Team BA.', 'ba-discussion': 'Team BA: hai analyst tranh luận để chốt yêu cầu, rồi tạo HANDOFF.', 'implement': 'Team Implement nhận HANDOFF và bắt đầu viết code' + (S.loop > 1 ? ' — sửa lỗi QC vừa tìm ra (vòng ' + S.loop + ').' : '.'),
73
- 'qc': 'Team QC kiểm tra sản phẩm' + (S.loop > 1 ? ' lần ' + S.loop + '.' : '.'), 'ba-review': 'Team BA đối chiếu sản phẩm với yêu cầu ban đầu.', 'delivery': 'Director tổng hợp báo cáo và giao hàng.'};
102
+ 'extra-team': 'Một team bổ sung đang làm phần việc của mình.', 'qc': 'Team QC kiểm tra sản phẩm' + (S.loop > 1 ? ' lần ' + S.loop + '.' : '.'), 'review': 'Director đối chiếu kết quả với yêu cầu gốc.', 'delivery': 'Director tổng hợp báo cáo và giao hàng.'};
74
103
  setNarr(m[st] || '');
75
104
  }
76
105
 
@@ -148,19 +177,22 @@
148
177
  S.events.push(e); S.dirty = true;
149
178
  var now = performance.now(), a = e.agentId ? A(e.agentId) : null;
150
179
  if (e.type === 'run.started') {
151
- S.started = Date.parse(e.at); S.config = e.config; S.simulated = e.simulated; S.run = S.run || {}; S.run.runId = e.runId; S.run.goal = e.goal; S.run.running = true; setupAgents(e.config);
180
+ S.started = Date.parse(e.at); S.config = e.config; S.simulated = e.simulated; S.run = S.run || {}; S.run.runId = e.runId; S.run.goal = e.goal; S.run.running = true; S.lane = null; S.laneBy = ''; net.setActiveTeams(null); setupAgents(e.config);
152
181
  $('goal').textContent = e.goal; $('goal').title = e.goal; $('runid').textContent = e.runId.replace('team-', '');
153
182
  setNarr('Mission: ' + e.goal.slice(0, 120)); feedBanner('dir', '◆ MISSION STARTED — ' + e.goal); feedAtts(e.attachments);
154
183
  comicCaption('Episode 1: ' + e.goal.slice(0, 90), 'director');
155
184
  }
156
185
  S.lastAt = Date.parse(e.at);
186
+ if (S.waiting && (e.type === 'agent.started' || e.type === 'user.message' || e.type === 'run.completed' || e.type === 'stage.changed')) { S.waiting = null; if (e.type !== 'run.completed') setNarr('Director is working on your answer…'); }
157
187
  switch (e.type) {
158
188
  case 'stage.changed': {
159
- var idx = STAGES.indexOf(e.stage), prev = S.stageIdx;
160
- if (prev >= 0 && S.lastStageAt) S.stageTimes[STAGES[prev] + (e.loop > 1 && prev >= 2 && prev <= 3 ? '#' + e.loop : '')] = Date.parse(e.at) - S.lastStageAt;
161
- S.lastStageAt = Date.parse(e.at); S.loop = e.loop; S.stageIdx = idx; net.setStage(idx, e.loop); narrate(e.stage);
162
- feedPhase(PHASE[e.stage] + (e.loop > 1 ? ' · loop ' + e.loop : ''), STAGE_TEAM[e.stage]);
163
- comicCaption(['Meanwhile, at the Director’s desk…', 'Team BA huddles to debate the requirements…', 'Meanwhile, at Team IMPLEMENT…' + (e.loop > 1 ? ' (round ' + e.loop + ')' : ''), 'Meanwhile, at Team QC…', 'Team BA reviews the delivery…', 'The Director prepares the final report…'][idx], STAGE_TEAM[e.stage]);
189
+ var xt = e.stage === 'extra-team' ? extrasOf(S.config).filter(function (t) { return t.id === e.team; })[0] : null;
190
+ if (e.stage === 'ba-review') break; /* journals written before the review stage was removed: shown as no stage of its own */
191
+ var prevKey = S.stageKey, key = xt ? 'x:' + xt.id : e.stage, sl = stageList(S.config), idx = Math.max(0, sl.map(function (z) { return z.key; }).indexOf(key));
192
+ if (prevKey && S.lastStageAt) S.stageTimes[prevKey + (e.loop > 1 && (prevKey === 'implement' || prevKey === 'qc') ? '#' + e.loop : '')] = Date.parse(e.at) - S.lastStageAt;
193
+ S.stageKey = key; S.lastStageAt = Date.parse(e.at); S.loop = e.loop; S.stageIdx = idx; net.setStage(idx, e.loop, sl.length); narrate(xt ? 'extra-team' : e.stage);
194
+ feedPhase(xt ? xt.name + ' team at work' + (e.loop > 1 ? ' · loop ' + e.loop : '') : PHASE[e.stage] + (e.loop > 1 ? ' · loop ' + e.loop : ''), xt ? xt.id : STAGE_TEAM[e.stage]);
195
+ comicCaption(e.stage === 'review' ? 'The Director checks the result against your request…' : xt ? 'Meanwhile, at Team ' + xt.name + '…' : ['Meanwhile, at the Director’s desk…', 'Team BA huddles to debate the requirements…', 'Meanwhile, at Team IMPLEMENT…' + (e.loop > 1 ? ' (round ' + e.loop + ')' : ''), 'Meanwhile, at Team QC…', 'The Director prepares the final report…'][e.stage === 'director-intake' ? 0 : e.stage === 'ba-discussion' ? 1 : e.stage === 'implement' ? 2 : e.stage === 'qc' ? 3 : 4], xt ? xt.id : STAGE_TEAM[e.stage]);
164
196
  break;
165
197
  }
166
198
  case 'agent.started':
@@ -177,15 +209,33 @@
177
209
  case 'agent.failed': if (a) { a.state = 'failed'; a.activity = e.reason; net.setState(e.agentId, 'failed'); } S.fails.push(e); feedBanner('fail', '✕ ' + nm(e.agentId) + ' failed: ' + plain(e.reason).slice(0, 220) + ' (click for details)', function () { showFailure(); }); break;
178
210
  case 'handoff.created':
179
211
  S.handoffs.push(e); if (!S.history) { net.handoff(e.from, e.to, e.title); showHoBanner('📦 HANDOFF ' + TL[e.from] + ' → ' + TL[e.to]); }
180
- feedBanner('ho', '📦 HANDOFF ' + (TL[e.from] || e.from) + ' → ' + (TL[e.to] || e.to) + ' · ' + e.title); comicHandoff(e);
212
+ feedBanner('ho', '📦 ' + teamLbl(e.from) + ' → ' + teamLbl(e.to) + ' · ' + e.title, e.text ? function () { showMessage({from: e.from, to: e.to, at: e.at, text: e.text}); } : null); comicHandoff(e);
181
213
  S.order.forEach(function (id) { if (A(id).cfg.team === e.from) { A(id).state = 'idle'; net.setState(id, 'idle'); } });
182
214
  break;
215
+ case 'flow.back': {
216
+ var fb = e.kind === 'ask' ? '? ' + teamLbl(e.from) + ' asked ' + teamLbl(e.to) + ': ' + e.reason : '↩ ' + teamLbl(e.from) + ' returned to ' + teamLbl(e.to) + ': ' + e.reason;
217
+ S.flowBacks.push(e); feedBanner(e.kind === 'ask' ? 'ask' : 'ret', fb);
218
+ comicSimple(e.kind === 'ask' ? 'director' : 'you', (e.kind === 'ask' ? 'ASK-BACK · ' : 'RETURN · ') + teamLbl(e.from) + ' → ' + teamLbl(e.to), e.reason);
219
+ break;
220
+ }
183
221
  case 'qc.verdict': S.verdicts.push(e); if (!S.history) net.verdict(e.verdict);
184
222
  feedBanner(e.verdict === 'PASS' ? 'pass' : 'fail', (e.verdict === 'PASS' ? '✔ QC PASS' : '✕ QC FAIL') + ' · loop ' + e.loop + ' — ' + e.summary);
185
223
  comicVerdict(e); setNarr(e.verdict === 'FAIL' ? 'QC phát hiện lỗi → trả về Implement để sửa.' : 'QC PASS — sản phẩm đạt yêu cầu!');
186
224
  break;
187
225
  case 'user.message': feedBanner('you', '▸ OWNER: ' + e.text); feedAtts(e.attachments); comicSimple('you', 'OWNER', e.text + (e.attachments && e.attachments.length ? ' 📎 ' + e.attachments.length + ' file(s)' : '')); break;
188
226
  case 'director.decision': feedBanner('dir', '◆ DIRECTOR ' + e.decision.toUpperCase() + ' — ' + e.note); comicSimple('director', 'DIRECTOR · ' + e.decision.toUpperCase(), e.note); break;
227
+ case 'lane.chosen': {
228
+ var ln = ((S.config && S.config.lanes) || []).filter(function (l) { return l.id === e.laneId; })[0];
229
+ S.lane = ln ? {id: ln.id, name: ln.name, order: ln.order.slice()} : {id: e.laneId, name: e.name, order: []}; S.laneBy = e.by; net.setActiveTeams(S.lane.order);
230
+ feedBanner('dir', e.by === 'owner' ? '◆ Owner fixed lane ' + e.name : e.by === 'fallback' ? '◆ Lane chosen by fallback: ' + e.name + (e.reason ? ' · ' + e.reason : '') : '◆ Director chose lane ' + e.name + ': ' + e.reason);
231
+ comicSimple('director', 'LANE · ' + e.name, e.reason || e.by);
232
+ break;
233
+ }
234
+ case 'review.verdict': S.verdicts.push(e); if (!S.history) net.verdict(e.verdict);
235
+ feedBanner(e.verdict === 'PASS' ? 'pass' : 'fail', 'Director review · ' + e.verdict + ' — ' + e.summary);
236
+ comicSimple('director', 'DIRECTOR REVIEW · ' + e.verdict, e.summary);
237
+ break;
238
+ case 'run.waiting': S.waiting = {round: e.round, questions: e.questions, assumptions: e.assumptions}; feedQuestions(e); setNarr('Director needs your answer'); break;
189
239
  case 'subagent.started':
190
240
  if (a) { a.subs[e.childId] = {kind: e.kind || 'sub', text: e.task, state: 'run'}; net.spawnSub(e.agentId, e.childId, e.kind); feedSub(e.agentId, '◆ spawned ' + (e.kind || 'subagent') + ': ' + e.task); comicSub(e); }
191
241
  break;
@@ -193,10 +243,11 @@
193
243
  case 'subagent.finished': if (a && a.subs[e.childId]) { a.subs[e.childId].state = e.ok ? 'done' : 'failed'; net.finishSub(e.childId, e.ok); feedSub(e.agentId, (e.ok ? '✓ ' : '✕ ') + a.subs[e.childId].kind + ': ' + e.summary); } break;
194
244
  case 'run.completed':
195
245
  S.ended = Date.parse(e.at); S.outcome = e.outcome; S.reportText = e.report; if (S.run) S.run.running = false;
196
- if (S.stageIdx >= 0) S.stageTimes[STAGES[S.stageIdx]] = Date.parse(e.at) - S.lastStageAt;
197
- if (e.outcome === 'delivered') { S.stageIdx = 6; net.setStage(6, S.loop); }
246
+ if (S.stageKey) S.stageTimes[S.stageKey] = Date.parse(e.at) - S.lastStageAt;
247
+ if (e.outcome === 'delivered') { var sl2 = stageList(S.config); S.stageIdx = sl2.length; S.stageKey = 'done'; net.setStage(sl2.length, S.loop, sl2.length); }
198
248
  S.order.forEach(function (id) { if (A(id).state === 'thinking') { A(id).state = 'idle'; net.setState(id, 'idle'); } });
199
- setNarr(e.outcome === 'delivered' ? 'MISSION DELIVERED ✔' : 'Run ended: ' + e.outcome + (e.outcome === 'failed' ? ' · click to see why' : '')); $('now').classList.toggle('click', e.outcome === 'failed'); comicCaption(e.outcome === 'delivered' ? 'THE END — mission delivered!' : 'The run ended: ' + e.outcome, 'director');
249
+ if (e.outcome === 'declined') feedBanner('fail', '◆ Director could not take this request');
250
+ setNarr(e.outcome === 'delivered' ? 'MISSION DELIVERED ✔' : e.outcome === 'declined' ? 'Director could not take this request' : 'Run ended: ' + e.outcome + (e.outcome === 'failed' ? ' · click to see why' : '')); $('now').classList.toggle('click', e.outcome === 'failed'); comicCaption(e.outcome === 'delivered' ? 'THE END — mission delivered!' : 'The run ended: ' + e.outcome, 'director');
200
251
  showOverlay(e);
201
252
  break;
202
253
  }
@@ -206,6 +257,7 @@
206
257
 
207
258
  /* feed */
208
259
  function feedScroll() { var f = $('feed'); f.scrollTop = f.scrollHeight; }
260
+ function teamLbl(id) { if (id === 'director') return 'Director'; var t = extrasOf(S.config).filter(function (x) { return x.id === id; })[0]; return t ? t.name : ({ba: 'BA', implement: 'Implement', qc: 'QC'})[id] || id; }
209
261
  function feedPhase(t, team) { $('feed').appendChild(h('div', {class: 'fphase', style: 'color:' + TC[team], text: '▍' + t})); feedScroll(); }
210
262
  function feedBanner(kind, t, onclick) { $('feed').appendChild(h('div', {class: 'fban ' + kind + (onclick ? ' click' : ''), text: t, onclick: onclick})); feedScroll(); count(); }
211
263
  function fmtSize(n) { return n >= 1048576 ? (n / 1048576).toFixed(1) + ' MB' : n >= 1024 ? Math.round(n / 1024) + ' KB' : n + ' B'; }
@@ -220,6 +272,13 @@
220
272
  S.atts = (S.atts || []).concat(list);
221
273
  $('feed').appendChild(h('div', {class: 'fatts'}, list.map(attChip))); feedScroll();
222
274
  }
275
+ function feedQuestions(e) {
276
+ var qs = String(e.questions || '').split('\n').map(function (l) { return l.replace(/^\s*\d+[.)]\s*/, '').trim(); }).filter(Boolean);
277
+ var as = e.assumptions ? String(e.assumptions).split('\n').map(function (l) { return l.replace(/^\s*[-*\d.)]+\s*/, '').trim(); }).filter(Boolean) : [];
278
+ $('feed').appendChild(h('div', {class: 'qcard'}, [h('b', {text: 'Director needs your answer · round ' + e.round + ' of 3'}), h('ol', {}, qs.map(function (q) { return h('li', {text: q}); })),
279
+ as.length ? h('div', {class: 'ml', text: 'IF YOU DO NOT ANSWER, THE DIRECTOR WILL ASSUME'}) : null, as.length ? h('ul', {}, as.map(function (q) { return h('li', {text: q}); })) : null,
280
+ h('div', {class: 'qhint', text: as.length ? 'Type your answer below, or choose Proceed with assumptions.' : 'Type your answer below. No team starts until you answer.'})])); feedScroll(); count();
281
+ }
223
282
  function feedSub(parent, t) { $('feed').appendChild(h('div', {class: 'fsub', text: '↳ ' + nm(parent) + ' ' + t})); feedScroll(); }
224
283
  function count() { $('feedcount').textContent = S.events.filter(function (e) { return e.type === 'agent.message'; }).length + ' MESSAGES'; }
225
284
  function typeInto(el, text) {
@@ -231,7 +290,7 @@
231
290
  var txt = h('div', {class: 'ft'});
232
291
  var row = h('div', {class: 'fm', style: '--tc:' + col + ';--tg:' + hexA(col, .3) + ';--tg2:' + hexA(col, .1), onclick: function () { showMessage({from: e.agentId, to: e.to, at: e.at, tokens: e.tokens, text: e.text}); }}, [
233
292
  h('div', {class: 'fav', text: ini(e.agentId)}),
234
- h('div', {class: 'fb'}, [h('div', {class: 'fh'}, [h('b', {text: nm(e.agentId)}), h('span', {class: 'to', text: '→ ' + nm(e.to)}), h('span', {class: 'tm', text: clock(e.at) + (e.tokens ? ' · ' + e.tokens + ' tok' : '')})]), txt])]);
293
+ h('div', {class: 'fb'}, [h('div', {class: 'fh'}, [h('b', {text: nm(e.agentId)}), h('span', {class: 'to', text: '→ ' + nm(e.to)}), e.round ? h('span', {class: 'rnd', text: 'round ' + e.round}) : null, h('span', {class: 'tm', text: clock(e.at) + (e.tokens ? ' · ' + e.tokens + ' tok' : '')})]), txt])]);
235
294
  $('feed').appendChild(row); typeInto(txt, short); feedScroll(); count();
236
295
  }
237
296
 
@@ -272,9 +331,18 @@
272
331
 
273
332
  /* overlay */
274
333
  function showHoBanner(t) { var b = $('hobanner'); b.textContent = t; b.classList.add('on'); clearTimeout(b._t); b._t = setTimeout(function () { b.classList.remove('on'); }, 3200); }
334
+ function showDeclined(e, ov) {
335
+ var rep = String(e.report || ''), m1 = /REASON:\s*([\s\S]*?)(?:\n\s*WHAT WOULD WORK:|$)/.exec(rep), m2 = /WHAT WOULD WORK:\s*([\s\S]*)$/.exec(rep);
336
+ ov.innerHTML = '';
337
+ ov.appendChild(h('div', {class: 'mission declined'}, [h('div', {class: 'ml', text: 'NO TEAM STARTED'}), h('h1', {text: 'Director could not take this request'}), h('div', {text: (S.run && S.run.goal) || ''}),
338
+ h('div', {class: 'dcard'}, [h('div', {class: 'ml', text: 'REASON'}), h('div', {class: 'dtxt', text: (m1 ? m1[1] : rep).trim()}), m2 && m2[1].trim() ? h('div', {class: 'ml', style: 'margin-top:10px', text: 'WHAT WOULD WORK'}) : null, m2 && m2[1].trim() ? h('div', {class: 'dtxt', text: m2[1].trim()}) : null]),
339
+ h('div', {style: 'display:flex;gap:10px;justify-content:center'}, [h('button', {class: 'primary', text: 'Start a new request', onclick: function () { ov.hidden = true; $('msg').focus(); }}), h('button', {text: 'View transcript', onclick: function () { ov.hidden = true; showArtifact('Transcript', 'transcript.md'); }}), h('button', {text: 'Close', onclick: function () { ov.hidden = true; }})])]));
340
+ ov.hidden = !(!S.history || SHOT === 'delivery');
341
+ }
275
342
  function showOverlay(e) {
276
343
  var ok = e.outcome === 'delivered', ov = $('overlay');
277
- var fails = S.verdicts.filter(function (v) { return v.verdict === 'FAIL'; }).length;
344
+ if (e.outcome === 'declined') { showDeclined(e, ov); return; }
345
+ var fails = S.verdicts.filter(function (v) { return v.verdict === 'FAIL' && v.type === 'qc.verdict'; }).length;
278
346
  ov.innerHTML = '';
279
347
  ov.appendChild(h('div', {class: 'mission' + (ok ? '' : ' fail')}, [
280
348
  h('div', {class: 'ml', text: ok ? 'ALL STAGES COMPLETE' : 'RUN ENDED'}), h('h1', {text: ok ? 'MISSION DELIVERED' : e.outcome.toUpperCase()}),
@@ -318,11 +386,12 @@
318
386
  }
319
387
  function renderRoster() {
320
388
  var r = $('roster'), keep = r.scrollTop; r.innerHTML = '';
321
- ['director', 'ba', 'implement', 'qc'].forEach(function (team) {
389
+ var dimmed = function (t) { return !!S.lane && t !== 'director' && S.lane.order.indexOf(t) < 0; };
390
+ ['director'].concat(orderOf(S.config)).forEach(function (team) {
322
391
  var ids = S.order.filter(function (i) { return A(i).cfg.team === team; }); if (!ids.length) return;
323
- r.appendChild(h('div', {class: 'rteam', style: 'color:' + TC[team]}, [h('i', {style: 'background:' + TC[team]}), TL[team]]));
392
+ r.appendChild(h('div', {class: 'rteam' + (dimmed(team) ? ' dim' : ''), style: 'color:' + TC[team]}, [h('i', {style: 'background:' + TC[team]}), TL[team]]));
324
393
  ids.forEach(function (id) {
325
- var a = A(id), c = TC[team], el = h('div', {class: 'tile ' + a.state + (S.selected === id ? ' sel' : ''), style: '--tc:' + c + ';--tg:' + hexA(c, .4), onclick: function () { S.selected = id; net.select(id); S.dirty = true; }});
394
+ var a = A(id), c = TC[team], el = h('div', {class: 'tile ' + a.state + (S.selected === id ? ' sel' : '') + (dimmed(team) ? ' dim' : ''), style: '--tc:' + c + ';--tg:' + hexA(c, .4), onclick: function () { S.selected = id; net.select(id); S.dirty = true; }});
326
395
  var work = a.state === 'thinking';
327
396
  el.appendChild(h('div', {class: 'trow'}, [h('div', {class: 'av w' + net.initials(a.cfg).length, text: net.initials(a.cfg)}), h('div', {style: 'min-width:0;flex:1'}, [h('div', {class: 'tname', text: a.cfg.name}), h('div', {class: 'tsub'}, [h('span', {class: 'pill', text: a.cfg.cli}), a.cfg.model ? h('span', {class: 'pill', title: a.cfg.model, text: a.cfg.model}) : null])]),
328
397
  h('div', {class: 'tright'}, [h('span', {class: 'sp ' + a.state}, [h('i'), a.state]), h('span', {class: 'tok', text: (work ? fmtT(performance.now() - a.t0) + ' · ' : '') + fmtN(a.tokens) + ' tok'})])]));
@@ -367,42 +436,61 @@
367
436
  r.appendChild(h('button', {text: '× deselect', style: 'margin-top:6px', onclick: function () { S.selected = null; net.select(null); S.dirty = true; }}));
368
437
  } else {
369
438
  r.appendChild(h('h3', {text: 'Handoffs & verdicts'}));
370
- S.handoffs.slice(-3).forEach(function (e) { r.appendChild(h('div', {class: 'card ho'}, [h('div', {class: 'ml', text: '📦 ' + e.from + ' → ' + e.to}), h('div', {text: e.title})])); });
371
- S.verdicts.slice(-3).forEach(function (e) { r.appendChild(h('div', {class: 'card ' + (e.verdict === 'PASS' ? 'pass' : 'fail')}, [h('b', {class: e.verdict === 'PASS' ? 'ok' : 'bad', text: e.verdict + ' · loop ' + e.loop}), h('div', {style: 'font-size:12px', text: e.summary})])); });
439
+ S.handoffs.slice(-3).forEach(function (e) {
440
+ var secs = []; String(e.text || '').split(/^#### /m).slice(1).forEach(function (blk) { var nl = blk.indexOf('\n'); secs.push([blk.slice(0, nl < 0 ? blk.length : nl).trim(), plain(nl < 0 ? '' : blk.slice(nl))]); });
441
+ r.appendChild(h('div', {class: 'card ho' + (e.text ? ' click' : ''), title: e.text ? 'Click to read the full handoff' : '', onclick: e.text ? function () { showMessage({from: e.from, to: e.to, at: e.at, text: e.text}); } : null}, [h('div', {class: 'ml', text: '📦 ' + teamLbl(e.from) + ' → ' + teamLbl(e.to)}), h('div', {text: e.title})].concat(secs.map(function (x) { return h('div', {class: 'hos'}, [h('b', {text: x[0]}), h('span', {text: x[1].length > 110 ? x[1].slice(0, 109) + '…' : x[1]})]); }))));
442
+ });
443
+ S.verdicts.slice(-3).forEach(function (e) { r.appendChild(h('div', {class: 'card ' + (e.verdict === 'PASS' ? 'pass' : 'fail')}, [h('b', {class: e.verdict === 'PASS' ? 'ok' : 'bad', text: e.type === 'review.verdict' ? 'Director review · ' + e.verdict : e.verdict + ' · loop ' + e.loop}), h('div', {style: 'font-size:12px', text: e.summary})])); });
372
444
  if (!S.handoffs.length && !S.verdicts.length) r.appendChild(h('div', {class: 'tact', text: 'Click an agent to inspect it.'}));
373
445
  if (S.atts && S.atts.length) { r.appendChild(h('h3', {style: 'margin-top:12px', text: 'Attachments · ' + S.atts.length})); r.appendChild(h('div', {class: 'tact', text: 'Every team gets these with the request.'})); r.appendChild(h('div', {class: 'fatts', style: 'margin-top:6px'}, S.atts.map(attChip))); }
374
446
  }
375
447
  r.appendChild(h('h3', {style: 'margin-top:12px', text: 'Telemetry'}));
376
- var tele = h('div', {class: 'tele'}), pct = S.stageIdx < 0 ? 0 : Math.max(0, Math.min(1, (S.stageIdx + (S.outcome ? 0 : .5)) / 6));
448
+ var tele = h('div', {class: 'tele'}), pct = S.stageIdx < 0 ? 0 : Math.max(0, Math.min(1, (S.stageIdx + (S.outcome ? 0 : .5)) / Math.max(1, stageList(S.config).length)));
377
449
  var gauge = h('div', {class: 'card gauge'}), circ = 2 * Math.PI * 28;
378
450
  gauge.innerHTML = '<svg width="74" height="74" viewBox="0 0 74 74"><circle cx="37" cy="37" r="28" fill="none" stroke="#1a2538" stroke-width="6"/><circle cx="37" cy="37" r="28" fill="none" stroke="#21D6E8" stroke-width="6" stroke-linecap="round" stroke-dasharray="' + (circ * pct).toFixed(1) + ' ' + circ.toFixed(1) + '" transform="rotate(-90 37 37)"/><text x="37" y="42" text-anchor="middle" fill="#fff" font-family="monospace" font-size="15">' + Math.round(pct * 100) + '%</text></svg><span class="ml">PROGRESS</span>';
379
451
  var tk = h('div', {class: 'card'}); tk.innerHTML = '<span class="ml">TOKENS / TIME</span>' + lineSvg(S.tokBuckets.map(function (x) { return x[1]; }), '#4F8CFF');
380
452
  var mb = h('div', {class: 'card'}); mb.innerHTML = '<span class="ml">MSGS / 10s</span>' + barSvg();
381
- var sd = h('div', {class: 'card'}); sd.innerHTML = '<span class="ml">STAGE DURATIONS</span>' + Object.keys(S.stageTimes).slice(-4).map(function (k) { return '<div class="kv mono" style="font-size:10px"><span>' + k.replace('director-intake', 'intake').replace('ba-discussion', 'ba').replace('ba-review', 'review') + '</span><span>' + fmtT(S.stageTimes[k]) + '</span></div>'; }).join('');
453
+ var sd = h('div', {class: 'card'}); sd.innerHTML = '<span class="ml">STAGE DURATIONS</span>' + Object.keys(S.stageTimes).slice(-4).map(function (k) { return '<div class="kv mono" style="font-size:10px"><span>' + k.replace('director-intake', 'intake').replace('ba-discussion', 'ba') + '</span><span>' + fmtT(S.stageTimes[k]) + '</span></div>'; }).join('');
382
454
  [gauge, tk, mb, sd].forEach(function (x) { tele.appendChild(x); }); r.appendChild(tele); r.scrollTop = keep;
383
455
  }
384
456
  function renderStrip() {
385
457
  var st = $('stages'); st.innerHTML = '';
386
- STAGE_LABEL.forEach(function (l, i) {
387
- var cls = S.stageIdx > i ? 'done' : S.stageIdx === i ? 'cur' : '', dur = S.stageTimes[STAGES[i]];
388
- st.appendChild(h('div', {class: 'st ' + cls}, [l, cls === 'done' && dur ? h('small', {text: fmtT(dur)}) : null, i === 3 && S.loop > 1 ? h('small', {text: 'loop ' + S.loop}) : null]));
458
+ var list = stageList(S.config), cur = S.stageKey === 'done' ? list.length : list.map(function (x) { return x.key; }).indexOf(S.stageKey);
459
+ $('lanename').textContent = S.lane ? 'Lane: ' + S.lane.name : ''; $('lanename').hidden = !S.lane;
460
+ list.forEach(function (x, i) {
461
+ var cls = cur > i ? 'done' : cur === i ? 'cur' : '', dur = S.stageTimes[x.key], xs = x.key.slice(0, 2) === 'x:';
462
+ st.appendChild(h('div', {class: 'st ' + cls + (x.key === 'review' ? ' rv' : ''), style: xs ? 'border-color:' + hexA(TC[x.team] || '#8A9AAF', .6) : ''}, [x.label, cls === 'done' && dur ? h('small', {text: fmtT(dur)}) : null, x.key === 'qc' && S.loop > 1 ? h('small', {text: 'loop ' + S.loop}) : null]));
389
463
  });
390
464
  }
391
465
  function renderTop() {
392
466
  var live = S.run && S.run.running && !S.outcome, b = $('badge');
393
- b.className = 'badge ' + (S.outcome ? 'done' : live ? (S.replay ? 'replay' : 'live') : '');
394
- b.querySelector('span').textContent = S.outcome ? (S.replay ? 'REPLAY DONE' : S.outcome === 'delivered' ? 'COMPLETE' : String(S.outcome).toUpperCase()) : live ? (S.replay ? 'REPLAY' : 'LIVE') : 'IDLE';
467
+ b.className = 'badge ' + (S.outcome === 'declined' ? 'replay' : S.outcome ? 'done' : live ? (S.replay ? 'replay' : 'live') : '');
468
+ b.querySelector('span').textContent = S.outcome ? (S.replay ? 'REPLAY DONE' : S.outcome === 'delivered' ? 'COMPLETE' : String(S.outcome).toUpperCase()) : live ? (S.replay ? 'REPLAY' : S.waiting ? 'WAITING' : 'LIVE') : 'IDLE';
395
469
  var end = S.outcome || S.replay ? (S.lastAt || S.started) : Date.now();
396
470
  $('elapsed').textContent = S.started ? fmtT(end - S.started) : '00:00'; $('tokens').textContent = fmtN(S.tokens); $('msgs').textContent = S.msgs;
397
471
  $('active').textContent = S.order.filter(function (i) { return A(i).state === 'thinking'; }).length + activeSubs();
398
472
  $('idleHint').style.display = S.run ? 'none' : ''; $('now').style.display = S.run ? '' : 'none';
399
473
  /* composer: talks to the Director during a run, starts a mission when nothing is running */
400
- var sim = simDefault(), mode = live ? 'live' : sim ? 'sim' : 'real';
474
+ var sim = simDefault(), wt = !!(live && S.waiting), mode = wt ? 'wait' + (S.waiting.assumptions ? 'A' : '') : live ? 'live' : sim ? 'sim' : 'real';
401
475
  if (S.cmode !== mode) {
402
- S.cmode = mode; $('clabel').textContent = live ? 'OWNER → DIRECTOR' : 'NEW MISSION → DIRECTOR'; $('send').textContent = live ? 'Send ▸' : 'Start ▸'; $('chips').style.display = live ? '' : 'none';
403
- $('msg').placeholder = live ? 'Message the Director… (Enter to send)' : 'Describe the mission and press Enter to start the team…';
404
- $('cnote').textContent = live ? '' : sim ? 'Demo mode: no real agent is configured, so this starts a simulated run.' : 'Starts real agents in ' + shortPath(S.projectRoot); $('cnote').title = S.projectRoot || '';
476
+ S.cmode = mode; $('clabel').textContent = wt ? 'ANSWER → DIRECTOR' : live ? 'OWNER → DIRECTOR' : 'NEW MISSION → DIRECTOR'; $('send').textContent = wt ? 'Send answer ▸' : live ? 'Send ▸' : 'Start ▸'; $('chips').style.display = live && !wt ? '' : 'none';
477
+ $('msg').placeholder = wt ? 'Answer the Director…' : live ? 'Message the Director… (Enter to send)' : 'Describe the mission and press Enter to start the team…';
478
+ $('cnote').textContent = wt ? 'The Director is waiting for you: no team has started and nothing is running.' : live ? '' : sim ? 'Demo mode: no real agent is configured, so this starts a simulated run.' : 'Starts real agents in ' + shortPath(S.projectRoot); $('cnote').title = S.projectRoot || '';
479
+ waitButtons(wt); if (wt) setTimeout(function () { $('msg').focus(); }, 30);
405
480
  }
481
+ var lanes = (S.config && S.config.lanes) || [], sig = live ? '' : lanes.map(function (l) { return l.id + ':' + l.name; }).join('|');
482
+ if (S.laneSig !== sig) { S.laneSig = sig; var old = $('lane').value, ns = laneSelect(); $('lane').innerHTML = ns ? ns.innerHTML : ''; if (old && ns && Array.prototype.some.call($('lane').options, function (o) { return o.value === old; })) $('lane').value = old; }
483
+ $('lanewrap').hidden = !sig;
484
+ }
485
+ function laneSelect() {
486
+ var lanes = (S.config && S.config.lanes) || []; if (!lanes.length) return null;
487
+ var sel = h('select', {class: 'laneSel', title: 'Lane for this request. Auto: the Director decides which lane fits.'}); sel.appendChild(h('option', {value: '', text: 'Lane: Auto (Director decides)'}));
488
+ lanes.forEach(function (l) { sel.appendChild(h('option', {value: l.id, text: 'Lane: ' + l.name})); }); return sel;
489
+ }
490
+ function waitButtons(wt) {
491
+ var b = $('wbtns'); b.innerHTML = ''; b.hidden = !wt; if (!wt) return;
492
+ if (S.waiting && S.waiting.assumptions) b.appendChild(h('button', {class: 'chip', text: 'Proceed with assumptions', onclick: function () { api('POST', '/api/runs/current/proceed').then(function (r) { if (r.status !== 200) toast(r.body.error || 'could not proceed'); }); }}));
493
+ b.appendChild(h('button', {class: 'chip', text: 'Stop', onclick: function () { api('POST', '/api/runs/current/stop').then(function (r) { if (r.status !== 200) toast(r.body.error || 'No active run'); }); }}));
406
494
  }
407
495
  var lastRender = 0;
408
496
  function loop(now) {
@@ -428,13 +516,15 @@
428
516
  function renderRuns() {
429
517
  var box = $('runs'); box.innerHTML = '<div class="ml" style="margin:6px 0 10px">PAST RUNS — open to replay</div>';
430
518
  api('GET', '/api/runs').then(function (r) {
431
- var rows = r.body.runs || [], t = h('table', {class: 'runs'}); t.innerHTML = '<tr><th>Date</th><th>Goal</th><th>Outcome</th><th>Duration</th><th>Replay</th></tr>';
519
+ var rows = r.body.runs || [], t = h('table', {class: 'runs'}); t.innerHTML = '<tr><th>Date</th><th>Goal</th><th>Lane</th><th>Outcome</th><th>Duration</th><th>Replay</th></tr>';
432
520
  rows.forEach(function (x) {
433
521
  var tr = h('tr'); tr.appendChild(h('td', {class: 'mono', text: x.startedAt ? new Date(x.startedAt).toLocaleString() : x.runId})); tr.appendChild(h('td', {text: (x.simulated ? '[demo] ' : '') + x.goal}));
434
- tr.appendChild(h('td', {class: x.outcome === 'delivered' ? 'ok' : x.outcome === 'failed' ? 'bad' : '', text: x.outcome})); tr.appendChild(h('td', {class: 'mono', text: fmtT(x.durationMs)}));
522
+ var lbl = x.outcome === 'declined' ? 'declined: the Director could not take this request' : x.outcome === 'incomplete' ? (x.waiting ? 'interrupted while waiting for your answer' : 'interrupted before it finished') : x.outcome;
523
+ tr.appendChild(h('td', {text: x.lane || ''}));
524
+ tr.appendChild(h('td', {class: x.outcome === 'delivered' ? 'ok' : x.outcome === 'failed' ? 'bad' : x.outcome === 'declined' || x.outcome === 'incomplete' ? 'warn' : '', title: x.outcome === 'incomplete' ? 'A run lives only in the CKit process that started it and is not resumed after CKit stops or restarts. Start the request again as a new run.' : '', text: lbl})); tr.appendChild(h('td', {class: 'mono', text: fmtT(x.durationMs)}));
435
525
  var td = h('td'); [1, 2, 4].forEach(function (sp) { td.appendChild(h('button', {text: sp + '×', style: 'margin-right:4px', onclick: function () { replay(x.runId, sp); }})); }); tr.appendChild(td); t.appendChild(tr);
436
526
  });
437
- if (!rows.length) t.appendChild(h('tr', {}, [h('td', {colSpan: 5, text: 'No runs yet.'})]));
527
+ if (!rows.length) t.appendChild(h('tr', {}, [h('td', {colSpan: 6, text: 'No runs yet.'})]));
438
528
  box.appendChild(t);
439
529
  });
440
530
  }
@@ -442,10 +532,11 @@
442
532
  function replay(id, speed) { api('POST', '/api/runs/' + id + '/replay', {speed: speed}).then(function (r) { if (r.status !== 200) { toast(r.body.error || 'replay failed'); return; } S.replay = true; setComic(false); setView('live'); }); }
443
533
  function newRunDialog() {
444
534
  var goal = h('textarea', {rows: 4, placeholder: 'Describe the mission… e.g. "Add a dark-mode toggle to the settings page"'}), sim = h('input', {type: 'checkbox', style: 'width:auto'});
445
- sim.checked = simDefault();
535
+ sim.checked = simDefault(); var laneSel = laneSelect();
446
536
  openModal(h('div', {class: 'dlg'}, [h('header', {}, [h('b', {text: 'NEW RUN'}), h('button', {text: '✕', onclick: closeModal})]),
447
537
  h('div', {class: 'body'}, [h('div', {class: 'ml', text: 'GOAL'}), goal, h('div', {class: 'ml', style: 'margin-top:12px', text: 'WORKSPACE (agents run in this folder)'}), h('div', {class: 'mono', style: 'font-size:12px;word-break:break-all;color:var(--cy)', text: S.projectRoot || ''}), h('div', {class: 'ml', style: 'margin-top:12px', text: 'ATTACHMENTS (any file type; the Director and every team read them)'}), h('div', {style: 'margin:6px 0'}, [h('button', {text: '📎 Attach files', onclick: function () { $('file').click(); }})]), h('div', {class: 'attlist'}), h('label', {style: 'display:flex;gap:8px;align-items:center;margin-top:12px'}, [sim, 'Demo mode (simulated agents, no API cost)'])]),
448
- h('footer', {}, [h('button', {text: 'Cancel', onclick: closeModal}), h('button', {class: 'primary', text: 'Start ▸', onclick: function () { startRun(goal.value, sim.checked); }})])]));
538
+ h('footer', {}, [h('button', {text: 'Cancel', onclick: closeModal}), h('button', {class: 'primary', text: 'Start ▸', onclick: function () { startRun(goal.value, sim.checked, laneSel ? laneSel.value : ''); }})])]));
539
+ if (laneSel) $('modal').querySelector('.body').appendChild(h('div', {style: 'margin-top:12px'}, [h('div', {class: 'ml', text: 'LANE'}), laneSel]));
449
540
  renderPending(); setTimeout(function () { goal.focus(); }, 30);
450
541
  }
451
542
  /* attachments waiting to be sent: uploaded as soon as they are picked, claimed by id when the message / mission is sent */
@@ -487,14 +578,14 @@
487
578
  document.addEventListener('dragleave', function (ev) { if (!ev.relatedTarget) $('composer').classList.remove('drop'); });
488
579
  document.addEventListener('drop', function (ev) { if (hasFiles(ev)) { ev.preventDefault(); $('composer').classList.remove('drop'); addFiles(ev.dataTransfer.files); } });
489
580
 
490
- function startRun(goal, sim) {
581
+ function startRun(goal, sim, lane) {
491
582
  var ids = pendingIds(); if (!ids) return Promise.resolve(false);
492
583
  if (!goal.trim() && !ids.length) return Promise.resolve(false);
493
- return api('POST', '/api/runs', {goal: goal, simulated: sim, attachments: ids}).then(function (r) { if (r.status !== 200) { toast(r.body.error || 'could not start the run'); return false; } clearPending(); closeModal(); S.replay = false; setView('live'); return true; });
584
+ return api('POST', '/api/runs', Object.assign({goal: goal, simulated: sim, attachments: ids}, lane ? {lane: lane} : {})).then(function (r) { if (r.status !== 200) { toast(r.body.error || 'could not start the run'); return false; } clearPending(); closeModal(); S.replay = false; setView('live'); return true; });
494
585
  }
495
586
  function send(text) {
496
587
  var chip = !!text; text = (text || $('msg').value).trim(); if (!text && !PEND.length) return;
497
- if (!(S.run && S.run.running && !S.outcome)) { startRun(text, simDefault()).then(function (ok) { if (ok) $('msg').value = ''; }); return; }
588
+ if (!(S.run && S.run.running && !S.outcome)) { startRun(text, simDefault(), $('lanewrap').hidden ? '' : $('lane').value).then(function (ok) { if (ok) $('msg').value = ''; }); return; }
498
589
  var ids = chip ? [] : pendingIds(); if (!ids) return;
499
590
  api('POST', '/api/runs/current/message', {text: text, attachments: ids}).then(function (r) { if (r.status !== 200) toast(r.body.error || 'No active run'); else { if (!chip) { $('msg').value = ''; clearPending(); } } });
500
591
  }
@@ -537,13 +628,48 @@
537
628
  /* config editor (settings view + popup) */
538
629
  function strip(cfg) {
539
630
  var c = JSON.parse(JSON.stringify(cfg));
540
- [c.director].concat(c.teams.ba, c.teams.implement, c.teams.qc).forEach(function (a) { delete a.hasKey; delete a._auto; if (a.baseUrl === '') delete a.baseUrl; if (!a.persona) delete a.persona; if (!a.short) delete a.short; });
631
+ cfgAgents(c).forEach(function (a) { delete a.hasKey; delete a._auto; if (a.baseUrl === '') delete a.baseUrl; if (!a.persona) delete a.persona; if (!a.short) delete a.short; if (typeof a.cliArgs !== 'string' || !a.cliArgs.trim()) delete a.cliArgs; else a.cliArgs = a.cliArgs.trim(); });
632
+ ['ba', 'implement', 'qc'].forEach(function (k) { if (!c.teams[k]) c.teams[k] = []; });
633
+ if (c.missions) { Object.keys(c.missions).forEach(function (k) { if (!String(c.missions[k] || '').trim()) delete c.missions[k]; }); if (!Object.keys(c.missions).length) delete c.missions; }
634
+ if (c.extraTeams && !c.extraTeams.length) delete c.extraTeams;
635
+ c.order = orderOf(c);
636
+ if (typeof c.systemPrompt === 'string' && c.systemPrompt.trim()) c.systemPrompt = c.systemPrompt.trim(); else delete c.systemPrompt;
637
+ if (c.directorReview !== false) delete c.directorReview;
638
+ if (!c.lanes || !c.lanes.length) delete c.lanes;
639
+ (c.extraTeams || []).forEach(function (t) { delete t.runAfter; });
541
640
  return c;
542
641
  }
642
+ var ENH = {}, ENH_BUSY = ''; /* Enhance state per field; one request at a time; a proposal is never applied until the owner says so */
543
643
  function mountEditor(box, modal) {
544
644
  var draft = JSON.parse(JSON.stringify(S.config)), sel = 'director', tab = Q.get('tab') || 'form', dirty = false, errors = [], note = '', jsonText = '';
545
645
  var serverCfg = JSON.stringify(strip(draft));
546
- function allA() { return [draft.director].concat(draft.teams.ba, draft.teams.implement, draft.teams.qc); }
646
+ var selTeam = null; /* team whose header fields are shown instead of an agent */
647
+ function laneMode() { return !!(draft.lanes && draft.lanes.length); }
648
+ function enhance(kind, ids, ta, apply) {
649
+ var key = kind + '|' + (ids.team || '') + '|' + (ids.agent || '') + '|' + (ids.lane || ''), st = ENH[key], box2 = h('div');
650
+ var btn = h('button', {class: 'enhbtn', text: st && st.state === 'run' ? '' : '\u2726 Enhance', title: 'Rewrite this text so it is clear and specific. You decide whether to use the result.'});
651
+ var sync = function () { var empty = !ta.value.trim(), busy = !!ENH_BUSY; btn.disabled = empty || busy; btn.title = empty ? 'Type a few words first' : busy ? 'Another Enhance is running' : 'Rewrite this text so it is clear and specific. You decide whether to use the result.'; };
652
+ if (st && st.state === 'run') { btn.appendChild(h('span', {class: 'spin'})); btn.appendChild(document.createTextNode(' Enhancing\u2026')); }
653
+ ta.addEventListener('input', sync); sync();
654
+ btn.addEventListener('click', function () {
655
+ if (ENH_BUSY || !ta.value.trim()) return;
656
+ ENH_BUSY = key; ENH[key] = {state: 'run', orig: ta.value}; render();
657
+ api('POST', '/api/enhance-prompt', {kind: kind, text: ENH[key].orig, ids: ids}).then(function (res) {
658
+ ENH_BUSY = '';
659
+ if (res.status === 200 && res.body.ok) ENH[key] = {state: 'prop', orig: ENH[key].orig, proposal: res.body.proposal};
660
+ else ENH[key] = {state: 'bad', orig: ENH[key].orig, reason: res.body.reason || res.body.error || 'enhance failed'};
661
+ render();
662
+ });
663
+ });
664
+ box2.appendChild(h('div', {class: 'enh'}, [btn]));
665
+ if (st && st.state === 'prop') box2.appendChild(h('div', {class: 'prop'}, [h('div', {class: 'ml', text: 'YOUR TEXT'}), h('div', {class: 'pt orig', text: st.orig}), h('div', {class: 'ml', text: 'PROPOSAL'}), h('div', {class: 'pt', text: st.proposal}),
666
+ h('div', {class: 'pb'}, [h('button', {class: 'primary', text: 'Use this', onclick: function () { delete ENH[key]; apply(st.proposal); mark(); render(); }}), h('button', {text: 'Discard', onclick: function () { delete ENH[key]; render(); }})])]));
667
+ if (st && st.state === 'bad') { box2.appendChild(h('pre', {class: 'chkerr', text: st.reason})); box2.appendChild(h('div', {class: 'fix'}, [h('b', {text: 'How to fix '}), 'Enhance uses the Director\'s CLI. Open the Director agent, press "Check this CLI + model", and fix what it reports; your text was not changed. You can also edit it by hand.'])); box2.appendChild(h('button', {text: 'Dismiss', onclick: function () { delete ENH[key]; render(); }})); }
668
+ return box2;
669
+ }
670
+ function laneTags(id) { return (draft.lanes || []).filter(function (l) { return l.order.indexOf(id) >= 0; }); }
671
+ function dropFromLanes(id) { (draft.lanes || []).forEach(function (l) { l.order = l.order.filter(function (x) { return x !== id; }); }); }
672
+ function allA() { return cfgAgents(draft); }
547
673
  function find(id) { return allA().filter(function (a) { return a.id === id; })[0]; }
548
674
  function mark() { dirty = JSON.stringify(strip(draft)) !== serverCfg; }
549
675
  function render() {
@@ -567,15 +693,89 @@
567
693
  });
568
694
  }
569
695
  function jsonTab() { var t = h('textarea', {class: 'json', spellcheck: false}); t.value = jsonText || JSON.stringify(strip(draft), null, 2); t.addEventListener('input', function () { jsonText = t.value; dirty = true; }); return h('div', {style: 'height:' + (modal ? '56vh' : '66vh')}, [t]); }
696
+ function teamDefs() {
697
+ var d = [{id: 'director', label: 'DIRECTOR', list: [draft.director]}];
698
+ var ord = orderOf(draft); if (selTeam && BUILTIN[selTeam] && ord.indexOf(selTeam) < 0) ord.push(selTeam);
699
+ ord.forEach(function (id, i) {
700
+ var x = (draft.extraTeams || []).filter(function (t) { return t.id === id; })[0];
701
+ d.push(x ? {id: id, label: 'TEAM ' + String(x.name).toUpperCase(), list: x.agents, extra: x, n: i + 1, of: ord.length} : {id: id, label: TL[id], list: draft.teams[id] || [], n: i + 1, of: ord.length});
702
+ });
703
+ return d;
704
+ }
705
+ function newAgent(team, access) {
706
+ var n = 1, id; do { id = team + '-' + n; n++; } while (find(id));
707
+ var src = (draft.teams.implement || [])[0] || {};
708
+ return {id: id, name: (TL[team] || team).replace('TEAM ', '') + ' ' + (n - 1), team: team, cli: src.cli || (CLIS.filter(function (c) { return c.installed; })[0] || {cli: 'claude-code'}).cli, model: src.model || null, access: access};
709
+ }
710
+ function listOf(team) { var x = (draft.extraTeams || []).filter(function (t) { return t.id === team; })[0]; return x ? x.agents : (draft.teams[team] = draft.teams[team] || []); }
711
+ function addTeam(kind) {
712
+ if (kind === 'custom') {
713
+ var n = 1, id; do { id = 'team-' + n; n++; } while ((draft.extraTeams || []).some(function (t) { return t.id === id; }) || find(id));
714
+ var ag = newAgent(id, 'read'); ag.name = 'New agent'; ag.id = id + '-1'; var k = 1; while (find(ag.id)) { k++; ag.id = id + '-' + k; }
715
+ var ord0 = orderOf(draft);
716
+ draft.extraTeams = (draft.extraTeams || []).concat([{id: id, name: 'New team', mission: 'Describe what this team does for the goal', agents: [ag]}]);
717
+ draft.order = ord0.concat([id]);
718
+ selTeam = id; sel = ag.id;
719
+ } else { var ord1 = orderOf(draft); draft.teams[kind] = [newAgent(kind, kind === 'implement' ? 'write' : 'read')]; draft.order = ord1.concat([kind]); selTeam = null; sel = draft.teams[kind][0].id; }
720
+ mark(); render();
721
+ }
722
+ function addMenu() {
723
+ var wrap = h('div', {style: 'position:relative;margin-top:8px'}), missing = ['ba', 'implement', 'qc'].filter(function (t) { return !(draft.teams[t] || []).length; });
724
+ var s2 = h('select', {style: 'width:100%'}); s2.appendChild(h('option', {value: '', text: '+ Add team…'}));
725
+ missing.forEach(function (t) { s2.appendChild(h('option', {value: t, text: TL[t].replace('TEAM ', 'Team ')})); });
726
+ s2.appendChild(h('option', {value: 'custom', text: 'Custom team'}));
727
+ s2.addEventListener('change', function () { if (s2.value) addTeam(s2.value); });
728
+ wrap.appendChild(s2); return wrap;
729
+ }
730
+ function move(id, d) {
731
+ var o = orderOf(draft), i = o.indexOf(id), j = i + d;
732
+ if (i < 0 || j < 0 || j >= o.length) return;
733
+ o.splice(i, 1); o.splice(j, 0, id); draft.order = o; mark(); render();
734
+ }
735
+ function posControls(t) {
736
+ var o = orderOf(draft), i = o.indexOf(t.id);
737
+ return h('div', {class: 'poscl'}, [h('b', {text: 'Step ' + (i + 1) + ' of ' + o.length}),
738
+ h('button', {text: '▲ Up', title: 'Run earlier', disabled: i <= 0, onclick: function () { move(t.id, -1); }}),
739
+ h('button', {text: '▼ Down', title: 'Run later', disabled: i < 0 || i >= o.length - 1, onclick: function () { move(t.id, 1); }})]);
740
+ }
741
+ function posOrLanes(t) {
742
+ if (!laneMode()) return posControls(t);
743
+ var ls = laneTags(t.id);
744
+ return h('div', {class: 'clinote', style: 'margin:0', text: ls.length ? 'Order is set inside each lane. In: ' + ls.map(function (l) { return l.name; }).join(', ') : 'Not in any lane yet. Add it to a lane under Lanes (below), otherwise it never runs.'});
745
+ }
746
+ function teamHeader(t) {
747
+ var f = h('div'), isX = !!t.extra, o = isX ? t.extra : draft;
748
+ f.appendChild(h('div', {class: 'sec', text: 'TEAM'}));
749
+ var mission = isX ? t.extra.mission : ((draft.missions || {})[t.id] || DEFAULT_MISSION[t.id]);
750
+ var ta = h('textarea', {rows: 3, value: mission, placeholder: 'What does this team do for the goal?'});
751
+ ta.addEventListener('input', function () { if (isX) t.extra.mission = ta.value; else { draft.missions = draft.missions || {}; draft.missions[t.id] = ta.value; } var was = dirty; mark(); if (dirty !== was) render(); });
752
+ var row = [];
753
+ if (isX) {
754
+ row.push(fld('Team name', bind(h('input', {value: t.extra.name}), t.extra, 'name')));
755
+ row.push(fld('Position in the flow', posOrLanes(t), 'Work goes Director, then team 1, 2, 3 ... Use the arrows to change the order.'));
756
+ f.appendChild(h('div', {class: 'row2'}, row));
757
+ } else f.appendChild(h('div', {class: 'row2'}, [fld('Position in the flow', posOrLanes(t), 'Work goes Director, then team 1, 2, 3 ... Use the arrows to change the order.'), h('div', {class: 'clinote', text: 'Built-in team "' + t.id + '"' + (t.id === 'ba' ? '; also reviews the finished work at the end.' : '.')})]));
758
+ f.appendChild(fld('Mission', ta, 'The Director reads this when it splits the work; every agent of the team gets it in its prompt.'));
759
+ f.appendChild(enhance('mission', {team: t.id}, ta, function (v) { if (isX) t.extra.mission = v; else { draft.missions = draft.missions || {}; draft.missions[t.id] = v; } }));
760
+ f.appendChild(h('div', {style: 'margin:10px 0'}, [h('button', {class: 'danger', text: 'Remove team', onclick: function () {
761
+ draft.order = orderOf(draft).filter(function (x) { return x !== t.id; }); dropFromLanes(t.id);
762
+ if (isX) draft.extraTeams = draft.extraTeams.filter(function (x) { return x.id !== t.id; }); else { draft.teams[t.id] = []; if (draft.missions) delete draft.missions[t.id]; }
763
+ selTeam = null; sel = 'director'; mark(); render(); }})]));
764
+ return f;
765
+ }
570
766
  function form() {
571
767
  var wrap = h('div', {class: 'cfg', style: modal ? 'height:58vh' : ''}), left = h('div'), right = h('div');
572
- [['director', 'DIRECTOR'], ['ba', 'TEAM BA'], ['implement', 'TEAM IMPLEMENT'], ['qc', 'TEAM QC']].forEach(function (g) {
573
- var team = g[0], list = team === 'director' ? [draft.director] : draft.teams[team];
574
- left.appendChild(h('div', {class: 'rteam', style: 'color:' + TC[team]}, [h('i', {style: 'background:' + TC[team]}), g[1]]));
575
- list.forEach(function (a) { left.appendChild(h('div', {class: 'al' + (sel === a.id ? ' sel' : ''), style: '--tc:' + TC[team] + ';--tg:' + hexA(TC[team], .3), onclick: function () { sel = a.id; render(); }}, [h('b', {text: a.name}), h('small', {text: a.cli + (a.model ? ' · ' + a.model : '')})])); });
576
- if (team !== 'director') left.appendChild(h('button', {text: '+ Add agent', style: 'width:100%;margin-bottom:6px', onclick: function () { var n = draft.teams[team].length + 1, id = team + '-' + n; while (find(id)) { n++; id = team + '-' + n; } draft.teams[team].push({id: id, name: TL[team].replace('TEAM ', '') + ' ' + n, team: team, cli: (CLIS.filter(function (c) { return c.installed; })[0] || {cli: 'claude-code'}).cli, model: null, access: team === 'implement' ? 'write' : 'read'}); sel = id; mark(); render(); }}));
768
+ teamDefs().forEach(function (t) {
769
+ var team = t.id, color = TC[team] || '#8A9AAF', isDir = team === 'director';
770
+ left.appendChild(h('div', {class: 'rteam' + (selTeam === team ? ' sel' : ''), style: 'color:' + color + (isDir ? '' : ';cursor:pointer'), title: isDir ? '' : 'Click to edit this team (name, mission, when it runs)', onclick: isDir ? null : function () { selTeam = team; render(); }}, [isDir ? h('i', {style: 'background:' + color}) : h('span', {class: 'nbadge', style: 'background:' + color, text: String(t.n)}), h('span', {style: 'flex:1', text: t.label + (isDir ? '' : ' ✎')}), isDir ? null : h('span', {}, laneTags(team).map(function (l) { return h('span', {class: 'ltag', title: 'In lane ' + l.name, text: l.name}); })), isDir || laneMode() ? null : h('button', {class: 'mv', text: '▲', title: 'Move up (run earlier)', disabled: t.n <= 1, onclick: function (ev) { ev.stopPropagation(); move(team, -1); }}), isDir || laneMode() ? null : h('button', {class: 'mv', text: '▼', title: 'Move down (run later)', disabled: t.n >= t.of, onclick: function (ev) { ev.stopPropagation(); move(team, 1); }})]));
771
+ t.list.forEach(function (a) { left.appendChild(h('div', {class: 'al' + (sel === a.id && !selTeam ? ' sel' : ''), style: '--tc:' + color + ';--tg:' + hexA(color, .3), onclick: function () { sel = a.id; selTeam = null; render(); }}, [h('b', {text: a.name}), h('small', {text: a.cli + (a.model ? ' · ' + a.model : '') + (a.cliArgs ? ' · +args' : '')})])); });
772
+ if (!isDir) left.appendChild(h('button', {text: '+ Add agent', style: 'width:100%;margin-bottom:6px', onclick: function () { var ag = newAgent(team, team === 'implement' ? 'write' : 'read'); listOf(team).push(ag); sel = ag.id; selTeam = null; mark(); render(); }}));
577
773
  });
578
- right.appendChild(editAgent(find(sel) || draft.director)); right.appendChild(limits()); wrap.appendChild(left); wrap.appendChild(right); return wrap;
774
+ left.appendChild(addMenu());
775
+ var cur = selTeam ? teamDefs().filter(function (x) { return x.id === selTeam; })[0] : null;
776
+ if (selTeam && !cur) selTeam = null;
777
+ if (cur && cur.id !== 'director') right.appendChild(teamHeader(cur)); else right.appendChild(editAgent(find(sel) || draft.director));
778
+ right.appendChild(projectBox()); right.appendChild(lanesBox()); right.appendChild(limits()); wrap.appendChild(left); wrap.appendChild(right); return wrap;
579
779
  }
580
780
  function fld(label, input, hint) { return h('div', {class: 'fld'}, [h('label', {class: 'ml', text: label}), input, hint ? h('div', {class: 'ml', style: 'margin-top:3px;text-transform:none', text: hint}) : null]); }
581
781
  function bind(el, obj, key, num) {
@@ -598,7 +798,9 @@
598
798
  var sn = h('input', {value: a.short || '', maxLength: 4, placeholder: net.initials({name: a.name || '?', team: a.team}), style: 'text-transform:uppercase;font-family:var(--mono);font-weight:700;letter-spacing:.08em', title: 'Shown inside the agent circle. 1-4 letters or digits. Empty = ' + net.initials({name: a.name || '?', team: a.team}) + ' (from the name).'});
599
799
  sn.addEventListener('input', function () { var v = sn.value.replace(/[^\p{L}\p{N}]/gu, '').toUpperCase().slice(0, 4); if (v !== sn.value) sn.value = v; });
600
800
  f.appendChild(h('div', {class: 'row2', style: 'grid-template-columns:150px 1fr 1fr'}, [fld('Short name (max 4)', bind(sn, a, 'short')), fld('Name', bind(h('input', {value: a.name}), a, 'name')), fld('Team', h('input', {value: a.team, disabled: true}))]));
601
- f.appendChild(fld('Persona / extra guidance (optional)', bind(h('textarea', {rows: 2, value: a.persona || ''}), a, 'persona')));
801
+ var pta = bind(h('textarea', {rows: 2, value: a.persona || ''}), a, 'persona');
802
+ f.appendChild(fld('Persona / extra guidance (optional)', pta));
803
+ f.appendChild(enhance('persona', {team: a.team, agent: a.id}, pta, function (v) { a.persona = v; }));
602
804
  f.appendChild(h('div', {class: 'sec', text: 'ENGINE'}));
603
805
  /* an agent is: which CLI of this machine, and which of that CLI's own models. `api` stays selectable only where it is already in use. */
604
806
  var info = function (n) { return CLIS.filter(function (c) { return c.cli === n; })[0]; }, ci = info(a.cli);
@@ -606,6 +808,7 @@
606
808
  cli.addEventListener('change', function () { a.cli = cli.value; a.model = null; a._auto = true; mark(); render(); });
607
809
  var acc = h('select'); ['read', 'write'].forEach(function (o) { var op = h('option', {text: o === 'write' ? 'Read + write (can change code)' : 'Read only (changes nothing)', value: o}); if (o === a.access) op.selected = true; acc.appendChild(op); }); acc.addEventListener('change', function () { a.access = acc.value; mark(); render(); });
608
810
  f.appendChild(h('div', {class: 'row3'}, [fld('CLI', cli), fld('Model', modelPick(a, ci)), fld('Access', acc)]));
811
+ if (a.cli === 'claude-code' || a.cli === 'codex' || a.cli === 'omp') f.appendChild(fld('Extra CLI arguments (optional)', bind(h('input', {value: a.cliArgs || '', maxLength: 500, placeholder: '--settings ./other-settings.json', spellcheck: false, style: 'font-family:var(--mono)'}), a, 'cliArgs'), 'Added to this agent\'s start command as typed. Leave empty to use the CLI\'s defaults. No ~ or $VARIABLE expansion; quote values with spaces. The live "Check this CLI + model" test does not use these.'));
609
812
  f.appendChild(h('div', {class: 'clinote', text: a.access === 'write' ? 'Access: this agent reads the whole project and may change files in it.' : 'Access: this agent reads the whole project (code, docs, attachments) but changes nothing. Pick “Read + write” for agents that must edit code.'}));
610
813
  if (ci && ci.installed) {
611
814
  /* verify the pair with one real tiny turn; result is cached per CLI + model */
@@ -629,12 +832,54 @@
629
832
  a.hasKey ? h('span', {class: 'ok mono', text: 'key stored ✓'}) : null]), 'Stored in your user config dir as agent-' + a.id + '; never shown again.'));
630
833
  f.appendChild(h('div', {style: 'display:flex;align-items:center'}, [h('button', {text: 'Test connection', onclick: function () { res.className = 'mono'; if (dirty) { res.textContent = 'save first'; return; } res.textContent = 'testing…'; api('POST', '/api/test-connection', {agentId: a.id}).then(function (r) { var s = r.body.status || r.body.error; res.textContent = '● ' + s + (r.body.http ? ' (HTTP ' + r.body.http + ')' : ''); res.className = 'mono ' + (s === 'ok' ? 'ok' : 'bad'); }); }}), res]));
631
834
  }
632
- if (!isDir) f.appendChild(h('div', {style: 'margin-top:14px'}, [h('button', {class: 'danger', text: 'Remove agent', onclick: function () { draft.teams[a.team] = draft.teams[a.team].filter(function (x) { return x.id !== a.id; }); sel = 'director'; mark(); render(); }})]));
835
+ if (!isDir) f.appendChild(h('div', {style: 'margin-top:14px'}, [h('button', {class: 'danger', text: 'Remove agent', onclick: function () { var L = listOf(a.team), at = L.indexOf(a); if (at >= 0) L.splice(at, 1); sel = 'director'; mark(); render(); }})]));
836
+ return f;
837
+ }
838
+ function projectBox() {
839
+ var f = h('div'); f.appendChild(h('div', {class: 'sec', text: 'PROJECT-WIDE'}));
840
+ var sp = h('textarea', {rows: 4, value: draft.systemPrompt || '', maxLength: 8000, placeholder: 'Optional'});
841
+ sp.addEventListener('input', function () { draft.systemPrompt = sp.value; var was = dirty; mark(); if (dirty !== was) render(); });
842
+ f.appendChild(fld('System prompt (optional)', sp, 'Sent to every agent in this project. Leave empty if your project already has its own agent instructions.'));
843
+ f.appendChild(enhance('system', {}, sp, function (v) { draft.systemPrompt = v; }));
844
+ var cb = h('input', {type: 'checkbox', checked: draft.directorReview !== false});
845
+ cb.addEventListener('change', function () { if (cb.checked) delete draft.directorReview; else draft.directorReview = false; mark(); render(); });
846
+ f.appendChild(h('div', {class: 'chkrow'}, [cb, h('div', {}, [h('div', {text: 'Director reviews the result against your request before delivery'}), h('div', {class: 'ml', style: 'text-transform:none;margin-top:2px', text: 'Adds one Director turn; may send the work back to the last team.'})])]));
847
+ return f;
848
+ }
849
+ function slug(name) { var b = String(name || 'lane').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 24) || 'lane', id = b, n = 2; while ((draft.lanes || []).some(function (l) { return l.id === id; })) { id = b + '-' + n; n++; } return id; }
850
+ function lanesBox() {
851
+ var f = h('div'); f.appendChild(h('div', {class: 'sec', text: 'LANES'}));
852
+ var lanes = draft.lanes || [], tn = function (id) { var t = teamDefs().filter(function (x) { return x.id === id; })[0]; return t ? t.label.replace(/^TEAM /, '') : id; };
853
+ if (!lanes.length) {
854
+ f.appendChild(h('div', {class: 'row2', style: 'grid-template-columns:1fr auto;align-items:center'}, [h('div', {class: 'clinote', style: 'margin:0', text: 'One flow for every request'}), h('button', {text: '+ Add lane', title: 'Different kinds of request can use different teams. The Director picks the lane.', onclick: function () { var o = orderOf(draft); draft.lanes = [{id: 'default', name: 'Default', when: 'General requests', order: o}]; mark(); render(); }})]));
855
+ return f;
856
+ }
857
+ f.appendChild(h('div', {class: 'clinote', text: 'The Director reads each lane\'s "When to use" and picks one lane per request; only that lane\'s teams run, in the order shown.'}));
858
+ lanes.forEach(function (l, li) {
859
+ var nm2 = h('input', {value: l.name, placeholder: 'Lane name'}); nm2.addEventListener('input', function () { l.name = nm2.value; var was = dirty; mark(); if (dirty !== was) render(); });
860
+ var when = h('textarea', {rows: 2, value: l.when || '', placeholder: 'Which requests belong in this lane? e.g. "Code changes: features, bug fixes, refactors"'}); when.addEventListener('input', function () { l.when = when.value; var was = dirty; mark(); if (dirty !== was) render(); });
861
+ var box3 = h('div', {class: 'lane'}, [h('div', {class: 'lh'}, [nm2, h('button', {class: 'danger', text: 'Remove lane', onclick: function () {
862
+ var gone = draft.lanes.splice(li, 1)[0];
863
+ if (!draft.lanes.length) { delete draft.lanes; draft.order = gone.order.slice(); }
864
+ mark(); render(); }})]), fld('When to use', when, 'Written for the Director.'), enhance('lane', {lane: l.id}, when, function (v) { l.when = v; })]);
865
+ box3.appendChild(h('div', {class: 'ml', text: 'TEAMS IN THIS LANE, IN ORDER'}));
866
+ if (!l.order.length) box3.appendChild(h('div', {class: 'clinote bad', text: 'No teams yet. A lane needs at least one team, or remove it; saving is refused otherwise.'}));
867
+ l.order.forEach(function (id, i) {
868
+ var mv = function (d) { var j = i + d; if (j < 0 || j >= l.order.length) return; l.order.splice(i, 1); l.order.splice(j, 0, id); mark(); render(); };
869
+ box3.appendChild(h('div', {class: 'lteam'}, [h('span', {class: 'nbadge', style: 'background:' + (TC[id] || '#8A9AAF'), text: String(i + 1)}), h('span', {class: 'nm', text: tn(id)}),
870
+ h('button', {text: '▲', title: 'Run earlier', disabled: i === 0, onclick: function () { mv(-1); }}), h('button', {text: '▼', title: 'Run later', disabled: i === l.order.length - 1, onclick: function () { mv(1); }}),
871
+ h('button', {text: 'Remove from lane', onclick: function () { l.order.splice(i, 1); mark(); render(); }})]));
872
+ });
873
+ var avail = orderOf(draft).filter(function (id) { return l.order.indexOf(id) < 0; });
874
+ if (avail.length) { var sel2 = h('select', {style: 'margin-top:6px'}); sel2.appendChild(h('option', {value: '', text: '+ Add team to lane…'})); avail.forEach(function (id) { sel2.appendChild(h('option', {value: id, text: tn(id)})); }); sel2.addEventListener('change', function () { if (sel2.value) { l.order.push(sel2.value); mark(); render(); } }); box3.appendChild(sel2); }
875
+ f.appendChild(box3);
876
+ });
877
+ f.appendChild(h('button', {text: '+ Add lane', onclick: function () { draft.lanes.push({id: slug('lane-' + (draft.lanes.length + 1)), name: 'Lane ' + (draft.lanes.length + 1), when: '', order: []}); mark(); render(); }}));
633
878
  return f;
634
879
  }
635
880
  function limits() {
636
881
  var f = h('div'); f.appendChild(h('div', {class: 'sec', text: 'LIMITS'}));
637
- f.appendChild(h('div', {class: 'row3'}, [fld('BA rounds', bind(h('input', {type: 'number', value: draft.limits.baRounds, min: 1}), draft.limits, 'baRounds', true)), fld('QC loops', bind(h('input', {type: 'number', value: draft.limits.qcLoops, min: 0}), draft.limits, 'qcLoops', true)), fld('Agent timeout (ms)', bind(h('input', {type: 'number', value: draft.limits.agentTimeoutMs}), draft.limits, 'agentTimeoutMs', true))]));
882
+ f.appendChild(h('div', {class: 'row3'}, [fld('Discussion rounds per team', bind(h('input', {type: 'number', value: draft.limits.baRounds, min: 1}), draft.limits, 'baRounds', true)), fld('Max send-backs per team', bind(h('input', {type: 'number', value: draft.limits.qcLoops, min: 0}), draft.limits, 'qcLoops', true)), fld('Agent timeout (ms)', bind(h('input', {type: 'number', value: draft.limits.agentTimeoutMs}), draft.limits, 'agentTimeoutMs', true))]));
638
883
  return f;
639
884
  }
640
885
  render();