@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
@@ -1,33 +1,14 @@
1
1
  #!/bin/bash
2
- # PreToolUse hook: hard-enforce an absolute context token cap (compact.hardCapTokens,
3
- # default 235000 inside the shipped 250k compact.contextWindowTokens; Claude Code itself
4
- # auto-compacts earlier, at round(hardCap * autoCompactWindowRatio)), separate from the
5
- # soft/hard advisory pressure phases in
6
- # compact-threshold.mjs (default soft=115000/hard=184000, which only print a suggestion).
2
+ # PreToolUse hook: ADVISORY reminder once estimated context passes compact.hardCapTokens
3
+ # (default 235000 inside the shipped 250k compact.contextWindowTokens). It NEVER blocks and
4
+ # never exits 2: compaction is only a reminder — the host (Claude Code / Codex / omp)
5
+ # auto-compacts by itself and work resumes from docs/STATUS.md. Over the cap it emits one
6
+ # structured systemMessage per cooldown telling the model to keep working: land the current
7
+ # step, persist remaining steps to docs/STATUS.md, delegate broad reads to subagents.
7
8
  #
8
- # Those advisory phases are just injected text — nothing stops the agent from ignoring
9
- # them and letting a session run to hundreds of thousands of tokens with no compaction.
10
- # This gate is the backstop: once estimatedTotalTokens >= hardCapTokens, Edit/Write/Bash
11
- # are refused (exit 2) until a real compaction happens. Real compaction is detected via
12
- # the PreCompact hook (reinject-context.mjs), which resets the tracked counter — see
13
- # resetCompactPressureState in compact-threshold.mjs. No advisory bypass, no exceptions.
14
- #
15
- # Matcher is Edit|Write|Bash only. Read/Grep/Glob stay open so the agent can still
16
- # investigate, report status, and tell the user to run /compact — gating those too would
17
- # just brick the session with no way out, since only the user (not the agent) can invoke
18
- # real compaction.
19
- #
20
- # Grace window (compact.hardCapGraceCalls, default 10): blocking the very first tool call
21
- # past the cap strands a handoff run or ordinary routed task mid-edit — files half-written,
22
- # no durable completion state — which is strictly worse than letting it land. When RUN.md
23
- # shows an unfinished handoff run, or the shared ledger proves an unfinished session-bound
24
- # ordinary task, the gate allows a BOUNDED number of further calls so it can land the current
25
- # edit/verification and persist resume state; after that it blocks exactly as before. The
26
- # budget is per over-cap episode, not per wave: it only resets when the estimate actually
27
- # drops (i.e. a real compaction happened), so a task cannot mint itself fresh grace forever.
28
- #
29
- # Config toggle: compact.hardCapBlock (default true). Set to false only to debug this
30
- # gate itself; it must not become a normal escape hatch.
9
+ # Matcher is Edit|Write|Bash only. Real compaction resets the tracked counter (PreCompact hook,
10
+ # or compact_boundary entries in the transcript). Config toggle: compact.hardCapBlock=false
11
+ # silences the advisory entirely.
31
12
 
32
13
  PROJECT_ROOT="${CLAUDE_PROJECT_DIR:-$PWD}"
33
14
  HOOK_DIR="$(cd "$(dirname "$0")" && pwd)"
@@ -42,19 +23,18 @@ source "$HOOK_DIR/../ukit/runtime/hook-telemetry.sh" 2>/dev/null || true
42
23
  ukit_stage_hook_input 2097152 truncate
43
24
  __ukit_main_stage_rc=$?
44
25
  if [ "$__ukit_main_stage_rc" -ne 0 ]; then
45
- # Infra failure during staging (mktemp/truncate): payload was never
46
- # inspected — announce the degrade (SPEC §8), never a silent pass.
47
- # TASK-003: `deny`, not `ask` — ask auto-approves under bypassPermissions.
48
- ukit_emit_permission_decision deny "UKit could not fully read this tool-call payload (stdin staging was cut at the deadline/size bound), so context hard-cap gate cannot prove it safe."
26
+ # Infra failure during staging: advisory gate fails open (never blocks).
27
+ printf '%s\n' '{"systemMessage":"UKit context hard-cap gate: could not read the tool-call payload; this call proceeded without the context check."}'
28
+ exit 0
49
29
  fi
