Skip to content
Merged
Show file tree
Hide file tree
Changes from 9 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1065,6 +1065,7 @@ ECC/
| | |-- session-end.js # Save state on session end
| | |-- pre-compact.js # Pre-compaction state saving
| | |-- suggest-compact.js # Strategic compaction suggestions
| | |-- context-gate.js # Opt-in checkpoint-and-restart gate at 90% context (ECC_CONTEXT_GATE_MODE=enforce; advisory by default)
| | |-- evaluate-session.js # Extract patterns from sessions
| |-- setup-package-manager.js # Interactive PM setup
|
Expand Down
1 change: 1 addition & 0 deletions hooks/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ User request → Claude picks a tool → PreToolUse hook runs → Tool executes
- **Stop** hooks run after each Claude response.
- **SessionStart/SessionEnd** hooks run at session lifecycle boundaries.
- **PreCompact** hooks run before context compaction, useful for saving state.
- **UserPromptSubmit** hooks run when the user submits a prompt, before Claude sees it. Their JSON output can inject `additionalContext` for the turn (used by `user-prompt:context-gate` to run an end-of-session checkpoint protocol at high context usage). **Enforcement is opt-in**: by default the gate runs in `advisory` mode — completely inert, doing no per-prompt work and suppressing nothing. Setting `ECC_CONTEXT_GATE_MODE=enforce` turns on the protocol: at or above the gate threshold it orders a clean stopping point and a session-scoped checkpoint (written under the handoff dir, never the project root), and the advisory hooks defer — `suggest-compact` and `ecc-context-monitor` suppress their `/compact` suggestions and context warnings (via `scripts/lib/context-gate-state.js`) so the gate owns end-of-session messaging without contradiction. When the gate cannot evaluate usage (missing/unreadable transcript), or is left in advisory mode, those hooks keep their own warnings.

## Hooks in This Plugin

