@ngockhoale/ukit 3.5.17 → 3.5.19

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 (62) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/manifests/platform.full.yaml +48 -0
  3. package/package.json +1 -1
  4. package/scripts/audit/field-replay.mjs +7 -7
  5. package/scripts/audit/field-telemetry.mjs +4 -3
  6. package/scripts/release/run-core-batch.mjs +10 -0
  7. package/src/cli/commands/mission.js +102 -0
  8. package/src/cli/commands/rescue.js +83 -0
  9. package/src/cli/index.js +14 -0
  10. package/src/core/compact/contextBudget.js +62 -41
  11. package/src/core/compact/threshold.js +14 -32
  12. package/src/core/observability/schema/registry.js +91 -0
  13. package/src/core/runtimeConfig.js +53 -2
  14. package/src/render/buildVariables.js +2 -5
  15. package/template_project/.claude/commands/ukit/handoff-implement.md +3 -3
  16. package/template_project/.claude/commands/ukit/handoff-review.md +3 -3
  17. package/template_project/.claude/hooks/context-hardcap-gate.sh +47 -20
  18. package/template_project/.claude/hooks/context-window-guard.sh +82 -27
  19. package/template_project/.claude/hooks/handoff-resume.sh +11 -2
  20. package/template_project/.claude/hooks/mission-capture.mjs +37 -0
  21. package/template_project/.claude/hooks/post-compact-observe.mjs +34 -0
  22. package/template_project/.claude/hooks/sensitive-data-guard.mjs +35 -3
  23. package/template_project/.claude/hooks/shell-watch.mjs +34 -0
  24. package/template_project/.claude/hooks/stop-failure-rescue.mjs +109 -0
  25. package/template_project/.claude/settings.json +36 -4
  26. package/template_project/.claude/ukit/index/test-batches-adapters.mjs +8 -3
  27. package/template_project/.claude/ukit/index/test-batches.mjs +80 -28
  28. package/template_project/.claude/ukit/runtime/compact-threshold.mjs +15 -29
  29. package/template_project/.claude/ukit/runtime/context-capacity.mjs +64 -1
  30. package/template_project/.claude/ukit/runtime/execution-ledger.mjs +44 -3
  31. package/template_project/.claude/ukit/runtime/hook-chain-runner.mjs +20 -1
  32. package/template_project/.claude/ukit/runtime/loop-state.mjs +17 -2
  33. package/template_project/.claude/ukit/runtime/mission/checkpoint.mjs +85 -0
  34. package/template_project/.claude/ukit/runtime/mission/classify.mjs +182 -0
  35. package/template_project/.claude/ukit/runtime/mission/drift.mjs +58 -0
  36. package/template_project/.claude/ukit/runtime/mission/graph.mjs +381 -0
  37. package/template_project/.claude/ukit/runtime/mission/hooks.mjs +199 -0
  38. package/template_project/.claude/ukit/runtime/mission/journal.mjs +68 -0
  39. package/template_project/.claude/ukit/runtime/mission/metrics.mjs +64 -0
  40. package/template_project/.claude/ukit/runtime/mission/recall.mjs +132 -0
  41. package/template_project/.claude/ukit/runtime/mission/redact.mjs +25 -0
  42. package/template_project/.claude/ukit/runtime/mission/restore.mjs +107 -0
  43. package/template_project/.claude/ukit/runtime/mission/store.mjs +231 -0
  44. package/template_project/.claude/ukit/runtime/mission/working.mjs +88 -0
  45. package/template_project/.claude/ukit/runtime/prompt-injection-cap.mjs +33 -0
  46. package/template_project/.claude/ukit/runtime/reinject-context.mjs +87 -6
  47. package/template_project/.claude/ukit/runtime/rescue/bundle.mjs +122 -0
  48. package/template_project/.claude/ukit/runtime/rescue/classify-failure.mjs +136 -0
  49. package/template_project/.claude/ukit/runtime/rescue/lease.mjs +65 -0
  50. package/template_project/.claude/ukit/runtime/rescue/reconstruct.mjs +273 -0
  51. package/template_project/.claude/ukit/runtime/rescue/recovery-state.mjs +120 -0
  52. package/template_project/.claude/ukit/runtime/rescue/rollover.mjs +151 -0
  53. package/template_project/.claude/ukit/runtime/sensitive-value-scanner.mjs +1 -1
  54. package/template_project/.claude/ukit/runtime/shell-watch.mjs +294 -0
  55. package/template_project/.claude/ukit/runtime/stop-coordinator.mjs +154 -0
  56. package/template_project/.omp/config.yml +2 -2
  57. package/template_project/.omp/hooks/pre/ukit-bridge.js +69 -2
  58. package/template_project/AGENTS.md +4 -2
  59. package/template_project/CLAUDE.md +4 -2
  60. package/template_project/docs/AI_HANDOFF/RULES.md +4 -4
  61. package/template_project/instructions/core.md +4 -2
  62. package/template_project/ukit/storage/config.json +32 -10