50
30
  # BUG-C21-01 / TASK-003: degraded input first salvages tool_name — a COMPLETE
51
- # recovered name takes the normal verdict path below; an unrecoverable one is
52
- # refused with `deny` (never `ask`: bypassPermissions auto-approves ask).
31
+ # recovered name takes the normal path below; an unrecoverable one fails open.
53
32
  if ukit_input_degraded; then
54
33
  if UKIT_SALVAGED_TOOL_NAME="$(ukit_salvage_tool_field "$UKIT_INPUT_FILE" "tool_name")"; then
55
34
  UKIT_SALVAGE_ACTIVE=1
56
35
  else
57
- ukit_emit_permission_decision deny "UKit could not fully read this tool-call payload (stdin staging was cut at the deadline/size bound) and the tool name could not be recovered, so context hard-cap gate cannot prove it safe."
36
+ printf '%s\n' '{"systemMessage":"UKit context hard-cap gate: payload truncated and tool name unrecoverable; this call proceeded without the context check."}'
37
+ exit 0
58
38
  fi
59
39
  fi
60
40
  else
@@ -89,12 +69,7 @@ else
89
69
  # path's ukit_emit_input_degraded.
90
70
  rm -f "$UKIT_INPUT_FILE"
91
71
  UKIT_INPUT_FILE=""
92
- # TASK-223 + TASK-003: same emit shape as ukit_emit_permission_decision —
93
- # exit 0 on the direct host (non-zero discards stdout there), exit 2 inside
94
- # the omp chain. `deny`, never `ask`: bypassPermissions auto-approves ask.
95
- printf '%s\n' '{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"deny","permissionDecisionReason":"UKit could not fully read this tool-call payload (stdin staging was cut at the deadline/size bound), so context hard-cap gate cannot prove it safe."}}'
96
- echo "BLOCKED: context hard-cap gate could not inspect a truncated/stalled payload; refused fail-closed." >&2
97
- if [ -n "${UKIT_HOOK_CHAIN_RUNNER:-}" ]; then exit 2; fi
72
+ printf '%s\n' '{"systemMessage":"UKit context hard-cap gate: payload truncated/stalled; this call proceeded without the context check."}'
98
73
  exit 0
99
74
  fi
100
75
  trap '[ -n "$UKIT_INPUT_FILE" ] && rm -f "$UKIT_INPUT_FILE"' EXIT
@@ -146,23 +121,6 @@ async function pathExists(filePath) {
146
121
  }
147
122
  }
148
123
 