Expand Down
9 changes: 9 additions & 0 deletions hooks/hooks.json
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,15 @@
"timeout": 10
}
]
},
{
"hooks": [
{
"type": "command",
"command": "node -e \"const p=require('path');const r=(function(){var p=require('path'),f=require('fs'),o=require('os');var e=process.env.CLAUDE_PLUGIN_ROOT;if(e&&e.trim())return e.trim();var d=p.join(o.homedir(),'.claude');function L(x){try{return require(p.join(x,'scripts','lib','resolve-ecc-root')).resolveEccRoot()}catch(_){return null}}var r=L(d);if(r)return r;var s=['ecc','ecc@ecc','marketplaces/ecc','everything-claude-code','everything-claude-code@everything-claude-code','marketplaces/everything-claude-code'];for(var i=0;i<s.length;i++){r=L(p.join(d,'plugins',s[i]));if(r)return r}try{var g=['ecc','everything-claude-code'];for(var j=0;j<g.length;j++){var c=p.join(d,'plugins','cache',g[j]);var O=f.readdirSync(c);for(var k=0;k<O.length;k++){var q=p.join(c,O[k]);var V=f.readdirSync(q);for(var m=0;m<V.length;m++){r=L(p.join(q,V[m]));if(r)return r}}}}catch(_){}return d})();const s=p.join(r,'scripts/hooks/plugin-hook-bootstrap.js');process.env.CLAUDE_PLUGIN_ROOT=r;process.argv.splice(1,0,s);require(s)\" node scripts/hooks/run-with-flags.js user-prompt:context-gate scripts/hooks/context-gate.js standard,strict",

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Custom installs miss the gate

The new launcher searches only under ~/.claude, unlike the neighboring launchers that honor CLAUDE_CONFIG_DIR. If a managed install exists only under a custom config directory and CLAUDE_PLUGIN_ROOT is unset, the launcher cannot load the bootstrap and the gate never runs.

Use the same root lookup as the other hooks.

Prompt To Fix With AI
This is a comment left during a code review.
Path: hooks/hooks.json
Line: 119

Comment:
**Custom installs miss the gate**

The new launcher searches only under `~/.claude`, unlike the neighboring launchers that honor `CLAUDE_CONFIG_DIR`. If a managed install exists only under a custom config directory and `CLAUDE_PLUGIN_ROOT` is unset, the launcher cannot load the bootstrap and the gate never runs.

Use the same root lookup as the other hooks.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

"timeout": 10
}
]
}
],
"PreCompact": [
Expand Down
5 changes: 5 additions & 0 deletions hooks/hooks.metadata.json
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,11 @@
"id": "prompt:hookify-runtime",
"description": "Evaluate project-local Hookify prompt rules before a user prompt is processed",
"fingerprint": "e59b2f099bf7"
},
{
"id": "user-prompt:context-gate",
"description": "Opt-in checkpoint-and-restart gate (ECC_CONTEXT_GATE_MODE=enforce): at >=90% context, order a clean stopping point, a session-scoped checkpoint under the handoff dir, and a fresh-session resume command. Default mode is advisory — inert, suppresses nothing",
"fingerprint": "13d8180d18ec"
}
],
"PreCompact": [
Expand Down
386 changes: 386 additions & 0 deletions scripts/hooks/context-gate.js

Large diffs are not rendered by default.

26 changes: 23 additions & 3 deletions scripts/hooks/ecc-context-monitor.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ const fs = require('fs');
const os = require('os');
const path = require('path');
const { sanitizeSessionId, readBridge, renameWithRetry } = require('../lib/session-bridge');
const { gateOwnsTranscript } = require('../lib/context-gate-state');

const CONTEXT_WARNING_PCT = 35;
const CONTEXT_CRITICAL_PCT = 25;
Expand Down Expand Up @@ -122,8 +123,17 @@ function evaluateConditions(bridge, options = {}) {
const warnings = [];
const remaining = bridge.context_remaining_pct;

// Context warnings (skip if no context data)
if (remaining !== null && remaining !== undefined) {
// Defer to the context-gate ONLY when the caller confirmed it is active
// (options.gateActive, resolved from the transcript by gateOwnsTranscript):
// the critical message below ("ask the user ... do NOT autonomously save
// state or write handoff files") directly contradicts the gate's checkpoint
// order on the same turns. A gate that cannot evaluate usage (missing or
// unreadable transcript) reports inactive, so this warning stays as the
// fallback and a low-context session is never left with no guidance.
const gateActive = options.gateActive === true;

// Context warnings (skip if no context data, or if the gate is active)
if (remaining !== null && remaining !== undefined && !gateActive) {
if (remaining <= CONTEXT_CRITICAL_PCT) {
warnings.push({
severity: 3,
Expand Down Expand Up @@ -229,7 +239,17 @@ function run(rawInput) {
// If bridge is stale, null out context data (still check cost/scope/loop)
const evalBridge = isStale ? { ...bridge, context_remaining_pct: null } : bridge;

const warnings = evaluateConditions(evalBridge, { costWarnings: costWarningsEnabled() });
// Gate deference needs the transcript (gateOwnsTranscript reads real
// usage, never the bridge approximation). Only pay that read when a
// context warning could actually fire.
const transcriptPath = typeof input.transcript_path === 'string' ? input.transcript_path : '';
const remainingPct = evalBridge.context_remaining_pct;
const contextWarningPossible = remainingPct !== null && remainingPct !== undefined && remainingPct <= CONTEXT_WARNING_PCT;

const warnings = evaluateConditions(evalBridge, {
costWarnings: costWarningsEnabled(),
gateActive: contextWarningPossible && gateOwnsTranscript(transcriptPath)
});
if (warnings.length === 0) {
// Clear dedupe state when the condition resolves, so the SAME warning text
// recurring later (context dips, recovers, dips again; a loop that stops
Expand Down
26 changes: 20 additions & 6 deletions scripts/hooks/suggest-compact.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ const {
computeContextBucket,
formatWindowLabel
} = require('../lib/transcript-context');
const { isGateActive, gateOwnsTranscript } = require('../lib/context-gate-state');

const COUNTER_FILE_PREFIX = 'claude-tool-count-';
const CONTEXT_BUCKET_FILE_PREFIX = 'claude-context-bucket-';
Expand Down Expand Up @@ -161,7 +162,8 @@ function readLastContextBucket(bucketFile) {
/**
* Build the context-size suggestion when the transcript shows the session has
* crossed into a new context bucket. Returns null when the signal is silent
* (no transcript, below threshold, disabled, or already fired for the bucket).
* (no transcript, below threshold, disabled, gate active, or already fired
* for the bucket).
*
* Never throws — any transcript or state-file failure silently disables the
* signal so the hook keeps its always-exit-0 contract.
Expand All @@ -171,7 +173,14 @@ function buildContextSuggestion(transcriptPath, bucketFile, env) {
const usage = readLatestContextTokens(transcriptPath);
if (!usage) return null;

const { windowTokens, inferred } = resolveContextWindow(usage.tokens, usage.model);
const { windowTokens, inferred } = resolveContextWindow(usage.tokens, usage.model, env);

// Defer to the context-gate at/above its threshold: the gate is ordering a
// checkpoint-and-restart there, and a /compact suggestion in the same
// band is a contradictory instruction (compaction is the lossy path the
// gate exists to preempt).
if (isGateActive({ tokens: usage.tokens, windowTokens, env })) return null;

const threshold = resolveContextThreshold(env, windowTokens);
if (threshold <= 0) return null; // COMPACT_CONTEXT_THRESHOLD=0 disables

Expand Down Expand Up @@ -242,10 +251,15 @@ async function main() {
}

// Secondary signal: tool-call count at threshold, then every 25 calls.
if (count === threshold) {
messages.push(`[StrategicCompact] ${threshold} tool calls reached - consider /compact if transitioning phases`);
} else if (count > threshold && (count - threshold) % 25 === 0) {
messages.push(`[StrategicCompact] ${count} tool calls - good checkpoint for /compact if context is stale`);
// Also silenced while the context-gate is active — the gate check reads
// the transcript, so it only runs when a count message would fire.
const countWouldFire = count === threshold || (count > threshold && (count - threshold) % 25 === 0);
if (countWouldFire && !gateOwnsTranscript(transcriptPath, process.env)) {
if (count === threshold) {
messages.push(`[StrategicCompact] ${threshold} tool calls reached - consider /compact if transitioning phases`);
} else {
messages.push(`[StrategicCompact] ${count} tool calls - good checkpoint for /compact if context is stale`);
}
}

// log() writes to stderr (debug log). Per the Claude Code hooks guide,
Expand Down
224 changes: 224 additions & 0 deletions scripts/lib/context-gate-state.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,224 @@
/**
* Context-gate state — shared threshold resolution and activity check.
*
* Single source of truth for the context-gate thresholds so the advisory
* hooks (suggest-compact, ecc-context-monitor) can defer to the gate
* instead of emitting contradictory guidance in the same context band.
* The gate orders a checkpoint-and-restart; the advisory hooks suggest
* /compact or "ask the user" — both must go silent once the gate owns
* the turn.
*/

'use strict';

const { isHookEnabled } = require('./hook-flags');
const { readLatestContextTokens, resolveContextWindow } = require('./transcript-context');

const DEFAULT_GATE_PCT = 90;
const DEFAULT_EMERGENCY_PCT = 96;
const MIN_PCT = 1;
const MAX_PCT = 100;

/**
* Gate operating mode. Enforcement is OPT-IN: a default install leaves the
* gate in `advisory`, where it is completely inert and suppresses nothing —
* the advisory hooks (suggest-compact, ecc-context-monitor) keep their normal
* behavior. Only `enforce` turns on the checkpoint-and-restart order and the
* advisory-hook deference.
*/
const DEFAULT_GATE_MODE = 'advisory';
const GATE_MODE_ADVISORY = 'advisory';
const GATE_MODE_ENFORCE = 'enforce';
const GATE_MODE_OFF = 'off';
const VALID_GATE_MODES = new Set([GATE_MODE_ADVISORY, GATE_MODE_ENFORCE, GATE_MODE_OFF]);

/** Hook id and profiles exactly as registered in hooks/hooks.json. */
const GATE_HOOK_ID = 'user-prompt:context-gate';
const GATE_HOOK_PROFILES = 'standard,strict';

/** Env names already warned about this process — keeps the note one-time. */
const warnedEnvNames = new Set();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Invalid setting warning repeats

If ECC_CONTEXT_GATE_PCT=150 remains configured, the warning is remembered only within one hook process. Each fresh gate or advisory-hook invocation prints it again. Repeated prompts and tool calls therefore produce recurring hook-log noise, making other messages harder to notice.

Artifacts

Executable hook warning reproduction script

  • The authored Node script launches the registered hook runner in fresh processes against a transcript and monitor bridge, then checks warning counts and hook outputs.

Hook output with a valid gate threshold

  • Running the reproduction script with threshold 90 produced no warnings across nine hook calls, establishing the comparison baseline.

Hook output with an invalid gate threshold

  • Running the same script with threshold 150 produced one warning per fresh hook call, confirming cross-process repetition.

View artifacts

T-Rex Ran code and verified through T-Rex

Prompt To Fix With AI
This is a comment left during a code review.
Path: scripts/lib/context-gate-state.js
Line: 27

Comment:
**Invalid setting warning repeats**

If `ECC_CONTEXT_GATE_PCT=150` remains configured, the warning is remembered only within one hook process. Each fresh gate or advisory-hook invocation prints it again. Repeated prompts and tool calls therefore produce recurring hook-log noise, making other messages harder to notice.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!


/**
* Emit a one-time stderr note that an env override was present but rejected.
* Deduped per env name so the gate re-firing on every prompt (and multiple
* hooks resolving the same setting) cannot turn this into a spam stream.
* Never throws — a logging failure must not change threshold resolution.
* @param {string} name
* @param {*} raw
* @param {number} fallback
*/
function warnRejected(name, raw, fallback) {
if (warnedEnvNames.has(name)) return;
warnedEnvNames.add(name);
try {
process.stderr.write(
`[context-gate] ignoring invalid ${name}="${raw}" ` +
`(expected a whole integer 0-100); using default ${fallback}.\n`
);
} catch {
/* stderr unavailable — resolution still returns the deterministic fallback */
}
}

/**
* Emit a one-time stderr note that ECC_CONTEXT_GATE_MODE was present but
* unrecognized. Shares the per-process dedupe Set with warnRejected so a
* typo can never turn the re-firing hook into a stderr spam stream, and a
* typo'd mode can never silently flip enforcement on. Never throws.
* @param {*} raw
*/
function warnRejectedMode(raw) {
const name = 'ECC_CONTEXT_GATE_MODE';
if (warnedEnvNames.has(name)) return;
warnedEnvNames.add(name);
try {
process.stderr.write(
`[context-gate] ignoring invalid ${name}="${raw}" ` +
`(expected advisory, enforce, or off); using default ${DEFAULT_GATE_MODE}.\n`
);
} catch {
/* stderr unavailable — resolution still returns the deterministic fallback */
}
}

/**
* Resolve the gate operating mode from the environment. Enforcement is
* opt-in: an unset, blank, or unrecognized value resolves to `advisory`
* (inert, suppresses nothing). A rejected value also surfaces a one-time
* stderr note, so a mistyped mode never silently enables — or disables —
* the checkpoint-and-restart order.
* @param {object} [env]
* @returns {'advisory'|'enforce'|'off'}
*/
function resolveGateMode(env = process.env) {
const raw = env && env.ECC_CONTEXT_GATE_MODE;
if (raw === undefined || raw === null) return DEFAULT_GATE_MODE;
const str = String(raw).trim().toLowerCase();
if (str === '') return DEFAULT_GATE_MODE;
if (VALID_GATE_MODES.has(str)) return str;
warnRejectedMode(raw);
return DEFAULT_GATE_MODE;
}

/**
* Resolve a percent setting from the environment.
* `0` disables the gate entirely; invalid values fall back to the default.
* A whole decimal integer is required — parseInt-style partial parses
* ('90abc' -> 90, '0x1' -> 0) would silently shift or disable the gate.
* When an override is PRESENT but rejected (e.g. a typo'd '50.5' or '150'),
* the return stays the deterministic fallback, but a one-time stderr note
* surfaces the misconfiguration so a silently re-armed default gate — which
* orders session restarts — does not go unnoticed.
* @param {object} env
* @param {string} name
* @param {number} fallback
* @returns {number}
*/
function resolvePct(env, name, fallback) {
const raw = env && env[name];
if (raw !== undefined && raw !== null && raw !== '') {
const str = String(raw).trim();
// A whitespace-only value is treated as unset: silent fallback, no note.
if (str === '') return fallback;
if (/^(?:0|[1-9]\d*)$/.test(str)) {
const parsed = Number(str);
if (parsed === 0) return 0;
if (Number.isInteger(parsed) && parsed >= MIN_PCT && parsed <= MAX_PCT) {
return parsed;
}
}
// Present but unparseable or out of range: deterministic fallback + one note.
warnRejected(name, raw, fallback);
}
return fallback;
}

/**
* Gate threshold percent for the given environment (0 = gate disabled).
* @param {object} [env]
* @returns {number}
*/
function resolveGatePct(env = process.env) {
return resolvePct(env, 'ECC_CONTEXT_GATE_PCT', DEFAULT_GATE_PCT);
}

/**
* Emergency escalation percent for the given environment.
* @param {object} [env]
* @returns {number}
*/
function resolveEmergencyPct(env = process.env) {
return resolvePct(env, 'ECC_CONTEXT_GATE_EMERGENCY_PCT', DEFAULT_EMERGENCY_PCT);
}

/**
* True when the context-gate hook is ENFORCING for this environment: the
* operator opted into enforce mode, the profile allows it, it is not in
* ECC_DISABLED_HOOKS, and the threshold is not 0. Says nothing about current
* occupancy. In the default (advisory) mode this is false, so the advisory
* hooks never defer and the gate never fires — enforcement is opt-in.
* @param {object} [env]
* @returns {boolean}
*/
function isGateEnabled(env = process.env) {
if (resolveGateMode(env) !== GATE_MODE_ENFORCE) return false;
if (resolveGatePct(env) === 0) return false;
return isHookEnabled(GATE_HOOK_ID, { profiles: GATE_HOOK_PROFILES, env });
}

/**
* True when the gate is enabled AND the observed occupancy has reached
* its threshold — i.e. the gate is issuing (or about to issue) the
* checkpoint order and advisory hooks must stay silent.
* @param {object} params
* @param {number} params.tokens - Observed context tokens.
* @param {number} params.windowTokens - Resolved window size.
* @param {object} [params.env]
* @returns {boolean}
*/
function isGateActive({ tokens, windowTokens, env = process.env }) {
if (!Number.isFinite(tokens) || !Number.isFinite(windowTokens) || windowTokens <= 0) {
return false;
}
if (!isGateEnabled(env)) return false;
const pct = Math.floor((tokens / windowTokens) * 100);
return pct >= resolveGatePct(env);
Comment on lines +184 to +186

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Warnings stop before checkpoint instructions

With ECC_CONTEXT_GATE_MODE=enforce, a tool chain can cross 90% after UserPromptSubmit ran below the threshold. isGateActive() then silences both advisory hooks, but the gate cannot issue its checkpoint instructions until the next user prompt. Long-running work can reach context exhaustion without those instructions.

Keep the warnings until the gate has actually issued its message, or run the gate when tool calls cross the threshold.

Knowledge Base Used: Hooks, memory, and host events

Prompt To Fix With AI
This is a comment left during a code review.
Path: scripts/lib/context-gate-state.js
Line: 184-186

Comment:
**Warnings stop before checkpoint instructions**

With `ECC_CONTEXT_GATE_MODE=enforce`, a tool chain can cross 90% after `UserPromptSubmit` ran below the threshold. `isGateActive()` then silences both advisory hooks, but the gate cannot issue its checkpoint instructions until the next user prompt. Long-running work can reach context exhaustion without those instructions.

Keep the warnings until the gate has actually issued its message, or run the gate when tool calls cross the threshold.

**Knowledge Base Used:** [Hooks, memory, and host events](https://app.greptile.com/-/switch-tenant?tenant=ecc-tools&next=%2Fcustom-context%2Fknowledge-base%2Faffaan-m%2Fecc%2F-%2Fdocs%2Fhooks-memory-and-host-events.md)

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

}

/**
* True when the gate is CONFIRMED active for the given session transcript:
* gate enabled, transcript readable, usage resolved, and occupancy at/above
* the threshold. Returns false whenever the gate cannot evaluate usage
* (missing/unreadable transcript, no usage record) — callers use this to
* decide whether to defer to the gate, and a gate that cannot fire must
* never silence its fallbacks. Never throws.
* @param {string} transcriptPath
* @param {object} [env]
* @returns {boolean}
*/
function gateOwnsTranscript(transcriptPath, env = process.env) {
try {
const usage = readLatestContextTokens(transcriptPath);
if (!usage) return false;
const { windowTokens } = resolveContextWindow(usage.tokens, usage.model, env);
return isGateActive({ tokens: usage.tokens, windowTokens, env });
} catch {
return false;
}
}

module.exports = {
resolvePct,
resolveGateMode,
gateOwnsTranscript,
resolveGatePct,
resolveEmergencyPct,
isGateEnabled,
isGateActive,
DEFAULT_GATE_PCT,
DEFAULT_EMERGENCY_PCT,
DEFAULT_GATE_MODE,
GATE_HOOK_ID,
GATE_HOOK_PROFILES
};
Loading