@ngockhoale/ukit 3.5.15 → 3.5.18

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 (77) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/manifests/platform.full.yaml +48 -0
  3. package/package.json +2 -1
  4. package/scripts/release/heavy-first.mjs +12 -0
  5. package/scripts/release/release-steps.mjs +7 -4
  6. package/scripts/release/run-core-batch.mjs +50 -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/diagnostics/routeOutcomes.js +5 -1
  15. package/src/diagnostics/skillAccuracy.js +5 -2
  16. package/src/render/buildVariables.js +2 -5
  17. package/template_project/.claude/commands/ukit/handoff-implement.md +3 -3
  18. package/template_project/.claude/commands/ukit/handoff-review.md +3 -3
  19. package/template_project/.claude/hooks/context-hardcap-gate.sh +47 -20
  20. package/template_project/.claude/hooks/context-window-guard.sh +82 -27
  21. package/template_project/.claude/hooks/delegation-gate.mjs +1 -1
  22. package/template_project/.claude/hooks/handoff-resume.sh +11 -2
  23. package/template_project/.claude/hooks/mission-capture.mjs +37 -0
  24. package/template_project/.claude/hooks/post-compact-observe.mjs +34 -0
  25. package/template_project/.claude/hooks/shell-watch.mjs +34 -0
  26. package/template_project/.claude/hooks/skill-router.sh +13 -0
  27. package/template_project/.claude/hooks/stop-failure-rescue.mjs +109 -0
  28. package/template_project/.claude/settings.json +36 -4
  29. package/template_project/.claude/skills/backend-api/SKILL.md +1 -1
  30. package/template_project/.claude/skills/delivery/SKILL.md +1 -1
  31. package/template_project/.claude/skills/docs-manager/SKILL.md +1 -1
  32. package/template_project/.claude/skills/duraone/SKILL.md +2 -1
  33. package/template_project/.claude/skills/file-organizer/SKILL.md +1 -1
  34. package/template_project/.claude/skills/frontend/SKILL.md +1 -1
  35. package/template_project/.claude/skills/frontend-vue/SKILL.md +1 -1
  36. package/template_project/.claude/skills/pdf-processing/SKILL.md +1 -1
  37. package/template_project/.claude/skills/postgres/SKILL.md +1 -1
  38. package/template_project/.claude/skills/testing-quality/SKILL.md +2 -0
  39. package/template_project/.claude/skills/webapp-testing/SKILL.md +1 -1
  40. package/template_project/.claude/ukit/index/route-task.mjs +3 -1
  41. package/template_project/.claude/ukit/index/tier-lane.mjs +1 -1
  42. package/template_project/.claude/ukit/runtime/compact-threshold.mjs +15 -29
  43. package/template_project/.claude/ukit/runtime/context-capacity.mjs +64 -1
  44. package/template_project/.claude/ukit/runtime/execution-ledger.mjs +107 -4
  45. package/template_project/.claude/ukit/runtime/hook-chain-runner.mjs +20 -1
  46. package/template_project/.claude/ukit/runtime/mission/checkpoint.mjs +85 -0
  47. package/template_project/.claude/ukit/runtime/mission/classify.mjs +182 -0
  48. package/template_project/.claude/ukit/runtime/mission/drift.mjs +58 -0
  49. package/template_project/.claude/ukit/runtime/mission/graph.mjs +381 -0
  50. package/template_project/.claude/ukit/runtime/mission/hooks.mjs +199 -0
  51. package/template_project/.claude/ukit/runtime/mission/journal.mjs +68 -0
  52. package/template_project/.claude/ukit/runtime/mission/metrics.mjs +64 -0
  53. package/template_project/.claude/ukit/runtime/mission/recall.mjs +132 -0
  54. package/template_project/.claude/ukit/runtime/mission/redact.mjs +25 -0
  55. package/template_project/.claude/ukit/runtime/mission/restore.mjs +107 -0
  56. package/template_project/.claude/ukit/runtime/mission/store.mjs +231 -0
  57. package/template_project/.claude/ukit/runtime/mission/working.mjs +88 -0
  58. package/template_project/.claude/ukit/runtime/prompt-injection-cap.mjs +33 -0
  59. package/template_project/.claude/ukit/runtime/reinject-context.mjs +87 -6
  60. package/template_project/.claude/ukit/runtime/rescue/bundle.mjs +122 -0
  61. package/template_project/.claude/ukit/runtime/rescue/classify-failure.mjs +136 -0
  62. package/template_project/.claude/ukit/runtime/rescue/lease.mjs +65 -0
  63. package/template_project/.claude/ukit/runtime/rescue/reconstruct.mjs +273 -0
  64. package/template_project/.claude/ukit/runtime/rescue/recovery-state.mjs +120 -0
  65. package/template_project/.claude/ukit/runtime/rescue/rollover.mjs +151 -0
  66. package/template_project/.claude/ukit/runtime/sensitive-value-scanner.mjs +1 -1
  67. package/template_project/.claude/ukit/runtime/shell-watch.mjs +278 -0
  68. package/template_project/.claude/ukit/runtime/stop-coordinator.mjs +154 -0
  69. package/template_project/.omp/RULES.md +1 -1
  70. package/template_project/.omp/config.yml +2 -2
  71. package/template_project/.omp/hooks/pre/ukit-bridge.js +69 -2
  72. package/template_project/AGENTS.md +5 -1
  73. package/template_project/CLAUDE.md +5 -1
  74. package/template_project/docs/AI_HANDOFF/RULES.md +4 -4
  75. package/template_project/instructions/core.md +5 -1
  76. package/template_project/instructions/overlays/omp-rules.md +1 -1
  77. package/template_project/ukit/storage/config.json +32 -10
