@ngockhoale/ukit 3.5.11 → 3.5.14

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 (35) hide show
  1. package/CHANGELOG.md +62 -0
  2. package/manifests/documentation.yaml +11 -0
  3. package/manifests/platform.full.yaml +39 -2
  4. package/package.json +1 -1
  5. package/scripts/audit/field-replay.mjs +194 -0
  6. package/scripts/audit/field-telemetry.mjs +341 -0
  7. package/scripts/release/candidate-state.mjs +4 -1
  8. package/template_project/.claude/agents/code-reviewer.md +1 -0
  9. package/template_project/.claude/agents/feature-implementer.md +1 -0
  10. package/template_project/.claude/hooks/completion-gate.sh +3 -3
  11. package/template_project/.claude/hooks/context-hardcap-gate.sh +40 -230
  12. package/template_project/.claude/hooks/context-window-guard.sh +1 -1
  13. package/template_project/.claude/hooks/sensitive-data-guard.mjs +297 -13
  14. package/template_project/.claude/settings.json +2 -2
  15. package/template_project/.claude/skills/code-review/SKILL.md +14 -0
  16. package/template_project/.claude/skills/testing-quality/SKILL.md +31 -1
  17. package/template_project/.claude/skills/testing-quality/memory-safe-tests.md +133 -0
  18. package/template_project/.claude/ukit/index/post-edit-verify.mjs +3 -7
  19. package/template_project/.claude/ukit/index/pre-edit-backup.mjs +1 -0
  20. package/template_project/.claude/ukit/index/test-batches-adapters.mjs +261 -0
  21. package/template_project/.claude/ukit/index/test-batches.mjs +829 -0
  22. package/template_project/.claude/ukit/runtime/compact-threshold.mjs +3 -3
  23. package/template_project/.claude/ukit/runtime/execution-ledger.mjs +92 -3
  24. package/template_project/.claude/ukit/runtime/output-compression.mjs +28 -1
  25. package/template_project/.claude/ukit/runtime/safe-patch-core.mjs +22 -0
  26. package/template_project/.claude/ukit/runtime/stop-coordinator.mjs +40 -4
  27. package/template_project/.omp/agents/code-reviewer.md +1 -0
  28. package/template_project/.omp/agents/feature-implementer.md +1 -0
  29. package/template_project/.omp/config.yml +1 -1
  30. package/template_project/AGENTS.md +1 -1
  31. package/template_project/CLAUDE.md +1 -1
  32. package/template_project/docs/AI_HANDOFF/RULES.md +1 -1
  33. package/template_project/docs/memory/testing.md +10 -0
  34. package/template_project/instructions/core.md +1 -1
  35. package/template_project/ukit/storage/config.json +3 -3
@@ -1551,13 +1551,13 @@ async function runCli() {
1551
1551
  if (nextState?.phase === 'hard') {
1552
1552
  process.stdout.write(
1553
1553
  `[ukit-skill-router] Context pressure: hard (est ${nextState.estimatedTotalTokens} / soft ${nextState.softThreshold} / hard ${nextState.hardThreshold}). `
1554
- + 'FIRST THING IN YOUR REPLY, tell the user plainly — do not stay silent: "Context sắp đầy — hãy gõ /compact ngay bây giờ (run /compact now)". '
1555
- + 'Then hold heavy work: no new investigations, subagents, or large edits until the user has compacted.\n',
1554
+ + 'Do NOT end the turn to ask the user for /compact — keep working: land the step in flight, persist remaining steps to docs/STATUS.md, '
1555
+ + 'delegate broad reads/searches to subagents, and continue the task. The host auto-compacts and UKit resumes from disk.\n',
1556
1556
  );
1557
1557
  } else if (nextState?.phase === 'soft') {
1558
1558
  process.stdout.write(
1559
1559
  `[ukit-skill-router] Context pressure: soft (est ${nextState.estimatedTotalTokens} / soft ${nextState.softThreshold} / hard ${nextState.hardThreshold}). `
1560
- + 'Finish the current step, then tell the user to run /compact at the next natural pause instead of continuing indefinitely.\n',
1560
+ + 'Keep working; keep replies and reads lean and persist progress to docs/STATUS.md so a host auto-compact resumes cleanly.\n',
1561
1561
  );
1562
1562
  }
1563
1563
  }
@@ -1042,6 +1042,56 @@ function maskedVerificationStage(command, depth = 0, options = {}) {
1042
1042
  return sawRunner ? null : text;
1043
1043
  }
1044
1044
 
