@ngockhoale/ukit 3.5.19 → 3.5.20

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/CHANGELOG.md CHANGED
@@ -2,6 +2,18 @@
2
2
 
3
3
  All notable changes to UKit are documented here.
4
4
 
5
+ ## 3.5.20 - 2026-11-21
6
+
7
+ Field-telemetry fix round 6 (live session + field data since 3.5.19).
8
+
9
+ - **Stop gates honour background waits (R6-1).** When the completion gate releases a Stop because a background job or subagent is still running (WAIT), the mission gate no longer blocks that Stop. The WAIT now travels through the stop coordinator (`outcome: waiting`, `waitingOn`), and the mission gate releases it with a note that it is not completion.
10
+ - **Status questions are not requirements (R6-2).** Progress checks such as "đã xong tới đâu rồi", "vậy là xong chưa", "còn lỗi không", "…rồi sao", "sao vẫn chưa …" and "is it done yet" are classified as questions, so they no longer become mission requirements that need acceptance evidence. Work requests ("sửa lỗi login đi", "thêm nút export CSV") are unchanged, and a status check appended to a work clause ("thêm nút export, chạy test chưa", "sửa login rồi chạy test chưa") keeps the work requirement.
11
+ - **Old pauses no longer release every later stop (R6-7).** The stop coordinator used to scan past newer owner turns that were not control phrases. One "dừng đi" therefore released 83 later stops in one BAGuide session over 17 hours. Now a later owner work request (short or long) supersedes an older pause/cancel. A read-only question asked during a pause ("health check: is everything ok?") keeps the pause, and peer-envelope text is still skipped. Ref: anthropics/claude-code#101528.
12
+ - **Same-command temp cleanup is allowed (R6-4).** A recursive delete of `"$P"` is no longer blocked when `P` was assigned from `mktemp -d` in an earlier segment of the same command, quoted, and never reassigned; the exemption also requires every other segment to start with an allow-listed command that cannot assign shell variables, and no substitution, arithmetic, grouping, `eval` or `printf` anywhere in the command. Every other recursive delete of a variable stays blocked.
13
+ - **Ranked multi-section reports pass through uncompressed (R6-10).** Output compression recognises `N.` rank prefixes and sections whose numbering restarts. The field-telemetry report no longer comes back reordered.
14
+ - **Field audit tools (R6-3, R6-5).** `field-telemetry` normalises job/task/agent ids, so one class no longer splits per id. `--since` accepts `YYYY-MM-DDTHH:MM[:SS][Z]` for post-release windows; `field-replay` uses the same cutoff.
15
+ - R6-6 (batch planner per-file history) was checked against data: after 3.5.19, all 798/798 files have measured durations, so no code change was needed.
16
+
5
17
  ## 3.5.19 - 2026-11-21
6
18
 
7
19
  Field-telemetry fix round 5 and faster batched test runs.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ngockhoale/ukit",
3
- "version": "3.5.19",
3
+ "version": "3.5.20",
4
4
  "description": "Install/update an index-first AI workspace for Claude Code, OpenAI Codex and omp (Oh My Pi).",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -10,7 +10,7 @@
10
10
  * sample commands per class (redacted + truncated; values never printed).
11
11
  *
12
12
  * Usage: node scripts/audit/field-replay.mjs [--projects-dir DIR] [--match SUBSTR]...
13
- * [--since YYYY-MM-DD] [--limit N] [--sample-chars N] [--hook sensitive] [--mode inproc|cli] [--json]
13
+ * [--since YYYY-MM-DD[THH:MM]] [--limit N] [--sample-chars N] [--hook sensitive] [--mode inproc|cli] [--json]
14
14
  *
15
15
  * Hooks are registered in HOOKS below; add block-dangerous / execution-ledger
16
16
  * (PostToolUse) by adding an entry with its own payload builder + verdict parser.
@@ -22,7 +22,7 @@ import path from 'node:path';
22
22
  import readline from 'node:readline';
23
23
  import { spawn } from 'node:child_process';
24
24
  import { fileURLToPath, pathToFileURL } from 'node:url';
25
- import { parseArgs, listTranscripts, normalizeMessage, redact, truncate } from './field-telemetry.mjs';
25
+ import { parseArgs, listTranscripts, normalizeMessage, redact, truncate, beforeSince } from './field-telemetry.mjs';
26
26
 