149
- // An unfinished handoff run — same cursor file the resume hook and the advisory
150
- // context guard read. `Phase: done` and `Phase: blocked` are both terminal (the
151
- // same posture stop-coordinator.mjs uses); only other phases mean a run is in flight.
152
- async function readRunCursor() {
153
- try {
154
- const text = await fsp.readFile(path.join(projectRoot, 'docs', 'AI_HANDOFF', 'RUN.md'), 'utf8');
155
- const runPhase = (text.match(/^Phase:\s*(.+)$/m)?.[1] || '').trim();
156
- if (!runPhase || /^(done|blocked)\b/i.test(runPhase)) return null;
157
- return {
158
- phase: runPhase,
159
- cursor: (text.match(/^Cursor:\s*(.+)$/m)?.[1] || '').trim(),
160
- };
161
- } catch {
162
- return null;
163
- }
164
- }
165
-
166
124
  (async () => {
167
125
  let rawInput = '';
168
126
  try { rawInput = await fsp.readFile(process.env.INPUT_FILE || '', 'utf8'); } catch {}
@@ -220,10 +178,6 @@ async function readRunCursor() {
220
178
  }
221
179
 
222
180
  const mod = await import(pathToFileURL(thresholdModulePath).href);
223
- const ledgerModulePath = path.join(hookDir, '..', 'ukit', 'runtime', 'execution-ledger.mjs');
224
- const ledgerMod = (await pathExists(ledgerModulePath))
225
- ? await import(pathToFileURL(ledgerModulePath).href)
226
- : null;
227
181
  const pressurePath = path.join(projectRoot, '.ukit', 'storage', 'cache', 'compact-pressure.json');
228
182
  const rawState = await readJsonSafe(pressurePath, null);
229
183
 
@@ -251,178 +205,36 @@ async function readRunCursor() {
251
205
  // the gate is fail-closed, so it must read the same evidence the guard wrote.
252
206
  const thresholds = await mod.buildCompactThresholds({ ...config, projectRoot });
253
207
 
254
- // The grace budget must survive parallel subagents hitting the cap in the same episode.
255
- // A read-modify-write of one JSON file under-counts (two processes both read used=3 and
256
- // both write 4, silently multiplying the budget), so each spent call is claimed with an
257
- // exclusive-create sentinel file (openSync 'wx'): the sentinels present ARE the number
258
- // of grace calls spent, and one claim can never be counted twice.
259
- // Grace is a landing allowance for THIS session's over-cap episode. The old global
260
- // `hardcap-grace.json.N` slot pool let session A consume session B's allowance (and A
261
- // clearing it refilled B's spent pool), so parallel sessions could be hard-blocked mid-
262
- // landing for no reason. Keep the fallback `default` for hosts that omit session_id: in
263
- // that legacy shape sibling workers still deliberately share one bounded allowance.
264
- const rawGraceSessionId = typeof payload.session_id === 'string' && payload.session_id.trim()
208
+ // Advisory only: this gate NEVER blocks. Context compaction is a reminder — the host
209
+ // auto-compacts by itself and work resumes from docs/STATUS.md. Cooldown state is a
210
+ // per-session file so parallel sessions do not silence each other.
211
+ const rawSessionId = typeof payload.session_id === 'string' && payload.session_id.trim()
265
212
  ? payload.session_id.trim()
266
213
  : 'default';
267
- const graceSessionKey = rawGraceSessionId.replace(/[^a-zA-Z0-9._-]/g, '_').slice(0, 96) || 'default';
268
- const graceDir = path.join(projectRoot, '.ukit', 'storage', 'cache');
269
- const graceBaseName = `hardcap-grace.${graceSessionKey}.json`;
270
- const gracePath = path.join(graceDir, graceBaseName);
271
- const slotPath = (n) => path.join(graceDir, `${graceBaseName}.${n}`);
272
- const slotPattern = new RegExp(`^${graceBaseName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\.(\\d+)$`);
273
- const readSlots = async () => {
274
- try {
275
- return (await fsp.readdir(graceDir))
276
- .map((name) => slotPattern.exec(name))
277
- .filter(Boolean)
278
- .map((m) => Number(m[1]))
279
- .sort((a, b) => a - b);
280
- } catch {
281
- return [];
282
- }
283
- };
284
- const clearGrace = async () => {
285
- try { await fsp.rm(gracePath, { force: true }); } catch { /* advisory only */ }
286
- for (const n of await readSlots()) {
287
- try { await fsp.rm(slotPath(n), { force: true }); } catch { /* advisory only */ }
288
- }
289
- };
214
+ const sessionKey = rawSessionId.replace(/[^a-zA-Z0-9._-]/g, '_').slice(0, 96) || 'default';
215
+ const advisoryPath = path.join(projectRoot, '.ukit', 'storage', 'cache', `hardcap-grace.${sessionKey}.json`);
216
+ const COOLDOWN_MS = 10 * 60 * 1000;
290
217
 
291
218
  if (state.estimatedTotalTokens < thresholds.hardCapTokens) {
292
- // Back under the cap — the episode is over, so the next one starts with a full budget.
293
- await clearGrace();
219
+ // Back under the cap — the next over-cap episode advises again.
220
+ try { await fsp.rm(advisoryPath, { force: true }); } catch { /* advisory only */ }
294
221
  process.exit(0);
295
222
  return;
296
223
  }
297
224
 
298
- const run = await readRunCursor();
299
- let ordinaryTask = null;
300
- if (!run && ledgerMod) {
301
- try {
302
- ordinaryTask = await ledgerMod.readResumableExecution(projectRoot, payload);
303
- } catch {
304
- ordinaryTask = null;
305
- }
306
- }
307
- const resumable = run || ordinaryTask;
308
- if (resumable) {
309
- // Invalid config must not turn the landing allowance negative/zero (which makes every
310
- // unfinished run hard-block immediately). This hook is a liveness backstop, so malformed
311
- // values deliberately fall back to the documented default rather than fail closed.
312
- const configuredGraceCalls = config?.compact?.hardCapGraceCalls;
313
- const graceCalls = typeof configuredGraceCalls === 'number'
314
- && Number.isFinite(configuredGraceCalls)
315
- && Number.isInteger(configuredGraceCalls)
316
- && configuredGraceCalls > 0
317
- ? configuredGraceCalls
318
- : 10;
319
-
320
- let slots = await readSlots();
321
- let startedAtTokens = null;
322
- for (const n of slots) {
323
- const data = await readJsonSafe(slotPath(n), null);
324
- if (data && Number.isFinite(data.startedAtTokens)) {
325
- startedAtTokens = Math.max(startedAtTokens ?? -Infinity, data.startedAtTokens);
326
- }
327
- }
328
- // Reset only when the estimate actually fell since grace started: that is the signal a
329
- // real compaction/shed happened. Advancing the cursor alone must NOT top the budget up,
330
- // otherwise a long run gets unlimited grace and the ceiling stops meaning anything.
331
- if (startedAtTokens !== null && state.estimatedTotalTokens < startedAtTokens) {
332
- await clearGrace();
333
- slots = [];
334
- startedAtTokens = null;
335
- }
336
- const spent = slots.length > 0 ? slots[slots.length - 1] : 0;
337
- if (startedAtTokens === null) startedAtTokens = state.estimatedTotalTokens;
338
-
339
- if (spent < graceCalls) {
340
- // Claim the next slot atomically: EEXIST means a parallel worker already claimed it,
341
- // step to the next. A filesystem error keeps the old fail-open behavior — losing the
342
- // counter must never block a landing — at the cost of one extra granted call.
343
- let used = 0;
344
- let counterFailed = false;
345
- try {
346
- await fsp.mkdir(graceDir, { recursive: true });
347
- for (let n = spent + 1; n <= graceCalls; n += 1) {
348
- try {
349
- // Exclusive-create via 'wx' keeps the EEXIST race semantics of the old
350
- // openSync('wx') claim: the sentinel exists exactly once per spent call.
351
- const handle = await fsp.open(slotPath(n), 'wx');
352
- try {
353
- await handle.writeFile(JSON.stringify({ startedAtTokens, used: n, ts: Date.now() }));
354
- } finally {
355
- await handle.close();
356
- }
357
- used = n;
358
- break;
359
- } catch (err) {
360
- if (err?.code === 'EEXIST') continue;
361
- throw err;
362
- }
363
- }
364
- } catch {
365
- counterFailed = true;
366
- }
367
- if (used === 0 && counterFailed) used = spent + 1;
368
- if (used > 0 && used <= graceCalls) {
369
- try {
370
- await fsp.writeFile(gracePath, JSON.stringify({ startedAtTokens, used }));
371
- if (ordinaryTask && ledgerMod && used === 1) {
372
- await ledgerMod.writeResumeIntent(projectRoot, payload);
373
- }
374
- } catch {
375
- // Losing the counter or advisory resume intent must not block the run.
376
- }
377
- const landing = run
378
- ? `An unfinished handoff run is in flight (Phase: ${run.phase}${run.cursor ? `, Cursor: ${run.cursor}` : ''}), so this call is allowed instead of stranding it mid-edit.`
379
- : 'An unfinished ordinary routed task is in flight, so this call is allowed instead of stranding it before compaction.';
380
- process.stderr.write(
381
- [
382
- `CONTEXT OVER CAP — grace ${used}/${graceCalls} (~${state.estimatedTotalTokens} tokens >= ${thresholds.hardCapTokens}).`,
383
- landing,
384
- run
385
- ? 'Spend the remaining grace on LANDING, not on new work: finish the current edit, commit, update docs/AI_HANDOFF/RUN.md, push.'
386
- : 'Spend the remaining grace on LANDING, not on new work: finish the current mutation or verification, then compact as soon as the host allows it.',
387
- 'Do NOT start a new task, open new files, or spawn agents. When grace runs out the gate blocks hard.',
388
- 'Tell the user in your reply that context is over the cap and they should run /compact as soon as this landing step is complete.',
389
- 'After compaction, the SessionStart resume hook replays the safe cursor and the task continues automatically.',
390
- ].join('\n') + '\n',
391
- );
392
- // The stderr contract above only reaches the model — if the turn dies before the
393
- // model relays it, the user sees nothing. Mirror the first grace call as a
394
- // structured systemMessage so the /compact advice is user-visible regardless.
395
- if (used === 1) {
396
- process.stdout.write(`${JSON.stringify({
397
- systemMessage: `UKit: context is over the hard cap (~${state.estimatedTotalTokens} tokens). A short landing window (${graceCalls} calls) is active — run /compact when it ends; the task resumes automatically after compaction.`,
398
- })}\n`);
399
- }
400
- process.exit(0);
401
- return;
402
- }
403
- // Every slot was claimed while we raced — the budget is genuinely spent; fall
404
- // through to the hard block below.
405
- }
225
+ const last = await readJsonSafe(advisoryPath, null);
226
+ if (last && Number.isFinite(last.ts) && Date.now() - last.ts >= 0 && Date.now() - last.ts < COOLDOWN_MS) {
227
+ process.exit(0);
228
+ return;
406
229
  }
407
-
408
- const lines = [
409
- `BLOCKED (context hard cap): estimated context ~${state.estimatedTotalTokens} tokens >= hard cap ${thresholds.hardCapTokens}.`,
410
- 'FIRST ACTION IN YOUR REPLY — tell the user plainly, do not just stop silently: "Context đã đầy — hãy gõ /compact ngay (run /compact now)".',
411
- 'Typing "continue" alone will hit this same block; only /compact (or a new session) resets the counter. After compacting, resume the interrupted task.',
412
- 'This is an absolute ceiling (compact.hardCapTokens), separate from the soft/hard advisory phases — those were apparently not followed.',
413
- `Edit/Write/Bash refused (tool_name=${toolName}) until real compaction happens.`,
414
- resumable
415
- ? 'The unfinished-run grace window (compact.hardCapGraceCalls) is already exhausted — progress should be committed and the cursor written by now.'
416
- : 'No resumable unfinished routed task was found, so there is no grace window to spend.',
417
- 'Do not work around this by summarizing inline and continuing, and do not reach for a non-gated write tool.',
418
- ];
419
- process.stderr.write(`${lines.join('\n')}\n`);
420
- // stderr reaches the model, not reliably the user. Pair the hard block with a
421
- // structured systemMessage so "why did it stop" always has a user-visible answer.
230
+ try {
231
+ await fsp.mkdir(path.dirname(advisoryPath), { recursive: true });
232
+ await fsp.writeFile(advisoryPath, JSON.stringify({ ts: Date.now(), tokens: state.estimatedTotalTokens }));
233
+ } catch { /* losing the cooldown only repeats the advisory */ }
422
234
  process.stdout.write(`${JSON.stringify({
423
- systemMessage: `UKit blocked ${toolName}: context is over the hard cap (~${state.estimatedTotalTokens} tokens >= ${thresholds.hardCapTokens}) and the landing window is spent. Run /compact now; after compaction the task continues automatically.`,
235
+ systemMessage: `UKit: context is large (~${state.estimatedTotalTokens} tokens >= ${thresholds.hardCapTokens}). Keep working — nothing is blocked. Land the current step, persist the remaining steps to docs/STATUS.md, delegate broad reads to subagents, and let the host auto-compact; work resumes from docs/STATUS.md.`,
424
236
  })}\n`);
425
- process.exit(2);
237
+ process.exit(0);
426
238
  })().catch((err) => {
427
239
  // A logic error here fails OPEN: this is a backstop on top of advisory nudges,
428
240
  // not a correctness gate — a broken gate must not brick every session.
@@ -431,7 +243,7 @@ async function readRunCursor() {
431
243
  process.stderr.write(`context-hardcap-gate: internal error, failing open: ${err?.message ?? err}\n`);
432
244
  try {
433
245
  process.stdout.write(`${JSON.stringify({
434
- systemMessage: `UKit context hard-cap gate: internal error (${String(err?.message ?? err).slice(0, 200)}) — the gate failed open and did NOT enforce the hard cap this call; run: ukit install to repair.`,
246
+ systemMessage: `UKit context hard-cap gate: internal error (${String(err?.message ?? err).slice(0, 200)}) — the gate failed open and did NOT run the context advisory this call; run: ukit install to repair.`,
435
247
  })}\n`);
436
248
  } catch {}
437
249
  process.exit(0);
@@ -440,11 +252,9 @@ NODE
440
252
 
441
253
  NODE_RC=$?
442
254
  # Fail-open parity with the in-block catch and the deadline path: a node crash
443
- # (missing runtime, OOM, preload failure) means the cap was never evaluated —
444
- # announce the degrade (SPEC §8) and release, never a silent non-blocking hook
445
- # error. Exit 2 (a real hard-cap block) passes through untouched.
446
- if [ "$NODE_RC" -ne 0 ] && [ "$NODE_RC" -ne 2 ]; then
447
- printf '%s\n' '{"systemMessage":"UKit context hard-cap gate: evaluation crashed before finishing; this tool call proceeded without the hard-cap check. Run `ukit install` if this repeats."}'
255
+ # means the advisory was never evaluated — announce the degrade (SPEC §8) and release.
256
+ if [ "$NODE_RC" -ne 0 ]; then
257
+ printf '%s\n' '{"systemMessage":"UKit context hard-cap gate: evaluation crashed before finishing; this tool call proceeded without the context check. Run `ukit install` if this repeats."}'
448
258
  exit 0
449
259
  fi
450
- exit "$NODE_RC"
260
+ exit 0
@@ -438,7 +438,7 @@ if (withinCooldown) {
438
438
  lines_out.push('1) LAND ONE THING: pick the smallest in-flight item you can finish end-to-end in ≤3 tool calls (edit + verify), complete exactly that one, and report it done. Do not open anything new.');
439
439
  lines_out.push('2) DEFER THE REST: write each remaining step as one line into docs/STATUS.md (update-status skill), or split what remains into bounded docs/AI_HANDOFF tasks — a fresh context then continues from disk without re-reading this thread.');
440
440
  lines_out.push('3) DELEGATE anything broad that must still run (searches, big reads, multi-file edits) to subagents instead of doing it inline — their tool output stays in their own windows, not this one.');
441
- lines_out.push('4) Then make the user\'s next action the FIRST sentence of your reply: "Context sắp đầy — gõ /compact ngay (run /compact now)". After /compact UKit auto-resumes from disk; if the compacted session is still large, ask for a fresh session instead. Do not keep working silently until tools start being refused.');
441
+ lines_out.push('4) Then KEEP WORKING on the task — do NOT end your turn to ask the user to /compact. The host auto-compacts when the window fills and UKit resumes from docs/STATUS.md; a stop that only asks for /compact is a stalled run. Mention the context pressure in one line at your next natural report, never as the reason to stop.');
442
442
  if (sidechainEntries > 0) {
443
443
  lines_out.push(`Note: ${sidechainEntries} subagent entries in this stretch — each teammate carries its own context window, and every finished report is injected back here, so running many at once is the fastest way to overflow this session. Avoid spawning more until context drops back under the cap.`);
444
444
  }