@ngockhoale/ckit 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/README.md +14 -2
  2. package/dist/src/gui/server.d.ts +3 -1
  3. package/dist/src/gui/server.js +41 -15
  4. package/dist/src/team/bus.d.ts +60 -0
  5. package/dist/src/team/bus.js +172 -0
  6. package/dist/src/team/config.js +5 -4
  7. package/dist/src/team/engine.d.ts +33 -1
  8. package/dist/src/team/engine.js +1095 -170
  9. package/dist/src/team/mcp/hub.d.ts +16 -0
  10. package/dist/src/team/mcp/hub.js +99 -0
  11. package/dist/src/team/mcp/stdio-server.d.ts +2 -0
  12. package/dist/src/team/mcp/stdio-server.js +103 -0
  13. package/dist/src/team/runners.d.ts +4 -0
  14. package/dist/src/team/runners.js +8 -2
  15. package/dist/src/team/scheduler.d.ts +20 -0
  16. package/dist/src/team/scheduler.js +73 -0
  17. package/dist/src/team/sessions/claude.d.ts +16 -5
  18. package/dist/src/team/sessions/claude.js +127 -13
  19. package/dist/src/team/sessions/codex.d.ts +3 -2
  20. package/dist/src/team/sessions/codex.js +21 -3
  21. package/dist/src/team/sessions/fallback.js +6 -2
  22. package/dist/src/team/sessions/index.d.ts +1 -1
  23. package/dist/src/team/sessions/index.js +3 -3
  24. package/dist/src/team/sessions/omp.d.ts +12 -3
  25. package/dist/src/team/sessions/omp.js +95 -8
  26. package/dist/src/team/sessions/proc.d.ts +20 -2
  27. package/dist/src/team/sessions/proc.js +64 -18
  28. package/dist/src/team/sessions/types.d.ts +23 -2
  29. package/dist/src/team/telemetry.d.ts +32 -0
  30. package/dist/src/team/telemetry.js +135 -0
  31. package/dist/src/team/types.d.ts +173 -1
  32. package/dist/src/tui/team/model.js +10 -0
  33. package/gui/app.css +23 -0
  34. package/gui/app.js +208 -6
  35. package/gui/comic/comic.css +86 -0
  36. package/gui/comic/engine.js +44 -0
  37. package/gui/comic/render.js +73 -16
  38. package/gui/index.html +1 -1
  39. package/package.json +1 -1
package/README.md CHANGED
@@ -17,7 +17,19 @@ No env file and no API key are needed: every agent uses the login of its own CLI
17
17
 
18
18
  ## Agent Company (team mode)
19
19
 