27
27
  const REPO = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..');
28
28
  const HOOK_DIR = path.join(REPO, 'template_project', '.claude', 'hooks');
@@ -55,7 +55,7 @@ export function extractBashCommands(line, out, { since } = {}) {
55
55
  return;
56
56
  }
57
57
  if (o?.type !== 'assistant' || !Array.isArray(o.message?.content)) return;
58
- if (since && typeof o.timestamp === 'string' && o.timestamp.slice(0, 10) < since) return;
58
+ if (beforeSince(o.timestamp, since)) return;
59
59
  for (const c of o.message.content) {
60
60
  if (c && c.type === 'tool_use' && c.name === 'Bash' && typeof c.input?.command === 'string' && c.input.command.trim()) {
61
61
  out.set(c.input.command, (out.get(c.input.command) || 0) + 1);
@@ -129,7 +129,7 @@ export function classifyResults(results, hook, { samples = 40, sampleChars = 200
129
129
  export async function main(argv = process.argv.slice(2)) {
130
130
  const opts = parseArgs(argv);
131
131
  if (opts.help) {
132
- process.stdout.write('Usage: field-replay.mjs [--projects-dir DIR] [--match SUBSTR]... [--since YYYY-MM-DD] [--limit N] [--sample-chars N] [--hook sensitive] [--mode inproc|cli] [--json]\n');
132
+ process.stdout.write('Usage: field-replay.mjs [--projects-dir DIR] [--match SUBSTR]... [--since YYYY-MM-DD[THH:MM]] [--limit N] [--sample-chars N] [--hook sensitive] [--mode inproc|cli] [--json]\n');
133
133
  return 0;
134
134
  }
135
135
  const hook = HOOKS[opts.hook];
@@ -17,7 +17,7 @@
17
17
  * the assistant tool_use block with the same id.
18
18
  *
19
19
  * Usage: node scripts/audit/field-telemetry.mjs [--projects-dir DIR]
20
- * [--match SUBSTR]... [--since YYYY-MM-DD] [--json]
20
+ * [--match SUBSTR]... [--since YYYY-MM-DD[THH:MM]] [--json]
21
21
  */
22
22
  import fs from 'node:fs';
23
23
  import fsp from 'node:fs/promises';
@@ -33,11 +33,29 @@ const HEX_RE = /\b(?=[0-9a-f]*[0-9])(?=[0-9a-f]*[a-f])[0-9a-f]{7,}\b/gi;
33
33
  const PATH_RE = /(?<![\w.-])(?:~|\$[A-Z_]+|\.{1,2})?(?:\/[^\s"'`:,;()<>\]\[{}]+)+\/?|\b[\w.-]+(?:\/[\w.-]+){2,}\b|\b[\w.-]+(?:\/[\w.-]+)*\/[\w-]+\.[A-Za-z]\w{0,5}\b/g;
34
34
  // ^ relative paths need >=2 slashes or a file extension, so "dotenv/secret" stays readable.
35
35
  const NUM_RE = /\b\d+(?:\.\d+)?(?:ms|s|m|h|d|%|x|MB|KB|GB)?\b/g;
36
+ // Host background job / agent ids (`b0efx3x02`, `tasks/b9t9a0mz3.output`) after a job-ish word: one class, not one per id.
37
+ const JOB_ID_RE = /\b(job|verification|agent|task|tasks\/|task-id>?)(\s*)(?=[a-z0-9]*\d)(?=[a-z0-9]*[a-z])[a-z0-9]{6,20}\b/gi;
38
+
39
+ // `--since` accepts YYYY-MM-DD or an ISO datetime (YYYY-MM-DDTHH:MM[:SS][Z]); a zone-less value is UTC.
40
+ export const SINCE_RE = /^\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?Z?)?$/;
41
+ export function sinceToMs(since) {
42
+ if (!since) return 0;
43
+ const iso = since.length === 10 ? `${since}T00:00:00Z` : (since.endsWith('Z') ? since : `${since}Z`);
44
+ const ms = Date.parse(iso);
45
+ return Number.isFinite(ms) ? ms : 0;
46
+ }
47
+ // True when a transcript timestamp is before the window start (unknown timestamps stay in the window).
48
+ export function beforeSince(ts, since) {
49
+ if (!since || typeof ts !== 'string') return false;
50
+ const ms = Date.parse(ts);
51
+ return Number.isFinite(ms) ? ms < sinceToMs(since) : false;
52
+ }
36
53
 
37
54
  export function normalizeMessage(text, max = 140) {
38
55
  let s = String(text ?? '');
39
56
  s = s.replace(/<\/?system-reminder>/g, ' ');
40
57
  s = s.replace(UUID_RE, '#').replace(TOOLU_RE, '#');
58
+ s = s.replace(JOB_ID_RE, '$1$2#');
41
59
  s = s.replace(PATH_RE, '<p>');
42
60
  s = s.replace(HEX_RE, '#');
43
61
  s = s.replace(NUM_RE, 'N');
@@ -95,12 +113,12 @@ export function parseTranscriptLine(line, acc, { since } = {}) {
95
113
  }
96
114
  if (!o || typeof o !== 'object') return;
97
115
  const ts = o.timestamp;
98
- if (since && typeof ts === 'string' && ts.slice(0, 10) < since) {
116
+ if (beforeSince(ts, since)) {
99
117
  // still learn tool_use ids so later blocks can resolve their command
100
118
  if (o.type !== 'assistant') return;
101
119
  }
102
120
  const day = isoDay(ts);
103
- const inWindow = !since || day === 'unknown' || day >= since;
121
+ const inWindow = !since || day === 'unknown' || !beforeSince(ts, since);
104
122
 
105
123
  // assistant tool_use → remember Bash commands by id
106
124
  if (o.type === 'assistant' && Array.isArray(o.message?.content)) {
@@ -251,12 +269,12 @@ export function parseArgs(argv) {
251
269
  else if (a === '--help' || a === '-h') opts.help = true;
252
270
  }
253
271
  if (!opts.match.length) opts.match = ['KHOA-EXTENAL'];
254
- if (opts.since && !/^\d{4}-\d{2}-\d{2}$/.test(opts.since)) throw new Error(`--since must be YYYY-MM-DD, got ${opts.since}`);
272
+ if (opts.since && (!SINCE_RE.test(opts.since) || !sinceToMs(opts.since))) throw new Error(`--since must be YYYY-MM-DD or YYYY-MM-DDTHH:MM[:SS][Z], got ${opts.since}`);
255
273
  return opts;
256
274
  }
257
275
 
258
276
  export async function listTranscripts({ projectsDir, match, since }) {
259
- const sinceMs = since ? Date.parse(`${since}T00:00:00Z`) : 0;
277
+ const sinceMs = sinceToMs(since);
260
278
  const out = [];
261
279
  const walk = async (dir) => {
262
280
  let entries;
@@ -311,7 +329,7 @@ function renderText(rep, meta) {
311
329
  export async function main(argv = process.argv.slice(2)) {
312
330
  const opts = parseArgs(argv);
313
331
  if (opts.help) {
314
- process.stdout.write('Usage: field-telemetry.mjs [--projects-dir DIR] [--match SUBSTR]... [--since YYYY-MM-DD] [--json]\n');
332
+ process.stdout.write('Usage: field-telemetry.mjs [--projects-dir DIR] [--match SUBSTR]... [--since YYYY-MM-DD[THH:MM]] [--json]\n');
315
333
  return 0;
316
334
  }
317
335
  const t0 = Date.now();
@@ -245,7 +245,37 @@ async function evaluate({ command, projectRoot, env, deadlineMs, signal }) {
245
245
  let verdictGeneric = false;
246
246
  let directSeen = false;
247
247
 
248
- for (const rawSegment of scan.split(/[;&|\n]/)) {
248
+ // R6-4: a quoted `"$P"` target is a directory this same command just created with
249
+ // `P=$(mktemp -d …)` — safe to remove. Only when that assignment is the ONLY place the
250
+ // name appears unexpanded. Builtins can assign through COMPUTED names (read/getopts/
251
+ // printf -v/eval/((…))/wait -p …), so enumerating them is unsound: instead EVERY other
252
+ // segment must start with a literal allow-listed command that cannot assign shell
253
+ // variables, and the command may hold no other substitution/arithmetic/grouping syntax.
254
+ const segments = scan.split(/[;&|\n]/);
255
+ const mktempVars = new Map(); // name -> index of the segment that assigned it
256
+ const MKTEMP_ASSIGN = /^\s*([A-Za-z_]\w*)=\$\(\s*mktemp((?:\s+[-\w.\/]+)*)\s*\)\s*$/;
257
+ const SAFE_HEAD = new Set(['cd', 'echo', 'ls', 'cat', 'cp', 'mv', 'mkdir', 'touch', 'git', 'node', 'npm', 'npx', 'yarn', 'pnpm', 'tar', 'unzip', 'grep', 'find', 'true', 'pwd', 'rm', 'sed', 'head', 'tail', 'wc', 'diff', 'cmp']);
258
+ const otherSegmentsSafe = segments.every((seg) => {
259
+ if (!seg.trim() || MKTEMP_ASSIGN.test(seg)) return true;
260
+ const head = seg.trim().split(/\s+/)[0];
261
+ return SAFE_HEAD.has(head);
262
+ });
263
+ const scanWithoutAssigns = scan.split('\n').join(';').split(/(?=[;&|])/).map((s) => s.replace(/^([;&|]+\s*)?[A-Za-z_]\w*=\$\(\s*mktemp[^)]*\)/, '$1')).join('');
264
+ const plainBraces = scanWithoutAssigns.replace(/\$\{[A-Za-z_]\w*\}/g, '$V');
265
+ const exoticSyntax = /\$\(|`|\$'|\$"|\(\(|[(){}]|\beval\b|\bprintf\b/.test(plainBraces);
266
+ if (otherSegmentsSafe && !exoticSyntax) segments.forEach((seg, idx) => {
267
+ const m = MKTEMP_ASSIGN.exec(seg);
268
+ if (!m || !/(^|\s)-[a-zA-Z]*d/.test(m[2]) || /(^|\s)-[a-zA-Z]*u/.test(m[2])) return;
269
+ const bare = scan.match(new RegExp(`(^|[^$\\w{])${m[1]}(?!\\w)`, 'g')) || [];
270
+ if (bare.length === 1 && !mktempVars.has(m[1])) mktempVars.set(m[1], idx);
271
+ });
272
+ const isFreshTempTarget = (target, idx) => {
273
+ const v = /^"\$(?:\{([A-Za-z_]\w*)\}|([A-Za-z_]\w*))"$/.exec(target);
274
+ const name = v && (v[1] || v[2]);
275
+ return Boolean(name) && mktempVars.has(name) && mktempVars.get(name) < idx;
276
+ };
277
+
278
+ for (const [segIdx, rawSegment] of segments.entries()) {
249
279
  const segment = rawSegment;
250
280
  if (!segment) continue;
251
281
  const tokens = segment.trimStart().split(/\s+/).filter(Boolean);
@@ -295,7 +325,9 @@ async function evaluate({ command, projectRoot, env, deadlineMs, signal }) {
295
325
  for (let target of targets) {
296
326
  // Strip ONE trailing slash (never shrink a bare `/` or `~` to '').
297
327
  if (target.length > 1 && target.endsWith('/')) target = target.slice(0, -1);
298
- if (UNSAFE_ONE_TARGET_RE.test(target)) {
328
+ if (isFreshTempTarget(target, segIdx)) {
329
+ // created by this command's own `mktemp -d`: always inside the OS temp area
330
+ } else if (UNSAFE_ONE_TARGET_RE.test(target)) {
299
331
  anyUnsafe = true;
300
332
  allSafe = false;
301
333
  } else if (SAFE_ONE_TARGET_RE.test(target)) {
@@ -6078,6 +6078,8 @@ async function runEvaluateStop() {
6078
6078
  process.stderr.write(`[ukit-completion] ${result.reason}\n`);
6079
6079
  emit({ systemMessage: advisory ? `${message} ${advisory}` : message,
6080
6080
  ...(result.outcome === 'blocked' || result.outcome === 'handback' ? { outcome: 'blocked', complete: false } : {}),
6081
+ // R6-1: a WAIT release names the pending job/agent so later Stop lanes (mission gate) honour it.
6082
+ ...(result.wait === true && result.waitingOn ? { outcome: 'waiting', complete: false, waitingOn: result.waitingOn } : {}),
6081
6083
  });
6082
6084
  return;
6083
6085
  }
@@ -40,6 +40,10 @@ export function overlapScore(a, b) {
40
40
 
41
41
  const RE = {
42
42
  question: /^(?:what|how|why|where|when|which|who|whom|is|are|was|were|does|do|did|can|could|should|would|will|la gi|tai sao|nhu the nao|o dau|bao nhieu|co phai|lam sao)\b|\?\s*$/,
43
+ // R6-2: Vietnamese status questions rarely end with '?' — a trailing question particle marks them.
44
+ viQuestionTail: /\b(?:chua|khong|ko|nhi|chua nhi|duoc chua)\s*[?!.]*$/,
45
+ // Progress/status checks are questions even when they name a work verb ("đã fix chưa", "xong tới đâu rồi").
46
+ statusQuestion: /\b(?:da|xong|fix|sua|chay|lam|done)\b.*\bchua\s*[?!.]*$|\b(?:toi dau|den dau|the nao|ra sao|sao) roi\s*[?!.]*$|\btien do\b.*\b(?:roi|the nao|ra sao)\b|\broi sao\s*[?!.]*$|^(?:sao|tai sao) (?:van|lai|chua|khong|ko|con)\b|^(?:is it|are we|is this) (?:done|finished|ready)\b/,
43
47
  imperative: /\b(?:implement|add|fix|create|make|build|change|update|remove|delete|write|refactor|include|replace|rename|move|thay|doi|them|sua|xoa|tao|lam|cap nhat|viet)\b/,
44
48
  supersede: /\b(?:instead of|no longer|rather than|replace|replaced|switch from|change\b.+\bto|thay vi|khong con|doi\b.+\bsang|doi\b.+\bthanh|bo\b.+\bdung)\b/,
45
49
  defect: /\b(?:fix|bug|bugs|broken|crash|crashes|regress\w*|fails?|failing|loi|hong|khong chay|sua loi)\b/,
@@ -55,9 +59,24 @@ const RE = {
55
59
  const FILE_RE = /(?:[\w@.-]+\/)+[\w@.-]+|\b[\w-]+\.(?:mjs|cjs|js|jsx|ts|tsx|json|md|css|scss|html|py|sh|yml|yaml|go|rs|java|sql)\b/g;
56
60
 
57
61
  const cleanFiles = (a) => [...new Set((a || []).map((x) => x.replace(/[.,;:]+$/, '')))];
62
+ // A status check only owns the segment when no other clause carries a work request:
63
+ // "da fix chua?" is a question, "them nut export, chay test chua" is still work.
64
+ // Clauses split on punctuation and conjunctions; a clause is a work order only when it
65
+ // STARTS with an imperative verb ("sua login", "them nut export") — "da sua" (past marker)
66
+ // reports status, so "da sua va chay test chua" stays a question.
67
+ const CLAUSE_SPLIT = /\s*[,;]\s*|\s+(?:va|roi|and|then|thi|sau do)\s+/;
68
+ const IMPERATIVE_START = new RegExp(`^(?:(?:please|hay|giup|lam on|ok|oke|cu|tiep tuc)\\s+)*${RE.imperative.source}`);
69
+ function isStatusQuestion(f) {
70
+ if (!RE.statusQuestion.test(f)) return false;
71
+ const clauses = f.split(CLAUSE_SPLIT).map((c) => c.trim()).filter(Boolean);
72
+ if (clauses.length < 2) return true;
73
+ return !clauses.some((c) => !RE.statusQuestion.test(c) && IMPERATIVE_START.test(c));
74
+ }
75
+
58
76
  function kindOf(segment) {
59
77
  const f = foldText(segment);
60
- if (RE.question.test(f) && !RE.imperative.test(f)) return 'question';
78
+ if (isStatusQuestion(f)) return 'question';
79
+ if ((RE.question.test(f) || RE.viQuestionTail.test(f)) && !RE.imperative.test(f)) return 'question';
61
80
  if (RE.prohibition.test(f)) return 'prohibition';
62
81
  if (RE.defect.test(f)) return 'defect';
63
82
  if (RE.test.test(f)) return 'test';
@@ -1471,22 +1471,32 @@ export function isVerbatimOutputCommand(command) {
1471
1471
  // monotonically) up to RANKED_TABLE_MAX_TOKENS passes through raw. The configured
1472
1472
  // outputMaxTokens budget still governs every other output.
1473
1473
  const RANKED_TABLE_MAX_TOKENS = 6000;
1474
- const RANKED_LINE_RE = /^\s*(\d+(?:\.\d+)?)(?:\s|[:|,x×]|$)/;
1474
+ // R6-10: a rank prefix `N.` / `N)` counts too (" 1. 38 class…"), and a multi-section report
1475
+ // (sections split by non-numbered header lines, numbering restarting per section) is ranked when
1476
+ // every contiguous numbered run is itself monotonic.
1477
+ const RANKED_LINE_RE = /^\s*(\d+(?:\.\d+)?)(?:\s|[:|,x×.)]|$)/;
1475
1478
  export function isPassThroughOutput(text) {
1476
1479
  const lines = String(text ?? '').split('\n').filter((l) => l.trim());
1477
1480
  if (estimateTokenCount(String(text ?? '')) > RANKED_TABLE_MAX_TOKENS) return false;
1478
- const nums = [];
1481
+ const runs = [];
1482
+ let run = null;
1483
+ let numbered = 0;
1479
1484
  for (const line of lines) {
1480
1485
  const m = RANKED_LINE_RE.exec(stripAnsi(line));
1481
- if (m) nums.push(Number(m[1]));
1482
- }
1483
- if (nums.length < 8 || nums.length < lines.length * 0.6) return false;
1484
- let asc = true; let desc = true;
1485
- for (let i = 1; i < nums.length; i += 1) {
1486
- if (nums[i] < nums[i - 1]) asc = false;
1487
- if (nums[i] > nums[i - 1]) desc = false;
1488
- }
1489
- return asc || desc;
1486
+ if (!m) { run = null; continue; }
1487
+ if (!run) { run = []; runs.push(run); }
1488
+ run.push(Number(m[1]));
1489
+ numbered += 1;
1490
+ }
1491
+ if (numbered < 8 || numbered < lines.length * 0.6) return false;
1492
+ return runs.every((nums) => {
1493
+ let asc = true; let desc = true;
1494
+ for (let i = 1; i < nums.length; i += 1) {
1495
+ if (nums[i] < nums[i - 1]) asc = false;
1496
+ if (nums[i] > nums[i - 1]) desc = false;
1497
+ }
1498
+ return asc || desc;
1499
+ });
1490
1500
  }
1491
1501
 
1492
1502
  function mergeDeep(base, override) {
@@ -247,6 +247,8 @@ export function normalizeEvaluatorStdout(stdout) {
247
247
  if (parsed && typeof parsed.systemMessage === 'string' && parsed.systemMessage) {
248
248
  return { kind: 'advisory', systemMessage: parsed.systemMessage,
249
249
  ...(parsed.outcome === 'blocked' && parsed.complete === false ? { outcome: 'blocked', complete: false } : {}),
250
+ ...(parsed.outcome === 'waiting' && parsed.complete === false && typeof parsed.waitingOn === 'string' && parsed.waitingOn
251
+ ? { outcome: 'waiting', complete: false, waitingOn: parsed.waitingOn.slice(0, 80) } : {}),
250
252
  };
251
253
  }
252
254
  // A message-less non-completion release (the finite handback was already delivered) is never a pass.
@@ -374,6 +376,7 @@ export function coordinateStopDecisions({ completion = null, watchdog = null, ha
374
376
  policyOwner: 'none',
375
377
  policies,
376
378
  ...(completion?.outcome === 'blocked' && completion?.complete === false ? { blockedOutcome: true } : {}),
379
+ ...(completion?.outcome === 'waiting' && completion?.waitingOn ? { waitingOn: completion.waitingOn } : {}),
377
380
  };
378
381
  }
379
382
 
@@ -2631,7 +2634,22 @@ const RESUME_RE = new RegExp(
2631
2634
  'iu',
2632
2635
  );
2633
2636
  const SYNTHETIC_USER_PREFIX = /^(?:<system-reminder|<task-notification|<local-command|<user-prompt-submit-hook|Stop hook feedback|\[ukit|Caveat:|\[Request interrupted)/i;
2634
- const RESUME_COMMAND_TAG = /^<command-name>\/?(?:ukit:)?handoff-(?:fullstack|implement)(?![\w-])/;
2637
+ // Lazy: the mission classifier is optional for this module (partial installs / sandboxes); without it a
2638
+ // trailing '?' is the only question signal.
2639
+ let classifyPromptFn;
2640
+ async function loadClassifyPrompt() {
2641
+ if (classifyPromptFn === undefined) {
2642
+ try { classifyPromptFn = (await import('./mission/classify.mjs')).classifyPrompt || null; } catch { classifyPromptFn = null; }
2643
+ }
2644
+ return classifyPromptFn;
2645
+ }
2646
+ async function isReadOnlyOwnerQuestion(text) {
2647
+ const classify = await loadClassifyPrompt();
2648
+ if (typeof classify !== 'function') return /\?\s*$/.test(text);
2649
+ try { return classify({ text }).relation?.type === 'question'; } catch { return false; }
2650
+ }
2651
+ const PEER_ENVELOPE_START =/^(?:Another Claude session sent a message|<(?:agent|teammate)-message[\s>])/;
2652
+ const RESUME_COMMAND_TAG =/^<command-name>\/?(?:ukit:)?handoff-(?:fullstack|implement)(?![\w-])/;
2635
2653
 
2636
2654
  function genuineUserText(entry) {
2637
2655
  if (!entry || entry.type !== 'user' || entry.isSidechain === true || entry.isMeta === true) return null;
@@ -2693,10 +2711,18 @@ export async function detectUserInterruption(transcriptPath, {
2693
2711
  const text = genuineUserText(entry);
2694
2712
  if (text === null) continue;
2695
2713
  if (RESUME_COMMAND_TAG.test(text)) return { kind: null };
2696
- if (text.length > INTERRUPT_MAX_TEXT) continue;
2697
- if (CANCEL_RE.test(text)) return { kind: 'cancel' };
2698
- if (PAUSE_RE.test(text)) return { kind: 'pause' };
2699
- if (RESUME_RE.test(text)) return { kind: null };
2714
+ // Peer-envelope-shaped text (merged peer block) is not a decisive owner turn: keep scanning.
2715
+ if (PEER_ENVELOPE_START.test(text)) continue;
2716
+ if (text.length <= INTERRUPT_MAX_TEXT) {
2717
+ if (CANCEL_RE.test(text)) return { kind: 'cancel' };
2718
+ if (PAUSE_RE.test(text)) return { kind: 'pause' };
2719
+ if (RESUME_RE.test(text)) return { kind: null };
2720
+ }
2721
+ // R6-7: a read-only question during a pause ("health check: is everything ok?") keeps the pause;
2722
+ // any later owner WORK request (long or short) supersedes an older pause/cancel — one "dừng đi"
2723
+ // must not release every later stop of the session.
2724
+ if (await isReadOnlyOwnerQuestion(text)) continue;
2725
+ return { kind: null };
2700
2726
  }
2701
2727
  return { kind: null };
2702
2728
  } catch {
@@ -3178,6 +3204,11 @@ export async function evaluateMissionGate({ merged, projectRoot, payload = {}, o
3178
3204
  const g = await gm.loadGraph({ projectRoot, missionId: mid });
3179
3205
  const live = (r) => (r.status === 'active' || r.status === 'conflict') && r.kind !== 'question';
3180
3206
  if (!Object.values(g.state.reqs).some(live)) return merged;
3207
+ // R6-1: the completion gate released this Stop as a WAIT on a pending host background job/agent.
3208
+ // Blocking cannot produce that result, so the mission gate releases too (advisory, no block budget).
3209
+ if (typeof merged.waitingOn === 'string' && merged.waitingOn) {
3210
+ return { ...merged, systemMessage: [merged.systemMessage, `[ukit-mission] waiting on ${merged.waitingOn}; the mission continues when its task-notification arrives (not completion).`].filter(Boolean).join('\n') };
3211
+ }
3181
3212
 
3182
3213
  // Ledger evidence: a passing verification receipt newer than the task's done claim verifies its ACs.
3183
3214
  const receipt = await newestPassingVerification(projectRoot);