@ngockhoale/ckit 0.4.0 → 0.4.2

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.
@@ -33,7 +33,7 @@ export declare function ruleDecision(text: string): {
33
33
  decision: 'continue' | 'redirect' | 'stop';
34
34
  note: string;
35
35
  };
36
- /** Last `VERDICT: PASS|FAIL` wins; no verdict at all counts as FAIL (conservative). */
36
+ /** Last `VERDICT: PASS|FAIL` line wins; no verdict at all counts as FAIL (conservative). */
37
37
  export declare function parseVerdict(text: string): 'PASS' | 'FAIL';
38
38
  export interface DirectorDecision {
39
39
  readonly kind: 'proceed' | 'need' | 'cannot';
@@ -36,7 +36,7 @@ class NodeCancelled extends Error {
36
36
  } // a PARALLEL_EXECUTE node stopped because a sibling node redirected or halted the flow // run already finished (stop) or failed; unwinds the pipeline
37
37
  const oneLine = (s, max = 200) => { const t = s.replace(/\s+/g, ' ').trim(); return t.length > max ? `${t.slice(0, max - 1)}…` : t; };
38
38
  const clip = (s, max) => s.length > max ? `${s.slice(0, max)}\n[...truncated]` : s;
39
- const STOP_RE = /^\s*(stop|dừng)/i, REDIRECT_RE = /^\s*(redirect|đổi hướng)[:\s]\s*/i;
39
+ const STOP_RE = /^\s*(stop|dừng)(?![\p{L}\p{N}_])/iu, REDIRECT_RE = /^\s*(redirect|đổi hướng)[:\s]\s*/i;
40
40
  /** Pure rule-based owner-chat decision (director cli 'auto', and the fallback for model directors). */
41
41
  export function ruleDecision(text) {
42
42
  if (STOP_RE.test(text))
@@ -45,11 +45,20 @@ export function ruleDecision(text) {
45
45
  return { decision: 'redirect', note: text.replace(REDIRECT_RE, '').trim() || text.trim() };
46
46
  return { decision: 'continue', note: text.trim() };
47
47
  }
48
- /** Last `VERDICT: PASS|FAIL` wins; no verdict at all counts as FAIL (conservative). */
49
- export function parseVerdict(text) {
50
- const all = [...text.matchAll(/VERDICT\s*[:\-]?\s*\**\s*(PASS|FAIL)/gi)];
48
+ /** The last `<LABEL>: PASS|FAIL` verdict line wins. Lines that start with the label (after Markdown bullets/bold/headings) take precedence, so prose that
49
+ * merely mentions the syntax ("No VERDICT: PASS because ...") never overrides a real verdict line; mid-line matches are the fallback only. */
50
+ const lastVerdict = (text, label) => {
51
+ const line = new RegExp(`^[ \\t>*_#-]*(?:(?:QC|FINAL|OVERALL|DIRECTOR)[ \\t]+)?${label}[ \\t]*(?:\\*\\*|__)?[ \\t]*[:\\-–]?[ \\t]*(?:\\*\\*|__)?[ \\t]*(PASS|FAIL)\\b`, 'gim');
52
+ const any = new RegExp(`\\b${label}\\s*[:\\-]?\\s*\\**\\s*(PASS|FAIL)\\b`, 'gi');
53
+ let all = [...text.matchAll(line)];
54
+ if (!all.length)
55
+ all = [...text.matchAll(any)];
51
56
  const last = all[all.length - 1]?.[1];
52
- return last && last.toUpperCase() === 'PASS' ? 'PASS' : 'FAIL';
57
+ return last ? last.toUpperCase() : null;
58
+ };
59
+ /** Last `VERDICT: PASS|FAIL` line wins; no verdict at all counts as FAIL (conservative). */
60
+ export function parseVerdict(text) {
61
+ return lastVerdict(text, 'VERDICT') === 'PASS' ? 'PASS' : 'FAIL';
53
62
  }
54
63
  /** The Director's first-turn decision line (lenient: case, bullets, bold, dashes). No decision line = PROCEED. Never throws. */
55
64
  export function parseDirectorDecision(text) {
@@ -99,8 +108,7 @@ export function parseHandoff(text) {
99
108
  const AGREED_RE = /^[ \t>*_#-]*AGREED\b[^\n]*$/im;
100
109
  /** Last `REVIEW: PASS|FAIL` wins; null when no verdict line exists. */
101
110
  export function parseReview(text) {
102
- const all = [...text.matchAll(/REVIEW\s*[:\-]?\s*\**\s*(PASS|FAIL)/gi)], last = all[all.length - 1]?.[1];
103
- return last ? last.toUpperCase() : null;
111
+ return lastVerdict(text, 'REVIEW');
104
112
  }
105
113
  /** Parses a Director checkpoint reply. decision null = unreadable (callers accept). Consults: first 2 `CONSULT <agent id>: <question>` lines. */
106
114
  export function parseCheckpoint(text) {
@@ -699,46 +707,73 @@ export function startTeamRun(opts) {
699
707
  setWait(agent.id, 'waiting-first-output');
700
708
  const firstOut = () => { if (waits.get(agent.id) === 'waiting-first-output')
701
709
  setWait(agent.id, 'generating'); };
710
+ // Stall watchdog: a provider stream can go silent mid-turn (seen on a real run: the stream abandoned a tool_use block and then sent only pings,
711
+ // so the CLI hung until agentTimeoutMs). No model output for stallMs while waiting for or generating output (never while a tool runs) aborts
712
+ // this attempt; the turn is retried once on a fresh process, then fails with a clear reason instead of hanging.
713
+ const stallMs = Math.min(Math.max(1000, Number(process.env['CKIT_STALL_MS']) || 240000), Math.max(1000, config.limits.agentTimeoutMs - 1000));
714
+ // Per-turn runners do not report tool calls, so a quiet long command looks like 'generating' there: only sessions (which report executing-tool) watch 'generating'.
715
+ let lastOut = Date.now(), stalled = false, att = new AbortController(), watch = null, inSession = false;
716
+ const bump = () => { lastOut = Date.now(); };
717
+ if (!own) {
718
+ watch = setInterval(() => { const w = waits.get(agent.id); if ((w === 'waiting-first-output' || (inSession && w === 'generating')) && Date.now() - lastOut > stallMs && !att.signal.aborted) {
719
+ stalled = true;
720
+ att.abort();
721
+ } }, Math.max(200, Math.min(5000, stallMs / 4)));
722
+ watch.unref?.();
723
+ }
702
724
  try {
703
725
  const raw = rawSink(agent);
704
- const runOpts = {
705
- cwd: opts.projectRoot, timeoutMs: config.limits.agentTimeoutMs, signal: ctl.signal, ...(atts.length ? { images: images() } : {}),
726
+ const runOpts = () => ({
727
+ cwd: opts.projectRoot, timeoutMs: config.limits.agentTimeoutMs, signal: AbortSignal.any([ctl.signal, att.signal]), ...(atts.length ? { images: images() } : {}),
706
728
  onRaw: (stream, line) => raw(`[${stamp()}] ${stream}: ${line.endsWith('\n') ? line : `${line}\n`}`),
707
- onActivity: text => { firstOut(); agentLog(agent, `[${stamp()}] activity: ${oneLine(text, 400)}\n`); emit({ type: 'agent.activity', agentId: agent.id, text: oneLine(text, 160) }); const l = own ? null : stepOf(text); if (l)
729
+ onActivity: text => { bump(); firstOut(); agentLog(agent, `[${stamp()}] activity: ${oneLine(text, 400)}\n`); emit({ type: 'agent.activity', agentId: agent.id, text: oneLine(text, 160) }); const l = own ? null : stepOf(text); if (l)
708
730
  step(l); },
709
- onStep: (label, k, total) => step(oneLine(label, 80), k, total),
731
+ onStep: (label, k, total) => { bump(); step(oneLine(label, 80), k, total); },
710
732
  onSubagent: e => {
733
+ bump();
711
734
  agentLog(agent, `[${stamp()}] subagent ${e.type} ${e.childId}: ${e.type === 'started' ? e.task : e.type === 'activity' ? e.text : e.summary}\n`);
712
735
  emit(e.type === 'started' ? { type: 'subagent.started', agentId: agent.id, childId: e.childId, kind: e.kind, task: oneLine(e.task, 160) }
713
736
  : e.type === 'activity' ? { type: 'subagent.activity', agentId: agent.id, childId: e.childId, text: oneLine(e.text, 160) }
714
737
  : { type: 'subagent.finished', agentId: agent.id, childId: e.childId, ok: e.ok, summary: oneLine(e.summary, 200) });
715
738
  },
716
- };
739
+ });
740
+ const fresh = () => { stalled = false; att = new AbortController(); bump(); setWait(agent.id, 'waiting-first-output'); };
717
741
  const sess = sessionFor(agent, scheduler !== null && agent.team !== 'director' ? true : false);
718
742
  let res;
719
743
  if (!sess)
720
- res = await runner(agent, prompt, runOpts);
744
+ res = await runner(agent, prompt, runOpts());
721
745
  else {
722
746
  running.set(agent.id, sess);
723
747
  const ent = myEntries.get(sessKey(agent));
724
748
  if (ent)
725
749
  ent.busy = true;
750
+ inSession = true;
726
751
  try {
727
- res = await sess.send(prompt, { ...runOpts, onDelta: t => { firstOut(); pushDelta(agent.id, t); }, onFirstOutput: firstOut,
728
- onTool: (phase, name, text) => { firstOut(); setWait(agent.id, phase === 'call' ? 'executing-tool' : 'generating', phase === 'call' ? name : undefined); liveEmit({ type: 'agent.tool', agentId: agent.id, phase, name: oneLine(name, 80), text: oneLine(journal.redact(text), phase === 'call' ? 300 : 400) }); } }); // redact the whole text first, then shorten
752
+ res = await sess.send(prompt, { ...runOpts(), onDelta: t => { bump(); firstOut(); pushDelta(agent.id, t); }, onFirstOutput: () => { bump(); firstOut(); },
753
+ onTool: (phase, name, text) => { bump(); firstOut(); setWait(agent.id, phase === 'call' ? 'executing-tool' : 'generating', phase === 'call' ? name : undefined); liveEmit({ type: 'agent.tool', agentId: agent.id, phase, name: oneLine(name, 80), text: oneLine(journal.redact(text), phase === 'call' ? 300 : 400) }); } }); // redact the whole text first, then shorten
729
754
  }
730
755
  finally {
731
756
  flushDelta(agent.id);
732
757
  running.delete(agent.id);
733
758
  if (ent)
734
759
  ent.busy = false;
760
+ inSession = false;
735
761
  }
736
- if (!res.ok && res.transport && !abort.signal.aborted && !ctl.signal.aborted) {
762
+ if (!res.ok && (res.transport || stalled) && !abort.signal.aborted && !ctl.signal.aborted) {
737
763
  dropSession(agent);
738
- runOpts.onActivity?.(`Persistent session failed (${oneLine(res.reason, 100)}); retrying this turn with a fresh one-shot process`);
739
- res = await runner(agent, prompt, runOpts);
764
+ const why = stalled ? `no model output for ${Math.round(stallMs / 1000)} s (stalled stream)` : oneLine(res.reason, 100);
765
+ runOpts().onActivity?.(`Persistent session failed (${why}); retrying this turn with a fresh one-shot process`);
766
+ fresh(); // after the notice: the notice counts as output (firstOut) and must not mark the new attempt as already generating
767
+ res = await runner(agent, prompt, runOpts());
740
768
  }
741
769
  }
770
+ if (!res.ok && stalled && !sess && !abort.signal.aborted && !ctl.signal.aborted) {
771
+ runOpts().onActivity?.(`No model output for ${Math.round(stallMs / 1000)} s (stalled stream); retrying this turn with a fresh process`);
772
+ fresh();
773
+ res = await runner(agent, prompt, runOpts());
774
+ }
775
+ if (!res.ok && stalled && !abort.signal.aborted && !ctl.signal.aborted)
776
+ res = { ok: false, reason: `no model output for ${Math.round(stallMs / 1000)} s, twice (the provider stream stalled); check the CLI/provider connection` };
742
777
  if (res.ok && !own)
743
778
  step(last);
744
779
  return done(res.ok ? res : { ok: false, reason: withArgsNote(agent, res.reason) });
@@ -747,6 +782,8 @@ export function startTeamRun(opts) {
747
782
  return done({ ok: false, reason: withArgsNote(agent, e instanceof Error ? e.message : 'runner threw') });
748
783
  }
749
784
  finally {
785
+ if (watch)
786
+ clearInterval(watch);
750
787
  abort.signal.removeEventListener('abort', onAbort);
751
788
  signal?.removeEventListener('abort', onAbort);
752
789
  if (turnCtl.get(agent.id) === ctl)
@@ -858,7 +895,7 @@ export function startTeamRun(opts) {
858
895
  if (modelDirector()) {
859
896
  const answered = qaRounds.length ? `\nYOUR EARLIER QUESTIONS AND THE OWNER'S ANSWERS:\n${qaRounds.map((q, i) => `Round ${i + 1} questions:\n${q.questions}\nOwner's answer:\n${q.answer}`).join('\n\n')}\n` : '';
860
897
  const limitNote = forced ? '\nThe owner chose to proceed with your stated assumptions: answer "DECISION: PROCEED" now.' : needRounds >= 3 ? '\nYou already asked 3 times: you must not use NEED INFO again. Choose PROCEED with stated assumptions, or CANNOT DO.' : '';
861
- const ask = () => directorAsk('intake brief', `${role(config.director, `You are the Director. First triage the owner request, then (only on PROCEED) split it between your teams.\nYour reply must contain exactly one decision line on its own line: "DECISION: PROCEED", "DECISION: NEED INFO" or "DECISION: CANNOT DO".\n- PROCEED: write a short overall summary (scope), an "ASSUMPTIONS:" list when you assumed anything, then one section per listed team, each starting with a line exactly "### TEAM <team id>" followed by: what this team must do for this goal, the expected deliverable, and what is out of scope for it. Assign every part of the goal to exactly one listed team and assign nothing to a team that is not listed.\n- NEED INFO: no team starts. Write a numbered list of at most 5 specific questions, each with why you need it; when sensible add a line "ASSUMPTIONS IF NO ANSWER:" followed by what you would assume.\n- CANNOT DO: write "REASON:" and then "WHAT WOULD WORK:" with 1 to 3 alternatives.\nRules: prefer PROCEED with stated assumptions when the gap is small and a wrong guess is cheap. Use NEED INFO only when a wrong guess wastes work or risks damage. Use CANNOT DO only when no reasonable reading of the request can be achieved with the configured teams, their access and this workspace. Never invent requirements. Never start teams on a request you do not understand. Answer in the owner's language. You may read project files (read only) to decide. Check the work is assignable: changing files needs a team with a write agent.\nOn PROCEED also add a line "MODE: <mode>" and a line "MODE REASON: <one sentence>". Modes: DIRECT = you answer it yourself right now (a question answerable from the request, the project files or a small lookup): put the complete answer for the owner in your reply and write no team sections; DELEGATE <agent id> = one best-fit agent does it alone (single-scope investigation or small fix); PARALLEL_MERGE = several agents give independent views at the same time and their team leads merge (options, reviews, risk); PARALLEL_EXECUTE = multi-part implementation through the teams. Never activate an agent just because it is configured; choose the cheapest mode that is good enough.\nWith DELEGATE, PARALLEL_MERGE, PARALLEL_EXECUTE or TARGETED_DISCUSSION also add a line "TEAMS: <team ids, comma separated>" naming ONLY the teams that must run (the pipeline order is kept); every other team is skipped. A read-only goal (a question, analysis or review where no file may change) activates no team with a write agent and no Test or QC team: those exist to change and verify files.\nWith PARALLEL_EXECUTE also add a line "DEPENDS: <team> <- <team>, <team>; <team> <- none; ..." saying which teams need which other teams' results first; teams with no dependency between them run at the same time (a team may only depend on teams earlier in the pipeline order; writes to the workspace are still serialized by CKit).${limitNote}`, true)}\n${accessFacts()}\n${lanes.length ? `LANES (choose exactly one; you may not invent lanes or teams):\n${laneRosterText()}\n${ownerLane ? `The owner FIXED the lane: "${ownerLane.id}". Brief only its teams. You may still answer NEED INFO or CANNOT DO.` : 'On PROCEED you MUST include a line "LANE: <lane id>" and a line "LANE REASON: <one sentence>", and write sections only for the teams of that lane. If no lane fits, answer DECISION: CANNOT DO with the reason "no lane fits" and say which lane would be needed; if the request is unclear between lanes, use NEED INFO.'}` : `TEAM ROSTER (pipeline order):\n${rosterText()}`}\n${common()}${answered}`);
898
+ const ask = () => directorAsk('intake brief', `${role(config.director, `You are the Director. First triage the owner request, then (only on PROCEED) split it between your teams.\nYour reply must contain exactly one decision line on its own line: "DECISION: PROCEED", "DECISION: NEED INFO" or "DECISION: CANNOT DO".\n- PROCEED: write a short overall summary (scope), an "ASSUMPTIONS:" list when you assumed anything, then one section per listed team, each starting with a line exactly "### TEAM <team id>" followed by: what this team must do for this goal, the expected deliverable, and what is out of scope for it. Assign every part of the goal to exactly one listed team and assign nothing to a team that is not listed.\n- NEED INFO: no team starts. Write a numbered list of at most 5 specific questions, each with why you need it; when sensible add a line "ASSUMPTIONS IF NO ANSWER:" followed by what you would assume.\n- CANNOT DO: write "REASON:" and then "WHAT WOULD WORK:" with 1 to 3 alternatives.\nRules: prefer PROCEED with stated assumptions when the gap is small and a wrong guess is cheap. Use NEED INFO only when a wrong guess wastes work or risks damage. Use CANNOT DO only when no reasonable reading of the request can be achieved with the configured teams, their access and this workspace. Never invent requirements. Never start teams on a request you do not understand. Answer in the owner's language. You may read project files (read only) to decide. Check the work is assignable: changing files needs a team with a write agent.\nOn PROCEED also add a line "MODE: <mode>" and a line "MODE REASON: <one sentence>". Modes: DIRECT = you answer it yourself right now (a question answerable from the request, the project files or a small lookup): put the complete answer for the owner in your reply and write no team sections; DELEGATE <agent id> = one best-fit agent does it alone (single-scope investigation or small fix); PARALLEL_MERGE = several agents give independent views at the same time and their team leads merge (options, reviews, risk); PARALLEL_EXECUTE = multi-part implementation through the teams. Never activate an agent just because it is configured; choose the cheapest mode that is good enough.\nWith DELEGATE, PARALLEL_MERGE, PARALLEL_EXECUTE or TARGETED_DISCUSSION also add a line "TEAMS: <team ids, comma separated>" naming ONLY the teams that must run (the pipeline order is kept); every other team is skipped. A read-only goal (a question, analysis or review where no file may change) activates no team with a write agent and no Test or QC team: those exist to change and verify files.\nWith PARALLEL_EXECUTE also add a line "DEPENDS: <team> <- <team>, <team>; <team> <- none; ..." saying which teams need which other teams' results first; teams with no dependency between them run at the same time. Do not chain every team after the previous one: list only real data dependencies (example for ba, implement, test, security, qc: "DEPENDS: implement <- ba; test <- implement; security <- implement; qc <- test, security" — Test and Security both only need the implementation, so they review it at the same time) (a team may only depend on teams earlier in the pipeline order; writes to the workspace are still serialized by CKit).${limitNote}`, true)}\n${accessFacts()}\n${lanes.length ? `LANES (choose exactly one; you may not invent lanes or teams):\n${laneRosterText()}\n${ownerLane ? `The owner FIXED the lane: "${ownerLane.id}". Brief only its teams. You may still answer NEED INFO or CANNOT DO.` : 'On PROCEED you MUST include a line "LANE: <lane id>" and a line "LANE REASON: <one sentence>", and write sections only for the teams of that lane. If no lane fits, answer DECISION: CANNOT DO with the reason "no lane fits" and say which lane would be needed; if the request is unclear between lanes, use NEED INFO.'}` : `TEAM ROSTER (pipeline order):\n${rosterText()}`}\n${common()}${answered}`);
862
899
  for (let attempt = 0; attempt < 2; attempt++) {
863
900
  const t = await ask();
864
901
  if (t?.trim())
@@ -1109,11 +1146,23 @@ export function startTeamRun(opts) {
1109
1146
  const earlyPlans = new Map();
1110
1147
  /** PF-TEST: once the contract (the team right before Implement) is accepted, a later Tester team starts deriving test scenarios in parallel with Implement, read-only. It blocks nothing; only the Tester's own pass waits for it. */
1111
1148
  const startEarlyTest = (k) => {
1112
- if (earlyTest || graph || collabMode === 'DIRECT' || collabMode === 'DELEGATE' || process.env['CKIT_EARLY_TEST'] === '0')
1149
+ if (earlyTest || collabMode === 'DIRECT' || collabMode === 'DELEGATE' || process.env['CKIT_EARLY_TEST'] === '0')
1113
1150
  return;
1114
1151
  const impl = order.indexOf('implement'), tid = order.find((x, i) => i > impl && x !== 'qc' && /\btesters?\b/i.test(teamName(x))); // a team named "Tester" (the default Tester team)
1115
1152
  if (impl < 0 || k !== impl - 1 || !tid)
1116
1153
  return;
1154
+ if (graph) {
1155
+ const seen = new Set(), q = [...(graph.get(tid) ?? [])];
1156
+ while (q.length) {
1157
+ const d = q.pop();
1158
+ if (!seen.has(d)) {
1159
+ seen.add(d);
1160
+ q.push(...(graph.get(d) ?? []));
1161
+ }
1162
+ }
1163
+ if (!seen.has('implement'))
1164
+ return;
1165
+ } // the Tester does not wait for Implement: its own pass starts now, no early plan needed
1117
1166
  const agents = agentsOf(tid);
1118
1167
  if (!agents.length)
1119
1168
  return;
@@ -1619,6 +1668,13 @@ export function startTeamRun(opts) {
1619
1668
  if (ctl.signal.aborted)
1620
1669
  throw new NodeCancelled();
1621
1670
  halted();
1671
+ if (earlyTest && earlyTest.id === id && !earlyPlans.has(id)) {
1672
+ setWait(agentsOf(id)[0]?.id ?? id, 'waiting-dependency', earlyTest.taskId);
1673
+ const plan = await earlyTest.p;
1674
+ halted();
1675
+ if (plan)
1676
+ earlyPlans.set(id, plan);
1677
+ }
1622
1678
  const my = new AbortController();
1623
1679
  nctl.set(id, my);
1624
1680
  started.add(id);
@@ -1667,6 +1723,8 @@ export function startTeamRun(opts) {
1667
1723
  continue;
1668
1724
  }
1669
1725
  }
1726
+ if (cp.decision !== 'return')
1727
+ startEarlyTest(k); // PF-TEST in the task graph too: the Tester designs tests from the contract while Implement works
1670
1728
  for (const d of dependents(id)) {
1671
1729
  if (cp.dispatch)
1672
1730
  dispatches.set(d, cp.dispatch);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ngockhoale/ckit",
3
- "version": "0.4.0",
3
+ "version": "0.4.2",
4
4
  "description": "CKit — local Agent Company: a Director plus BA / Implement / QC teams running your own codex, claude and omp CLIs, with a web Mission Control (ckit gui).",
5
5
  "type": "module",
6
6
  "bin": {