@ngockhoale/ckit 0.4.1 → 0.4.3

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';
@@ -68,7 +68,7 @@ export declare function mergeFindings(cs: readonly AgentContribution[]): MergedF
68
68
  /** Streaming redaction (review item 5): returns the redacted text that is safe to emit now and the raw tail to keep.
69
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
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): {
71
+ export declare function splitRedacted(pending: string, redact: (t: string) => string, overlap: number, final: boolean, known?: readonly string[]): {
72
72
  emit: string;
73
73
  keep: string;
74
74
  };
@@ -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) {
@@ -171,19 +179,28 @@ export function mergeFindings(cs) {
171
179
  /** Streaming redaction (review item 5): returns the redacted text that is safe to emit now and the raw tail to keep.
172
180
  * The tail (at least `overlap` chars, cut at whitespace) is held back so a secret split across chunks is redacted as a whole; the prefix is emitted
173
181
  * only when redacting the whole buffer ends exactly with the redacted tail (no match spans the cut). `final` = the turn ended: emit everything. */
174
- export function splitRedacted(pending, redact, overlap, final) {
182
+ export function splitRedacted(pending, redact, overlap, final, known = []) {
183
+ const inSecret = (cut) => known.some(k => { if (!k)
184
+ return false; for (let i = pending.indexOf(k, Math.max(0, cut - k.length + 1)); i >= 0 && i < cut; i = pending.indexOf(k, i + 1))
185
+ return true; return false; });
175
186
  if (final)
176
187
  return { emit: redact(pending), keep: '' };
177
188
  for (let lim = pending.length - overlap; lim > 0;) {
178
189
  let cut = lim;
179
190
  while (cut > 0 && !/\s/.test(pending[cut - 1]))
180
191
  cut--;
181
- if (cut <= 0)
182
- break;
183
- const all = redact(pending), tail = redact(pending.slice(cut));
184
- if (all.endsWith(tail))
185
- return { emit: all.slice(0, all.length - tail.length), keep: pending.slice(cut) };
186
- lim = cut - 1; // a match spans this cut: try an earlier whitespace
192
+ if (cut <= 0) {
193
+ if (lim < overlap)
194
+ break;
195
+ cut = lim;
196
+ const c = pending.charCodeAt(cut - 1);
197
+ if (c >= 0xd800 && c <= 0xdbff)
198
+ cut--;
199
+ } // no whitespace: hard cut (never inside a surrogate pair), kept only when no redaction spans it
200
+ const all = redact(pending), head = redact(pending.slice(0, cut));
201
+ if (!inSecret(cut) && head + redact(pending.slice(cut)) === all)
202
+ return { emit: head, keep: pending.slice(cut) };
203
+ lim = !/\s/.test(pending[cut - 1]) ? cut - overlap : cut - 1; // a match spans this cut: try earlier
187
204
  }
188
205
  return { emit: '', keep: pending };
189
206
  }
@@ -192,13 +209,19 @@ const MODE_RE = /^[ \t>*_#-]*MODE[ \t]*\**[ \t]*:\**[ \t]*\**[ \t]*(DIRECT|DELEG
192
209
  const READ_ONLY_RE = /(?<![\p{L}])read[ -]?only(?![\p{L}])|(?<![\p{L}])(?:review|analy[sz]e|analysis|explain|inspect) only(?![\p{L}])|(?<![\p{L}])(?:do not|don't|dont|never|without) (?:change|changing|modify|modifying|edit|editing|touch|touching|write|writing)(?![\p{L}])[^.\n]{0,20}(?<![\p{L}])(?:files?|code|anything|the repo|the project)(?![\p{L}])|(?<![\p{L}])no (?:code |file )?changes(?![\p{L}])|chỉ đọc|không (?:được )?(?:sửa|thay đổi|chỉnh sửa)/giu;
193
210
  /** A request to change something (EN + VI): a goal that asks for it is never read-only, whatever scope words it also contains. */
194
211
  const CHANGE_RE = /(?<![\p{L}])(?:fix|implement|add|change|modify|edit|update|create|write|refactor|rename|delete|remove|build|patch|apply|install|sửa|thêm|đổi|thay đổi|tạo|xóa|xoá|viết|cài)(?![\p{L}])/iu;
212
+ /** "how to fix", "cách sửa", "làm sao để thêm": a change that is described or explained, not requested. */
213
+ const HOW_TO_HEAD = String.raw `(?<![\p{L}])(?:how (?:to|do (?:i|we|you)|should (?:i|we)|would (?:i|we|you)|can (?:i|we))|cách(?: để)?|làm (?:sao|thế nào)(?: để)?|tại sao phải|why (?:to|should (?:i|we))) `;
214
+ const HOW_TO_RE = new RegExp(String.raw `${HOW_TO_HEAD}[^.,;!?\n]*?(?=$|[.,;!?\n]| (?:rồi|then|and|also|sau đó|và|với|plus)(?![\p{L}]))`, 'gimu'); // the clause ends at punctuation or a conjunction
215
+ const HOW_TO_FULL_RE = new RegExp(String.raw `${HOW_TO_HEAD}[^.,;!?\n]*`, 'gimu'); // with an explicit no-write directive: the clause runs to punctuation
216
+ /** The owner forbade writing in so many words (not only a "read-only" label): "do not change any files", "no code changes", "không sửa". */
217
+ const NO_WRITE_RE = /(?<![\p{L}])(?:do not|don't|dont|never|without) (?:change|changing|modify|modifying|edit|editing|touch|touching|write|writing)(?![\p{L}])[^.\n]{0,20}(?<![\p{L}])(?:files?|code|anything|the repo|the project)(?![\p{L}])|(?<![\p{L}])no (?:code |file )?changes(?![\p{L}])|không (?:được )?(?:sửa|thay đổi|chỉnh sửa)/iu;
195
218
  /** PF-MODES: the owner asked for a read-only result (question, analysis, review) - no team may change files.
196
219
  * The scope phrase must open the goal (first 25 chars) and the rest of the goal (after removing the scope phrases and [bracket tags]) must not ask for a change. */
197
220
  export const isReadOnlyGoal = (goal) => {
198
- const g = goal.replace(/\[[^\]]*\]/g, ' ').trim(), first = [...g.matchAll(READ_ONLY_RE)][0];
221
+ const g = goal.replace(/\[[^\]]*\]/g, ' ').replace(/[^\S\n]+/g, ' ').trim(), first = [...g.matchAll(READ_ONLY_RE)][0];
199
222
  if (!first || (first.index ?? 0) > 25)
200
223
  return false;
201
- return !CHANGE_RE.test(g.replace(READ_ONLY_RE, ' '));
224
+ return !CHANGE_RE.test(g.replace(READ_ONLY_RE, ' ').replace(NO_WRITE_RE.test(g) ? HOW_TO_FULL_RE : HOW_TO_RE, ' '));
202
225
  };
203
226
  /** The Director's "TEAMS: a, b" line: the configured teams it activates (lowercased ids), or null when absent. */
204
227
  export function parseTeams(text) {
@@ -227,8 +250,8 @@ export function parseDepends(text) {
227
250
  export function buildGraph(order, deps) {
228
251
  const g = new Map();
229
252
  order.forEach((id, k) => {
230
- const said = deps?.get(id);
231
- g.set(id, said ? [...new Set(said.filter(d => order.indexOf(d) >= 0 && order.indexOf(d) < k))] : k > 0 ? [order[k - 1]] : []);
253
+ const said = deps?.get(id), valid = said ? [...new Set(said.filter(d => order.indexOf(d) >= 0 && order.indexOf(d) < k))] : [];
254
+ g.set(id, said && (valid.length || !said.length) ? valid : k > 0 ? [order[k - 1]] : []); // "x <- none" = no dependency; only unknown/later ids = keep the owner order
232
255
  });
233
256
  const qk = order.indexOf('qc');
234
257
  if (qk > 0) {
@@ -493,6 +516,12 @@ export function startTeamRun(opts) {
493
516
  return { ask, ret, clean: keep.join('\n').trim() || text };
494
517
  };
495
518
  const assumptionsBlock = () => assumptions ? `\nASSUMPTIONS MADE (the owner did not confirm them; the Director decided to proceed with these):\n${assumptions}\n` : '';
519
+ /** The GOAL line is shortened to 2000 chars; the Director's intake reads the whole request so no requirement is lost before the split. */
520
+ const fullGoalBlock = () => goal.length <= 2000 ? '' : goal.length <= 30000 ? `\nFULL OWNER REQUEST (the GOAL line above is shortened; read all of it):\n${goal}\n` : `\nFULL OWNER REQUEST: it is ${goal.length} chars, too long for this prompt. The first part is below; the WHOLE request is saved at ${goalFile()} - read that file completely before you decide.\n${clip(goal, 30000)}\n`;
521
+ let goalPath = '';
522
+ const goalFile = () => { if (!goalPath) {
523
+ goalPath = join(journal.runDir, journal.writeArtifact('owner-request.md', goal));
524
+ } return goalPath; };
496
525
  const common = () => `GOAL: ${oneLine(goal, 2000)}\n${assumptionsBlock()}${notes.length ? `\nOWNER NOTES (follow them):\n${notes.map(n => `- ${n}`).join('\n')}\n` : ''}${intakeIntro ? `\nDIRECTOR BRIEF:\n${intakeIntro}\n` : ''}${attachmentPromptBlock(atts, excerpts)}`;
497
526
  // ---- one agent turn ----
498
527
  /** Heuristic step label for real runners' activity lines (null = not a step boundary). */
@@ -572,7 +601,7 @@ export function startTeamRun(opts) {
572
601
  deltaBuf.delete(agentId);
573
602
  return;
574
603
  }
575
- const { emit: text, keep } = splitRedacted(b.text, t => journal.redact(t), OVERLAP, final);
604
+ const { emit: text, keep } = splitRedacted(b.text, t => journal.redact(t), OVERLAP, final, known);
576
605
  b.text = keep;
577
606
  if (!keep)
578
607
  deltaBuf.delete(agentId);
@@ -887,7 +916,7 @@ export function startTeamRun(opts) {
887
916
  if (modelDirector()) {
888
917
  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` : '';
889
918
  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.' : '';
890
- const ask = () => directorAsk('intake brief', `${role(config.director, `You are the Director. First triage the owner request, then (only on PROCEED) split it between your teams.\nYour reply must contain exactly one decision line on its own line: "DECISION: PROCEED", "DECISION: NEED INFO" or "DECISION: CANNOT DO".\n- PROCEED: write a short overall summary (scope), an "ASSUMPTIONS:" list when you assumed anything, then one section per listed team, each starting with a line exactly "### TEAM <team id>" followed by: what this team must do for this goal, the expected deliverable, and what is out of scope for it. Assign every part of the goal to exactly one listed team and assign nothing to a team that is not listed.\n- NEED INFO: no team starts. Write a numbered list of at most 5 specific questions, each with why you need it; when sensible add a line "ASSUMPTIONS IF NO ANSWER:" followed by what you would assume.\n- CANNOT DO: write "REASON:" and then "WHAT WOULD WORK:" with 1 to 3 alternatives.\nRules: prefer PROCEED with stated assumptions when the gap is small and a wrong guess is cheap. Use NEED INFO only when a wrong guess wastes work or risks damage. Use CANNOT DO only when no reasonable reading of the request can be achieved with the configured teams, their access and this workspace. Never invent requirements. Never start teams on a request you do not understand. Answer in the owner's language. You may read project files (read only) to decide. Check the work is assignable: changing files needs a team with a write agent.\nOn PROCEED also add a line "MODE: <mode>" and a line "MODE REASON: <one sentence>". Modes: DIRECT = you answer it yourself right now (a question answerable from the request, the project files or a small lookup): put the complete answer for the owner in your reply and write no team sections; DELEGATE <agent id> = one best-fit agent does it alone (single-scope investigation or small fix); PARALLEL_MERGE = several agents give independent views at the same time and their team leads merge (options, reviews, risk); PARALLEL_EXECUTE = multi-part implementation through the teams. Never activate an agent just because it is configured; choose the cheapest mode that is good enough.\nWith DELEGATE, PARALLEL_MERGE, PARALLEL_EXECUTE or TARGETED_DISCUSSION also add a line "TEAMS: <team ids, comma separated>" naming ONLY the teams that must run (the pipeline order is kept); every other team is skipped. A read-only goal (a question, analysis or review where no file may change) activates no team with a write agent and no Test or QC team: those exist to change and verify files.\nWith PARALLEL_EXECUTE also add a line "DEPENDS: <team> <- <team>, <team>; <team> <- none; ..." saying which teams need which other teams' results first; teams with no dependency between them run at the same time. Do not chain every team after the previous one: list only real data dependencies (example for ba, implement, test, security, qc: "DEPENDS: implement <- ba; test <- implement; security <- implement; qc <- test, security" — Test and Security both only need the implementation, so they review it at the same time) (a team may only depend on teams earlier in the pipeline order; writes to the workspace are still serialized by CKit).${limitNote}`, true)}\n${accessFacts()}\n${lanes.length ? `LANES (choose exactly one; you may not invent lanes or teams):\n${laneRosterText()}\n${ownerLane ? `The owner FIXED the lane: "${ownerLane.id}". Brief only its teams. You may still answer NEED INFO or CANNOT DO.` : 'On PROCEED you MUST include a line "LANE: <lane id>" and a line "LANE REASON: <one sentence>", and write sections only for the teams of that lane. If no lane fits, answer DECISION: CANNOT DO with the reason "no lane fits" and say which lane would be needed; if the request is unclear between lanes, use NEED INFO.'}` : `TEAM ROSTER (pipeline order):\n${rosterText()}`}\n${common()}${answered}`);
919
+ 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()}${fullGoalBlock()}${answered}`);
891
920
  for (let attempt = 0; attempt < 2; attempt++) {
892
921
  const t = await ask();
893
922
  if (t?.trim())
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ngockhoale/ckit",
3
- "version": "0.4.1",
3
+ "version": "0.4.3",
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": {