@ngockhoale/ukit 3.5.9 → 3.5.11

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 CHANGED
@@ -2,6 +2,23 @@
2
2
 
3
3
  All notable changes to UKit are documented here.
4
4
 
5
+ ## 3.5.11 - 2026-11-19
6
+
7
+ Hotfix for 3.5.10 output compression. Since 3.5.10 the summary replaces the Bash output on Claude Code, and the replacement also hit commands whose output *is* the content: `sed -n 25,120p file` returned ten mangled lines instead of the code, and chained status commands (`node -p …; npm view …; git status`) lost whole sections.
8
+
9
+ - **Content reads pass through raw.** `cat`, `sed`, `head`, `tail`, `nl`, `bat`, `less`, `more`, `jq`, `diff`, `awk`, `cut`, `git show`/`diff`/`blame`/`cat-file` and `git log -p` are never summarized. Listing-only `git diff --stat`/`--name-only` still compress.
10
+ - **Bounded and chained commands pass through raw.** A pipeline that already ends in `head`/`tail`/`sed`, or several commands chained with `;`/`&&`/`||` (a leading `cd …` is ignored), keeps its full output.
11
+ - Test runs, builds, installs, searches and long listings compress exactly as in 3.5.10.
12
+
13
+ ## 3.5.10 - 2026-11-19
14
+
15
+ Sessions compacted after two or three prompts. Three causes, all fixed at the source; no new command. No host was run live; the checks are unit, parity and hook-process tests.
16
+
17
+ - **Claude Code now knows the real context window.** Gateway aliases such as `unic-opus` are unknown to Claude Code, which then assumes 200k and compacts around 167k. `compact.contextWindowTokens` (default 250000) renders `CLAUDE_CODE_MAX_CONTEXT_TOKENS`, and `CLAUDE_CODE_AUTO_COMPACT_WINDOW` is `0.8 × hardCapTokens` = 188000. omp keeps `compaction.thresholdTokens` from the same budget.
18
+ - **One budget, consistent defaults.** `tokenThreshold` 115000, `hardCapTokens` 235000, both below the declared window. A hard cap above the window (old installs carried 500000) is clamped to the window at runtime, so teams that never edit their config get the new limits after `ukit update`.
19
+ - **Output compression really replaces the output.** The PostToolUse hook used to add its summary next to the full Bash output, so nothing was saved. On Claude Code it now returns `hookSpecificOutput.updatedToolOutput` with the summary, only when the full output was written to a tee log the summary points to. omp and Codex keep plain-text output.
20
+ - Stale tracked `.omp/RULES.md` re-rendered (worktree preflight tests).
21
+
5
22
  ## 3.5.9 - 2026-11-18
6
23
 
7
24
  Playbooks now reach the agent. A telemetry review of 164 Claude Code sessions (1,426 unique prompts) found the playbook feature had no effect: only 9% of prompts got a playbook, 79% were dropped as ambiguous (for example bug-fix + release), and no session ever opened a playbook file, because the prompt hook never printed one and route-task pointed at a relative path that does not exist in projects. No new command was added; the change is in what the existing hooks and instructions deliver. No host was run live; the checks are unit, parity and hook-process tests.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ngockhoale/ukit",
3
- "version": "3.5.9",
3
+ "version": "3.5.11",
4
4
  "description": "Install/update an index-first AI workspace for Claude Code, OpenAI Codex and omp (Oh My Pi).",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -1,11 +1,12 @@
1
1
  import { readFileSync } from 'node:fs';
2
2
  import { fileURLToPath } from 'node:url';
3
3
 
4
- // The shipped compact.tokenThreshold / compact.hardCapTokens / compact.autoCompactWindowRatio
5
- // trio is the ONLY place the context budget is written down. Every other number — the
6
- // code-side defaults, CLAUDE_CODE_AUTO_COMPACT_WINDOW in .claude/settings.json, and
4
+ // The shipped compact.tokenThreshold / contextWindowTokens / hardCapTokens /
5
+ // autoCompactWindowRatio numbers are the ONLY place the context budget is written down. Every other number — the
6
+ // code-side defaults, CLAUDE_CODE_MAX_CONTEXT_TOKENS + CLAUDE_CODE_AUTO_COMPACT_WINDOW in
7
+ // .claude/settings.json, and
7
8
  // compaction.thresholdTokens in .omp/config.yml — is read or derived from here, so retuning
8
- // UKit for a different model context window is a three-number edit in
9
+ // UKit for a different model context window is a config-only edit in
9
10
  // template_project/ukit/storage/config.json and nothing else.
10
11
  const SHIPPED_CONFIG_URL = new URL('../../../template_project/ukit/storage/config.json', import.meta.url);
11
12
 
@@ -15,6 +16,7 @@ const EMERGENCY_BUDGET = {
15
16
  tokenThreshold: 50_000,
16
17
  hardCapTokens: 160_000,
17
18
  autoCompactWindowRatio: 0.7,
19
+ contextWindowTokens: 200_000,
18
20
  };