1045
+ // Field telemetry #3 (2026-11-20): `runner > log 2>&1; echo "exit=$?"` and zsh
1046
+ // `runner | tail; echo "exit=${pipestatus[1]}"` were the top "unproven" storms. A status echoed
1047
+ // IMMEDIATELY after the runner IS the runner's status — the same proof OpenHands (PS1 `"exit_code": "$?"`)
1048
+ // and SWE-ReX (`echo $?` after each command) rely on. Accepted only when: the echo is the LAST unit, holds
1049
+ // exactly one status reference and no other expansion, the reference points at the single runner (bash
1050
+ // PIPESTATUS is 0-based, zsh pipestatus 1-based; `$?` only after a non-pipeline runner), the command before
1051
+ // the echo is itself unmasked, and the LAST stdout line is exactly the echo literal with a number. Anything
1052
+ // else returns null and the caller keeps the fail-closed "unproven" verdict.
1053
+ const STATUS_ECHO_RE = /^echo\s+(?:"([^"$`\\]*)(\$\?|\$\{\?\}|\$\{PIPESTATUS\[(\d)\]\}|\$\{pipestatus\[(\d)\]\})([^"$`\\]*)"|([^\s"'$`\\;|&<>()]*)(\$\?|\$\{\?\}|\$\{PIPESTATUS\[(\d)\]\}|\$\{pipestatus\[(\d)\]\})([^\s"'$`\\;|&<>()]*))$/;
1054
+ function bashStdoutText(response) {
1055
+ if (typeof response === 'string') return response;
1056
+ if (!response || typeof response !== 'object' || Array.isArray(response)) return '';
1057
+ for (const key of ['stdout', 'output', 'content']) if (typeof response[key] === 'string') return response[key];
1058
+ return '';
1059
+ }
1060
+ function printedRunnerStatus(command, toolResponse) {
1061
+ const text = String(command || '').trim();
1062
+ if (!text || /\n/.test(text) || executableSubstitutions(text).length) return null;
1063
+ const units = verificationShellUnits(text);
1064
+ if (!units || units.length < 2) return null;
1065
+ const echo = units[units.length - 1];
1066
+ const m = STATUS_ECHO_RE.exec(echo.text);
1067
+ if (!m || echo.separator) return null;
1068
+ const before = m[1] ?? m[6] ?? '';
1069
+ const ref = m[2] ?? m[7];
1070
+ const after = m[5] ?? m[10] ?? '';
1071
+ const bashIdx = m[3] ?? m[8];
1072
+ const zshIdx = m[4] ?? m[9];
1073
+ const end = units.length - 2;
1074
+ if (units[end].separator !== ';') return null;
1075
+ let start = end;
1076
+ while (start > 0 && (units[start - 1].separator === '|' || units[start - 1].separator === '|&')) start -= 1;
1077
+ let stage;
1078
+ if (bashIdx !== undefined) stage = Number(bashIdx);
1079
+ else if (zshIdx !== undefined) stage = Number(zshIdx) - 1;
1080
+ else if (ref === '$?' || ref === '${?}') stage = start === end ? 0 : -1;
1081
+ if (!(stage >= 0) || start + stage > end) return null;
1082
+ const runner = units[start + stage];
1083
+ if (!isVerificationCommand(runner.text)) return null;
1084
+ for (let i = start; i <= end; i += 1) if (i !== start + stage && isVerificationCommand(units[i].text)) return null;
1085
+ // The prefix plus the runner alone must already be an unmasked verification command.
1086
+ const head = [...units.slice(0, start).map((u) => `${u.text} ${u.separator}`), runner.text].join(' ');
1087
+ if (maskedVerificationStage(head) !== null) return null;
1088
+ const lines = bashStdoutText(toolResponse).replace(/\s+$/, '').split(/\r?\n/);
1089
+ const last = lines[lines.length - 1] ?? '';
1090
+ if (!last.startsWith(before) || !last.endsWith(after)) return null;
1091
+ const digits = last.slice(before.length, last.length - after.length);
1092
+ return /^\d{1,3}$/.test(digits) ? Number(digits) : null;
1093
+ }
1094
+
1045
1095
  // Announce through the in-proc hook emitter only (never fd 1 from library callers).
1046
1096
  // Host launch acknowledgement of a backgrounded Bash call (Claude Code: structured
1047
1097
  // `backgroundTaskId`, or the fixed "running in background" text). Structured field first.
@@ -1134,7 +1184,7 @@ function hostCompletionExit(transcriptPath, id) {
1134
1184
  // ANY notification, with or without an exit code, ends the pending state), memoized per (path, mtimeMs, size) so repeated Stop checks do not re-read the file.
1135
1185
  const HOST_SCAN_CACHE = [];
1136
1186
  function scanHostNotifications(transcriptPath) {
1137
- const empty = { notified: new Set(), exits: new Map() };
1187
+ const empty = { notified: new Set(), exits: new Map(), asyncAgents: new Map() };
1138
1188
  if (!transcriptPath) return empty;
1139
1189
  let st;
1140
1190
  try { st = fsSync.statSync(transcriptPath); } catch { return empty; }
@@ -1142,11 +1192,22 @@ function scanHostNotifications(transcriptPath) {
1142
1192
  if (hit) return hit.scan;
1143
1193
  let raw;
1144
1194
  try { raw = fsSync.readFileSync(transcriptPath, 'utf8'); } catch { return empty; }
1145
- const scan = { notified: new Set(), exits: new Map() };
1195
+ const scan = { notified: new Set(), exits: new Map(), asyncAgents: new Map() };
1146
1196
  for (const line of raw.split('\n')) {
1147
- if (!line.includes('<task-id>')) continue;
1197
+ const asyncLaunch = line.includes('"async_launched"');
1198
+ if (!asyncLaunch && !line.includes('<task-id>')) continue;
1148
1199
  let o;
1149
1200
  try { o = JSON.parse(line); } catch { continue; }
1201
+ // Field telemetry #1 (2026-11-20): Claude Code background subagents (`Agent` with run_in_background) are
1202
+ // host-written `toolUseResult: { isAsync, status: 'async_launched', agentId }` tool results, finished by the
1203
+ // same <task-notification> as a background shell. 149 of 487 Stop blocks fired while such an agent was still
1204
+ // running — blocking cannot produce its result, so it gets the same bounded WAIT as a background shell.
1205
+ const tur = o?.type === 'user' ? o.toolUseResult : null;
1206
+ if (asyncLaunch && tur && tur.isAsync === true && tur.status === 'async_launched'
1207
+ && typeof tur.agentId === 'string' && /^[A-Za-z0-9_-]{1,64}$/.test(tur.agentId)) {
1208
+ scan.asyncAgents.set(tur.agentId, Date.parse(o.timestamp) || 0);
1209
+ continue;
1210
+ }
1150
1211
  let text = null;
1151
1212
  if (o?.type === 'queue-operation' && o.operation === 'enqueue' && typeof o.content === 'string') text = o.content;
1152
1213
  else if (o?.type === 'user' && typeof o.message?.content === 'string') text = o.message.content;
@@ -3357,6 +3418,21 @@ function pendingBackgroundJob(ledger, { unreleasedOnly = false } = {}) {
3357
3418
  return null;
3358
3419
  }
3359
3420
 
3421
+ // A host background subagent launched during this task ledger and not yet finished (no task-notification).
3422
+ // Claude Code only (host-written transcript); other hosts return null and keep their existing behaviour.
3423
+ function pendingAsyncAgent(ledger, { unreleasedOnly = false } = {}) {
3424
+ if (!ledger?.transcriptPath) return null;
3425
+ const scan = scanHostNotifications(ledger.transcriptPath);
3426
+ const since = Number(ledger.startedAt) || 0;
3427
+ let latest = null;
3428
+ for (const [id, ts] of scan.asyncAgents) {
3429
+ if (scan.notified.has(id) || (since && ts && ts + 2000 < since)) continue;
3430
+ if (unreleasedOnly && (ledger.waitReleasedFor || []).includes(id)) continue;
3431
+ latest = id;
3432
+ }
3433
+ return latest;
3434
+ }
3435
+
3360
3436
  function liveBaseLedger(event, current, payload, routeState, harness, fallbackLedger, projectRoot = null) {
3361
3437
  if (current && routeState?.taskInstanceId && current.taskInstanceId !== routeState.taskInstanceId
3362
3438
  && routeState.predecessor && current.taskInstanceId === routeState.predecessor.predecessorTaskInstanceId) {
@@ -3851,6 +3927,14 @@ export async function recordExecutionReceipt({
3851
3927
  if (ledgerMessageEmitter) {
3852
3928
  try { ledgerMessageEmitter(`${JSON.stringify({ systemMessage: isOmpBackgroundId(receipt.backgroundTaskId) ? `UKit execution-ledger: UNSUPPORTED_EVIDENCE — omp job ${receipt.backgroundTaskId} has no exit status and cannot count as a pass; run the verification once in the foreground (async:false) for a native exit.` : `UKit execution-ledger: background verification ${receipt.backgroundTaskId || '(unknown id)'} is pending. Wait for the same job; do not launch a duplicate. After the host task-notification, Read its tasks/<id>.output through the final exit footer to ingest completion; Bash/grep does not ingest it.` })}\n`); } catch { /* advisory */ }
3853
3929
  }
3930
+ } else if (maskedStage && receipt.success && recognizedRunner
3931
+ && (exitCode === 0 || (exitCode === null && hostProvesCleanBashExit(harness, payload, toolResponse)))
3932
+ && printedRunnerStatus(toolInput.command, toolResponse) !== null) {
3933
+ // The wrapper exited cleanly AND printed the runner's own status as its last line.
3934
+ const printed = printedRunnerStatus(toolInput.command, toolResponse);
3935
+ receipt.exitCode = printed;
3936
+ receipt.exitProof = 'printed-status';
3937
+ receipt.success = printed === 0;
3854
3938
  } else if (maskedStage && receipt.success) {
3855
3939
  receipt.success = false;
3856
3940
  receipt.exitStatusUnproven = true;
@@ -5140,6 +5224,11 @@ function evaluateCompletionContract({ state = {}, ledger = {}, cwd, phase = null
5140
5224
  // At most ONE WAIT release per (task, job id): the CLI records it (`wait-released`), after which a job that
5141
5225
  // is still pending falls back to the normal gate (finite cap, pending-job wording, never an edit demand).
5142
5226
  const waitingOn = pendingBackgroundJob(effectiveLedger, { unreleasedOnly: true });
5227
+ const waitingAgent = waitingOn ? null : pendingAsyncAgent(effectiveLedger, { unreleasedOnly: true });
5228
+ if (waitingAgent) {
5229
+ return { continue: false, notify: true, complete: false, wait: true, outcome: 'waiting', waitingOn: waitingAgent, missingEvidence,
5230
+ reason: `UKit WAIT: a background subagent this task launched is still running. Blocking this Stop cannot produce its result, so it is released without spending continuation budget. Missing ${missingEvidence.join(', ')} until the subagent reports back; when its task-notification arrives, review its result, then run the verification yourself and continue. Do not launch a duplicate agent.` };
5231
+ }
5143
5232
  if (waitingOn) {
5144
5233
  return { continue: false, notify: true, complete: false, wait: true, outcome: 'waiting', waitingOn, missingEvidence,
5145
5234
  reason: `UKit WAIT: background job ${waitingOn} is pending. Wait for the same job; do not launch a duplicate. This Stop is released without spending continuation budget and without demanding an edit. Missing ${missingEvidence.join(', ')} until the host task-notification arrives; then Read tasks/${waitingOn}.output through the exit footer and continue with the next milestone (artifact verification, authorized deploy, live verification). Do not relaunch the job.` };
@@ -1463,6 +1463,32 @@ export function isVerbatimOutputCommand(command) {
1463
1463
  return false;
1464
1464
  }
1465
1465
 
1466
+ // Field telemetry #11 (2026-11-20): a numerically ranked cluster list (~50 lines) came back
1467
+ // reordered with its middle dropped — the line picker lifts "important" lines ahead of the
1468
+ // rest, which destroys the order a ranked/sorted table IS. rtk-ai/rtk (#582) reports the
1469
+ // same lesson: summarising content whose structure is the information costs more turns than
1470
+ // it saves. A count-ranked table (≥ 8 lines led by a number, ≥ 60% of lines, sorted
1471
+ // monotonically) up to RANKED_TABLE_MAX_TOKENS passes through raw. The configured
1472
+ // outputMaxTokens budget still governs every other output.
1473
+ const RANKED_TABLE_MAX_TOKENS = 6000;
1474
+ const RANKED_LINE_RE = /^\s*(\d+(?:\.\d+)?)(?:\s|[:|,x×]|$)/;
1475
+ export function isPassThroughOutput(text) {
1476
+ const lines = String(text ?? '').split('\n').filter((l) => l.trim());
1477
+ if (estimateTokenCount(String(text ?? '')) > RANKED_TABLE_MAX_TOKENS) return false;
1478
+ const nums = [];
1479
+ for (const line of lines) {
1480
+ 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;
1490
+ }
1491
+
1466
1492
  function mergeDeep(base, override) {
1467
1493
  if (!override || typeof override !== 'object' || Array.isArray(override)) {
1468
1494
  return override === undefined ? base : override;
@@ -1558,7 +1584,8 @@ async function main() {
1558
1584
  }
1559
1585
 
1560
1586
  // 3.5.11: content reads, bounded pipelines and chained commands pass through raw.
1561
- if (isVerbatimOutputCommand(command)) {
1587
+ // 3.5.14 (#11): count-ranked tables pass through raw (their order is the content).
1588
+ if (isVerbatimOutputCommand(command) || isPassThroughOutput(stdout)) {
1562
1589
  process.exit(0);
1563
1590
  return;
1564
1591
  }
@@ -1,6 +1,7 @@
1
1
  import fs from 'node:fs/promises';
2
2
  import fsSync from 'node:fs';
3
3
  import path from 'node:path';
4
+ import os from 'node:os';
4
5
  import { spawnSync } from 'node:child_process';
5
6
 
6
7
  export const DEFAULT_SAFE_PATCH_CONFIG = {
@@ -80,6 +81,26 @@ export function resolveProjectFile(projectRoot, filePath) {
80
81
  };
81
82
  }
82
83
 
84
+ function osTempRoots() {
85
+ const roots = ['/tmp', '/private/tmp', os.tmpdir(), process.env.TMPDIR].filter(Boolean);
86
+ for (const r of [...roots]) { try { roots.push(fsSync.realpathSync(r)); } catch { /* absent root */ } }
87
+ return [...new Set(roots.map((r) => path.resolve(r)))].filter((r) => r !== path.parse(r).root);
88
+ }
89
+
90
+ /** True when an absolute target lies strictly inside an OS temp dir (scratch files; never project scope). */
91
+ export function isOsTempPath(filePath, projectRoot) {
92
+ const raw = String(filePath || '').trim();
93
+ if (!raw || !path.isAbsolute(raw)) return false;
94
+ const candidates = [path.resolve(raw), realpathNearest(path.resolve(raw))].filter(Boolean);
95
+ // A project that itself lives inside a temp root (sandboxes) gets no exemption for that root.
96
+ const home = projectRoot ? [path.resolve(projectRoot), realpathNearest(path.resolve(projectRoot))].filter(Boolean) : [];
97
+ const insideRoot = (c, root) => { const rel = path.relative(root, c); return rel && !rel.startsWith('..') && !path.isAbsolute(rel); };
98
+ return candidates.some((c) => osTempRoots().filter((root) => !home.some((h) => insideRoot(h, root) || h === root)).some((root) => {
99
+ const rel = path.relative(root, c);
100
+ return rel && !rel.startsWith('..') && !path.isAbsolute(rel);
101
+ }));
102
+ }
103
+
83
104
  function realpathNearest(absolute) {
84
105
  // Real path of the deepest existing ancestor + the not-yet-existing tail, so a Write
85
106
  // that creates a new file is judged by where it would actually land (symlinks resolved).
@@ -145,6 +166,7 @@ export function resolveEditTarget(projectRoot, filePath) {
145
166
  };
146
167
  }
147
168
  }
169
+ if (isOsTempPath(filePath, root)) error.osTemp = true;
148
170
  throw error;
149
171
  }
150
172
  }
@@ -9,7 +9,7 @@
9
9
  * Stalled-cursor releases are advisory, never completion evidence.
10
10
  * Completion infrastructure failures block with redacted reasons (details only
11
11
  * on stderr); watchdog failures are advisory and reported verbatim.
12
- * UKIT_HOOK_DEADLINE_MS bounds execution (wrapper default 5000ms), including the ledger
12
+ * UKIT_HOOK_DEADLINE_MS bounds execution (wrapper default 10000ms), including the ledger
13
13
  * child. Deadline expiry synchronously emits a fail-closed block and reaps the
14
14
  * child before exit0: empty stdout would incorrectly release the wrapper.
15
15
  * Exported evaluators, merge, normalization and redaction seams are tested directly.
@@ -112,7 +112,22 @@ function writeDecisionLine(payload) {
112
112
  * Emit the fixed fail-closed block for the deadline path, exactly once, synchronously.
113
113
  * Exported so the deadline behaviour is directly testable.
114
114
  */
115
+ // Field telemetry #2 (2026-11-20): a reentrant Stop (`stop_hook_active: true` — the host already continued
116
+ // the turn once for a Stop block) whose fail-closed evaluator fails or overruns AGAIN cannot be helped by a
117
+ // second block: the infrastructure, not the task, is failing. Claude Code's own default for a failed or
118
+ // timed-out hook is non-blocking. The FIRST failure still blocks fail-closed; the repeat releases with a
119
+ // visible "not verified" advisory (outcome blocked, never complete). Set from main() before evaluation.
120
+ let reentrantStop = false;
121
+ export function setReentrantStop(value) { reentrantStop = value === true; }
122
+ export function infrastructureReleaseReason() {
123
+ return 'UKit stop coordinator: the completion evaluator failed or ran out of time again on a re-entered stop, so this stop is released WITHOUT verification (not complete — completion is unproven). This is usually a busy machine or slow disk; tell the user the task state is unverified. Only if this repeats across turns, run: ukit install.';
124
+ }
125
+ function emitReentrantInfrastructureRelease() {
126
+ return writeDecisionLine({ systemMessage: infrastructureReleaseReason(), policyOwner: 'fail-closed', outcome: 'blocked', complete: false });
127
+ }
128
+
115
129
  export function emitDeadlineBlock() {
130
+ if (reentrantStop) return emitReentrantInfrastructureRelease();
116
131
  return writeDecisionLine({
117
132
  decision: 'block',
118
133
  reason: redactDeadlineReason(),
@@ -143,14 +158,14 @@ export const DEDUPE_WINDOW_MS = 2000;
143
158
 
144
159
  // Budget slices inside the hook deadline: the ledger child gets the larger slice, each
145
160
  // watchdog lock acquisition gets a short one. The ledger slice is 1500ms under a short
146
- // deadline and grows with a longer one (the shipped wrapper arms 5000ms) up to 3000ms,
147
- // always leaving 1500ms for the advisory lanes and the decision write. Field telemetry:
161
+ // deadline and grows with a longer one (the shipped wrapper arms 10000ms → 7000ms) capped at 8000ms:
162
+ // min(8000, max(min(3000, d-1500), d-3000)), leaving 1500-3000ms for the advisory lanes and the decision write. Field telemetry:
148
163
  // on a loaded machine / external volume a healthy evaluation overran 1500ms and the
149
164
  // stop was blocked as an "infrastructure failure".
150
165
  export function resolveLedgerBudgetMs(deadlineMs) {
151
166
  const deadline = Number(deadlineMs);
152
167
  if (!Number.isFinite(deadline) || deadline <= 3000) return 1500;
153
- return Math.min(3000, deadline - 1500);
168
+ return Math.min(8000, Math.max(Math.min(3000, deadline - 1500), deadline - 3000));
154
169
  }
155
170
  const LEDGER_BUDGET_MS = resolveLedgerBudgetMs(HOOK_DEADLINE_MS);
156
171
  export const LOCK_BUDGET_MS = 600;
@@ -3254,6 +3269,21 @@ export async function runStopCoordinator({
3254
3269
  } catch {
3255
3270
  ownership = { status: 'UNKNOWN', reason: 'handoff provenance runtime unavailable' };
3256
3271
  }
3272
+ // Field-telemetry #5 (2026-11-20): an UNKNOWN ownership beside a terminal
3273
+ // cursor (`Phase: done`, not paused) has no run to protect. Emitting "report
3274
+ // BLOCKED and reconcile provenance" on every stop there produced ~2,500
3275
+ // advisories (BAGuide 1,680, CKit 283) and marked healthy stops BLOCKED.
3276
+ // OWNED cursors still go through evaluateHandoffCursor (ExitPredicate); only
3277
+ // the UNKNOWN advisory/blockedOutcome lane is quieted.
3278
+ if (ownership.status === 'UNKNOWN' && ownership.reason !== 'run cursor absent') {
3279
+ try {
3280
+ const cursorText = await fs.readFile(path.join(runRoot, 'docs/AI_HANDOFF/RUN.md'), 'utf8');
3281
+ const phase = /^Phase:\s*(\S+)/im.exec(cursorText)?.[1]?.toLowerCase();
3282
+ if (phase === 'done' && !/^Paused:\s*yes\b/im.test(cursorText)) {
3283
+ ownership = { status: 'NOT_OWNED', reason: 'terminal run cursor (Phase: done)' };
3284
+ }
3285
+ } catch { /* unreadable cursor keeps the strict UNKNOWN lane */ }
3286
+ }
3257
3287
  if (ownership.reason === 'run cursor absent') {
3258
3288
  try {
3259
3289
  const watchdogRuntime = await import('./task-watchdog.mjs');
@@ -3453,9 +3483,14 @@ async function main() {
3453
3483
  } catch {
3454
3484
  payload = {}; // malformed payload: forward the raw text to the ledger, which owns crash counting
3455
3485
  }
3486
+ setReentrantStop(payload?.stop_hook_active === true);
3456
3487
  const projectRoot = process.env.CLAUDE_PROJECT_DIR || payload?.cwd || process.cwd();
3457
3488
  const { skip, merged } = await runStopCoordinator({ projectRoot, payload, rawInput, now: Date.now() });
3458
3489
  if (skip || !merged) return;
3490
+ if (merged.decision === 'block' && merged.policyOwner === 'fail-closed' && reentrantStop) {
3491
+ emitReentrantInfrastructureRelease();
3492
+ return;
3493
+ }
3459
3494
 
3460
3495
  // Synchronous writes through the shared emission gate: the deadline timer can fire
3461
3496
  // between any two turns of the event loop, and an already-written decision must never
@@ -3540,6 +3575,7 @@ if (isDirectRun()) {
3540
3575
  main().catch((error) => {
3541
3576
  // Last-resort failure INSIDE the coordinator: still fail-closed, still redacted.
3542
3577
  process.stderr.write(`[ukit-stop-coordinator] ${error?.message || error}\n`);
3578
+ if (reentrantStop) { emitReentrantInfrastructureRelease(); return; }
3543
3579
  writeDecisionLine({ decision: 'block', reason: redactInfrastructureReason(), policyOwner: 'fail-closed' });
3544
3580
  });
3545
3581
  }
@@ -66,6 +66,7 @@ If any input is missing, return `CHANGES-REQUESTED` with reason "incomplete hand
66
66
  4. **Safety / security / data loss** — Destructive actions, auth/permission, path handling, unsafe shell/DB/file ops.
67
67
  5. **Performance / scale** — Accidental N+1, repeated I/O, large scans inside hot paths.
68
68
  6. **Maintainability** — Duplicated logic, dead branches, misleading naming, drift between docs/tests/source.
69
+ 6a. **Test hygiene (test diffs)** — Follow `.claude/skills/code-review/SKILL.md` § Test Diffs: app/server/client/DB fixtures without teardown, real-data reachability, per-test app registries, oversized new test files (count parametrize expansion), and tests skipped to save time/RAM. Run `node .claude/ukit/index/test-batches.mjs audit --changed`; an enforced ERROR on a new test file is `CHANGES-REQUESTED` unless the project records an exception.
69
70
  7. **Solution fit** — For each added block, ask with evidence and cite the construct + why (never the prose length):
70
71
  - Does new code duplicate an existing helper with the same semantics? A same-semantics duplicate is `CHANGES-REQUESTED` — reuse the existing helper.
71
72
  - Would the standard library or a native platform API satisfy every stated requirement? If yes, the custom implementation is avoidable.
@@ -42,6 +42,7 @@ and even then, report it, don't ask about it.
42
42
  ### 2. Plan Approach (< 1 minute)
43
43
 
44
44
  - List files to create/modify (max diff).
45
+ - **Tests you add:** plan the layout first (feature, category, expected case count incl. parametrize, target files, fixture teardown) and follow `.claude/skills/testing-quality/SKILL.md` § Writing Memory-Safe Tests — small focused files, every app/client/DB fixture torn down, test paths isolated before app import. Full-suite verification uses `node .claude/ukit/index/test-batches.mjs run`.
45
46
  - **Handoff mode only:** if no Test Plan exists in the task file and task is not `trivial`, write one inline before implementing (happy + ≥2 edge cases of different kinds; regression test if fixing a bug). In daily mode, skip this step.
46
47
  - **Choose the smallest solution that fully meets the stated requirements and project conventions.** When more than one option qualifies, prefer, in order: (1) reuse an existing codebase helper with the same semantics; (2) standard library, native platform API, or an already-installed dependency; (3) custom code or a new dependency (last resort). Never drop validation, security, accessibility, error handling, compatibility, or required tests to reduce code. A bugfix fixes the root cause and the affected callers. If the small option is insufficient, build the full option — never ship a weaker version and ask. No speculative abstraction for imagined needs.
47
48
 
@@ -134,7 +134,7 @@ memory:
134
134
  # edit any value here and `ukit update` keeps it. The legacy shipped 350000 is migrated
135
135
  # only when UKit's install ledger proves UKit wrote it; `ukit uninstall` reverts just
136
136
  # UKit's own additions and keeps your edits. Auto-compact must still trigger BEFORE
137
- # context-hardcap-gate blocks tool calls.
137
+ # context-hardcap-gate emits its (non-blocking) advisory.
138
138
  compaction:
139
139
  enabled: true
140
140
  thresholdTokens: {{omp.compactionThresholdTokens}}
@@ -35,7 +35,7 @@
35
35
 
36
36
  ## Long-Run Continuity
37
37
  <!-- RULES: LONG-01 LONG-02 -->
38
- - Near token-cap: **LAND one thing** end-to-end (edit + verify, ≤3 tool calls), **DEFER** the rest to `docs/STATUS.md` or bounded `docs/AI_HANDOFF/` tasks, **DELEGATE** broad work to subagents. Then compact.
38
+ - Near token-cap: **LAND one thing** end-to-end (edit + verify, ≤3 tool calls), **DEFER** the rest to `docs/STATUS.md` or bounded `docs/AI_HANDOFF/` tasks, **DELEGATE** broad work to subagents, then **keep working** — never end the turn just to ask the user for `/compact`; the host auto-compacts and work resumes from disk.
39
39
  - After compact/handoff: continue from persisted disk state — never reread pre-compact context; delegate broadly, keep replies short.
40
40
  - A run ends only on completion evidence, a genuine blocker, or a user-only action — every stop names its reason.
41
41
 
@@ -35,7 +35,7 @@
35
35
 
36
36
  ## Long-Run Continuity
37
37
  <!-- RULES: LONG-01 LONG-02 -->
38
- - Near token-cap: **LAND one thing** end-to-end (edit + verify, ≤3 tool calls), **DEFER** the rest to `docs/STATUS.md` or bounded `docs/AI_HANDOFF/` tasks, **DELEGATE** broad work to subagents. Then compact.
38
+ - Near token-cap: **LAND one thing** end-to-end (edit + verify, ≤3 tool calls), **DEFER** the rest to `docs/STATUS.md` or bounded `docs/AI_HANDOFF/` tasks, **DELEGATE** broad work to subagents, then **keep working** — never end the turn just to ask the user for `/compact`; the host auto-compacts and work resumes from disk.
39
39
  - After compact/handoff: continue from persisted disk state — never reread pre-compact context; delegate broadly, keep replies short.
40
40
  - A run ends only on completion evidence, a genuine blocker, or a user-only action — every stop names its reason.
41
41
 
@@ -82,7 +82,7 @@ Next: <bước kế tiếp chính xác>
82
82
  - Subagent ghi **full log vào task file trên đĩa**, chỉ trả về orchestrator ≤10 dòng (executor) / ≤6 dòng (reviewer). Paste log ngược lại orchestrator là nguyên nhân số 1 làm run chết vì hết context.
83
83
  - Hết mỗi wave: commit, ghi cursor, **collapse** wave đó còn 1 dòng/task trong bộ nhớ làm việc, rồi chạy tiếp.
84
84
  - Yêu cầu `/compact` **chỉ** được đặt ở cuối command, giữa 2 cycle. Giữa cycle thì tuyệt đối không — state đã nằm hết ở git + `INDEX.md` + `RUN.md` nên compact ở ranh giới cycle không mất gì.
85
- - Vượt `compact.hardCapTokens` (mặc định 235k, trong `compact.contextWindowTokens` 250k) mà `RUN.md` còn run dở **hoặc ordinary routed task có session execution ledger còn thiếu completion evidence**: `context-hardcap-gate` cho thêm `compact.hardCapGraceCalls` (mặc định 10) tool call rồi mới chặn cứng. **Grace đó chỉ để hạ cánh** — hoàn tất edit/verification đang dở và ghi state resume; không mở task mới, không đọc thêm file, không spawn agent. Hết grace là chặn thật; budget chỉ reset khi ước lượng token thực sự giảm (có compact thật), không reset theo wave.
85
+ - Vượt `compact.hardCapTokens` (mặc định 235k, trong `compact.contextWindowTokens` 250k) : `context-hardcap-gate` KHÔNG BAO GIỜ chặn tool, chỉ phát một advisory mỗi cooldown. Compaction chỉ là lời nhắc: hạ cánh bước hiện tại, ghi các bước còn lại vào `docs/STATUS.md`, giao việc đọc rộng cho subagent, rồi tiếp tục làm; host tự auto-compact và việc resume từ disk (`RUN.md`/`docs/STATUS.md`).
86
86
  - Không hook nào gọi được `/compact` — đó là lệnh client-only. Nhưng từ 2.1.3, settings mặc định đặt `env.CLAUDE_CODE_AUTO_COMPACT_WINDOW` = `autoCompactWindowRatio` × `hardCapTokens` (mặc định 0.8 × 235k = 188000) và `env.CLAUDE_CODE_MAX_CONTEXT_TOKENS` = `contextWindowTokens` (250000), render lúc install, nên **client tự auto-compact trước khi gate chặn**. Đường thường: auto-compact chạy → `handoff-resume.sh` replay cursor cho handoff run hoặc tiêu thụ resume intent cho ordinary task → chạy tiếp, không cần người gõ gì. Grace window ở trên chỉ còn là lưới an toàn.
87
87
  - Sửa một trong hai số đó thì phải giữ `autoCompactWindow < hardCapTokens`. Đảo thứ tự là deadlock: gate chặn tool trước → transcript ngừng lớn → ngưỡng auto-compact không bao giờ tới. `tests/core/autoCompactWindow.test.js` khóa bất biến này.
88
88
 
@@ -0,0 +1,10 @@
1
+ # Testing patterns (UKit default)
2
+
3
+ Seeded once by UKit; this file is yours — edit, extend or delete entries. Full rules: `.claude/skills/testing-quality/memory-safe-tests.md`.
4
+
5
+ - Pattern: run the full test suite with `node .claude/ukit/index/test-batches.mjs run` — sequential small batches, one fresh process per batch, every test file runs; only verdict PASS satisfies a release gate (FAIL/INCOMPLETE/UNSAFE do not). Do not add parallel workers (pytest-xdist -n, maxWorkers) to fix test memory: workers multiply RAM.
6
+ - Pattern: test suite memory blow-up / swap is usually a per-test leak, not runner speed — a fixture builds a fresh app per test that is never freed (global app registry, OpenAPI/docs singleton, module-level routers holding app refs, background tasks never cancelled). Fix fixture teardown; smaller batches or files alone do not fix it.
7
+ - Pattern: every test fixture that builds an app, server, client, DB connection, browser, thread or async task tears it down (yield + finally / afterAll): cancel tasks, close connections, unregister from registries, clear singletons. Prefer one app per module (scope=module) when tests do not mutate app state.
8
+ - Pattern: plan test files before writing them — count cases including parametrize expansion; budgets per file: unit 40, integration 20, app-heavy 10, e2e 10; split by behaviour, never into one 200-case test file. Check with `test-batches.mjs audit --changed`.
9
+ - Pattern: test isolation — set data, DB, log and telemetry paths to a temp dir before the app module is imported; app code reads paths from config at call time, not at import; disable schedulers, sweeps and auto-fetch in tests. Tests must never touch real project data, auth/system DBs or shared logs; prove it with `test-batches.mjs run --guard <data dir>`.
10
+ - Pattern: never skip, deselect or xfail tests to save RAM or time; RAM thresholds only flag heavy test files. Suspected test memory leak → `test-batches.mjs detect-leaks --file <file>` and `--resource-warnings` for unclosed DB connections.
@@ -32,7 +32,7 @@
32
32
 
33
33
  ## Long-Run Continuity
34
34
  <!-- RULES: LONG-01 LONG-02 -->
35
- - Near token-cap: **LAND one thing** end-to-end (edit + verify, ≤3 tool calls), **DEFER** the rest to `docs/STATUS.md` or bounded `docs/AI_HANDOFF/` tasks, **DELEGATE** broad work to subagents. Then compact.
35
+ - Near token-cap: **LAND one thing** end-to-end (edit + verify, ≤3 tool calls), **DEFER** the rest to `docs/STATUS.md` or bounded `docs/AI_HANDOFF/` tasks, **DELEGATE** broad work to subagents, then **keep working** — never end the turn just to ask the user for `/compact`; the host auto-compacts and work resumes from disk.
36
36
  - After compact/handoff: continue from persisted disk state — never reread pre-compact context; delegate broadly, keep replies short.
37
37
  - A run ends only on completion evidence, a genuine blocker, or a user-only action — every stop names its reason.
38
38
 
@@ -683,9 +683,9 @@
683
683
  "enabled": "B\u1eadt/t\u1eaft to\u00e0n b\u1ed9 helper compact c\u1ee7a UKit.",
684
684
  "tokenThreshold": "Ng\u01b0\u1ee1ng token chung cho runtime compact d\u00f9ng chung.",
685
685
  "contextWindowTokens": "Context window t\u1ed1i \u0111a UKit cho client d\u00f9ng (m\u1eb7c \u0111\u1ecbnh 250000, k\u1ec3 c\u1ea3 khi provider h\u1ed7 tr\u1ee3 1M). Render th\u00e0nh env.CLAUDE_CODE_MAX_CONTEXT_TOKENS \u2014 model alias gateway nh\u01b0 unic-opus kh\u00f4ng c\u00f3 trong b\u1ea3ng c\u1ee7a Claude Code n\u00ean n\u1ebfu thi\u1ebfu s\u1ed1 n\u00e0y client t\u1ef1 \u0111o\u00e1n 200k/1M v\u00e0 b\u1ecf qua budget UKit. Kh\u00f4ng khuy\u1ebfn kh\u00edch t\u0103ng.",
686
- "hardCapTokens": "Ng\u01b0\u1ee1ng c\u1ee9ng tuy\u1ec7t \u0111\u1ed1i (m\u1eb7c \u0111\u1ecbnh 235000 token \u01b0\u1edbc l\u01b0\u1ee3ng, n\u1eb1m trong contextWindowTokens 250000). Ch\u1ea1m/v\u01b0\u1ee3t ng\u01b0\u1ee1ng n\u00e0y th\u00ec context-hardcap-gate ch\u1eb7n Edit/Write/Bash \u2014 kh\u00f4ng ph\u1ea3i g\u1ee3i \u00fd n\u1eefa, l\u00e0 b\u1eaft bu\u1ed9c. Ph\u1ea3i \u2264 contextWindowTokens. env.CLAUDE_CODE_AUTO_COMPACT_WINDOW (.claude/settings.json) v\u00e0 compaction.thresholdTokens (.omp/config.yml) \u0111\u1ec1u \u0111\u01b0\u1ee3c SUY RA t\u1eeb s\u1ed1 n\u00e0y khi ch\u1ea1y ukit install.",
687
- "autoCompactWindowRatio": "Auto-compact ch\u1ea1y \u1edf bao nhi\u00eau ph\u1ea7n c\u1ee7a hardCapTokens (m\u1eb7c \u0111\u1ecbnh 0.8 \u2192 188000). Ph\u1ea3i < 1 \u0111\u1ec3 client t\u1ef1 compact TR\u01af\u1edaC khi context-hardcap-gate ch\u1eb7n tool; s\u1ed1 c\u00e0ng nh\u1ecf th\u00ec compact c\u00e0ng s\u1edbm.",
688
- "hardCapBlock": "N\u1ebfu true, hook context-hardcap-gate ch\u1eb7n c\u1ee9ng Edit/Write/Bash (exit 2) khi v\u01b0\u1ee3t hardCapTokens, cho t\u1edbi khi c\u00f3 compact th\u1eadt (PreCompact) reset l\u1ea1i b\u1ed9 \u0111\u1ebfm.",
686
+ "hardCapTokens": "Ng\u01b0\u1ee1ng c\u1ee9ng tuy\u1ec7t \u0111\u1ed1i (m\u1eb7c \u0111\u1ecbnh 235000 token \u01b0\u1edbc l\u01b0\u1ee3ng, n\u1eb1m trong contextWindowTokens 250000). Ch\u1ea1m/v\u01b0\u1ee3t ng\u01b0\u1ee1ng n\u00e0y th\u00ec context-hardcap-gate ch\u1ec9 nh\u1eafc (advisory, kh\u00f4ng bao gi\u1edd ch\u1eb7n tool); host t\u1ef1 auto-compact. Ph\u1ea3i \u2264 contextWindowTokens. env.CLAUDE_CODE_AUTO_COMPACT_WINDOW (.claude/settings.json) v\u00e0 compaction.thresholdTokens (.omp/config.yml) \u0111\u1ec1u \u0111\u01b0\u1ee3c SUY RA t\u1eeb s\u1ed1 n\u00e0y khi ch\u1ea1y ukit install.",
687
+ "autoCompactWindowRatio": "Auto-compact ch\u1ea1y \u1edf bao nhi\u00eau ph\u1ea7n c\u1ee7a hardCapTokens (m\u1eb7c \u0111\u1ecbnh 0.8 \u2192 188000). Ph\u1ea3i < 1 \u0111\u1ec3 client t\u1ef1 compact TR\u01af\u1edaC khi context-hardcap-gate nh\u1eafc; s\u1ed1 c\u00e0ng nh\u1ecf th\u00ec compact c\u00e0ng s\u1edbm.",
688
+ "hardCapBlock": "N\u1ebfu true, hook context-hardcap-gate nh\u1eafc (advisory systemMessage, kh\u00f4ng bao gi\u1edd ch\u1eb7n/exit 2) m\u1ed9t l\u1ea7n m\u1ed7i cooldown khi v\u01b0\u1ee3t hardCapTokens; false = t\u1eaft nh\u1eafc.",
689
689
  "hardCapGraceCalls": "S\u1ed1 tool call \u0111\u01b0\u1ee3c ph\u00e9p ch\u1ea1y ti\u1ebfp sau khi v\u01b0\u1ee3t hardCapTokens khi handoff run trong docs/AI_HANDOFF/RUN.md ho\u1eb7c ordinary routed task c\u00f3 session execution ledger c\u00f2n dang d\u1edf (m\u1eb7c \u0111\u1ecbnh 10). \u0110\u00e2y ch\u1ec9 l\u00e0 landing window: ho\u00e0n t\u1ea5t edit/verification \u0111ang d\u1edf v\u00e0 ghi state resume, kh\u00f4ng m\u1edf task m\u1edbi. H\u1ebft grace l\u00e0 ch\u1eb7n c\u1ee9ng nh\u01b0 c\u0169. Budget t\u00ednh theo m\u1ed7i \u0111\u1ee3t v\u01b0\u1ee3t cap, ch\u1ec9 reset khi \u01b0\u1edbc l\u01b0\u1ee3ng token th\u1eadt s\u1ef1 gi\u1ea3m (c\u00f3 compact th\u1eadt) \u2014 kh\u00f4ng reset theo wave.",
690
690
  "contextRotDetection": "Ph\u00e1t hi\u1ec7n context qu\u00e1 d\u00e0i/d\u1ec5 m\u1ee5c \u0111\u1ec3 gi\u1eef l\u1ea1i state quan tr\u1ecdng tr\u01b0\u1edbc khi AI nh\u1edb sai.",
691
691
  "askBeforeDrop": "Gi\u1eef th\u00e1i \u0111\u1ed9 th\u1eadn tr\u1ecdng tr\u01b0\u1edbc khi b\u1ecf context quan tr\u1ecdng. N\u1ebfu r\u1ee7i ro th\u00ec hand back cho main model.",