20
- A Director plus Team BA (2 agents discuss, then write one handoff) → Team Implement → Team QC (2 reviewers; FAIL returns to Implement, up to `limits.qcLoops`) → (optional) Director review against your original request → Director delivery report. Inside a team the agents discuss in bounded rounds (`limits.baRounds`, early stop on AGREED), the lead writes one `### HANDOFF` (DONE / DECISIONS / OPEN / FOR YOU) and the next team gets it in full. Before any team starts the Director triages the request (PROCEED / NEED INFO, up to 3 rounds, no turns are spent while it waits for you / CANNOT DO, shown as `declined`); runs live only in the CKit process that started them, so a run waiting for your answer is not resumed after a restart and shows in Runs as interrupted. You always talk to the Director; it can continue, redirect or stop the run. When a team asks the Director something only you can decide, the Director passes it on (at most 3 times per run): the run pauses, the question appears in the conversation and the request box turns into an amber ANSWER box (text, attached files and `@` mentions all work; "Proceed with assumptions" uses the Director's stated assumption).
20
+ A Director plus the default teams BA → Implement → Tester → Security → QC (FAIL returns to the team before, up to `limits.qcLoops`) → (optional) Director review against your original request → Director delivery report. Core V2 is **parallel-first** (see `docs/architecture/CKIT_CORE_V2.md`):
21
+ - **Modes.** The Director picks a mode per request:
22
+ - `DIRECT`: it answers itself, with no team turns;
23
+ - `DELEGATE <agent>`: one agent works;
24
+ - `PARALLEL_MERGE`: the default;
25
+ - `TARGETED_DISCUSSION`: exactly one clarification round.
26
+ - **Team work.** Members work independently and at the same time, then the lead merges their contributions and a deduplicated `MERGED FINDINGS` list into one `### HANDOFF` (DONE / DECISIONS / OPEN / FOR YOU), and the next team gets it in full. Legacy sequential discussion rounds only run when `limits.baRounds` > 0.
27
+ - **Decision Board.** Agents publish structured contributions (findings with severity and location, risks, recommendations, evidence). Decisions carry revisions.
28
+ - **Early Tester.** A team named "Tester" designs test scenarios while Implement is still coding.
29
+ - **Security team (default, read-only).** One agent (`security-claude`, claude, default model) reviews the change for secrets, auth, injection, unsafe spawn/exec, path traversal, dependency risk and data exposure, with severity and evidence per finding. It runs right before QC whenever the goal changes code and is skipped (journaled) for read-only goals. A critical finding wakes the Director at once and blocks Delivery: the work goes back to Implement (bounded), then the owner must reply `ACCEPT: <reason>` to deliver anyway. Like every team except the Director it can be edited or removed in Config; an existing `.ckit/team.json` is never changed.
30
+ - **Agent tools.** Agents can message each other and the Director through CKit's MCP tools, which use a local socket and never a network port.
31
+ - **Owner control.** Owner messages that arrive close together are coalesced into one Director decision; urgent wording or STOP is handled at once. Pause / Resume / Interrupt buttons stop new turns or abort running turns. An interrupted turn is redone after resume with your newest guidance.
32
+ - **Long prompts** are compacted. The full text is kept as a run artifact. Before any team starts the Director triages the request (PROCEED / NEED INFO, up to 3 rounds, no turns are spent while it waits for you / CANNOT DO, shown as `declined`); runs live only in the CKit process that started them, so a run waiting for your answer is not resumed after a restart and shows in Runs as interrupted. You always talk to the Director; it can continue, redirect or stop the run. When a team asks the Director something only you can decide, the Director passes it on (at most 3 times per run): the run pauses, the question appears in the conversation and the request box turns into an amber ANSWER box (text, attached files and `@` mentions all work; "Proceed with assumptions" uses the Director's stated assumption).
21
33
 
22
34
  ```bash
23
35
  ckit # no command, in a terminal: opens the GUI. First time in a project it lands on Config so setup is done there
@@ -28,7 +40,7 @@ ckit team --demo # same pipeline in the terminal, fully SIMULATED (no mo
28
40
  ckit team "<goal>" # real run with the agents in <project>/.ckit/team.json (codex / claude-code / omp / api)
29
41
  ckit team --init # write the default .ckit/team.json (--force overwrites)
30
42
  ```
31
- - Teams are configurable in Config: only the Director is mandatory; BA, Implement and QC can each be removed or re-added, and `+ Add team` creates your own team (`extraTeams` in `.ckit/team.json`: name, mission, agents). All teams follow one numbered flow, `order` (e.g. `["ba","implement","test","qc"]`, reorder with the arrows in Config; absent = ba, implement, qc with custom teams placed by the old `runAfter`): work goes Director -> team 1 -> team 2 ..., each team gets the Director's brief and the previous team's output. A team can end its message with `ASK PREVIOUS: <question>` (the team before it, or the Director, answers) or `RETURN TO PREVIOUS: <reason>` (QC's FAIL means the same); both are limited to `limits.qcLoops` per team boundary ("Max send-backs per team"). Each agent (Director too) also has an optional `cliArgs` text box ("Extra CLI arguments"), e.g. `--settings ./other-settings.json`: it is split like a shell would (quotes group; `~` and `$HOME` become your home folder, other `$VAR` are not expanded), appended to that agent's start command after CKit's own flags and before the prompt, and empty means not used.
43
+ - Teams are configurable in Config: only the Director is mandatory; BA, Implement and QC can each be removed or re-added, and `+ Add team` creates your own team (`extraTeams` in `.ckit/team.json`: name, mission, agents). All teams follow one numbered flow, `order` (default `["ba","implement","test","security","qc"]`, reorder with the arrows in Config; absent = ba, implement, qc with custom teams placed by the old `runAfter`): work goes Director -> team 1 -> team 2 ..., each team gets the Director's brief and the previous team's output. A team can end its message with `ASK PREVIOUS: <question>` (the team before it, or the Director, answers) or `RETURN TO PREVIOUS: <reason>` (QC's FAIL means the same); both are limited to `limits.qcLoops` per team boundary ("Max send-backs per team"). Each agent (Director too) also has an optional `cliArgs` text box ("Extra CLI arguments"), e.g. `--settings ./other-settings.json`: it is split like a shell would (quotes group; `~` and `$HOME` become your home folder, other `$VAR` are not expanded), appended to that agent's start command after CKit's own flags and before the prompt, and empty means not used.
32
44
 
33
45
  The Runs list replays a past run at 1×, 2× or 4×; the row being replayed is marked REPLAYING with a Stop button (also in the header), other rows show READY, and pressing another speed restarts the replay at that speed. Every run is journaled to `.ckit/team/runs/<runId>/` (`events.jsonl`, `handoff-ba.md`, `qc-report-N.md`, `transcript.md`, `report.md`). Real agents use their own CLI login; codex runs `read-only` unless the agent has `access: "write"` (then `workspace-write`), claude uses `acceptEdits` only for write access, never bypass.
34
46
 
@@ -1,10 +1,12 @@
1
+ import { startTeamRun } from '../team/engine.js';
1
2
  /** host: 127.0.0.1 = this machine only; any other value (e.g. 0.0.0.0, the `ckit gui` default) allows LAN access; the token is always required. */
2
3
  export interface GuiServerOptions {
3
4
  projectRoot: string;
4
5
  port?: number;
5
6
  host?: string;
6
7
  open?: boolean; /** Fixed access token (owner-chosen, >= 16 chars); default is a fresh random token per start. */
7
- token?: string;
8
+ token?: string; /** Test hook: replaces the engine's startTeamRun. */
9
+ startRun?: typeof startTeamRun;
8
10
  }
9
11
  export interface GuiServer {
10
12
  url: string;
@@ -18,6 +18,7 @@ import { dispatchRunner } from '../team/runners.js';
18
18
  import { splitCliArgs } from '../team/cli-args.js';
19
19
  import { handleFs } from './workspace-files.js';
20
20
  import { listWorkspace, searchFiles } from './file-index.js';
21
+ import { runTelemetry } from '../team/telemetry.js';
21
22
  import { listTeamRuns, readTeamJournal } from '../team/journal.js';
22
23
  import { DEFAULT_MISSIONS, allAgentsOf, effectiveOrder } from '../team/types.js';
23
24
  import { mkdirSync, writeFileSync } from 'node:fs';
@@ -104,7 +105,7 @@ export async function startGuiServer(opts) {
104
105
  const runs = new Map();
105
106
  let playback = null, focus = null;
106
107
  const sse = new Set();
107
- const MAX_LIVE_RUNS = 8, MAX_TRACKED_RUNS = 24;
108
+ const MAX_LIVE_RUNS = 12, MAX_TRACKED_RUNS = 24;
108
109
  const sendEvent = (res, e) => { res.write(`data: ${JSON.stringify(e)}\n\n`); };
109
110
  const toAll = (t, write) => { for (const r of [...sse, ...t.listeners]) {
110
111
  try {
@@ -113,7 +114,7 @@ export async function startGuiServer(opts) {
113
114
  catch { /* dead socket */ }
114
115
  } };
115
116
  const attach = (handle, goal, simulated, replay) => {
116
- const cur = { handle, goal, simulated, startedAt: new Date().toISOString(), outcome: null, ...(replay ? { replay } : {}), unsub: () => undefined, listeners: new Set() };
117
+ const cur = { handle, goal, simulated, startedAt: new Date().toISOString(), outcome: null, ...(replay ? { replay } : {}), unsub: () => undefined, listeners: new Set(), events: [], tele: null };
117
118
  if (replay) {
118
119
  playback?.unsub();
119
120
  playback = cur;
@@ -134,7 +135,10 @@ export async function startGuiServer(opts) {
134
135
  }
135
136
  catch { /* dead socket */ }
136
137
  }
137
- cur.unsub = handle.subscribe(e => toAll(cur, r => sendEvent(r, e)));
138
+ cur.unsub = handle.subscribe(e => { if (e.type !== 'agent.delta' && e.type !== 'agent.tool') {
139
+ cur.events.push(e);
140
+ cur.tele = null;
141
+ } toAll(cur, r => sendEvent(r, e)); });
138
142
  toAll(cur, r => r.write('event: ready\ndata: {}\n\n'));
139
143
  void handle.done.then(o => { cur.outcome = o; });
140
144
  return cur;
@@ -143,7 +147,13 @@ export async function startGuiServer(opts) {
143
147
  const liveReal = () => [...runs.values()].filter(t => t.outcome === null);
144
148
  /** 'current' = focus run; otherwise a tracked real run or the playback with that id. */
145
149
  const trackedOf = (id) => id === 'current' ? focus : runs.get(id) ?? (playback?.handle.runId === id ? playback : null);
146
- const view = (t) => ({ runId: t.handle.runId, goal: t.goal, simulated: t.simulated, startedAt: t.startedAt, running: t.outcome === null, outcome: t.outcome, ...(t.replay ? { replay: t.replay } : {}) });
150
+ const telemetryOf = (t) => {
151
+ const now = Date.now();
152
+ if (!t.tele || (t.outcome === null && now - t.tele.at > 500))
153
+ t.tele = { at: now, value: runTelemetry(t.events, now) };
154
+ return t.tele.value;
155
+ };
156
+ const view = (t) => ({ telemetry: telemetryOf(t), paused: t.outcome === null && telemetryOf(t).paused, runId: t.handle.runId, goal: t.goal, simulated: t.simulated, startedAt: t.startedAt, running: t.outcome === null, outcome: t.outcome, ...(t.replay ? { replay: t.replay } : {}) });
147
157
  /** Replays history to one client only; live events arrive through the shared fan-out. */
148
158
  const replayTo = (t, res) => { t.handle.subscribe(e => { try {
149
159
  sendEvent(res, e);
@@ -333,7 +343,7 @@ export async function startGuiServer(opts) {
333
343
  const cfgNow = loadConfig(), laneId = typeof b['lane'] === 'string' ? b['lane'] : '';
334
344
  if (laneId && !(cfgNow.lanes ?? []).some(l => l.id === laneId))
335
345
  return json(res, 400, { error: `unknown lane "${laneId.slice(0, 40)}"` });
336
- const handle = startTeamRun({ projectRoot: root, goal, config: cfgNow, simulated, attachments: files, ...(laneId ? { lane: laneId } : {}) });
346
+ const handle = (opts.startRun ?? startTeamRun)({ projectRoot: root, goal, config: cfgNow, simulated, attachments: files, ...(laneId ? { lane: laneId } : {}) });
337
347
  release(b['attachments']);
338
348
  attach(handle, goal, simulated);
339
349
  return json(res, 200, { runId: handle.runId });
@@ -422,7 +432,7 @@ export async function startGuiServer(opts) {
422
432
  }
423
433
  if (m === 'GET' && p === '/api/clis')
424
434
  return json(res, 200, { clis: detectClis(), configFile: teamConfigPath(root) });
425
- const act = /^\/api\/runs\/([^/]+)\/(message|proceed|stop)$/.exec(p);
435
+ const act = /^\/api\/runs\/([^/]+)\/(message|proceed|stop|pause|resume|interrupt)$/.exec(p);
426
436
  const actOn = () => {
427
437
  if (!act || m !== 'POST')
428
438
  return null;
@@ -463,6 +473,13 @@ export async function startGuiServer(opts) {
463
473
  t.handle.proceedWithAssumptions();
464
474
  return json(res, 200, { ok: true });
465
475
  }
476
+ if (a.kind === 'pause' || a.kind === 'resume' || a.kind === 'interrupt') {
477
+ const fn = t.handle[a.kind];
478
+ if (!fn)
479
+ return json(res, 409, { error: `this run cannot ${a.kind}` });
480
+ fn.call(t.handle);
481
+ return json(res, 200, { ok: true });
482
+ }
466
483
  t.handle.stop();
467
484
  // A playback has no run.completed of its own when it is cut short, so every open page is told directly.
468
485
  if (t.replay) {
@@ -593,20 +610,29 @@ export async function startGuiServer(opts) {
593
610
  openBrowser(url);
594
611
  return {
595
612
  url,
596
- close: () => new Promise(done => {
597
- for (const t of [...runs.values(), ...(playback ? [playback] : [])]) {
613
+ close: async () => {
614
+ const all = [...runs.values(), ...(playback ? [playback] : [])];
615
+ for (const t of all) {
598
616
  try {
599
617
  t.handle.stop();
600
618
  }
601
619
  catch { /* ignore */ }
602
- t.unsub();
603
620
  }
604
- for (const r of sse)
605
- r.end();
606
- release([...uploads.keys()]);
607
- server.close(() => done());
608
- server.closeAllConnections();
609
- }),
621
+ // Agent process groups must be gone before we resolve (cap 8 s).
622
+ await Promise.race([
623
+ Promise.all(all.map(t => Promise.resolve().then(() => t.handle.whenClosed?.()).catch(() => undefined))),
624
+ new Promise(ok => { setTimeout(ok, 8000).unref(); }),
625
+ ]);
626
+ for (const t of all)
627
+ t.unsub();
628
+ await new Promise(done => {
629
+ for (const r of sse)
630
+ r.end();
631
+ release([...uploads.keys()]);
632
+ server.close(() => done());
633
+ server.closeAllConnections();
634
+ });
635
+ },
610
636
  };
611
637
  }
612
638
  /** Folder the GUI works in: the current folder itself (symlinks resolved), never a parent. */
@@ -0,0 +1,60 @@
1
+ import type { Severity, TeamEventInput } from './types.js';
2
+ export interface BusMail {
3
+ readonly mailId: string;
4
+ readonly from: string;
5
+ readonly to: string;
6
+ readonly subject: string;
7
+ readonly text: string;
8
+ readonly replyTo?: string;
9
+ readonly kind: 'mail' | 'ask' | 'answer';
10
+ readonly at: string;
11
+ }
12
+ export interface ContributionInput {
13
+ findings: {
14
+ summary: string;
15
+ severity: Severity;
16
+ requirement?: string;
17
+ location?: string;
18
+ evidence?: string;
19
+ confidence?: number;
20
+ action?: string;
21
+ }[];
22
+ recommendations: string[];
23
+ risks: string[];
24
+ proposedDecisions: string[];
25
+ evidenceRefs: string[];
26
+ unresolvedQuestions: string[];
27
+ status: 'partial' | 'complete';
28
+ }
29
+ export interface ToolSpec {
30
+ readonly name: string;
31
+ readonly description: string;
32
+ readonly parameters: Record<string, unknown>;
33
+ }
34
+ export interface RunBusOptions {
35
+ runId: string;
36
+ emit: (ev: TeamEventInput) => void;
37
+ redact: (s: string) => string;
38
+ /** valid addressee: agent id, team id, 'director', 'all' */
39
+ isAddress: (id: string) => boolean;
40
+ teamOf: (agentId: string) => string | null;
41
+ onAsk: (from: string, question: string) => Promise<string>;
42
+ onProgress: (agentId: string, text: string) => void;
43
+ onContribution: (agentId: string, c: ContributionInput) => void;
44
+ }
45
+ export interface RunBus {
46
+ send(from: string, to: string, subject: string, text: string, o?: {
47
+ replyTo?: string;
48
+ kind?: BusMail['kind'];
49
+ }): BusMail | null;
50
+ unread(agentId: string): BusMail[];
51
+ markRead(agentId: string, ids: readonly string[], via: 'tool' | 'prompt' | 'steer'): void;
52
+ all(): readonly BusMail[];
53
+ callTool(agentId: string, name: string, args: unknown): Promise<{
54
+ text: string;
55
+ isError?: boolean;
56
+ }>;
57
+ toolSpecs(): ToolSpec[];
58
+ }
59
+ export declare const BUS_TOOL_SPECS: readonly ToolSpec[];
60
+ export declare function createRunBus(o: RunBusOptions): RunBus;
@@ -0,0 +1,172 @@
1
+ // Per-run in-memory message bus (Core V2 A2A). The durable record is the run journal: this module only emits events through a callback.
2
+ // Agents reach it through CKit MCP tools (callTool/toolSpecs); the engine reaches it directly (send/unread/markRead).
3
+ import { randomUUID } from 'node:crypto';
4
+ const SUBJECT_MAX = 200, TEXT_MAX = 8000, ID_MAX = 200, LIST_MAX = 50, ITEM_MAX = 2000;
5
+ const SEVERITIES = ['critical', 'high', 'medium', 'low', 'info'];
6
+ const clip = (s, n) => (s.length > n ? `${s.slice(0, n - 1)}…` : s);
7
+ const str = { type: 'string' };
8
+ const strList = { type: 'array', items: str, maxItems: LIST_MAX };
9
+ export const BUS_TOOL_SPECS = [
10
+ { name: 'ckit_send_message', description: 'Send a message to another agent, a team, the director or all. Recipients see it in their inbox / next prompt.',
11
+ parameters: { type: 'object', properties: { to: { ...str, description: "agent id, team id, 'director' or 'all'" }, subject: str, text: str, replyTo: { ...str, description: 'mailId this replies to' } }, required: ['to', 'subject', 'text'], additionalProperties: false } },
12
+ { name: 'ckit_read_inbox', description: 'Read (and mark as read) the messages addressed to you that you have not read yet.', parameters: { type: 'object', properties: {}, additionalProperties: false } },
13
+ { name: 'ckit_report_progress', description: 'Report a short progress line to the owner dashboard. Costs no model call.', parameters: { type: 'object', properties: { text: str }, required: ['text'], additionalProperties: false } },
14
+ { name: 'ckit_ask_director', description: 'Ask the director a blocking question and wait for the answer.', parameters: { type: 'object', properties: { question: str }, required: ['question'], additionalProperties: false } },
15
+ { name: 'ckit_publish_contribution', description: 'Publish your structured contribution (findings, recommendations, risks, proposed decisions) to the decision board.',
16
+ parameters: { type: 'object', properties: {
17
+ findings: { type: 'array', maxItems: LIST_MAX, items: { type: 'object', properties: { summary: str, severity: { type: 'string', enum: SEVERITIES }, requirement: str, location: str, evidence: str, confidence: { type: 'number', minimum: 0, maximum: 1 }, action: str }, required: ['summary', 'severity'], additionalProperties: false } },
18
+ recommendations: strList, risks: strList, proposedDecisions: strList, evidenceRefs: strList, unresolvedQuestions: strList, status: { type: 'string', enum: ['partial', 'complete'] }
19
+ }, required: ['findings'], additionalProperties: false } },
20
+ ];
21
+ const fail = (text) => ({ text, isError: true });
22
+ export function createRunBus(o) {
23
+ const mails = [];
24
+ const read = new Map(); // agentId -> mail ids
25
+ const readSet = (a) => { let s = read.get(a); if (!s) {
26
+ s = new Set();
27
+ read.set(a, s);
28
+ } return s; };
29
+ const record = (from, to, subject, text, x = {}) => {
30
+ const kind = x.kind ?? 'mail';
31
+ const replyTo = x.replyTo ? clip(o.redact(x.replyTo), ID_MAX) : undefined;
32
+ const mail = { mailId: randomUUID().slice(0, 12), from: clip(from, ID_MAX), to: clip(to, ID_MAX), subject: clip(o.redact(subject), SUBJECT_MAX), text: clip(o.redact(text), TEXT_MAX), ...(replyTo ? { replyTo } : {}), kind, at: new Date().toISOString() };
33
+ mails.push(mail);
34
+ o.emit({ type: 'agent.mail', mailId: mail.mailId, from: mail.from, to: mail.to, subject: mail.subject, text: mail.text, ...(replyTo ? { replyTo } : {}), kind });
35
+ return mail;
36
+ };
37
+ const bus = {
38
+ send(from, to, subject, text, x) {
39
+ if (!to || !o.isAddress(to))
40
+ return null;
41
+ return record(from, to, subject, text, x);
42
+ },
43
+ unread(agentId) {
44
+ const team = o.teamOf(agentId), seen = readSet(agentId);
45
+ return mails.filter(m => m.from !== agentId && !seen.has(m.mailId) && (m.to === agentId || m.to === 'all' || (team !== null && m.to === team)));
46
+ },
47
+ markRead(agentId, ids, via) {
48
+ const seen = readSet(agentId), fresh = [...new Set(ids)].filter(id => !seen.has(id) && mails.some(m => m.mailId === id));
49
+ if (!fresh.length)
50
+ return;
51
+ for (const id of fresh)
52
+ seen.add(id);
53
+ o.emit({ type: 'agent.mail.read', agentId, mailIds: fresh, via });
54
+ },
55
+ all: () => mails,
56
+ toolSpecs: () => BUS_TOOL_SPECS.map(s => ({ ...s })),
57
+ async callTool(agentId, name, args) {
58
+ try {
59
+ return await run(agentId, name, args);
60
+ }
61
+ catch (e) {
62
+ return fail(`${name} failed: ${e instanceof Error ? e.message : String(e)}`);
63
+ }
64
+ },
65
+ };
66
+ const strArg = (a, k, req, max = TEXT_MAX) => {
67
+ const v = a[k];
68
+ if (v === undefined)
69
+ return req ? new Error(`'${k}' is required`) : undefined;
70
+ if (typeof v !== 'string')
71
+ return new Error(`'${k}' must be a string`);
72
+ if (req && !v.trim())
73
+ return new Error(`'${k}' must not be empty`);
74
+ return v.length > max ? v.slice(0, max) : v;
75
+ };
76
+ const listArg = (a, k) => {
77
+ const v = a[k];
78
+ if (v === undefined)
79
+ return [];
80
+ if (!Array.isArray(v) || v.length > LIST_MAX || v.some(x => typeof x !== 'string'))
81
+ return new Error(`'${k}' must be an array of at most ${LIST_MAX} strings`);
82
+ return v.map(x => clip(o.redact(x), ITEM_MAX));
83
+ };
84
+ async function run(agentId, name, args) {
85
+ const a = args === undefined || args === null ? {} : args;
86
+ if (typeof a !== 'object' || Array.isArray(a))
87
+ return fail('arguments must be an object');
88
+ const r = a;
89
+ switch (name) {
90
+ case 'ckit_send_message': {
91
+ const to = strArg(r, 'to', true, ID_MAX), subject = strArg(r, 'subject', true, 10000), text = strArg(r, 'text', true, 100000), replyTo = strArg(r, 'replyTo', false, ID_MAX);
92
+ for (const v of [to, subject, text, replyTo])
93
+ if (v instanceof Error)
94
+ return fail(v.message);
95
+ const m = bus.send(agentId, to, subject, text, replyTo ? { replyTo: replyTo } : {});
96
+ return m ? { text: `sent ${m.mailId} to ${m.to}` } : fail(`unknown recipient '${String(to).slice(0, 60)}' (use an agent id, a team id, 'director' or 'all')`);
97
+ }
98
+ case 'ckit_read_inbox': {
99
+ const list = bus.unread(agentId);
100
+ if (!list.length)
101
+ return { text: 'inbox empty' };
102
+ bus.markRead(agentId, list.map(m => m.mailId), 'tool');
103
+ return { text: list.map(m => `[${m.mailId}] from ${m.from}${m.kind !== 'mail' ? ` (${m.kind})` : ''}${m.replyTo ? ` re ${m.replyTo}` : ''} — ${m.subject}\n${m.text}`).join('\n\n') };
104
+ }
105
+ case 'ckit_report_progress': {
106
+ const t = strArg(r, 'text', true, 500);
107
+ if (t instanceof Error)
108
+ return fail(t.message);
109
+ o.onProgress(agentId, o.redact(t));
110
+ return { text: 'progress recorded' };
111
+ }
112
+ case 'ckit_ask_director': {
113
+ const q = strArg(r, 'question', true, 4000);
114
+ if (q instanceof Error)
115
+ return fail(q.message);
116
+ const ask = record(agentId, 'director', 'question', q, { kind: 'ask' });
117
+ const answer = await o.onAsk(agentId, o.redact(q));
118
+ const ans = record('director', agentId, 're: question', answer, { kind: 'answer', replyTo: ask.mailId });
119
+ readSet(agentId).add(ans.mailId);
120
+ o.emit({ type: 'agent.mail.read', agentId, mailIds: [ans.mailId], via: 'tool' });
121
+ return { text: ans.text };
122
+ }
123
+ case 'ckit_publish_contribution': {
124
+ const rawF = r['findings'];
125
+ if (!Array.isArray(rawF))
126
+ return fail("'findings' must be an array");
127
+ if (rawF.length > LIST_MAX)
128
+ return fail(`at most ${LIST_MAX} findings`);
129
+ const findings = [];
130
+ for (const [i, f] of rawF.entries()) {
131
+ if (!f || typeof f !== 'object' || Array.isArray(f))
132
+ return fail(`findings[${i}] must be an object`);
133
+ const fr = f;
134
+ if (typeof fr['summary'] !== 'string' || !fr['summary'].trim())
135
+ return fail(`findings[${i}].summary is required`);
136
+ if (typeof fr['severity'] !== 'string' || !SEVERITIES.includes(fr['severity']))
137
+ return fail(`findings[${i}].severity must be one of ${SEVERITIES.join('|')}`);
138
+ const out = { summary: clip(o.redact(fr['summary']), ITEM_MAX), severity: fr['severity'] };
139
+ for (const k of ['requirement', 'location', 'evidence', 'action']) {
140
+ const v = fr[k];
141
+ if (v === undefined)
142
+ continue;
143
+ if (typeof v !== 'string')
144
+ return fail(`findings[${i}].${k} must be a string`);
145
+ out[k] = clip(o.redact(v), ITEM_MAX);
146
+ }
147
+ if (fr['confidence'] !== undefined) {
148
+ if (typeof fr['confidence'] !== 'number' || !Number.isFinite(fr['confidence']) || fr['confidence'] < 0 || fr['confidence'] > 1)
149
+ return fail(`findings[${i}].confidence must be a number 0..1`);
150
+ out.confidence = fr['confidence'];
151
+ }
152
+ findings.push(out);
153
+ }
154
+ const lists = {};
155
+ for (const k of ['recommendations', 'risks', 'proposedDecisions', 'evidenceRefs', 'unresolvedQuestions']) {
156
+ const v = listArg(r, k);
157
+ if (v instanceof Error)
158
+ return fail(v.message);
159
+ lists[k] = v;
160
+ }
161
+ const status = r['status'] ?? 'partial';
162
+ if (status !== 'partial' && status !== 'complete')
163
+ return fail("'status' must be 'partial' or 'complete'");
164
+ o.onContribution(agentId, { findings, ...lists, status });
165
+ return { text: `contribution recorded (${findings.length} findings, ${status})` };
166
+ }
167
+ default: return fail(`unknown tool '${name.slice(0, 60)}'`);
168
+ }
169
+ }
170
+ return bus;
171
+ }
172
+ //# sourceMappingURL=bus.js.map
@@ -12,9 +12,10 @@ export function defaultTeamConfig() {
12
12
  implement: [agent('dev-claude', 'Dev · Claude', 'implement', 'claude-code', 'write')],
13
13
  qc: [agent('qc-codex-1', 'QC · Codex 1', 'qc', 'codex', 'read'), agent('qc-codex-2', 'QC · Codex 2', 'qc', 'codex', 'read')],
14
14
  },
15
- extraTeams: [{ id: 'test', name: 'Tester', mission: "Run the project's real checks (build, unit/integration tests, and a quick manual check of the changed behaviour); write missing tests for the acceptance criteria when needed; report PASS/FAIL with the exact commands and output summary.", agents: [agent('tester-codex', 'Tester · Codex', 'test', 'codex', 'write')] }],
16
- order: ['ba', 'implement', 'test', 'qc'],
17
- limits: { baRounds: 2, qcLoops: 2, agentTimeoutMs: 900000 },
15
+ extraTeams: [{ id: 'test', name: 'Tester', mission: "Two testers work in parallel, independently. Test Architect: derive test scenarios from the acceptance criteria and contracts, write the missing tests and run the project's real checks (build, unit/integration tests). Adversarial Tester: hunt for edge cases, invalid input, regressions and security problems the happy path misses, and run them. Report PASS/FAIL with the exact commands and output summary.", agents: [agent('test-architect', 'Test Architect · Codex', 'test', 'codex', 'write'), agent('adversarial-tester', 'Adversarial Tester · Claude', 'test', 'claude-code', 'read')] },
16
+ { id: 'security', name: 'Security', mission: 'Security review of the changes against the goal (read-only: never change a file). Check secrets (hard-coded keys, tokens, credentials in code, logs or output), auth and authorization, injection (SQL, shell, HTML/XSS, template, prompt), unsafe spawn/exec, path traversal and unsafe file access, dependency risk (new or vulnerable packages, unpinned installs) and data exposure (sensitive data sent to the browser, logs, storage or the network). Report each problem on its own line as "FINDING [critical|high|medium|low|info]: <summary> [at <file:line>]" followed by its evidence (the code or command output that shows it). Use critical only for an exploitable problem or a leaked secret. Say "no security findings" when there are none.', agents: [agent('security-claude', 'Security', 'security', 'claude-code', 'read')] }],
17
+ order: ['ba', 'implement', 'test', 'security', 'qc'],
18
+ limits: { baRounds: 0, qcLoops: 2, agentTimeoutMs: 900000 },
18
19
  };
19
20
  }
20
21
  const CLIS = ['codex', 'claude-code', 'omp', 'api', 'auto', 'simulated'];
@@ -282,7 +283,7 @@ export function parseTeamConfig(json) {
282
283
  else if (sp.trim())
283
284
  systemPrompt = sp.trim();
284
285
  }
285
- const limits = { baRounds: int('baRounds', 1, 10), qcLoops: int('qcLoops', 0, 10), agentTimeoutMs: int('agentTimeoutMs', 1000, 7200000) };
286
+ const limits = { baRounds: int('baRounds', 0, 10), qcLoops: int('qcLoops', 0, 10), agentTimeoutMs: int('agentTimeoutMs', 1000, 7200000) };
286
287
  if (errors.length || !director)
287
288
  return { ok: false, errors };
288
289
  return { ok: true, config: { version: 1, director, teams: { ba, implement, qc }, ...(Object.keys(missions).length ? { missions } : {}), ...(extraTeams.length ? { extraTeams } : {}), ...(order ? { order } : {}), ...(lanes ? { lanes } : {}), ...(directorReview === false ? { directorReview } : {}), ...(systemPrompt ? { systemPrompt } : {}), limits } };
@@ -1,8 +1,10 @@
1
1
  import { type AttachmentInput } from './attachments.js';
2
2
  import { type OpenSession } from './sessions/index.js';
3
+ import { type ContributionInput } from './bus.js';
4
+ import { type AgentScheduler } from './scheduler.js';
3
5
  import { type WorkspaceLease } from './workspace-lease.js';
4
6
  import { type AgentRunner } from './runners.js';
5
- import { type TeamConfig, type TeamRunHandle } from './types.js';
7
+ import { type AgentContribution, type CollabMode, type MergedFinding, type TeamConfig, type TeamRunHandle } from './types.js';
6
8
  export interface StartTeamRunOptions {
7
9
  /** Persistent-session factory (default: native drivers for codex/claude-code/omp). Tests inject fakes. Ignored when `runner` is set or the run is simulated. */
8
10
  readonly openSession?: OpenSession;
@@ -21,6 +23,10 @@ export interface StartTeamRunOptions {
21
23
  readonly lane?: string;
22
24
  /** Workspace write lease (default: the shared per-project lease). Tests inject their own. */
23
25
  readonly lease?: WorkspaceLease;
26
+ /** PF-RES-SCHED global agent-process scheduler. Default: the process-wide one for real runs; simulated runs are not capped unless one is injected. */
27
+ readonly scheduler?: AgentScheduler | null;
28
+ /** Start the per-run CKit tool hub (MCP over a unix socket) and give agents the bus tools. Default: on for real native sessions (no injected openSession); env CKIT_MCP=0 turns it off. */
29
+ readonly tools?: boolean;
24
30
  }
25
31
  /** Pure rule-based owner-chat decision (director cli 'auto', and the fallback for model directors). */
26
32
  export declare function ruleDecision(text: string): {
@@ -55,6 +61,32 @@ export declare function parseCheckpoint(text: string): {
55
61
  question: string;
56
62
  }[];
57
63
  };
64
+ /** 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. */
65
+ export declare function contributionFrom(text: string, verdictFail?: boolean): ContributionInput;
66
+ /** 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. */
67
+ export declare function mergeFindings(cs: readonly AgentContribution[]): MergedFinding[];
68
+ /** Streaming redaction (review item 5): returns the redacted text that is safe to emit now and the raw tail to keep.
69
+ * 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
70
+ * only when redacting the whole buffer ends exactly with the redacted tail (no match spans the cut). `final` = the turn ended: emit everything. */
71
+ export declare function splitRedacted(pending: string, redact: (t: string) => string, overlap: number, final: boolean): {
72
+ emit: string;
73
+ keep: string;
74
+ };
75
+ /** PF-MODES: the owner asked for a read-only result (question, analysis, review) - no team may change files.
76
+ * 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. */
77
+ export declare const isReadOnlyGoal: (goal: string) => boolean;
78
+ /** The Director's "TEAMS: a, b" line: the configured teams it activates (lowercased ids), or null when absent. */
79
+ export declare function parseTeams(text: string): string[] | null;
80
+ /** 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. */
81
+ export declare function parseDepends(text: string): Map<string, string[]> | null;
82
+ /** 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);
83
+ * 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). */
84
+ export declare function buildGraph(order: readonly string[], deps: Map<string, string[]> | null): Map<string, string[]>;
85
+ /** The Director's collaboration mode line (PF-MODES), or null when absent. */
86
+ export declare function parseMode(text: string): {
87
+ mode: CollabMode;
88
+ reason: string;
89
+ } | null;
58
90
  export declare function startTeamRun(opts: StartTeamRunOptions): TeamRunHandle;
59
91
  /** Re-emits a journal with original relative timing / speed (gaps capped at 1.5s/speed). */
60
92
  export declare function replayTeamRun(runDir: string, opts?: {