19
21
 
20
22
  // Auto-compact must land strictly below hardCapTokens so the client heals itself before
@@ -44,10 +46,21 @@ export function deriveCompactBudget(compact = {}) {
44
46
  const tokenThreshold = Number.isFinite(source.tokenThreshold)
45
47
  ? source.tokenThreshold
46
48
  : EMERGENCY_BUDGET.tokenThreshold;
47
- const hardCapTokens = positiveInteger(source.hardCapTokens, EMERGENCY_BUDGET.hardCapTokens);
49
+ // compact.contextWindowTokens is the model window UKit tells the client to assume
50
+ // (CLAUDE_CODE_MAX_CONTEXT_TOKENS). It is a deliberate operator CEILING, not a probe of
51
+ // what the provider accepts: a gateway alias such as unic-opus is unknown to Claude Code,
52
+ // and without this it silently falls back to 200k (or 1M), ignoring UKit's budget.
53
+ const contextWindowTokens = positiveInteger(source.contextWindowTokens, EMERGENCY_BUDGET.contextWindowTokens);
54
+ // The hard cap must sit inside the window it guards; a cap above the window could never
55
+ // fire before the provider rejects the request.
56
+ const hardCapTokens = Math.min(
57
+ positiveInteger(source.hardCapTokens, EMERGENCY_BUDGET.hardCapTokens),
58
+ contextWindowTokens,
59
+ );
48
60
  return {
49
61
  tokenThreshold,
50
62
  hardCapTokens,
63
+ contextWindowTokens,
51
64
  autoCompactWindow: deriveAutoCompactWindow(hardCapTokens, source.autoCompactWindowRatio),
52
65
  };
53
66
  }
