@ngockhoale/ukit 3.5.17 → 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.
- package/CHANGELOG.md +10 -0
- package/manifests/platform.full.yaml +48 -0
- package/package.json +1 -1
- package/src/cli/commands/mission.js +102 -0
- package/src/cli/commands/rescue.js +83 -0
- package/src/cli/index.js +14 -0
- package/src/core/compact/contextBudget.js +62 -41
- package/src/core/compact/threshold.js +14 -32
- package/src/core/observability/schema/registry.js +91 -0
- package/src/core/runtimeConfig.js +53 -2
- package/src/render/buildVariables.js +2 -5
- package/template_project/.claude/commands/ukit/handoff-implement.md +3 -3
- package/template_project/.claude/commands/ukit/handoff-review.md +3 -3
- package/template_project/.claude/hooks/context-hardcap-gate.sh +47 -20
- package/template_project/.claude/hooks/context-window-guard.sh +82 -27
- package/template_project/.claude/hooks/handoff-resume.sh +11 -2
- package/template_project/.claude/hooks/mission-capture.mjs +37 -0
- package/template_project/.claude/hooks/post-compact-observe.mjs +34 -0
- package/template_project/.claude/hooks/shell-watch.mjs +34 -0
- package/template_project/.claude/hooks/stop-failure-rescue.mjs +109 -0
- package/template_project/.claude/settings.json +36 -4
- package/template_project/.claude/ukit/runtime/compact-threshold.mjs +15 -29
- package/template_project/.claude/ukit/runtime/context-capacity.mjs +64 -1
- package/template_project/.claude/ukit/runtime/execution-ledger.mjs +44 -3
- package/template_project/.claude/ukit/runtime/hook-chain-runner.mjs +20 -1
- package/template_project/.claude/ukit/runtime/mission/checkpoint.mjs +85 -0
- package/template_project/.claude/ukit/runtime/mission/classify.mjs +182 -0
- package/template_project/.claude/ukit/runtime/mission/drift.mjs +58 -0
- package/template_project/.claude/ukit/runtime/mission/graph.mjs +381 -0
- package/template_project/.claude/ukit/runtime/mission/hooks.mjs +199 -0
- package/template_project/.claude/ukit/runtime/mission/journal.mjs +68 -0
- package/template_project/.claude/ukit/runtime/mission/metrics.mjs +64 -0
- package/template_project/.claude/ukit/runtime/mission/recall.mjs +132 -0
- package/template_project/.claude/ukit/runtime/mission/redact.mjs +25 -0
- package/template_project/.claude/ukit/runtime/mission/restore.mjs +107 -0
- package/template_project/.claude/ukit/runtime/mission/store.mjs +231 -0
- package/template_project/.claude/ukit/runtime/mission/working.mjs +88 -0
- package/template_project/.claude/ukit/runtime/prompt-injection-cap.mjs +33 -0
- package/template_project/.claude/ukit/runtime/reinject-context.mjs +87 -6
- package/template_project/.claude/ukit/runtime/rescue/bundle.mjs +122 -0
- package/template_project/.claude/ukit/runtime/rescue/classify-failure.mjs +136 -0
- package/template_project/.claude/ukit/runtime/rescue/lease.mjs +65 -0
- package/template_project/.claude/ukit/runtime/rescue/reconstruct.mjs +273 -0
- package/template_project/.claude/ukit/runtime/rescue/recovery-state.mjs +120 -0
- package/template_project/.claude/ukit/runtime/rescue/rollover.mjs +151 -0
- package/template_project/.claude/ukit/runtime/sensitive-value-scanner.mjs +1 -1
- package/template_project/.claude/ukit/runtime/shell-watch.mjs +278 -0
- package/template_project/.claude/ukit/runtime/stop-coordinator.mjs +154 -0
- package/template_project/.omp/config.yml +2 -2
- package/template_project/.omp/hooks/pre/ukit-bridge.js +69 -2
- package/template_project/AGENTS.md +3 -1
- package/template_project/CLAUDE.md +3 -1
- package/template_project/docs/AI_HANDOFF/RULES.md +4 -4
- package/template_project/instructions/core.md +3 -1
- package/template_project/ukit/storage/config.json +32 -10
|
@@ -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
|
-
|
|
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
|
-
|
|
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)) {
|
|
@@ -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(
|
|
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,
|
|
347
|
-
|
|
348
|
-
|
|
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.
|
|
268
|
-
>
|
|
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
|
-
|
|
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:
|
|
3
|
-
#
|
|
4
|
-
#
|
|
5
|
-
#
|
|
6
|
-
#
|
|
7
|
-
#
|
|
8
|
-
#
|
|
9
|
-
#
|
|
10
|
-
#
|
|
11
|
-
#
|
|
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
|
-
//
|
|
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
|
-
|
|
219
|
-
|
|
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
|
|
@@ -127,12 +127,18 @@ try {
|
|
|
127
127
|
} catch { /* fall through to the defaults */ }
|
|
128
128
|
if (!runtimeConfig || typeof runtimeConfig !== 'object') runtimeConfig = {};
|
|
129
129
|
|
|
130
|
-
//
|
|
131
|
-
//
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
130
|
+
// UKit-owned context tiers (compact.bestTokens/okTokens/mandatoryTokens/stopTokens =
|
|
131
|
+
// 100k/150k/200k/250k; legacy hardCapTokens -> stopTokens, tokenThreshold -> bestTokens).
|
|
132
|
+
// Resolved by context-capacity.mjs; the inline fallback keeps the shipped numbers when the
|
|
133
|
+
// runtime helper is missing (pre-install tree).
|
|
134
|
+
function inlineTiers() {
|
|
135
|
+
const c = runtimeConfig?.compact ?? {};
|
|
136
|
+
const pos = (v) => (typeof v === 'number' && Number.isInteger(v) && v > 0 ? v : null);
|
|
137
|
+
const stop = pos(c.hardCapTokens) ?? pos(c.stopTokens) ?? 250_000;
|
|
138
|
+
const mandatory = Math.min(pos(c.mandatoryTokens) ?? 200_000, stop);
|
|
139
|
+
const ok = Math.min(pos(c.okTokens) ?? 150_000, mandatory);
|
|
140
|
+
const best = Math.min(pos(c.tokenThreshold) ?? pos(c.bestTokens) ?? 100_000, ok);
|
|
141
|
+
return { bestTokens: best, okTokens: ok, mandatoryTokens: mandatory, stopTokens: stop };
|
|
136
142
|
}
|
|
137
143
|
|
|
138
144
|
// H04: bounded async tail scan instead of a whole-transcript sync stat/read/split. The
|
|
@@ -184,6 +190,8 @@ for (let i = entries.length - 1; i >= 0; i -= 1) {
|
|
|
184
190
|
const estimatePartial = Boolean(tail?.truncated) && boundaryTs === null;
|
|
185
191
|
|
|
186
192
|
let contentChars = 0;
|
|
193
|
+
let usageTokens = 0;
|
|
194
|
+
let charsAfterUsage = 0;
|
|
187
195
|
let sidechainEntries = 0;
|
|
188
196
|
const modelSequence = [];
|
|
189
197
|
for (let i = start; i < entries.length; i += 1) {
|
|
@@ -200,12 +208,30 @@ for (let i = start; i < entries.length; i += 1) {
|
|
|
200
208
|
if (typeof model === 'string' && model.trim()) modelSequence.push(model.trim());
|
|
201
209
|
}
|
|
202
210
|
if (entry?.type !== 'user' && entry?.type !== 'assistant' && entry?.type !== 'attachment') continue;
|
|
211
|
+
// Hook bookkeeping attachments (hook_success carries the hook's full command line + stdout)
|
|
212
|
+
// are transcript-only: Claude Code never sends them to the model. Counting them inflated the
|
|
213
|
+
// estimate ~3x (400k reported vs ~134k real), so the alerts were noise and the real window
|
|
214
|
+
// was never tracked.
|
|
215
|
+
if (entry?.type === 'attachment' && /^hook_/.test(String(entry?.attachment?.type ?? ''))
|
|
216
|
+
&& entry.attachment.type !== 'hook_additional_context') continue;
|
|
217
|
+
// Real usage reported by the API for the newest main-chain assistant turn is the ground
|
|
218
|
+
// truth for everything sent before it; only entries after it are estimated from chars.
|
|
219
|
+
const usage = entry?.type === 'assistant' ? entry?.message?.usage : null;
|
|
220
|
+
if (usage && typeof usage === 'object') {
|
|
221
|
+
const real = (Number(usage.input_tokens) || 0) + (Number(usage.cache_read_input_tokens) || 0)
|
|
222
|
+
+ (Number(usage.cache_creation_input_tokens) || 0) + (Number(usage.output_tokens) || 0);
|
|
223
|
+
if (real > 0) { usageTokens = real; charsAfterUsage = 0; continue; }
|
|
224
|
+
}
|
|
203
225
|
try {
|
|
204
|
-
|
|
226
|
+
const chars = JSON.stringify(entry.message ?? entry.attachment ?? '').length;
|
|
227
|
+
contentChars += chars;
|
|
228
|
+
charsAfterUsage += chars;
|
|
205
229
|
} catch { /* unserialisable entry */ }
|
|
206
230
|
}
|
|
207
231
|
|
|
208
|
-
const estimatedTokens =
|
|
232
|
+
const estimatedTokens = usageTokens > 0
|
|
233
|
+
? usageTokens + Math.round(charsAfterUsage / CHARS_PER_TOKEN)
|
|
234
|
+
: Math.round(contentChars / CHARS_PER_TOKEN);
|
|
209
235
|
|
|
210
236
|
// Latest assistant model in the live window — this is the model that must fit the NEXT
|
|
211
237
|
// request, so capacity negotiation follows it. A mid-session gateway swap to a smaller
|
|
@@ -235,22 +261,29 @@ async function loadCapacityResolver() {
|
|
|
235
261
|
}
|
|
236
262
|
}
|
|
237
263
|
|
|
238
|
-
let
|
|
264
|
+
let tiers = inlineTiers();
|
|
265
|
+
let capacityModuleRef = null;
|
|
239
266
|
let capacitySource = 'default';
|
|
240
267
|
let negotiatedCapacity = null;
|
|
241
268
|
try {
|
|
242
269
|
const capacityModule = await loadCapacityResolver();
|
|
270
|
+
capacityModuleRef = capacityModule;
|
|
271
|
+
if (capacityModule && typeof capacityModule.resolveContextTiers === 'function') {
|
|
272
|
+
tiers = capacityModule.resolveContextTiers(runtimeConfig);
|
|
273
|
+
}
|
|
243
274
|
if (capacityModule && typeof capacityModule.resolveContextCapTokens === 'function') {
|
|
244
275
|
const resolved = capacityModule.resolveContextCapTokens({
|
|
245
276
|
env: process.env,
|
|
246
277
|
config: runtimeConfig,
|
|
247
278
|
modelMetadata: { model: currentModel },
|
|
248
279
|
});
|
|
249
|
-
hardCap = resolved.capTokens;
|
|
250
280
|
capacitySource = resolved.capacity?.source ?? 'default';
|
|
251
281
|
negotiatedCapacity = resolved.capacity ?? null;
|
|
252
282
|
}
|
|
253
283
|
} catch { /* negotiation is advisory — the operator ceiling already applies */ }
|
|
284
|
+
// The tiers are UKit policy and are never lowered by the negotiated model window;
|
|
285
|
+
// negotiation only feeds the published capacity record and diagnostics.
|
|
286
|
+
const hardCap = tiers.stopTokens;
|
|
254
287
|
const ratio = estimatedTokens / hardCap;
|
|
255
288
|
|
|
256
289
|
// Publish what this hook negotiated so the compact-threshold/hard-cap-gate path stops
|
|
@@ -350,8 +383,8 @@ if (swapDetected && persistedState.lastSwapModel !== currentModel) {
|
|
|
350
383
|
// prompts right after a fresh compact already measure >= 60% of the cap, the summary did
|
|
351
384
|
// not shrink the session enough — and re-compacting the same session recovers very little.
|
|
352
385
|
// The honest recovery moves are: stop re-inflating it with rereads, delegate broad work to
|
|
353
|
-
// subagents (separate windows), or
|
|
354
|
-
// the goal across). Fires once per compact boundary.
|
|
386
|
+
// subagents (separate windows), or keep going on disk state (UKit resume state carries
|
|
387
|
+
// the goal across the next auto-compaction). Fires once per compact boundary.
|
|
355
388
|
const POST_COMPACT_RATIO = 0.6;
|
|
356
389
|
const POST_COMPACT_WINDOW_MS = 10 * 60 * 1000;
|
|
357
390
|
const boundaryAgeMs = boundaryTs !== null ? Date.now() - boundaryTs : null;
|
|
@@ -365,27 +398,48 @@ if (justCompacted && ratio >= POST_COMPACT_RATIO && persistedState.lastPostCompa
|
|
|
365
398
|
'The compact did not shrink this session enough. Recover context now, in this order:',
|
|
366
399
|
'1) STOP re-reading old files, logs and tool outputs — durable state is in the PROJECT CONTEXT block or on disk. Rereads are what re-inflate a just-compacted session.',
|
|
367
400
|
'2) DELEGATE remaining broad work (searches, big reads, multi-file edits) to subagents: their tool output lives in their own windows; keep this context for decisions and short summaries only.',
|
|
368
|
-
'3) If substantial work still remains: land the current step, persist docs/STATUS.md, then
|
|
401
|
+
'3) If substantial work still remains: land the current step, persist docs/STATUS.md, then keep working in this session: the host auto-compacts and UKit resume state (PROJECT CONTEXT block + docs/STATUS.md) carries the goal forward. Never stop to ask the user for /compact or a new session.',
|
|
369
402
|
].join('\n') + '\n',
|
|
370
403
|
);
|
|
371
404
|
}
|
|
372
405
|
|
|
373
|
-
|
|
406
|
+
const tierOf = (tokens) => {
|
|
407
|
+
if (tokens >= tiers.stopTokens) return 'stop';
|
|
408
|
+
if (tokens >= tiers.mandatoryTokens) return 'red';
|
|
409
|
+
if (tokens >= tiers.okTokens) return 'orange';
|
|
410
|
+
if (tokens >= tiers.bestTokens) return 'yellow';
|
|
411
|
+
return 'green';
|
|
412
|
+
};
|
|
413
|
+
const fmt = (n) => Math.round(n).toLocaleString('en-US');
|
|
414
|
+
const tierMessage = (tier) => {
|
|
415
|
+
if (capacityModuleRef && typeof capacityModuleRef.contextTierMessage === 'function') {
|
|
416
|
+
return capacityModuleRef.contextTierMessage(tier, estimatedTokens, tiers);
|
|
417
|
+
}
|
|
418
|
+
return `UKit context ~${fmt(estimatedTokens)} tokens (tier ${tier}): land the current item, persist to docs/STATUS.md, delegate broad work; compaction is automatic - do not ask the user to /compact.`;
|
|
419
|
+
};
|
|
420
|
+
const tier = tierOf(estimatedTokens);
|
|
421
|
+
if (tier === 'green') process.exit(0);
|
|
374
422
|
|
|
375
423
|
const pct = Math.round(ratio * 100);
|
|
376
|
-
const phase =
|
|
424
|
+
const phase = tier;
|
|
377
425
|
|
|
378
|
-
// Debounce the directive
|
|
379
|
-
//
|
|
380
|
-
//
|
|
381
|
-
|
|
382
|
-
// the live transcript back under 0.8, since this whole branch exits early above.
|
|
383
|
-
const COOLDOWN_MS = phase === 'hard' ? 3 * 60 * 1000 : 8 * 60 * 1000;
|
|
426
|
+
// Debounce so the directive does not re-print in full every prompt while the tier is
|
|
427
|
+
// unchanged. Re-arms on tier change or after the cooldown, and resets naturally once real
|
|
428
|
+
// compaction drops the live transcript back under the best tier.
|
|
429
|
+
const COOLDOWN_MS = (tier === 'stop' || tier === 'red') ? 3 * 60 * 1000 : 8 * 60 * 1000;
|
|
384
430
|
|
|
385
431
|
const now = Date.now();
|
|
386
432
|
const withinCooldown = guardState.lastPhase === phase
|
|
387
433
|
&& (now - Number(guardState.lastActionAt || 0)) < COOLDOWN_MS;
|
|
388
434
|
|
|
435
|
+
if (tier === 'yellow') {
|
|
436
|
+
if (!withinCooldown) {
|
|
437
|
+
await writeGuardState({ ...persistedState, lastPhase: phase, lastActionAt: now });
|
|
438
|
+
process.stdout.write(`${tierMessage(tier)}\n`);
|
|
439
|
+
}
|
|
440
|
+
process.exit(0);
|
|
441
|
+
}
|
|
442
|
+
|
|
389
443
|
// A one-shot pipeline (handoff-fullstack) is mid-flight when RUN.md exists with a phase
|
|
390
444
|
// other than `done`. Telling the agent to stop and ask for /compact there is actively
|
|
391
445
|
// harmful: the human is deliberately away, the pipeline has a disk cursor that makes it
|
|
@@ -409,11 +463,12 @@ async function readRunCursor() {
|
|
|
409
463
|
const run = await readRunCursor();
|
|
410
464
|
|
|
411
465
|
const lines_out = [];
|
|
412
|
-
if (
|
|
413
|
-
lines_out.push(`UKIT CONTEXT
|
|
414
|
-
|
|
466
|
+
if (tier === 'stop') {
|
|
467
|
+
lines_out.push(`UKIT CONTEXT STOP - ${tierMessage(tier)} (capacitySource=${capacitySource}).`);
|
|
468
|
+
} else if (tier === 'red') {
|
|
469
|
+
lines_out.push(`UKIT CONTEXT ALERT - ${tierMessage(tier)} (${pct}% of the ${fmt(hardCap)} stop line, capacitySource=${capacitySource}).`);
|
|
415
470
|
} else {
|
|
416
|
-
lines_out.push(`UKIT CONTEXT WARNING
|
|
471
|
+
lines_out.push(`UKIT CONTEXT WARNING - ${tierMessage(tier)} (capacitySource=${capacitySource}).`);
|
|
417
472
|
}
|
|
418
473
|
|
|
419
474
|
if (estimatePartial) {
|
|
@@ -428,7 +483,7 @@ if (withinCooldown) {
|
|
|
428
483
|
lines_out.push('1) Finish the step in flight, then update docs/AI_HANDOFF/RUN.md so the cursor is current.');
|
|
429
484
|
lines_out.push('2) At the next wave boundary, collapse the finished wave to one line per task and stop re-reading task files, executor reports, and earlier diffs — that detail is already on disk.');
|
|
430
485
|
lines_out.push('3) Make sure spawned agents are returning their short summary form (<=10 lines), not pasted RED/verification logs. Pasted subagent logs are the usual cause of this warning.');
|
|
431
|
-
lines_out.push('4) Continue to the next wave/phase.
|
|
486
|
+
lines_out.push('4) Continue to the next wave/phase. Never stop to ask for /compact; the host auto-compacts and RUN.md carries the run across it.');
|
|
432
487
|
if (sidechainEntries > 0) {
|
|
433
488
|
lines_out.push(`Note: ${sidechainEntries} subagent entries in this stretch. Keep concurrency at or below handoff.maxParallelAgents and keep returns short; do not widen the batch while this warning stands.`);
|
|
434
489
|
}
|
|
@@ -438,7 +493,7 @@ if (withinCooldown) {
|
|
|
438
493
|
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
494
|
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
495
|
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(
|
|
496
|
+
lines_out.push(`4) Do NOT keep stacking new work: host auto-compaction is automatic and fires inside the ${fmt(tiers.okTokens)}-${fmt(tiers.mandatoryTokens)} band; the tool gate blocks new work at ${fmt(tiers.stopTokens)}. Land the one item and defer the rest to disk; keep working. Never ask the user to /compact.`);
|
|
442
497
|
if (sidechainEntries > 0) {
|
|
443
498
|
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
499
|
}
|
|
@@ -135,7 +135,7 @@ async function emitOrdinaryResume(payload, source) {
|
|
|
135
135
|
if (!runtimeExists) return false;
|
|
136
136
|
try {
|
|
137
137
|
const runtime = await import(pathToFileURL(runtimePath).href);
|
|
138
|
-
const intent = await runtime.readResumeIntent(projectRoot, payload, { consume: true });
|
|
138
|
+
const intent = await runtime.readResumeIntent(projectRoot, payload, { consume: true, compact: source === 'compact' });
|
|
139
139
|
if (!intent) return false;
|
|
140
140
|
const out = [
|
|
141
141
|
'UKIT ROUTED TASK RESUME — an unfinished ordinary routed task was preserved before context compaction.',
|
|
@@ -146,7 +146,16 @@ async function emitOrdinaryResume(payload, source) {
|
|
|
146
146
|
];
|
|
147
147
|
if (source === 'compact') {
|
|
148
148
|
out.push('');
|
|
149
|
-
out.push('
|
|
149
|
+
out.push('=== POST-COMPACTION RESUME ===');
|
|
150
|
+
// Snapshot fields come from the PreCompact checkpoint; absent on legacy intents.
|
|
151
|
+
if (intent.goal) out.push(`Goal: ${intent.goal.replace(/\s+/g, ' ').slice(0, 1200)}`);
|
|
152
|
+
if (intent.contract) out.push(`Contract: ${intent.contract}`);
|
|
153
|
+
if (intent.observedEvidence?.length) out.push(`Evidence observed: ${intent.observedEvidence.join(', ')}`);
|
|
154
|
+
if (intent.unmetEvidence?.length) out.push(`Unmet evidence: ${intent.unmetEvidence.join(', ')}`);
|
|
155
|
+
if (intent.nextStep) out.push(`Next step: ${intent.nextStep}`);
|
|
156
|
+
if (intent.git?.head) out.push(`Git at compaction: HEAD ${String(intent.git.head).slice(0, 12)}, ${intent.git.dirtyFiles || 0} dirty file(s) — re-check git status before mutating.`);
|
|
157
|
+
out.push('Compaction is not completion — continue the work now; the window is clean. Do not report status and wait, and do not ask the user to /compact or start a new session.');
|
|
158
|
+
out.push('=== END ===');
|
|
150
159
|
}
|
|
151
160
|
process.stdout.write(`${out.join('\n')}\n`);
|
|
152
161
|
return true;
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
// mission-capture.mjs - UserPromptSubmit + PostToolUse(TodoWrite|TaskCreate|TaskUpdate) chain step (WP4).
|
|
2
|
+
// Records the (redacted) prompt into the mission journal, classifies it into the requirement graph, and mirrors
|
|
3
|
+
// todo/task tool calls into graph task status. Emits nothing to the model except one short drift line when the
|
|
4
|
+
// drift signature changes. Advisory: always code 0, fail-open, deadline-bounded. Logic: ukit/runtime/mission/hooks.mjs.
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import { pathToFileURL, fileURLToPath } from 'node:url';
|
|
7
|
+
|
|
8
|
+
export const hookFailClosed = false;
|
|
9
|
+
const NONE = { code: 0, stdout: '', stderr: '' };
|
|
10
|
+
const MODULE_DIR = path.dirname(fileURLToPath(import.meta.url));
|
|
11
|
+
|
|
12
|
+
export async function runHook(ctx = {}) {
|
|
13
|
+
let timer;
|
|
14
|
+
try {
|
|
15
|
+
const projectRoot = ctx.projectRoot || process.cwd();
|
|
16
|
+
const payload = ctx.payload && typeof ctx.payload === 'object' ? ctx.payload : {};
|
|
17
|
+
const deadlineMs = Number(ctx.deadlineMs || process.env.HOOK_DEADLINE_MS) || 2000;
|
|
18
|
+
const timeout = new Promise((resolve) => { timer = setTimeout(() => resolve(''), Math.max(100, deadlineMs - 150)); timer.unref?.(); });
|
|
19
|
+
const work = (async () => {
|
|
20
|
+
const mod = await import(pathToFileURL(path.join(MODULE_DIR, '..', 'ukit', 'runtime', 'mission', 'hooks.mjs')).href);
|
|
21
|
+
if (payload.hook_event_name === 'PostToolUse') { await mod.todoMirrorStep({ projectRoot, payload }); return ''; }
|
|
22
|
+
if (payload.tool_name) return '';
|
|
23
|
+
return mod.captureStep({ projectRoot, payload });
|
|
24
|
+
})();
|
|
25
|
+
const text = await Promise.race([work, timeout]);
|
|
26
|
+
if (!text) return NONE;
|
|
27
|
+
const env = ctx.env || process.env;
|
|
28
|
+
const omp = payload.ukit_harness === 'omp' || env.UKIT_HARNESS === 'omp';
|
|
29
|
+
const stdout = omp ? `${text}\n`
|
|
30
|
+
: `${JSON.stringify({ hookSpecificOutput: { hookEventName: 'UserPromptSubmit', additionalContext: text } })}\n`;
|
|
31
|
+
return { code: 0, stdout, stderr: '' };
|
|
32
|
+
} catch {
|
|
33
|
+
return NONE;
|
|
34
|
+
} finally {
|
|
35
|
+
clearTimeout(timer);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
// post-compact-observe.mjs - PostCompact chain step (observe-only, always code 0, fail-open).
|
|
2
|
+
// Records COMPACT_SUCCEEDED; an empty/unusable summary (<200 chars) is flagged as failure class 11.
|
|
3
|
+
// Only the summary LENGTH is stored, never its text.
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { pathToFileURL, fileURLToPath } from 'node:url';
|
|
6
|
+
|
|
7
|
+
export const hookFailClosed = false;
|
|
8
|
+
const NONE = { code: 0, stdout: '', stderr: '' };
|
|
9
|
+
const HOOKS_DIR = path.dirname(fileURLToPath(import.meta.url));
|
|
10
|
+
export const MIN_SUMMARY_CHARS = 200;
|
|
11
|
+
|
|
12
|
+
async function handle(ctx) {
|
|
13
|
+
const root = ctx.projectRoot || process.cwd();
|
|
14
|
+
const p = ctx.payload || {};
|
|
15
|
+
const sw = await import(pathToFileURL(path.join(HOOKS_DIR, 'stop-failure-rescue.mjs')).href);
|
|
16
|
+
const len = typeof p.compact_summary === 'string' ? p.compact_summary.trim().length : 0;
|
|
17
|
+
const empty = len < MIN_SUMMARY_CHARS;
|
|
18
|
+
await sw.appendEvent(root, {
|
|
19
|
+
ts: new Date().toISOString(), type: 'COMPACT_SUCCEEDED', trigger: String(p.trigger || '').slice(0, 20),
|
|
20
|
+
summaryChars: len, ...(empty ? { cls: 11, name: 'empty-compaction-summary', flag: 'empty-summary' } : {}),
|
|
21
|
+
});
|
|
22
|
+
return NONE;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export async function runHook(ctx = {}) {
|
|
26
|
+
try {
|
|
27
|
+
const deadlineMs = Number(ctx.deadlineMs || process.env.HOOK_DEADLINE_MS) || 2000;
|
|
28
|
+
let timer;
|
|
29
|
+
const timeout = new Promise((resolve) => { timer = setTimeout(() => resolve(NONE), Math.max(100, deadlineMs - 100)); timer.unref?.(); });
|
|
30
|
+
return await Promise.race([handle(ctx), timeout]).finally(() => clearTimeout(timer));
|
|
31
|
+
} catch {
|
|
32
|
+
return NONE;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
// shell-watch.mjs - UserPromptSubmit chain step (advisory, always code 0, fail-open).
|
|
2
|
+
// Emits an ACTION directive when hung shells / stalled background tasks exist.
|
|
3
|
+
// Claude Code: JSON hookSpecificOutput.additionalContext; omp: plain text (bridge appends it).
|
|
4
|
+
// Logic lives in ukit/runtime/shell-watch.mjs.
|
|
5
|
+
import fsp from 'node:fs/promises';
|
|
6
|
+
import path from 'node:path';
|
|
7
|
+
import { pathToFileURL, fileURLToPath } from 'node:url';
|
|
8
|
+
|
|
9
|
+
export const hookFailClosed = false;
|
|
10
|
+
const NONE = { code: 0, stdout: '', stderr: '' };
|
|
11
|
+
const MODULE_DIR = path.dirname(fileURLToPath(import.meta.url));
|
|
12
|
+
|
|
13
|
+
export async function runHook(ctx = {}) {
|
|
14
|
+
try {
|
|
15
|
+
const projectRoot = ctx.projectRoot || process.cwd();
|
|
16
|
+
let config = null;
|
|
17
|
+
try { config = JSON.parse(await fsp.readFile(path.join(projectRoot, '.ukit', 'storage', 'config.json'), 'utf8')); } catch { /* defaults */ }
|
|
18
|
+
const mod = await import(pathToFileURL(path.join(MODULE_DIR, '..', 'ukit', 'runtime', 'shell-watch.mjs')).href);
|
|
19
|
+
// Deadline contract: never outlive the chain slot (ctx.deadlineMs or HOOK_DEADLINE_MS).
|
|
20
|
+
const deadlineMs = Number(ctx.deadlineMs || process.env.HOOK_DEADLINE_MS) || 2000;
|
|
21
|
+
let timer;
|
|
22
|
+
const timeout = new Promise((resolve) => { timer = setTimeout(() => resolve(''), Math.max(100, deadlineMs - 100)); timer.unref?.(); });
|
|
23
|
+
const text = await Promise.race([mod.runShellWatch({ projectRoot, config }), timeout]).finally(() => clearTimeout(timer));
|
|
24
|
+
if (!text) return NONE;
|
|
25
|
+
const env = ctx.env || process.env;
|
|
26
|
+
const omp = ctx.payload?.ukit_harness === 'omp' || env.UKIT_HARNESS === 'omp';
|
|
27
|
+
const stdout = omp
|
|
28
|
+
? `${text}\n`
|
|
29
|
+
: `${JSON.stringify({ hookSpecificOutput: { hookEventName: 'UserPromptSubmit', additionalContext: text } })}\n`;
|
|
30
|
+
return { code: 0, stdout, stderr: '' };
|
|
31
|
+
} catch {
|
|
32
|
+
return NONE;
|
|
33
|
+
}
|
|
34
|
+
}
|