@@ -76,16 +76,18 @@ export const HOOK_EVENT_MAP = {
76
76
  'Read|Grep|Glob': ['record-execution.mjs'],
77
77
  'Edit|Write': ['post-edit-verify.sh', 'record-execution.mjs', 'task-watchdog.sh', 'edit-hint.mjs'],
78
78
  Bash: ['compress-output.sh', 'record-execution.mjs'],
79
+ // WP4: mission todo mirror (omp tool names map to TodoWrite via TOOL_NAME_MAP).
80
+ 'TodoWrite|TaskCreate|TaskUpdate': ['mission-capture.mjs'],
79
81
  // Delegation result: releases the per-task execution claim taken by the pre-call guard.
80
82
  'MultiEdit|NotebookEdit|Agent|Task': ['record-execution.mjs'],
81
83
  },
82
- before_agent_start: ['sensitive-data-guard.mjs', 'record-execution.mjs', 'skill-router.sh', 'vision-router.sh', 'context-window-guard.sh'],
84
+ before_agent_start: ['sensitive-data-guard.mjs', 'record-execution.mjs', 'skill-router.sh', 'vision-router.sh', 'context-window-guard.sh', 'mission-capture.mjs', 'shell-watch.mjs'],
83
85
  'session.compacting': ['reinject-context.sh'],
84
86
  // TASK-003 (FR-003): the in-proc emit step runs LAST — project-important.sh
85
87
  // owns the mandate-first lead (TASK-042 contract); the emit is advisory,
86
88
  // <250ms, and writes the session's `execution.started` record after the
87
89
  // context-producing scripts.
88
- session_start: ['project-important.sh', 'auto-prune-bash.sh', 'reset-compact-pressure.sh', 'handoff-resume.sh', 'observability-emit.mjs', 'session-episode-start.mjs'],
90
+ session_start: ['project-important.sh', 'auto-prune-bash.sh', 'reset-compact-pressure.sh', 'handoff-resume.sh', 'reinject-context.sh', 'observability-emit.mjs', 'session-episode-start.mjs'],
89
91
  // TASK-002 (cycle 45): omp emits `session_stop` (no `session_end`); the chain
90
92
  // runs only on RELEASED stops inside runSessionStop — never on blocked or
91
93
  // dedupe-skipped stops, since `ukit memory episode` dedupes on meta.ledgerKey