@@ -5,11 +5,10 @@ import {
5
5
  readContextCapacityRecord,
6
6
  SOFT_TO_CAP_RATIO,
7
7
  } from '../../../template_project/.claude/ukit/runtime/compact-threshold.mjs';
8
- import { resolveContextCapTokens } from '../../../template_project/.claude/ukit/runtime/context-capacity.mjs';
8
+ import { resolveContextCapTokens, resolveContextTiers } from '../../../template_project/.claude/ukit/runtime/context-capacity.mjs';
9
9
  import { buildRuntimePaths } from '../runtimePaths.js';
10
10
  import { buildCompactMachineKey, compressLine, estimateTokenCount } from '../token/index.js';
11
11
  import { compactContextBlock } from './index.js';
12
- import { loadShippedCompactBudget } from './contextBudget.js';
13
12
 
14
13
  const DEFAULT_MAX_PROMPT_ENTRIES = 12;
15
14
  const DEFAULT_MAX_OUTPUT_ENTRIES = 12;
@@ -458,40 +457,27 @@ async function readNegotiatedCapacity(config = {}) {
458
457
  }
459
458
 
460
459
  export async function buildCompactThresholds(config = {}) {
461
- const shippedHardCap = positiveInteger(
462
- config?.compact?.hardCapTokens,
463
- loadShippedCompactBudget().hardCapTokens,
464
- );
465
- // Upgrade safety: an install that predates compact.contextWindowTokens still carries the
466
- // old 500k hard cap; the cap must never sit above the declared window it guards.
467
- const declaredWindow = positiveInteger(config?.compact?.contextWindowTokens, 0);
468
- const effectiveShippedHardCap = declaredWindow > 0 ? Math.min(shippedHardCap, declaredWindow) : shippedHardCap;
469
- const explicitSoftThreshold = finiteNumber(config?.compact?.tokenThreshold, 0);
470
- // Negotiated capacity (H22): the guard publishes what it derived from the live route and
471
- // this shared path consumes it; without a record the shipped tuning applies unchanged.
472
- const negotiated = await readNegotiatedCapacity(config);
473
- const hardCapTokens = negotiated
474
- ? Math.max(1, Math.min(effectiveShippedHardCap, negotiated.capTokens))
475
- : effectiveShippedHardCap;
476
- // An explicit operator tokenThreshold is honoured but still clamped under the
477
- // negotiated cap: an advisory soft/hard pair sitting at or above hardCapTokens can
478
- // never fire, because context-hardcap-gate.sh already refuses tools at the cap
479
- // (C92-H-01 — on a default install tokenThreshold is the shipped 150k default, not a
480
- // real operator choice, so this is correcting a number, not overriding intent).
481
- const softThreshold = explicitSoftThreshold > 0
482
- ? Math.max(1, Math.min(explicitSoftThreshold, hardCapTokens - 1))
483
- : Math.max(1, Math.round(hardCapTokens * SOFT_TO_CAP_RATIO));
460
+ // UKit-owned tiers (compact.bestTokens/okTokens/mandatoryTokens/stopTokens, legacy
461
+ // hardCapTokens -> stopTokens, tokenThreshold -> bestTokens). They are deliberately NOT
462
+ // clamped to contextWindowTokens or the negotiated model window: the tiers are UKit
463
+ // policy, and the host auto-compaction window (rendered separately) keeps sessions below
464
+ // stopTokens. The capacity record is still read for diagnostics only.
465
+ const tiers = resolveContextTiers(config);
466
+ const hardCapTokens = tiers.stopTokens;
467
+ const softThreshold = Math.max(1, Math.min(tiers.bestTokens, hardCapTokens - 1));
484
468
  const hardThreshold = Math.min(
485
469
  hardCapTokens,
486
470
  Math.max(softThreshold + 1, Math.round(softThreshold * 1.6)),
487
471
  );
488
472
  const baselineTokens = Math.max(120, Math.min(18_000, Math.round(softThreshold * 0.18)));
473
+ const negotiated = await readNegotiatedCapacity(config);
489
474
 
490
475
  return {
491
476
  softThreshold,
492
477
  hardThreshold,
493
478
  baselineTokens,
494
479
  hardCapTokens,
480
+ tiers,
495
481
  capacitySource: negotiated?.capacity?.source ?? 'shipped',
496
482
  capacityTokens: negotiated?.capacity?.tokens ?? null,
497
483
  };
@@ -689,13 +675,9 @@ export async function buildCompactPressureState(rawState = null, config = {}) {
689
675
  const thresholds = await buildCompactThresholds(config);
690
676
  const rawSoftThreshold = finiteNumber(rawState?.softThreshold, 0);
691
677
  const rawHardThreshold = finiteNumber(rawState?.hardThreshold, 0);
692
- if (!finiteNumber(config?.compact?.tokenThreshold, 0) && rawSoftThreshold > 0) {
693
- // A persisted pair is only honoured while it still sits inside the negotiated cap.
694
- // The record outlives capacity negotiation: an install that ran before the record
695
- // existed, or before the model was verified, carries thresholds tuned for the
696
- // shipped 500k ceiling — restoring them re-pins the advisory ABOVE the live
697
- // hardCapTokens forever (C92-H-02). Falling through keeps the freshly derived
698
- // pair, which is also what the rewritten record persists, so the file self-heals.
678
+ if (!finiteNumber(config?.compact?.tokenThreshold, 0) && !finiteNumber(config?.compact?.bestTokens, 0) && rawSoftThreshold > 0) {
679
+ // A persisted pair is honoured only while it sits strictly inside stopTokens, so a stale
680
+ // record can never pin the advisory at/above the stop line (C92-H-02).
699
681
  if (rawSoftThreshold < thresholds.hardCapTokens) {
700
682
  thresholds.softThreshold = rawSoftThreshold;
701
683
  thresholds.hardThreshold = Math.min(
@@ -380,6 +380,97 @@ export const REASON_CODES = Object.freeze({
380
380
  deprecated: null,
381
381
  privacy_class: 'internal',
382
382
  },
383
+ CONTEXT_PRESSURE_DETECTED: {
384
+ definition: "Context usage crossed the rescue pressure threshold.",
385
+ unit: null,
386
+ introduced_version: V1_3,
387
+ deprecated: null,
388
+ privacy_class: 'internal',
389
+ },
390
+ CHECKPOINT_SAVED: {
391
+ definition: "A mission checkpoint was persisted before compaction or rollover.",
392
+ unit: null,
393
+ introduced_version: V1_3,
394
+ deprecated: null,
395
+ privacy_class: 'internal',
396
+ },
397
+ COMPACT_STARTED: {
398
+ definition: "A compaction began.",
399
+ unit: null,
400
+ introduced_version: V1_3,
401
+ deprecated: null,
402
+ privacy_class: 'internal',
403
+ },
404
+ COMPACT_SUCCEEDED: {
405
+ definition: "A compaction finished successfully.",
406
+ unit: null,
407
+ introduced_version: V1_3,
408
+ deprecated: null,
409
+ privacy_class: 'internal',
410
+ },
411
+ COMPACT_FAILED: {
412
+ definition: "A compaction failed; payload carries the redacted failure fingerprint.",
413
+ unit: null,
414
+ introduced_version: V1_3,
415
+ deprecated: null,
416
+ privacy_class: 'internal',
417
+ },
418
+ RECOVERY_STARTED: {
419
+ definition: "The rescue supervisor began recovery outside the failed session.",
420
+ unit: null,
421
+ introduced_version: V1_3,
422
+ deprecated: null,
423
+ privacy_class: 'internal',
424
+ },
425
+ OFFLINE_CONTEXT_REBUILT: {
426
+ definition: "The restore bundle was rebuilt offline from durable records.",
427
+ unit: null,
428
+ introduced_version: V1_3,
429
+ deprecated: null,
430
+ privacy_class: 'internal',
431
+ },
432
+ SESSION_ROLLOVER_STARTED: {
433
+ definition: "A clean replacement session was requested for the mission.",
434
+ unit: null,
435
+ introduced_version: V1_3,
436
+ deprecated: null,
437
+ privacy_class: 'internal',
438
+ },
439
+ SESSION_ROLLOVER_SUCCEEDED: {
440
+ definition: "A replacement session process was started (not proof of progress).",
441
+ unit: null,
442
+ introduced_version: V1_3,
443
+ deprecated: null,
444
+ privacy_class: 'internal',
445
+ },
446
+ SESSION_RESTORED: {
447
+ definition: "The replacement session loaded the restore bundle.",
448
+ unit: null,
449
+ introduced_version: V1_3,
450
+ deprecated: null,
451
+ privacy_class: 'internal',
452
+ },
453
+ MISSION_CONTINUED: {
454
+ definition: "Evidence that the mission advanced in the replacement session.",
455
+ unit: null,
456
+ introduced_version: V1_3,
457
+ deprecated: null,
458
+ privacy_class: 'internal',
459
+ },
460
+ RECOVERY_BLOCKED: {
461
+ definition: "Recovery stopped on a terminal blocker (auth, owner STOP, open breaker).",
462
+ unit: null,
463
+ introduced_version: V1_3,
464
+ deprecated: null,
465
+ privacy_class: 'internal',
466
+ },
467
+ MISSION_COMPLETED_VERIFIED: {
468
+ definition: "The mission completed with valid acceptance evidence. Payloads are redacted.",
469
+ unit: null,
470
+ introduced_version: V1_3,
471
+ deprecated: null,
472
+ privacy_class: 'internal',
473
+ },
383
474
  });
384
475
 
385
476
  // Guard: registry privacy classes must stay inside the frozen vocabulary.
@@ -313,13 +313,27 @@ export function buildDefaultRuntimeConfig(overrides = {}) {
313
313
  affectVerification: true,
314
314
  affectDelegation: true,
315
315
  },
316
+ rescue: {
317
+ autoRollover: 'auto',
318
+ maxTurns: 40,
319
+ },
320
+ shellWatch: {
321
+ enabled: true,
322
+ staleMinutes: 20,
323
+ autoKillSelfMatchingLoops: true,
324
+ },
316
325
  security: {
317
326
  sensitiveDataGate: true,
318
327
  allowlistPath: '.ukit/storage/security/allowlist.json',
319
328
  },
320
329
  compact: {
321
330
  enabled: true,
322
- tokenThreshold: loadShippedCompactBudget().tokenThreshold,
331
+ bestTokens: loadShippedCompactBudget().bestTokens,
332
+ okTokens: loadShippedCompactBudget().okTokens,
333
+ mandatoryTokens: loadShippedCompactBudget().mandatoryTokens,
334
+ stopTokens: loadShippedCompactBudget().stopTokens,
335
+ maxPromptInjectionChars: 4000,
336
+ gatewayLimitTokens: null,
323
337
  contextRotDetection: true,
324
338
  askBeforeDrop: true,
325
339
  agentContext: {
@@ -717,6 +731,16 @@ export function validateRuntimeConfig(config) {
717
731
  pushBooleanError(errors, config.autonomy.affectDelegation, 'autonomy.affectDelegation');
718
732
  }
719
733
 
734
+ if (config.shellWatch !== undefined) {
735
+ if (!isPlainObject(config.shellWatch)) {
736
+ errors.push('shellWatch must be an object.');
737
+ } else {
738
+ pushBooleanError(errors, config.shellWatch.enabled, 'shellWatch.enabled');
739
+ pushPositiveNumberError(errors, config.shellWatch.staleMinutes, 'shellWatch.staleMinutes');
740
+ pushBooleanError(errors, config.shellWatch.autoKillSelfMatchingLoops, 'shellWatch.autoKillSelfMatchingLoops');
741
+ }
742
+ }
743
+
720
744
  if (!isPlainObject(config.security)) {
721
745
  errors.push('security must be an object.');
722
746
  } else {
@@ -728,11 +752,38 @@ export function validateRuntimeConfig(config) {
728
752
  errors.push(`agent must be one of: ${[...VALID_AGENTS].join(', ')}.`);
729
753
  }
730
754
 
755
+ if (config.rescue !== undefined) {
756
+ if (!isPlainObject(config.rescue)) {
757
+ errors.push('rescue must be an object.');
758
+ } else {
759
+ if (config.rescue.autoRollover !== undefined && !['auto', 'on', 'off'].includes(config.rescue.autoRollover)) {
760
+ errors.push("rescue.autoRollover must be one of: auto, on, off.");
761
+ }
762
+ if (config.rescue.maxTurns !== undefined) pushPositiveNumberError(errors, config.rescue.maxTurns, 'rescue.maxTurns');
763
+ }
764
+ }
765
+
731
766
  if (!isPlainObject(config.compact)) {
732
767
  errors.push('compact must be an object.');
733
768
  } else {
734
769
  pushBooleanError(errors, config.compact.enabled, 'compact.enabled');
735
- pushPositiveNumberError(errors, config.compact.tokenThreshold, 'compact.tokenThreshold');
770
+ for (const key of ['bestTokens', 'okTokens', 'mandatoryTokens', 'stopTokens']) {
771
+ pushPositiveNumberError(errors, config.compact[key], `compact.${key}`);
772
+ }
773
+ // Legacy keys (tokenThreshold -> bestTokens, hardCapTokens -> stopTokens) stay optional.
774
+ for (const key of ['tokenThreshold', 'hardCapTokens']) {
775
+ if (config.compact[key] !== undefined) {
776
+ pushPositiveNumberError(errors, config.compact[key], `compact.${key}`);
777
+ }
778
+ }
779
+ // Optional real gateway context limit (null = unset); caps the host auto-compact window.
780
+ if (config.compact.gatewayLimitTokens !== undefined && config.compact.gatewayLimitTokens !== null) {
781
+ pushPositiveNumberError(errors, config.compact.gatewayLimitTokens, 'compact.gatewayLimitTokens');
782
+ }
783
+ // Aggregate UserPromptSubmit additionalContext cap (hook-chain-runner); optional for older configs.
784
+ if (config.compact.maxPromptInjectionChars !== undefined) {
785
+ pushPositiveNumberError(errors, config.compact.maxPromptInjectionChars, 'compact.maxPromptInjectionChars');
786
+ }
736
787
  pushBooleanError(errors, config.compact.contextRotDetection, 'compact.contextRotDetection');
737
788
  pushBooleanError(errors, config.compact.askBeforeDrop, 'compact.askBeforeDrop');
738
789
  if (!isPlainObject(config.compact.agentContext)) {
@@ -123,7 +123,11 @@ export async function collectRouteOutcomes(projectRoot, { limitLedgers = 500 } =
123
123
  const cacheDir = path.join(projectRoot, '.ukit', 'storage', 'cache');
124
124
  // BL-004: rows evicted past the 40-entry ring cap spill to the segments
125
125
  // sidecar — they must still reach the join or coverage silently decays.
126
- const segmentEntries = await readJsonLines(path.join(cacheDir, SEGMENTS_REL));
126
+ // Field #8: the sidecar rotates to `.1` past its size cap — older generation first.
127
+ const segmentEntries = [
128
+ ...await readJsonLines(path.join(cacheDir, `${SEGMENTS_REL}.1`)),
129
+ ...await readJsonLines(path.join(cacheDir, SEGMENTS_REL)),
130
+ ];
127
131
  const auditDoc = await readJson(path.join(cacheDir, 'route-audit.json'));
128
132
  const auditEntries = Array.isArray(auditDoc?.entries) ? auditDoc.entries : [];
129
133
 
@@ -161,8 +161,11 @@ export async function collectSkillAccuracy(projectRoot, { limitLedgers = 500 } =
161
161
  : [];
162
162
  // BL-004: rows evicted past the ring cap live in the segments sidecar —
163
163
  // they still carry skillIds and must reach the join.
164
- const segmentEntries = (await readJsonLines(path.join(projectRoot, SEGMENTS_REL)))
165
- .filter(isObject);
164
+ // Field #8: the sidecar rotates to `.1` past its size cap — older generation first.
165
+ const segmentEntries = [
166
+ ...await readJsonLines(path.join(projectRoot, `${SEGMENTS_REL}.1`)),
167
+ ...await readJsonLines(path.join(projectRoot, SEGMENTS_REL)),
168
+ ].filter(isObject);
166
169
  result.auditRowsScanned = auditEntries.length + segmentEntries.length;
167
170
  // Dedupe on requestKey (newest wins, per collectRouteOutcomes): last write
168
171
  // wins, so scan oldest→newest — segments append oldest→newest (forward),
@@ -1,8 +1,5 @@
1
1
  import { loadShippedCompactBudget } from '../core/compact/contextBudget.js';
2
2
 
3
- // Starting omp compaction threshold; capped by the shared auto-compact window above.
4
- const OMP_COMPACTION_THRESHOLD_TOKENS = 90_000;
5
-
6
3
  const CODEGRAPH_SECTION = `
7
4
  ## CodeGraph Integration (active)
8
5
 
@@ -20,7 +17,7 @@ export function buildTemplateVariables({ projectContext, stackContext, packageVe
20
17
  // Derived, never hand-written: .claude/settings.json is read by Claude Code itself and so
21
18
  // cannot consult .ukit/storage/config.json at runtime. Baking the window in here keeps
22
19
  // compact.hardCapTokens the single number that retunes both.
23
- const { autoCompactWindow, contextWindowTokens } = loadShippedCompactBudget();
20
+ const { autoCompactWindow, contextWindowTokens, ompCompactionThresholdTokens } = loadShippedCompactBudget();
24
21
 
25
22
  // FR-004 — fail closed: `allow` only on an explicit user opt-in
26
23
  // (`orchestration.allowUnsafeEval === true`). Missing, unreadable, or
@@ -80,7 +77,7 @@ export function buildTemplateVariables({ projectContext, stackContext, packageVe
80
77
  },
81
78
  omp: {
82
79
  evalApproval,
83
- compactionThresholdTokens: String(Math.min(OMP_COMPACTION_THRESHOLD_TOKENS, autoCompactWindow)),
80
+ compactionThresholdTokens: String(ompCompactionThresholdTokens),
84
81
  },
85
82
  codegraphSection: withCodegraph ? CODEGRAPH_SECTION : '',
86
83
  };
@@ -343,6 +343,6 @@ Blocked (needs you): <TASK-xxx — one-line reason> | none
343
343
 
344
344
  **Next:** switch to strong model → `/ukit:handoff-review`
345
345
 
346
- If this session is now heavy, this is the right moment to `/compact` — the wave commits,
347
- `INDEX.md` and `RUN.md` hold all the state the review phase needs. Suggest it here, at the
348
- command boundary, never inside a wave.
346
+ If this session is now heavy, keep going: the wave commits, `INDEX.md` and `RUN.md` hold all
347
+ the state the review phase needs, and the host auto-compacts. At most one trailing report line
348
+ may say `/compact` is advisable if context is still high after compaction — never stop for it.
@@ -264,10 +264,10 @@ Blocked (needs you): <TASK-xxx> | none
264
264
 
265
265
  Then, as the last line:
266
266
 
267
- > Cycle finished. Run `/compact` before starting the next cycle — this session carries the
268
- > whole review history and the next cycle deserves a clean window.
267
+ > Cycle finished. State is persisted (git, INDEX.md, RUN.md); the host auto-compacts and the
268
+ > next cycle resumes from disk. (Optional: `/compact` is advisable only if context is still high.)
269
269
 
270
- This is the only place this command may ask for a compaction. All state lives in git,
270
+ Never stop to ask for a compaction — at most this one trailing line. All state lives in git,
271
271
  `INDEX.md` and `RUN.md`, so a compacted or fresh session resumes with nothing lost.
272
272
 
273
273
  > Orchestrator (this session) handles Step 1, 2e, 2f, and 3 directly — those are not delegated.
@@ -1,14 +1,17 @@
1
1
  #!/bin/bash
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.
8
- #
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.
2
+ # PreToolUse hook: UKit-owned context tiers (compact.bestTokens/okTokens/mandatoryTokens/
3
+ # stopTokens = 100k/150k/200k/250k, independent of any model window; legacy hardCapTokens
4
+ # maps to stopTokens).
5
+ # < 150k silent here (the UserPromptSubmit guard owns the green/yellow lines)
6
+ # 150k - 200k orange advisory: land the item, persist, delegate, start nothing new
7
+ # 200k - 250k red advisory: over the mandatory line, persist now
8
+ # >= 250k STOP: BLOCKS new Edit/Write/Bash (exit 2) EXCEPT persist-to-disk writes
9
+ # (docs/STATUS.md, docs/AI_HANDOFF/**, .ukit/**). Compaction is always
10
+ # automatic: the host auto-compacts (window 180k, see contextBudget.js) and
11
+ # UKit restores the work, so the message never asks the user to /compact.
12
+ # Real compaction resets the tracked counter (PreCompact hook, or compact_boundary entries
13
+ # in the transcript), which releases the block. Config toggle: compact.hardCapBlock=false
14
+ # silences the gate entirely. Infrastructure failures stay fail-open.
12
15
 
13
16
  PROJECT_ROOT="${CLAUDE_PROJECT_DIR:-$PWD}"
14
17
  HOOK_DIR="$(cd "$(dirname "$0")" && pwd)"
@@ -205,9 +208,7 @@ async function pathExists(filePath) {
205
208
  // the gate is fail-closed, so it must read the same evidence the guard wrote.
206
209
  const thresholds = await mod.buildCompactThresholds({ ...config, projectRoot });
207
210
 
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
+ // Per-session cooldown file so parallel sessions do not silence each other.
211
212
  const rawSessionId = typeof payload.session_id === 'string' && payload.session_id.trim()
212
213
  ? payload.session_id.trim()
213
214
  : 'default';
@@ -215,25 +216,47 @@ async function pathExists(filePath) {
215
216
  const advisoryPath = path.join(projectRoot, '.ukit', 'storage', 'cache', `hardcap-grace.${sessionKey}.json`);
216
217
  const COOLDOWN_MS = 10 * 60 * 1000;
217
218
 
218
- if (state.estimatedTotalTokens < thresholds.hardCapTokens) {
219
- // Back under the cap — the next over-cap episode advises again.
219
+ const capacityModule = await import(pathToFileURL(path.join(hookDir, '..', 'ukit', 'runtime', 'context-capacity.mjs')).href);
220
+ const tiers = thresholds.tiers || capacityModule.resolveContextTiers(config);
221
+ const tier = capacityModule.classifyContextTier(state.estimatedTotalTokens, tiers);
222
+
223
+ if (tier === 'green' || tier === 'yellow') {
224
+ // Back under the orange zone - the next episode advises again.
220
225
  try { await fsp.rm(advisoryPath, { force: true }); } catch { /* advisory only */ }
221
226
  process.exit(0);
222
227
  return;
223
228
  }
224
229
 
230
+ const message = capacityModule.contextTierMessage(tier, state.estimatedTotalTokens, tiers);
231
+
232
+ if (tier === 'stop') {
233
+ // Persist-to-disk writes stay allowed so the session can land its state before the host
234
+ // auto-compaction fires.
235
+ const input = payload?.tool_input || {};
236
+ const target = String(input.file_path || input.notebook_path || '');
237
+ const rel = target ? path.relative(projectRoot, path.resolve(projectRoot, target)).split(path.sep).join('/') : '';
238
+ const persistWrite = toolName !== 'Bash' && rel && !rel.startsWith('..')
239
+ && /^(docs\/(STATUS|WORKLOG|TASKS)\.md|docs\/AI_HANDOFF\/|\.ukit\/)/.test(rel);
240
+ if (persistWrite) {
241
+ process.stdout.write(`${JSON.stringify({ systemMessage: message })}\n`);
242
+ process.exit(0);
243
+ return;
244
+ }
245
+ process.stderr.write(`${message}\nAllowed now: Write/Edit to docs/STATUS.md, docs/AI_HANDOFF/** or .ukit/**.\n`);
246
+ process.exit(2);
247
+ return;
248
+ }
249
+
225
250
  const last = await readJsonSafe(advisoryPath, null);
226
- if (last && Number.isFinite(last.ts) && Date.now() - last.ts >= 0 && Date.now() - last.ts < COOLDOWN_MS) {
251
+ if (last && last.tier === tier && Number.isFinite(last.ts) && Date.now() - last.ts >= 0 && Date.now() - last.ts < COOLDOWN_MS) {
227
252
  process.exit(0);
228
253
  return;
229
254
  }
230
255
  try {
231
256
  await fsp.mkdir(path.dirname(advisoryPath), { recursive: true });
232
- await fsp.writeFile(advisoryPath, JSON.stringify({ ts: Date.now(), tokens: state.estimatedTotalTokens }));
257
+ await fsp.writeFile(advisoryPath, JSON.stringify({ ts: Date.now(), tier, tokens: state.estimatedTotalTokens }));
233
258
  } catch { /* losing the cooldown only repeats the advisory */ }
234
- process.stdout.write(`${JSON.stringify({
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.`,
236
- })}\n`);
259
+ process.stdout.write(`${JSON.stringify({ systemMessage: message })}\n`);
237
260
  process.exit(0);
238
261
  })().catch((err) => {
239
262
  // A logic error here fails OPEN: this is a backstop on top of advisory nudges,
@@ -251,6 +274,10 @@ async function pathExists(filePath) {
251
274
  NODE
252
275
 
253
276
  NODE_RC=$?
277
+ # Exit 2 is the deliberate STOP-tier block (message already on stderr); pass it through.
278
+ if [ "$NODE_RC" -eq 2 ]; then
279
+ exit 2
280
+ fi
254
281
  # Fail-open parity with the in-block catch and the deadline path: a node crash
255
282
  # means the advisory was never evaluated — announce the degrade (SPEC §8) and release.
256
283
  if [ "$NODE_RC" -ne 0 ]; then