@@ -462,13 +462,17 @@ export async function buildCompactThresholds(config = {}) {
462
462
  config?.compact?.hardCapTokens,
463
463
  loadShippedCompactBudget().hardCapTokens,
464
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;
465
469
  const explicitSoftThreshold = finiteNumber(config?.compact?.tokenThreshold, 0);
466
470
  // Negotiated capacity (H22): the guard publishes what it derived from the live route and
467
471
  // this shared path consumes it; without a record the shipped tuning applies unchanged.
468
472
  const negotiated = await readNegotiatedCapacity(config);
469
473
  const hardCapTokens = negotiated
470
- ? Math.max(1, Math.min(shippedHardCap, negotiated.capTokens))
471
- : shippedHardCap;
474
+ ? Math.max(1, Math.min(effectiveShippedHardCap, negotiated.capTokens))
475
+ : effectiveShippedHardCap;
472
476
  // An explicit operator tokenThreshold is honoured but still clamped under the
473
477
  // negotiated cap: an advisory soft/hard pair sitting at or above hardCapTokens can
474
478
  // never fire, because context-hardcap-gate.sh already refuses tools at the cap
@@ -20,7 +20,7 @@ export function buildTemplateVariables({ projectContext, stackContext, packageVe
20
20
  // Derived, never hand-written: .claude/settings.json is read by Claude Code itself and so
21
21
  // cannot consult .ukit/storage/config.json at runtime. Baking the window in here keeps
22
22
  // compact.hardCapTokens the single number that retunes both.
23
- const { autoCompactWindow } = loadShippedCompactBudget();
23
+ const { autoCompactWindow, contextWindowTokens } = loadShippedCompactBudget();
24
24
 
25
25
  // FR-004 — fail closed: `allow` only on an explicit user opt-in
26
26
  // (`orchestration.allowUnsafeEval === true`). Missing, unreadable, or
@@ -31,6 +31,7 @@ export function buildTemplateVariables({ projectContext, stackContext, packageVe
31
31
  return {
32
32
  compact: {
33
33
  autoCompactWindow: String(autoCompactWindow),
34
+ maxContextTokens: String(contextWindowTokens),
34
35
  },
35
36
  project: {
36
37
  name: projectContext.project.name,
@@ -1,9 +1,9 @@
1
1
  #!/bin/bash
2
2
  # PreToolUse hook: hard-enforce an absolute context token cap (compact.hardCapTokens,
3
- # default 500000, sized for a 1M window — must stay below the model's real context
4
- # window, so lower it on a 200k/256k model), separate from the
3
+ # default 235000 inside the shipped 250k compact.contextWindowTokens; Claude Code itself
4
+ # auto-compacts earlier, at round(hardCap * autoCompactWindowRatio)), separate from the
5
5
  # soft/hard advisory pressure phases in
6
- # compact-threshold.mjs (default soft=150000/hard=240000, which only print a suggestion).
6
+ # compact-threshold.mjs (default soft=115000/hard=184000, which only print a suggestion).
7
7
  #
8
8
  # Those advisory phases are just injected text — nothing stops the agent from ignoring
9
9
  # them and letting a session run to hundreds of thousands of tokens with no compaction.
@@ -132,7 +132,7 @@ if (!runtimeConfig || typeof runtimeConfig !== 'object') runtimeConfig = {};
132
132
  function operatorHardCap() {
133
133
  const value = runtimeConfig?.compact?.hardCapTokens;
134
134
  if (typeof value === 'number' && Number.isFinite(value) && Number.isInteger(value) && value > 0) return value;
135
- return 500_000;
135
+ return 235_000;
136
136
  }
137
137
 
138
138
  // H04: bounded async tail scan instead of a whole-transcript sync stat/read/split. The
@@ -11,6 +11,7 @@
11
11
  "defaultView": "chat",
12
12
  "autoCompactEnabled": true,
13
13
  "env": {
14
+ "CLAUDE_CODE_MAX_CONTEXT_TOKENS": "{{compact.maxContextTokens}}",
14
15
  "CLAUDE_CODE_AUTO_COMPACT_WINDOW": "{{compact.autoCompactWindow}}"
15
16
  },
16
17
  "permissions": {
@@ -452,7 +452,7 @@ function computeEstimatedTotalTokens({
452
452
  // real serving model. This record is how negotiated capacity reaches the shared
453
453
  // threshold/gate path; without it a verified 200k route would still compact at 240k.
454
454
  export const CAPACITY_RECORD_SEGMENTS = ['.ukit', 'storage', 'cache', 'context-capacity.json'];
455
- // Shipped tuning as a ratio of the absolute cap (150_000 soft of a 500_000 cap), so a
455
+ // Shipped tuning as a ratio of the absolute cap (fallback when no explicit tokenThreshold is set), so a
456
456
  // smaller verified window moves the advisory phases down with the cap they precede.
457
457
  export const SOFT_TO_CAP_RATIO = 0.3;
458
458
 
@@ -489,14 +489,18 @@ export async function resolveCompactCapacity(config = {}, { record } = {}) {
489
489
 
490
490
  export async function buildCompactThresholds(config = {}) {
491
491
  const explicitSoftThreshold = finiteNumber(config?.compact?.tokenThreshold, 0);
492
- const shippedHardCap = positiveInteger(config?.compact?.hardCapTokens, 500_000);
492
+ const shippedHardCap = positiveInteger(config?.compact?.hardCapTokens, 235_000);
493
+ // Upgrade safety: an install that predates compact.contextWindowTokens still carries the
494
+ // old 500k hard cap; the cap must never sit above the declared window it guards.
495
+ const declaredWindow = positiveInteger(config?.compact?.contextWindowTokens, 0);
496
+ const effectiveShippedHardCap = declaredWindow > 0 ? Math.min(shippedHardCap, declaredWindow) : shippedHardCap;
493
497
  // Only tighten once a record exists: an install with no evidence yet (and every caller
494
498
  // that passes no project root) keeps the shipped tuning unchanged.
495
499
  const record = await readContextCapacityRecord(config?.projectRoot);
496
500
  const negotiated = record ? await resolveCompactCapacity(config, { record }) : null;
497
501
  const hardCapTokens = negotiated
498
- ? Math.max(1, Math.min(shippedHardCap, negotiated.capTokens))
499
- : shippedHardCap;
502
+ ? Math.max(1, Math.min(effectiveShippedHardCap, negotiated.capTokens))
503
+ : effectiveShippedHardCap;
500
504
  // An explicit operator tokenThreshold is honoured but still clamped under the
501
505
  // negotiated cap: an advisory soft/hard pair sitting at or above hardCapTokens can
502
506
  // never fire, because context-hardcap-gate.sh already refuses tools at the cap
@@ -30,7 +30,7 @@ export const CAPACITY_ENV_VAR = 'UKIT_CONTEXT_WINDOW_TOKENS';
30
30
  export const DEFAULT_CAPACITY_TOKENS = 100_000;
31
31
  // The shipped operator ceiling (compact.hardCapTokens) — only ever an UPPER bound; negotiated
32
32
  // capacity can tighten it but never raise it.
33
- export const SHIPPED_HARD_CAP_TOKENS = 500_000;
33
+ export const SHIPPED_HARD_CAP_TOKENS = 235_000;
34
34
  // A verified window is only ever usable as an estimate: the response itself plus the
35
35
  // char/token estimator's own undercount must fit too, so only half the window becomes
36
36
  // the advisory cap (500k cap from a 1M window — the original tuning, made explicit).
@@ -133,8 +133,15 @@ export function resolveContextCapacity({ env = {}, config = {}, modelMetadata =
133
133
  export function resolveContextCapTokens({ env, config, modelMetadata } = {}) {
134
134
  const capacity = resolveContextCapacity({ env, config, modelMetadata });
135
135
  const operatorHardCap = parseConfigTokenCount(config?.compact?.hardCapTokens);
136
- const ceiling = operatorHardCap ?? SHIPPED_HARD_CAP_TOKENS;
137
- const derived = capacity.source === 'default'
136
+ // Upgrade safety: an old operator hard cap (500k) never outranks a declared smaller window.
137
+ const declaredWindow = parseConfigTokenCount(config?.compact?.contextWindowTokens);
138
+ const baseCeiling = operatorHardCap ?? SHIPPED_HARD_CAP_TOKENS;
139
+ const ceiling = declaredWindow !== null ? Math.min(baseCeiling, declaredWindow) : baseCeiling;
140
+ // compact.contextWindowTokens is an operator declaration made together with hardCapTokens
141
+ // (the shipped pair is 250k window / 235k cap), so it is NOT halved: halving it would
142
+ // silently drop the gate to 125k and block tools long before Claude Code auto-compacts.
143
+ // Only env / model-table evidence keeps the conservative half-window estimate.
144
+ const derived = capacity.source === 'default' || (capacity.source === 'config' && operatorHardCap !== null)
138
145
  ? (operatorHardCap ?? capacity.tokens)
139
146
  : Math.round(capacity.tokens * CAPACITY_TO_CAP_RATIO);
140
147
  return {
@@ -31,6 +31,51 @@ function emitSystemMessage(text) {
31
31
  } catch { /* stdout already gone */ }
32
32
  }
33
33
 
34
+ // 3.5.10 context-budget fix: on Claude Code, plain PostToolUse stdout is only ADDED
35
+ // context — the full raw Bash output still reached the model and `savedTokens` was
36
+ // fictional. `hookSpecificOutput.updatedToolOutput` replaces the tool output before it
37
+ // is sent to the model; its value must match the Bash tool_response shape
38
+ // ({stdout, stderr, interrupted, isImage}). omp keeps plain text (its bridge already
39
+ // swaps Bash content for hook stdout); Codex has no PostToolUse replacement, so plain
40
+ // text there too. Replacement is only allowed when the full output stays recoverable:
41
+ // a failing command whose tee persist failed (no rawPath) falls back to add-context.
42
+ function resolveHookHarness(payload) {
43
+ const fromPayload = typeof payload?.ukit_harness === 'string' ? payload.ukit_harness.trim() : '';
44
+ if (fromPayload) return fromPayload;
45
+ const fromEnv = typeof process.env.UKIT_HARNESS === 'string' ? process.env.UKIT_HARNESS.trim() : '';
46
+ return fromEnv || 'claude-code';
47
+ }
48
+
49
+ export function buildCompressedHookOutput(payload, summary, { rawPath = '' } = {}) {
50
+ const text = String(summary ?? '');
51
+ const harness = resolveHookHarness(payload);
52
+ if (harness !== 'claude-code' && harness !== 'claude') return text;
53
+ // Quality first: only replace when the summary itself carries the recovery line for
54
+ // a persisted tee log. A failed tee persist (rawPath '') or a summary that could not
55
+ // fit the hint keeps the add-context behaviour so the raw output still reaches the
56
+ // model — failing commands included.
57
+ const recoverable = typeof rawPath === 'string' && rawPath !== ''
58
+ && text.includes(`Tee log: ${rawPath}`);
59
+ if (!recoverable) return text;
60
+ const original = payload?.tool_response && typeof payload.tool_response === 'object'
61
+ && !Array.isArray(payload.tool_response)
62
+ ? payload.tool_response
63
+ : {};
64
+ const updatedToolOutput = {
65
+ ...original,
66
+ stdout: text,
67
+ stderr: '',
68
+ interrupted: typeof original.interrupted === 'boolean' ? original.interrupted : false,
69
+ isImage: false,
70
+ };
71
+ return JSON.stringify({
72
+ hookSpecificOutput: {
73
+ hookEventName: 'PostToolUse',
74
+ updatedToolOutput,
75
+ },
76
+ });
77
+ }
78
+
34
79
  // BUG-C23-10: bare `.catch(() => {})` swallowed every sweep failure — a
35
80
  // persistent EACCES/ENOSPC on .ukit meant silent non-convergence of the tee/
36
81
  // backlog bound (live dir observed at 2,417 files). Announce the first failure
@@ -1194,6 +1239,8 @@ function extractExitCode(payload) {
1194
1239
  payload?.tool_output?.exit_code,
1195
1240
  payload?.tool_result?.exitCode,
1196
1241
  payload?.tool_result?.exit_code,
1242
+ payload?.tool_response?.exitCode,
1243
+ payload?.tool_response?.exit_code,
1197
1244
  payload?.exitCode,
1198
1245
  payload?.exit_code,
1199
1246
  ];
@@ -1341,6 +1388,81 @@ function shouldCompress(config) {
1341
1388
  return Boolean(config?.tokenPipeline?.outputCompression);
1342
1389
  }
1343
1390
 
1391
+ // 3.5.11 quality fix: since 3.5.10 a summary REPLACES the Bash output on Claude Code.
1392
+ // For commands whose output is the content the model asked to read (cat/sed -n/head/
1393
+ // git diff …), for output already bounded by a trailing head/tail/sed stage, and for
1394
+ // chained commands (`a; b && c`) whose sections the line picker cannot keep apart, a
1395
+ // lossy summary drops source text or misfiles sections — quality > token savings, so
1396
+ // these pass through untouched.
1397
+ const VERBATIM_READ_HEADS = new Set([
1398
+ 'cat', 'sed', 'head', 'tail', 'nl', 'bat', 'less', 'more', 'jq', 'diff', 'awk', 'cut',
1399
+ ]);
1400
+ const VERBATIM_GIT_SUBCOMMANDS = new Set(['show', 'diff', 'blame', 'cat-file']);
1401
+ const BOUNDING_TAIL_STAGES = new Set(['head', 'tail', 'sed']);
1402
+
1403
+ function splitShellCommand(command) {
1404
+ const segments = [];
1405
+ let current = '';
1406
+ let ops = [];
1407
+ let quote = '';
1408
+ const text = String(command ?? '');
1409
+ for (let i = 0; i < text.length; i += 1) {
1410
+ const ch = text[i];
1411
+ if (quote) {
1412
+ if (ch === '\\' && quote === '"' && i + 1 < text.length) { current += ch + text[i + 1]; i += 1; continue; }
1413
+ if (ch === quote) quote = '';
1414
+ current += ch;
1415
+ continue;
1416
+ }
1417
+ if (ch === '\\' && i + 1 < text.length) { current += ch + text[i + 1]; i += 1; continue; }
1418
+ if (ch === '"' || ch === "'") { quote = ch; current += ch; continue; }
1419
+ const two = text.slice(i, i + 2);
1420
+ if (two === '&&' || two === '||') { segments.push(current); ops.push(two); current = ''; i += 1; continue; }
1421
+ if (ch === ';' || ch === '\n' || ch === '|') { segments.push(current); ops.push(ch === '|' ? '|' : ';'); current = ''; continue; }
1422
+ current += ch;
1423
+ }
1424
+ segments.push(current);
1425
+ return { segments: segments.map((s) => s.trim()), ops };
1426
+ }
1427
+
1428
+ function segmentWords(segment) {
1429
+ const words = segment.split(/\s+/).filter(Boolean);
1430
+ while (words.length && /^[A-Za-z_][A-Za-z0-9_]*=/.test(words[0])) words.shift();
1431
+ return words;
1432
+ }
1433
+
1434
+ export function isVerbatimOutputCommand(command) {
1435
+ const { segments, ops } = splitShellCommand(command);
1436
+ // Group pipe stages into pipelines; drop `cd …` navigation pipelines.
1437
+ const pipelines = [];
1438
+ let stages = [segments[0]];
1439
+ for (let i = 0; i < ops.length; i += 1) {
1440
+ if (ops[i] === '|') stages.push(segments[i + 1]);
1441
+ else { pipelines.push(stages); stages = [segments[i + 1]]; }
1442
+ }
1443
+ pipelines.push(stages);
1444
+ const meaningful = pipelines
1445
+ .map((p) => p.filter(Boolean))
1446
+ .filter((p) => p.length > 0 && !(p.length === 1 && segmentWords(p[0])[0] === 'cd'));
1447
+ if (meaningful.length > 1) return true;
1448
+ if (meaningful.length === 0) return false;
1449
+ const pipeline = meaningful[0];
1450
+ const first = segmentWords(pipeline[0]);
1451
+ const head = (first[0] || '').replace(/^.*\//, '');
1452
+ if (VERBATIM_READ_HEADS.has(head)) return true;
1453
+ if (head === 'git') {
1454
+ const sub = first.slice(1).find((w) => !w.startsWith('-'));
1455
+ const listingOnly = first.some((w) => /^--(stat|numstat|shortstat|name-only|name-status)\b/.test(w));
1456
+ if (VERBATIM_GIT_SUBCOMMANDS.has(sub) && !listingOnly) return true;
1457
+ if (sub === 'log' && first.some((w) => w === '-p' || w === '--patch')) return true;
1458
+ }
1459
+ if (pipeline.length > 1) {
1460
+ const last = segmentWords(pipeline[pipeline.length - 1]);
1461
+ if (BOUNDING_TAIL_STAGES.has((last[0] || '').replace(/^.*\//, ''))) return true;
1462
+ }
1463
+ return false;
1464
+ }
1465
+
1344
1466
  function mergeDeep(base, override) {
1345
1467
  if (!override || typeof override !== 'object' || Array.isArray(override)) {
1346
1468
  return override === undefined ? base : override;
@@ -1411,8 +1533,11 @@ async function main() {
1411
1533
  return;
1412
1534
  }
1413
1535
 
1414
- const stdout = extractText(payload?.tool_output ?? payload?.tool_result ?? payload, ['stdout', 'output', 'result']);
1415
- const stderr = extractText(payload?.tool_output ?? payload?.tool_result ?? payload, ['stderr', 'error']);
1536
+ // Claude Code carries Bash output under `tool_response`; omp/legacy payloads under
1537
+ // tool_output/tool_result.
1538
+ const toolOutputSource = payload?.tool_output ?? payload?.tool_response ?? payload?.tool_result ?? payload;
1539
+ const stdout = extractText(toolOutputSource, ['stdout', 'output', 'result']);
1540
+ const stderr = extractText(toolOutputSource, ['stderr', 'error']);
1416
1541
  const exitCode = extractExitCode(payload);
1417
1542
  if (!stdout.trim() && !stderr.trim()) {
1418
1543
  process.exit(0);
@@ -1432,6 +1557,12 @@ async function main() {
1432
1557
  return;
1433
1558
  }
1434
1559
 
1560
+ // 3.5.11: content reads, bounded pipelines and chained commands pass through raw.
1561
+ if (isVerbatimOutputCommand(command)) {
1562
+ process.exit(0);
1563
+ return;
1564
+ }
1565
+
1435
1566
  const requestKey = buildCompactMachineKey('tool-output-v1', {
1436
1567
  command,
1437
1568
  stdoutHash: buildCompactMachineKey('stdout', stripAnsi(stdout)),
@@ -1479,7 +1610,9 @@ async function main() {
1479
1610
  exitCode,
1480
1611
  }, sessionConfig);
1481
1612
  }
1482
- process.stdout.write(String(cached.content));
1613
+ process.stdout.write(buildCompressedHookOutput(payload, String(cached.content), {
1614
+ rawPath: cached.metadata?.rawPath ?? '',
1615
+ }));
1483
1616
  return;
1484
1617
  }
1485
1618
  }
@@ -1511,7 +1644,9 @@ async function main() {
1511
1644
  recoveryReason: historyMatch.recoveryReason,
1512
1645
  truncated: historyMatch.truncated,
1513
1646
  });
1514
- process.stdout.write(String(historyMatch.summary));
1647
+ process.stdout.write(buildCompressedHookOutput(payload, String(historyMatch.summary), {
1648
+ rawPath: historyMatch.rawPath,
1649
+ }));
1515
1650
  return;
1516
1651
  }
1517
1652
 
@@ -1607,7 +1742,9 @@ async function main() {
1607
1742
  });
1608
1743
  }
1609
1744
 
1610
- process.stdout.write(result.summary);
1745
+ process.stdout.write(buildCompressedHookOutput(payload, result.summary, {
1746
+ rawPath: rawOutputMetadata.rawPath,
1747
+ }));
1611
1748
  }
1612
1749
 
1613
1750
  // BUG-C23-13: only run main() on direct CLI invocation — an unguarded bottom
@@ -82,8 +82,8 @@ Next: <bước kế tiếp chính xác>
82
82
  - Subagent ghi **full log vào task file trên đĩa**, chỉ trả về orchestrator ≤10 dòng (executor) / ≤6 dòng (reviewer). Paste log ngược lại orchestrator là nguyên nhân số 1 làm run chết vì hết context.
83
83
  - Hết mỗi wave: commit, ghi cursor, **collapse** wave đó còn 1 dòng/task trong bộ nhớ làm việc, rồi chạy tiếp.
84
84
  - Yêu cầu `/compact` **chỉ** được đặt ở cuối command, giữa 2 cycle. Giữa cycle thì tuyệt đối không — state đã nằm hết ở git + `INDEX.md` + `RUN.md` nên compact ở ranh giới cycle không mất gì.
85
- - Vượt `compact.hardCapTokens` (mặc định 500k = 50% của context window 1M) mà `RUN.md` còn run dở **hoặc ordinary routed task có session execution ledger còn thiếu completion evidence**: `context-hardcap-gate` cho thêm `compact.hardCapGraceCalls` (mặc định 10) tool call rồi mới chặn cứng. **Grace đó chỉ để hạ cánh** — hoàn tất edit/verification đang dở và ghi state resume; không mở task mới, không đọc thêm file, không spawn agent. Hết grace là chặn thật; budget chỉ reset khi ước lượng token thực sự giảm (có compact thật), không reset theo wave.
86
- - Không hook nào gọi được `/compact` — đó là lệnh client-only. Nhưng từ 2.1.3, settings mặc định đặt `env.CLAUDE_CODE_AUTO_COMPACT_WINDOW` = 70% của `hardCapTokens` (mặc định 350000 < 500k), render lúc install, nên **client tự auto-compact trước khi gate chặn**. Đường thường: auto-compact chạy → `handoff-resume.sh` replay cursor cho handoff run hoặc tiêu thụ resume intent cho ordinary task → chạy tiếp, không cần người gõ gì. Grace window ở trên chỉ còn là lưới an toàn.
85
+ - Vượt `compact.hardCapTokens` (mặc định 235k, trong `compact.contextWindowTokens` 250k) mà `RUN.md` còn run dở **hoặc ordinary routed task có session execution ledger còn thiếu completion evidence**: `context-hardcap-gate` cho thêm `compact.hardCapGraceCalls` (mặc định 10) tool call rồi mới chặn cứng. **Grace đó chỉ để hạ cánh** — hoàn tất edit/verification đang dở và ghi state resume; không mở task mới, không đọc thêm file, không spawn agent. Hết grace là chặn thật; budget chỉ reset khi ước lượng token thực sự giảm (có compact thật), không reset theo wave.
86
+ - Không hook nào gọi được `/compact` — đó là lệnh client-only. Nhưng từ 2.1.3, settings mặc định đặt `env.CLAUDE_CODE_AUTO_COMPACT_WINDOW` = `autoCompactWindowRatio` × `hardCapTokens` (mặc định 0.8 × 235k = 188000) và `env.CLAUDE_CODE_MAX_CONTEXT_TOKENS` = `contextWindowTokens` (250000), render lúc install, nên **client tự auto-compact trước khi gate chặn**. Đường thường: auto-compact chạy → `handoff-resume.sh` replay cursor cho handoff run hoặc tiêu thụ resume intent cho ordinary task → chạy tiếp, không cần người gõ gì. Grace window ở trên chỉ còn là lưới an toàn.
87
87
  - Sửa một trong hai số đó thì phải giữ `autoCompactWindow < hardCapTokens`. Đảo thứ tự là deadlock: gate chặn tool trước → transcript ngừng lớn → ngưỡng auto-compact không bao giờ tới. `tests/core/autoCompactWindow.test.js` khóa bất biến này.
88
88
 
89
89
  ### Git
@@ -12,9 +12,10 @@
12
12
  },
13
13
  "compact": {
14
14
  "enabled": true,
15
- "tokenThreshold": 150000,
16
- "hardCapTokens": 500000,
17
- "autoCompactWindowRatio": 0.7,
15
+ "tokenThreshold": 115000,
16
+ "contextWindowTokens": 250000,
17
+ "hardCapTokens": 235000,
18
+ "autoCompactWindowRatio": 0.8,
18
19
  "hardCapBlock": true,
19
20
  "hardCapGraceCalls": 10,
20
21
  "contextRotDetection": true,
@@ -681,8 +682,9 @@
681
682
  "compact": {
682
683
  "enabled": "B\u1eadt/t\u1eaft to\u00e0n b\u1ed9 helper compact c\u1ee7a UKit.",
683
684
  "tokenThreshold": "Ng\u01b0\u1ee1ng token chung cho runtime compact d\u00f9ng chung.",
684
- "hardCapTokens": "Ng\u01b0\u1ee1ng c\u1ee9ng tuy\u1ec7t \u0111\u1ed1i (m\u1eb7c \u0111\u1ecbnh 500000 token \u01b0\u1edbc l\u01b0\u1ee3ng = 50% c\u1ee7a context window 1M). Ch\u1ea1m/v\u01b0\u1ee3t ng\u01b0\u1ee1ng n\u00e0y th\u00ec context coi nh\u01b0 qu\u00e1 d\u00e0i \u2014 kh\u00f4ng ph\u1ea3i g\u1ee3i \u00fd n\u1eefa, l\u00e0 b\u1eaft bu\u1ed9c. PH\u1ea2I th\u1ea5p h\u01a1n context window th\u1eadt c\u1ee7a model, n\u1ebfu kh\u00f4ng API s\u1ebd b\u00e1o l\u1ed7i v\u01b0\u1ee3t context tr\u01b0\u1edbc khi gate k\u1ecbp ch\u1eb7n \u2014 model 200k th\u00ec h\u1ea1 xu\u1ed1ng 100000, model 256k th\u00ec 128000. C\u1ea3 env.CLAUDE_CODE_AUTO_COMPACT_WINDOW (.claude/settings.json) l\u1eabn compaction.thresholdTokens (.omp/config.yml) \u0111\u1ec1u \u0111\u01b0\u1ee3c SUY RA t\u1eeb s\u1ed1 n\u00e0y khi ch\u1ea1y ukit install, n\u00ean ch\u1ec9 c\u1ea7n s\u1eeda \u1edf \u0111\u00e2y r\u1ed3i c\u00e0i l\u1ea1i l\u00e0 auto-compact c\u1ee7a c\u1ea3 Claude Code v\u00e0 omp \u0111\u1ed5i theo.",
685
- "autoCompactWindowRatio": "Auto-compact ch\u1ea1y \u1edf bao nhi\u00eau ph\u1ea7n c\u1ee7a hardCapTokens (m\u1eb7c \u0111\u1ecbnh 0.7 \u2192 350000). Ph\u1ea3i < 1 \u0111\u1ec3 client t\u1ef1 compact TR\u01af\u1edaC khi context-hardcap-gate ch\u1eb7n tool; s\u1ed1 c\u00e0ng nh\u1ecf th\u00ec compact c\u00e0ng s\u1edbm v\u00e0 c\u00e0ng nhi\u1ec1u \u0111\u1ec7m an to\u00e0n.",
685
+ "contextWindowTokens": "Context window t\u1ed1i \u0111a UKit cho client d\u00f9ng (m\u1eb7c \u0111\u1ecbnh 250000, k\u1ec3 c\u1ea3 khi provider h\u1ed7 tr\u1ee3 1M). Render th\u00e0nh env.CLAUDE_CODE_MAX_CONTEXT_TOKENS \u2014 model alias gateway nh\u01b0 unic-opus kh\u00f4ng c\u00f3 trong b\u1ea3ng c\u1ee7a Claude Code n\u00ean n\u1ebfu thi\u1ebfu s\u1ed1 n\u00e0y client t\u1ef1 \u0111o\u00e1n 200k/1M v\u00e0 b\u1ecf qua budget UKit. Kh\u00f4ng khuy\u1ebfn kh\u00edch t\u0103ng.",
686
+ "hardCapTokens": "Ng\u01b0\u1ee1ng c\u1ee9ng tuy\u1ec7t \u0111\u1ed1i (m\u1eb7c \u0111\u1ecbnh 235000 token \u01b0\u1edbc l\u01b0\u1ee3ng, n\u1eb1m trong contextWindowTokens 250000). Ch\u1ea1m/v\u01b0\u1ee3t ng\u01b0\u1ee1ng n\u00e0y th\u00ec context-hardcap-gate ch\u1eb7n Edit/Write/Bash \u2014 kh\u00f4ng ph\u1ea3i g\u1ee3i \u00fd n\u1eefa, l\u00e0 b\u1eaft bu\u1ed9c. Ph\u1ea3i \u2264 contextWindowTokens. env.CLAUDE_CODE_AUTO_COMPACT_WINDOW (.claude/settings.json) v\u00e0 compaction.thresholdTokens (.omp/config.yml) \u0111\u1ec1u \u0111\u01b0\u1ee3c SUY RA t\u1eeb s\u1ed1 n\u00e0y khi ch\u1ea1y ukit install.",
687
+ "autoCompactWindowRatio": "Auto-compact ch\u1ea1y \u1edf bao nhi\u00eau ph\u1ea7n c\u1ee7a hardCapTokens (m\u1eb7c \u0111\u1ecbnh 0.8 \u2192 188000). Ph\u1ea3i < 1 \u0111\u1ec3 client t\u1ef1 compact TR\u01af\u1edaC khi context-hardcap-gate ch\u1eb7n tool; s\u1ed1 c\u00e0ng nh\u1ecf th\u00ec compact c\u00e0ng s\u1edbm.",
686
688
  "hardCapBlock": "N\u1ebfu true, hook context-hardcap-gate ch\u1eb7n c\u1ee9ng Edit/Write/Bash (exit 2) khi v\u01b0\u1ee3t hardCapTokens, cho t\u1edbi khi c\u00f3 compact th\u1eadt (PreCompact) reset l\u1ea1i b\u1ed9 \u0111\u1ebfm.",
687
689
  "hardCapGraceCalls": "S\u1ed1 tool call \u0111\u01b0\u1ee3c ph\u00e9p ch\u1ea1y ti\u1ebfp sau khi v\u01b0\u1ee3t hardCapTokens khi handoff run trong docs/AI_HANDOFF/RUN.md ho\u1eb7c ordinary routed task c\u00f3 session execution ledger c\u00f2n dang d\u1edf (m\u1eb7c \u0111\u1ecbnh 10). \u0110\u00e2y ch\u1ec9 l\u00e0 landing window: ho\u00e0n t\u1ea5t edit/verification \u0111ang d\u1edf v\u00e0 ghi state resume, kh\u00f4ng m\u1edf task m\u1edbi. H\u1ebft grace l\u00e0 ch\u1eb7n c\u1ee9ng nh\u01b0 c\u0169. Budget t\u00ednh theo m\u1ed7i \u0111\u1ee3t v\u01b0\u1ee3t cap, ch\u1ec9 reset khi \u01b0\u1edbc l\u01b0\u1ee3ng token th\u1eadt s\u1ef1 gi\u1ea3m (c\u00f3 compact th\u1eadt) \u2014 kh\u00f4ng reset theo wave.",
688
690
  "contextRotDetection": "Ph\u00e1t hi\u1ec7n context qu\u00e1 d\u00e0i/d\u1ec5 m\u1ee5c \u0111\u1ec3 gi\u1eef l\u1ea1i state quan tr\u1ecdng tr\u01b0\u1edbc khi AI nh\u1edb sai.",