@@ -116,6 +118,8 @@ const TOOL_NAME_MAP = {
116
118
  cron_delete: 'CronDelete',
117
119
  cronlist: 'CronList',
118
120
  cron_list: 'CronList',
121
+ todo_write: 'TodoWrite',
122
+ todowrite: 'TodoWrite',
119
123
  task: 'Task',
120
124
  vibe_spawn: 'Task',
121
125
  agent: 'Task',
@@ -142,6 +146,9 @@ function matcherGroupFor(claudeToolName) {
142
146
  if (claudeToolName === 'Bash') {
143
147
  return 'Bash';
144
148
  }
149
+ if (claudeToolName === 'TodoWrite' || claudeToolName === 'TaskCreate' || claudeToolName === 'TaskUpdate') {
150
+ return 'TodoWrite|TaskCreate|TaskUpdate';
151
+ }
145
152
  if (claudeToolName === 'MultiEdit' || claudeToolName === 'NotebookEdit' || claudeToolName === 'Agent' || claudeToolName === 'Task') {
146
153
  return 'MultiEdit|NotebookEdit|Agent|Task';
147
154
  }
@@ -168,6 +175,8 @@ export const ADVISORY_SCRIPTS = new Set([
168
175
  // TASK-005: record-execution now runs as an .mjs module step (advisory).
169
176
  'record-execution.mjs',
170
177
  'edit-hint.mjs',
178
+ 'shell-watch.mjs',
179
+ 'mission-capture.mjs',
171
180
  'auto-allow-bash.sh',
172
181
  'pre-edit-backup.sh',
173
182
  'vision-router.sh',
@@ -1381,6 +1390,10 @@ export async function runSessionStart(pi, event, { projectRoot, context: extensi
1381
1390
  export async function runSessionCompact(pi, event, { projectRoot, context: extensionContext = {} }) {
1382
1391
  const metadata = runtimeMetadata(event, extensionContext);
1383
1392
  const payload = buildHookPayload('SessionStart', { ...metadata, source: 'compact' });
1393
+ // The session_start chain includes reinject-context.sh, which rebuilds the restoration block
1394
+ // on source=compact only (session_compact is where omp keeps model-visible context);
1395
+ // session.compacting only checkpoints (reinject returns early there for harness=omp), so the
1396
+ // block is delivered exactly once.
1384
1397
  const result = await runScriptChain(pi, HOOK_EVENT_MAP.session_start, payload, { projectRoot });
1385
1398
  // VERIFIED (2026-08-29, source read of omp v18.0.10 pi-coding-agent/src) PLAN.md §3 D3:
1386
1399
  // session_compact fires only after agent.replaceMessages()/rebaseAfterCompaction() already
@@ -2157,6 +2170,57 @@ export async function runSessionStop(
2157
2170
  });
2158
2171
  }
2159
2172
 
2173
+ // ── Context rescue (WP-R4): omp `auto_compaction_end` ──
2174
+ // Registered only when the pi API advertises the event. On a failed compaction (or willRetry:false) classify,
2175
+ // record COMPACT_FAILED, and request ONE ctx.compact() per rescue epoch. Everything is feature-detected and
2176
+ // fails open: a missing runtime/API never affects the session.
2177
+ const rescueCompactEpochs = new Set();
2178
+ export async function runAutoCompactionEnd(pi, event, { projectRoot, context: ctx = {} } = {}) {
2179
+ try {
2180
+ if (!event || !(event.result === 'failed' || event.willRetry === false)) return undefined;
2181
+ if (event.result && event.result !== 'failed' && event.willRetry !== false) return undefined;
2182
+ const rescueDir = '../../../.claude/ukit/runtime/rescue/';
2183
+ const cf = await import(`${rescueDir}classify-failure.mjs`);
2184
+ const rs = await import(`${rescueDir}recovery-state.mjs`);
2185
+ const input = { error: 'unknown', error_details: event.errorMessage ?? event.error ?? '', message: event.reason ?? '' };
2186
+ const c = cf.classifyFailure(input);
2187
+ const fp = cf.fingerprint(input);
2188
+ let epoch = 0;
2189
+ try { epoch = JSON.parse(await fs.promises.readFile(path.join(projectRoot, '.ukit', 'storage', 'rescue', 'lease.json'), 'utf8')).epoch || 0; } catch { /* no lease yet */ }
2190
+ const cur = await rs.readState({ root: projectRoot });
2191
+ const eventId = crypto.createHash('sha1').update(`omp|${fp}|${cur.version}|${epoch}`).digest('hex').slice(0, 24);
2192
+ if (c.action === 'block') {
2193
+ await rs.transition({ root: projectRoot, from: cur.state, to: 'BLOCKED', eventId, reason: c.name, fingerprint: fp, failure: true });
2194
+ return undefined;
2195
+ }
2196
+ if (cur.state === 'PAUSED_OWNER_STOP' || cur.state === 'BLOCKED') return undefined;
2197
+ if (cur.state !== 'COMPACT_FAILED') {
2198
+ await rs.transition({ root: projectRoot, from: cur.state, to: 'COMPACT_FAILED', eventId, reason: c.name, fingerprint: fp, failure: true });
2199
+ } else {
2200
+ await rs.recordFailure({ root: projectRoot, fingerprint: fp, eventId });
2201
+ }
2202
+ const key = `${projectRoot}|${epoch}`;
2203
+ if (rescueCompactEpochs.has(key) || typeof ctx.compact !== 'function') return undefined;
2204
+ const after = await rs.readState({ root: projectRoot });
2205
+ if (rs.breakerStatus(after, fp).open) return undefined;
2206
+ rescueCompactEpochs.add(key);
2207
+ await ctx.compact();
2208
+ } catch (error) {
2209
+ pi?.logger?.warn?.(`[UKit] rescue auto_compaction_end failed open: ${error?.message || error}`);
2210
+ }
2211
+ return undefined;
2212
+ }
2213
+
2214
+ export function piSupportsEvent(pi, name) {
2215
+ try {
2216
+ if (typeof pi?.hasEvent === 'function') return pi.hasEvent(name) === true;
2217
+ const list = pi?.supportedEvents ?? pi?.events;
2218
+ if (list instanceof Set) return list.has(name);
2219
+ if (Array.isArray(list)) return list.includes(name);
2220
+ } catch { /* fall through */ }
2221
+ return false;
2222
+ }
2223
+
2160
2224
  function installedProjectRoot() {
2161
2225
  const bridgeDir = path.dirname(fileURLToPath(import.meta.url));
2162
2226
  return path.resolve(bridgeDir, '../../..');
@@ -2181,6 +2245,9 @@ export default function hook(pi) {
2181
2245
  pi.on('session_switch', (event, context) => runSessionSwitch(pi, event, { projectRoot, context }));
2182
2246
  pi.on('session_compact', (event, context) => runSessionCompact(pi, event, { projectRoot, context }));
2183
2247
  pi.on('session_stop', (event, context) => runSessionStop(pi, event, { projectRoot, context }));
2248
+ if (piSupportsEvent(pi, 'auto_compaction_end')) {
2249
+ pi.on('auto_compaction_end', (event, context) => runAutoCompactionEnd(pi, event, { projectRoot, context }));
2250
+ }
2184
2251
  pi.on('before_subagent_spawn', async (event, context) => {
2185
2252
  if (await ownerStopBlocksStart(projectRoot, event, context)) return { block: true, reason: OWNER_STOP_START_REASON };
2186
2253
  return selectWorkerModel(event, { projectRoot, context });
@@ -35,9 +35,10 @@
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 **keep working** — never end the turn just to ask the user for `/compact`; the host auto-compacts and work resumes from disk.
38
+ - Context tiers (UKit-owned, model-independent): <100k best · 100-150k OK (prefer delegating broad reads, short replies) · 150-200k mandatory: stay under 200k — **LAND one thing** (edit + verify, ≤3 tool calls), **DEFER** the rest to `docs/STATUS.md` or bounded `docs/AI_HANDOFF/` tasks, **DELEGATE** broad work to subagents, start nothing new inline · 200-250k over the line: persist now · ≥250k STOP new work, persist state to disk only. Compaction is always automatic (host auto-compacts at ~150-180k, UKit restores work after) — never end the turn just to ask the user for `/compact`.
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
+ - Codex has no hooks: run `ukit mission capture "<prompt>"` on each new user request and `ukit mission restore` at session start or after a context reset.
41
42
 
42
43
  ## Index-First Loop
43
44
  <!-- RULE: IDX-01 -->
@@ -92,8 +93,9 @@ Chỉ active khi task đi qua `docs/AI_HANDOFF/` ("execute task TASK-xxx" hoặc
92
93
  <!-- RULES: BUDGET-02 BUDGET-03 -->
93
94
  - `docs/STATUS.md` for open-ended/continue; `docs/TASKS.md` only for queued-task prompts; `docs/WORKLOG.md` recent entries only. Verification: targeted first, widen on risk/shared scope, ask before broad runs.
94
95
  <!-- RULE: TEST-01 -->
95
- - **Full/large test suites run in batches:** run the whole suite (or any run beyond a few targeted files) with `node .claude/ukit/index/test-batches.mjs run` — sequential fresh-process batches, every file runs, only a `PASS` verdict (exit 0) counts as green; never add parallel workers or launch a second copy. Targeted 1-3 file runs use the bare runner directly.
96
+ - **Full/large test suites run in batches:** run the whole suite (or any run beyond a few targeted files) with `node .claude/ukit/index/test-batches.mjs run` — sequential fresh-process batches, every file runs, only a `PASS` verdict (exit 0) counts as green; never launch a second copy or add your own parallel workers; in-batch workers come only from the runner's `workers` setting. Targeted 1-3 file runs use the bare runner directly.
96
97
  - **Long commands run once:** start a full suite/release gate (>1 min) a single time; if it times out or goes to background, read its output — never launch a duplicate in parallel. Cheap deterministic gates first; trivial/simple tasks never need the full suite.
98
+ - **No hung shells:** a `[ukit-shell-watch] ACTION` line means kill the listed hung shells/stalled tasks and finish their work before the new prompt. Hookless engines (Codex): check `ps` for stale agent shells at the start of each prompt. Wait loops poll a pidfile / `kill -0 <pid>`, never a self-matching `pgrep -f`.
97
99
 
98
100
  ## Living Status Workflow
99
101
  <!-- RULE: STATUS-01 -->
@@ -35,9 +35,10 @@
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 **keep working** — never end the turn just to ask the user for `/compact`; the host auto-compacts and work resumes from disk.
38
+ - Context tiers (UKit-owned, model-independent): <100k best · 100-150k OK (prefer delegating broad reads, short replies) · 150-200k mandatory: stay under 200k — **LAND one thing** (edit + verify, ≤3 tool calls), **DEFER** the rest to `docs/STATUS.md` or bounded `docs/AI_HANDOFF/` tasks, **DELEGATE** broad work to subagents, start nothing new inline · 200-250k over the line: persist now · ≥250k STOP new work, persist state to disk only. Compaction is always automatic (host auto-compacts at ~150-180k, UKit restores work after) — never end the turn just to ask the user for `/compact`.
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
+ - Codex has no hooks: run `ukit mission capture "<prompt>"` on each new user request and `ukit mission restore` at session start or after a context reset.
41
42
 
42
43
  ## Index-First Loop
43
44
  <!-- RULE: IDX-01 -->
@@ -92,8 +93,9 @@ Chỉ active khi task đi qua `docs/AI_HANDOFF/` ("execute task TASK-xxx" hoặc
92
93
  <!-- RULES: BUDGET-02 BUDGET-03 -->
93
94
  - `docs/STATUS.md` for open-ended/continue; `docs/TASKS.md` only for queued-task prompts; `docs/WORKLOG.md` recent entries only. Verification: targeted first, widen on risk/shared scope, ask before broad runs.
94
95
  <!-- RULE: TEST-01 -->
95
- - **Full/large test suites run in batches:** run the whole suite (or any run beyond a few targeted files) with `node .claude/ukit/index/test-batches.mjs run` — sequential fresh-process batches, every file runs, only a `PASS` verdict (exit 0) counts as green; never add parallel workers or launch a second copy. Targeted 1-3 file runs use the bare runner directly.
96
+ - **Full/large test suites run in batches:** run the whole suite (or any run beyond a few targeted files) with `node .claude/ukit/index/test-batches.mjs run` — sequential fresh-process batches, every file runs, only a `PASS` verdict (exit 0) counts as green; never launch a second copy or add your own parallel workers; in-batch workers come only from the runner's `workers` setting. Targeted 1-3 file runs use the bare runner directly.
96
97
  - **Long commands run once:** start a full suite/release gate (>1 min) a single time; if it times out or goes to background, read its output — never launch a duplicate in parallel. Cheap deterministic gates first; trivial/simple tasks never need the full suite.
98
+ - **No hung shells:** a `[ukit-shell-watch] ACTION` line means kill the listed hung shells/stalled tasks and finish their work before the new prompt. Hookless engines (Codex): check `ps` for stale agent shells at the start of each prompt. Wait loops poll a pidfile / `kill -0 <pid>`, never a self-matching `pgrep -f`.
97
99
 
98
100
  ## Living Status Workflow
99
101
  <!-- RULE: STATUS-01 -->
@@ -81,10 +81,10 @@ Next: <bước kế tiếp chính xác>
81
81
 
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
- - 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) : `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
- - 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
- - 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.
84
+ - Không bao giờ dừng run để xin `/compact` hay session mới: state đã nằm hết ở git + `INDEX.md` + `RUN.md`, host tự auto-compact và run chạy tiếp từ disk. Tối đa một dòng cuối report nói `/compact` là nên làm nếu context vẫn cao sau compaction.
85
+ - Context tiers do UKit sở hữu, không phụ thuộc context window của model (`compact.bestTokens/okTokens/mandatoryTokens/stopTokens` = 100k/150k/200k/250k; khoá cũ `tokenThreshold` → `bestTokens`, `hardCapTokens` → `stopTokens` và thắng khoá mới): <100k xanh (im lặng) · 100–150k vàng (nhắc 1 dòng) · 150–200k cam BẮT BUỘC (hạ cánh việc đang làm, ghi phần còn lại vào `docs/STATUS.md`, giao việc rộng cho subagent, không mở việc mới inline) · 200–250k đỏ (vượt vạch bắt buộc, persist ngay) · ≥250k STOP: `context-hardcap-gate` chặn (exit 2) việc mới trừ ghi state ra đĩa (`docs/STATUS.md`, `docs/AI_HANDOFF/**`, `.ukit/**`). Không bao giờ yêu cầu người dùng chạy `/compact`: compaction luôn tự động, host auto-compact rồi UKit khôi phục việc (`RUN.md`/`docs/STATUS.md`).
86
+ - Không hook nào gọi được `/compact` — đó là lệnh client-only. Settings render `env.CLAUDE_CODE_AUTO_COMPACT_WINDOW` = `compact.hostAutoCompactTokens` (180000; Claude Code trừ buffer tóm tắt nên nén thực tế quanh 150–167k) và `compaction.thresholdTokens` của omp = `compact.ompCompactionThresholdTokens` (170000), cả hai trong dải 150–200k và < `stopTokens`, nên **host tự auto-compact trước khi gate chặn**. Chỉ `contextWindowTokens` kẹp các số render cho host, không hạ các tier. Đường thường: auto-compact chạy → `handoff-resume.sh` replay cursor / resume intent và `reinject-context` dựng lại context → chạy tiếp, không cần người gõ gì.
87
+ - Bất biến: `hostAutoCompact < stopTokens`. Đả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
 
89
89
  ### Git
90
90
 
@@ -32,9 +32,10 @@
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 **keep working** — never end the turn just to ask the user for `/compact`; the host auto-compacts and work resumes from disk.
35
+ - Context tiers (UKit-owned, model-independent): <100k best · 100-150k OK (prefer delegating broad reads, short replies) · 150-200k mandatory: stay under 200k — **LAND one thing** (edit + verify, ≤3 tool calls), **DEFER** the rest to `docs/STATUS.md` or bounded `docs/AI_HANDOFF/` tasks, **DELEGATE** broad work to subagents, start nothing new inline · 200-250k over the line: persist now · ≥250k STOP new work, persist state to disk only. Compaction is always automatic (host auto-compacts at ~150-180k, UKit restores work after) — never end the turn just to ask the user for `/compact`.
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
+ - Codex has no hooks: run `ukit mission capture "<prompt>"` on each new user request and `ukit mission restore` at session start or after a context reset.
38
39
 
39
40
  ## Index-First Loop
40
41
  <!-- RULE: IDX-01 -->
@@ -89,8 +90,9 @@ Chỉ active khi task đi qua `docs/AI_HANDOFF/` ("execute task TASK-xxx" hoặc
89
90
  <!-- RULES: BUDGET-02 BUDGET-03 -->
90
91
  - `docs/STATUS.md` for open-ended/continue; `docs/TASKS.md` only for queued-task prompts; `docs/WORKLOG.md` recent entries only. Verification: targeted first, widen on risk/shared scope, ask before broad runs.
91
92
  <!-- RULE: TEST-01 -->
92
- - **Full/large test suites run in batches:** run the whole suite (or any run beyond a few targeted files) with `node .claude/ukit/index/test-batches.mjs run` — sequential fresh-process batches, every file runs, only a `PASS` verdict (exit 0) counts as green; never add parallel workers or launch a second copy. Targeted 1-3 file runs use the bare runner directly.
93
+ - **Full/large test suites run in batches:** run the whole suite (or any run beyond a few targeted files) with `node .claude/ukit/index/test-batches.mjs run` — sequential fresh-process batches, every file runs, only a `PASS` verdict (exit 0) counts as green; never launch a second copy or add your own parallel workers; in-batch workers come only from the runner's `workers` setting. Targeted 1-3 file runs use the bare runner directly.
93
94
  - **Long commands run once:** start a full suite/release gate (>1 min) a single time; if it times out or goes to background, read its output — never launch a duplicate in parallel. Cheap deterministic gates first; trivial/simple tasks never need the full suite.
95
+ - **No hung shells:** a `[ukit-shell-watch] ACTION` line means kill the listed hung shells/stalled tasks and finish their work before the new prompt. Hookless engines (Codex): check `ps` for stale agent shells at the start of each prompt. Wait loops poll a pidfile / `kill -0 <pid>`, never a self-matching `pgrep -f`.
94
96
 
95
97
  ## Living Status Workflow
96
98
  <!-- RULE: STATUS-01 -->
@@ -6,16 +6,30 @@
6
6
  "affectVerification": true,
7
7
  "affectDelegation": true
8
8
  },
9
+ "rescue": {
10
+ "autoRollover": "auto",
11
+ "maxTurns": 40
12
+ },
13
+ "shellWatch": {
14
+ "enabled": true,
15
+ "staleMinutes": 20,
16
+ "autoKillSelfMatchingLoops": true
17
+ },
9
18
  "security": {
10
19
  "sensitiveDataGate": true,
11
20
  "allowlistPath": ".ukit/storage/security/allowlist.json"
12
21
  },
13
22
  "compact": {
14
23
  "enabled": true,
15
- "tokenThreshold": 115000,
16
- "contextWindowTokens": 250000,
17
- "hardCapTokens": 235000,
18
- "autoCompactWindowRatio": 0.8,
24
+ "bestTokens": 100000,
25
+ "okTokens": 150000,
26
+ "mandatoryTokens": 200000,
27
+ "stopTokens": 250000,
28
+ "contextWindowTokens": 200000,
29
+ "hostAutoCompactTokens": 180000,
30
+ "ompCompactionThresholdTokens": 170000,
31
+ "maxPromptInjectionChars": 4000,
32
+ "gatewayLimitTokens": null,
19
33
  "hardCapBlock": true,
20
34
  "hardCapGraceCalls": 10,
21
35
  "contextRotDetection": true,
@@ -675,17 +689,25 @@
675
689
  "affectVerification": "N\u1ebfu true, autonomy.level \u1ea3nh h\u01b0\u1edfng h\u00e0nh vi verification plan.",
676
690
  "affectDelegation": "N\u1ebfu true, autonomy.level \u1ea3nh h\u01b0\u1edfng ng\u01b0\u1ee1ng delegation."
677
691
  },
692
+ "shellWatch": {
693
+ "enabled": "Moi prompt UKit kiem tra shell treo/task nen bi ket va tra ve chi thi ACTION cho agent.",
694
+ "staleMinutes": "So phut khong hoat dong truoc khi shell/task bi coi la treo (mac dinh 20).",
695
+ "autoKillSelfMatchingLoops": "Tu kill vong lap until/while dung pgrep -f tu khop chinh no (chi cua user hien tai, qua staleMinutes); ghi log .ukit/storage/logs/shell-watch.log."
696
+ },
678
697
  "security": {
679
698
  "sensitiveDataGate": "B\u1eadt sensitive-data gate: ch\u1eb7n key/private data/secret (\u0111\u1ecdc file .env, *.pem, id_rsa; l\u1ec7nh bash dump secret; prompt ch\u1ee9a token) tr\u01b0\u1edbc khi ch\u00fang t\u1edbi AI. Ch\u1eb7n c\u1ef1c g\u1eaft theo y\u00eau c\u1ea7u: ch\u1ec9 c\u1ea7n nghi ng\u1edd l\u00e0 ch\u1eb7n v\u00e0 h\u1ecfi user. T\u1eaft ch\u1ec9 khi debug gate n\u00e0y.",
680
699
  "allowlistPath": "File allowlist JSON do USER t\u1ef1 t\u1ea1o \u0111\u1ec3 ph\u00ea duy\u1ec7t t\u01b0\u1eddng minh gi\u00e1 tr\u1ecb secret (sha256) ho\u1eb7c \u0111\u01b0\u1eddng d\u1eabn file \u0111\u01b0\u1ee3c ph\u00e9p g\u1eedi. File n\u00e0y \u0111\u01b0\u1ee3c protect-files.sh ch\u1eb7n AI t\u1ef1 s\u1eeda."
681
700
  },
682
701
  "compact": {
683
702
  "enabled": "B\u1eadt/t\u1eaft to\u00e0n b\u1ed9 helper compact c\u1ee7a UKit.",
684
- "tokenThreshold": "Ng\u01b0\u1ee1ng token chung cho runtime compact d\u00f9ng chung.",
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\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.",
703
+ "bestTokens": "Ng\u01b0\u1ee1ng xanh/t\u1ed1t nh\u1ea5t (m\u1eb7c \u0111\u1ecbnh 100000): d\u01b0\u1edbi m\u1ee9c n\u00e0y im l\u1eb7ng. UKit t\u1ef1 s\u1edf h\u1eefu 4 m\u1ed1c bestTokens/okTokens/mandatoryTokens/stopTokens, KH\u00d4NG ph\u1ee5 thu\u1ed9c context window c\u1ee7a model. Kho\u00e1 c\u0169 tokenThreshold (n\u1ebfu c\u00f2n trong config) \u0111\u01b0\u1ee3c map sang bestTokens.",
704
+ "okTokens": "Ng\u01b0\u1ee1ng v\u00e0ng (m\u1eb7c \u0111\u1ecbnh 150000): t\u1eeb bestTokens \u0111\u1ebfn \u0111\u00e2y ch\u1ec9 nh\u1eafc 1 d\u00f2ng \u2014 \u01b0u ti\u00ean giao vi\u1ec7c \u0111\u1ecdc r\u1ed9ng cho subagent, tr\u1ea3 l\u1eddi ng\u1eafn.",
705
+ "mandatoryTokens": "Ng\u01b0\u1ee1ng cam B\u1eaeT BU\u1ed8C (m\u1eb7c \u0111\u1ecbnh 200000): t\u1eeb okTokens \u0111\u1ebfn \u0111\u00e2y ph\u1ea3i gi\u1eef d\u01b0\u1edbi 200k \u2014 ho\u00e0n t\u1ea5t vi\u1ec7c \u0111ang l\u00e0m, ghi ph\u1ea7n c\u00f2n l\u1ea1i v\u00e0o docs/STATUS.md ho\u1eb7c handoff task, giao vi\u1ec7c r\u1ed9ng cho subagent, kh\u00f4ng m\u1edf vi\u1ec7c m\u1edbi inline. V\u01b0\u1ee3t 200k = c\u1ea3nh b\u00e1o \u0111\u1ecf leo thang.",
706
+ "stopTokens": "Ng\u01b0\u1ee1ng D\u1eeaNG (m\u1eb7c \u0111\u1ecbnh 250000): context-hardcap-gate ch\u1eb7n vi\u1ec7c m\u1edbi (ch\u1ec9 cho ph\u00e9p c\u00e1c l\u1ea7n ghi state ra \u0111\u0129a theo hardCapGraceCalls). N\u00e9n lu\u00f4n T\u1ef0 \u0110\u1ed8NG: host auto-compact s\u1ebd ch\u1ea1y v\u00e0 UKit kh\u00f4i ph\u1ee5c c\u00f4ng vi\u1ec7c \u2014 kh\u00f4ng bao gi\u1edd y\u00eau c\u1ea7u ng\u01b0\u1eddi d\u00f9ng ch\u1ea1y /compact. Kho\u00e1 c\u0169 hardCapTokens (n\u1ebfu c\u00f2n) \u0111\u01b0\u1ee3c map sang stopTokens v\u00e0 th\u1eafng kho\u00e1 m\u1edbi.",
707
+ "contextWindowTokens": "Context window UKit khai b\u00e1o cho client (m\u1eb7c \u0111\u1ecbnh 200000). Ch\u1ec9 d\u00f9ng \u0111\u1ec3 render env.CLAUDE_CODE_MAX_CONTEXT_TOKENS v\u00e0 k\u1eb9p c\u1eeda s\u1ed5 auto-compact c\u1ee7a host; KH\u00d4NG h\u1ea1 c\u00e1c m\u1ed1c bestTokens/okTokens/mandatoryTokens/stopTokens.",
708
+ "hostAutoCompactTokens": "C\u1eeda s\u1ed5 auto-compact c\u1ee7a host (m\u1eb7c \u0111\u1ecbnh 180000, render th\u00e0nh env.CLAUDE_CODE_AUTO_COMPACT_WINDOW; Claude Code tr\u1eeb buffer t\u00f3m t\u1eaft n\u00ean th\u1ef1c t\u1ebf n\u00e9n quanh 150k\u2013167k). Ph\u1ea3i n\u1eb1m trong d\u1ea3i 150k\u2013200k v\u00e0 < stopTokens \u0111\u1ec3 host lu\u00f4n t\u1ef1 n\u00e9n tr\u01b0\u1edbc m\u1ed1c d\u1eebng. Kh\u00f4ng bao gi\u1edd ghi DISABLE_AUTO_COMPACT. autoCompactWindowRatio (c\u0169) ch\u1ec9 c\u00f2n d\u00f9ng khi install c\u00f2n ghim hardCapTokens.",
709
+ "ompCompactionThresholdTokens": "Ng\u01b0\u1ee1ng compaction c\u1ee7a omp (m\u1eb7c \u0111\u1ecbnh 170000, render th\u00e0nh compaction.thresholdTokens trong .omp/config.yml), n\u1eb1m trong d\u1ea3i 150k\u2013200k.",
710
+ "hardCapBlock": "N\u1ebfu true, context-hardcap-gate ch\u1eb7n Edit/Write/Bash khi context >= stopTokens (tr\u1eeb c\u00e1c l\u1ea7n ghi state theo hardCapGraceCalls) v\u00e0 nh\u1eafc 1 d\u00f2ng theo m\u1ed1c v\u00e0ng/cam/\u0111\u1ecf; false = t\u1eaft gate.",
689
711
  "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
712
  "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
713
  "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.",
@@ -826,7 +848,7 @@
826
848
  "fullstack": {
827
849
  "stopGateEnabled": "B\u1eadt Stop gate handoff: RUN.md Phase != done/blocked \u2192 Stop hook t\u1eeb ch\u1ed1i stop k\u00e8m Next step, gi\u1eef handoff-fullstack ch\u1ea1y ti\u1ebfp thay v\u00ec \u0111\u1ee9ng sau recap. T\u1eaft ch\u1ec9 khi debug.",
828
850
  "stopGateMaxStalledBlocks": "Liveness breaker: cursor kh\u00f4ng nh\u00edch qua N l\u1ea7n block li\u00ean ti\u1ebfp th\u00ec gate th\u1ea3 stop (tr\u00e1nh v\u00f2ng l\u1eb7p v\u00f4 t\u1eadn). M\u1eb7c \u0111\u1ecbnh 12.",
829
- "stopGateScope": "session = Stop gate chỉ ép khi chính session này đang chạy handoff-fullstack (transcript có /ukit:handoff-fullstack hoặc resume marker); session mới mở chỉ để plan/việc khác không bị ép. project = cũ: mọi session trong repo đều bị ép khi RUN.md còn sống.",
851
+ "stopGateScope": "session = Stop gate ch\u1ec9 \u00e9p khi ch\u00ednh session n\u00e0y \u0111ang ch\u1ea1y handoff-fullstack (transcript c\u00f3 /ukit:handoff-fullstack ho\u1eb7c resume marker); session m\u1edbi m\u1edf ch\u1ec9 \u0111\u1ec3 plan/vi\u1ec7c kh\u00e1c kh\u00f4ng b\u1ecb \u00e9p. project = c\u0169: m\u1ecdi session trong repo \u0111\u1ec1u b\u1ecb \u00e9p khi RUN.md c\u00f2n s\u1ed1ng.",
830
852
  "stopGateMaxCrashStreaks": "Liveness breaker cho coordinator crash: sau N l\u1ea7n block li\u00ean ti\u1ebfp do infrastructure failure, gate th\u1ea3 stop k\u00e8m c\u1ea3nh b\u00e1o l\u1edbn. M\u1eb7c \u0111\u1ecbnh 3.",
831
853
  "quietScansRequired": "S\u1ed1 scan li\u00ean ti\u1ebfp kh\u00f4ng th\u1ea5y vi\u1ec7c m\u1edbi tr\u01b0\u1edbc khi handoff-fullstack \u0111\u01b0\u1ee3c ph\u00e9p \u0111\u00f3ng run. M\u1eb7c \u0111\u1ecbnh 2.",
832
854
  "idleWatchdogMin": "Kho\u1ea3ng ph\u00fat cho scheduled wakeup n\u1ebfu harness h\u1ed7 tr\u1ee3 (cron/loop). M\u1eb7c \u0111\u1ecbnh 5.",