clew_hook.py¶
clew_hook.py
A PostToolUse hook that names the index once per session, and can do nothing else.
_clear
None clew_hook._clear(str suffix)
Clear a tally, so pressure can fall as well as rise.
Source · 21 lines
def _clear(suffix: str) -> None:
"""THE DECAY THE POLICY WAS MISSING. Without it the tally is monotonic and the loudest tier is
a one-way door: a session measured at 1,339 searches needed ~408 consecutive index calls to
get back under a threshold of 20, so it never did, and the escalation designed to be rare
became the constant case.
Truncation, not deletion — the path is already ours and re-creating it invites a race with a
concurrent append. Every failure is swallowed for the same reason every other path here
swallows: this component must never be the thing that breaks a tool call.
@brief Reset one tally to zero.
@return None.
@version 1
"""
try:
with open(_marker_path() + suffix, "wb"):
pass
except Exception:
pass
Activity · 5 steps
Flows
_comment_note
str | None clew_hook._comment_note()
The comment note when the waiting count changed since it was last said, else None.
Source · 20 lines
def _comment_note() -> str | None:
"""SAID ONCE PER CHANGE. The session tally's SIZE is the count last announced (the same
byte-tally as the search pressure); a changed count is announced and recorded, a count of 0
resets it.
@brief Comment note.
@return Reply or None.
@version 1
"""
waiting = _waiting()
if waiting == _tally(_COMMENTS_SUFFIX):
return None
try:
with open(_marker_path() + _COMMENTS_SUFFIX, "wb") as handle:
handle.write(b"." * waiting)
except Exception:
return None
return _comments_payload(waiting) if waiting else None
Activity · 9 steps
Flows
_drain_stdin
bytes clew_hook._drain_stdin()
Drain stdin fully while keeping only the first _MAX_EVENT bytes.
Source · 31 lines
def _drain_stdin() -> bytes:
"""DRAIN EVERYTHING, KEEP ALMOST NOTHING. The caller writes the event into a pipe and would
block if nobody emptied it, so the read cannot be cut short — but nothing requires holding the
whole thing in memory. `sys.stdin.buffer.read()` did, and an adversarial audit measured a
2 GiB `tool_response` costing 2.4 s and proportional RAM on a component whose budget is ~45 ms
and which runs after EVERY matching tool call. A `Read` of a large file puts that file's whole
content in `tool_response`.
So this keeps the first `_MAX_EVENT` bytes — more than any real event's leading fields need —
and discards the rest as it goes. Memory becomes O(cap) instead of O(event). The time to pull
the bytes off the pipe is irreducible if the caller is not to block, and that is the tradeoff
being made deliberately rather than by omission.
A truncated prefix will not parse as JSON, which is correct: it lands on the fileless note.
@brief Read all of stdin, retaining a bounded prefix.
@return Up to `_MAX_EVENT` bytes.
@version 1
"""
chunks: list[bytes] = []
kept = 0
while True:
chunk = sys.stdin.buffer.read(_READ_CHUNK)
if not chunk:
break
if kept < _MAX_EVENT:
chunks.append(chunk[: _MAX_EVENT - kept])
kept += len(chunks[-1])
return b"".join(chunks)
Activity · 10 steps
Flows
_emit
None clew_hook._emit(str payload)
Write a reply, flushing inside the guard; on failure point stdout at the null device.
Source · 20 lines
def _emit(payload: str) -> None:
"""THE GUARDED WRITE `main` HAD INLINE, now shared with the comment note; its reasoning is in
`main`.
@brief Emit.
@return None.
@version 1
"""
try:
sys.stdout.write(payload)
sys.stdout.flush()
except Exception:
try:
null = os.open(os.devnull, os.O_WRONLY)
os.dup2(null, sys.stdout.fileno())
os.close(null)
except Exception:
pass
Activity · 10 steps
Flows
_event_command
str clew_hook._event_command(bytes raw)
The raw command a Bash event carries, without trusting anything else in it.
Source · 29 lines
def _event_command(raw: bytes) -> str:
"""SAME RUNGS AS `_target_name`, and every one of them falls to `''`. This runs on the hot
path — before the note is due — so it must be as unable to raise as that function is: a
traceback here reaches the model through stderr, which is the channel this file exists to
keep shut.
`''` IS NOT AN INSPECTION, so an unreadable event goes quiet. That is the right default for
the one modality this gates: a Bash call whose command cannot be read is not evidence that a
file was inspected.
@brief Read the Bash command out of the event.
@return The command, or ''.
@version 1
"""
if len(raw) > _MAX_EVENT:
return ""
try:
event = json.loads(raw)
except Exception:
return ""
if not isinstance(event, dict):
return ""
tool_input = event.get("tool_input")
if not isinstance(tool_input, dict):
return ""
command = tool_input.get("command")
return command if isinstance(command, str) else ""
Activity · 13 steps
Flows
_input_value
object clew_hook._input_value(object event, str modality)
The raw inspected-path value for one modality, before any sanitising.
Source · 25 lines
def _input_value(event: object, modality: str) -> object:
"""SHARED WITH `_target_name` SO ONE RULE READS THE EVENT. Two extractions would be two
answers to "which file did this call inspect", and the containment check below and the note's
own name would eventually disagree about it.
RETURNS THE VALUE UNSANITISED, which `_target_name` then reduces to a safe token. Nothing here
echoes it: the only other caller compares it against the repository root and discards it. That
is the one use for which a basename is useless and a raw path is safe.
@brief Read the modality's `tool_input` field.
@return The raw value, or None.
@version 1
"""
if not isinstance(event, dict):
return None
field = _FIELD_FOR.get(modality)
if field is None:
return None
tool_input = event.get("tool_input")
if not isinstance(tool_input, dict):
return None
value = tool_input.get(field)
return _bash_target(value) if modality == SHELL_FLAG else value
Activity · 10 steps
Flows
_is_due
bool clew_hook._is_due(int pressure)
Whether this search should carry a note, given the session's pressure.
Source · 19 lines
def _is_due(pressure: int) -> bool:
"""THE LOUD TIER NO LONGER FIRES ON EVERY CALL, AND THAT IS A FIX RATHER THAN A SOFTENING. It
did, and one measured session took ~30 near-identical injections past the threshold — which is
precisely the wallpaper condition this file's own reasoning says it exists to avoid. A banner on
every call is read as boilerplate, so the tier that matters most was the one being filtered
hardest. It now speaks every `_LOUD_INTERVAL` calls; the count keeps climbing, so the text
still escalates and the prompt cache still breaks.
@brief Apply the escalation policy to a pressure value.
@return True when a note is due.
@version 2
"""
if pressure < _QUIET_BELOW:
return False
if pressure >= _LOUD_AT:
return pressure % _LOUD_INTERVAL == 0
return pressure % _INTERVAL == 0
Activity · 5 steps
Flows
_is_inspection
bool clew_hook._is_inspection(object command)
Whether a shell command inspected a file at all — the question _bash_target does not ask.
Source · 33 lines
def _is_inspection(command: object) -> bool:
"""gh#11. This hook fired on EVERY Bash call, so `git push`, `sleep 25` and `rm -rf` were
counted and then REPORTED as file inspections — the note's own text says "N file-inspection
calls, no index call". The count was not merely noisy, it was false, and a payload that
misdescribes itself teaches a reader to discount everything else it says, which is the
argument this file makes about itself everywhere else.
Sampled from one real session, all six of these fired it: `git push origin main`,
`git status --short`, `gh run watch`, `sleep 20`, `rm -rf`, `pre-commit run --all-files`.
Not one is a question any index could answer, so the remedy the note names applies to none
of them.
ASKS A DIFFERENT QUESTION FROM `_bash_target`, WHICH IS WHY IT READS FURTHER. That function
asks "which file, unambiguously", and being wrong there costs a wrong filename — so it takes
the first segment only and refuses on any doubt. This asks "was anything inspected at all",
where being wrong costs one note, so it looks at EVERY segment: `cd x && grep ...` is a real
inspection that a first-segment rule would miss.
The verb is basenamed, so `/usr/bin/cat` counts. An unrecognised verb is not an inspection —
the same bias toward silence, pointed the other way.
@brief Whether the command reads a file.
@return True for an inspection.
@version 1
"""
if not isinstance(command, str) or any(bad in command for bad in _WRITE_MARKERS):
return False
segments = [command]
for sep in _SEGMENT_SPLIT:
segments = [part for whole in segments for part in whole.split(sep)]
return any(_segment_verb(segment) in _INSPECT_VERBS for segment in segments)
Activity · 6 steps
Flows
_marker_path
str clew_hook._marker_path()
The once-per-session marker path for this hook invocation.
Source · 25 lines
def _marker_path() -> str:
"""The marker gives "once per session" its memory: the hook is a fresh process every time, so
the fact that it has already spoken has to live somewhere.
KEYED ON THE SESSION. `CLAUDE_CODE_SESSION_ID` comes from the environment — Claude Code's own,
the same trust level as TMPDIR — and NOT from stdin, where repository-controlled text arrives.
It was confirmed present in a real hook process before being relied on. An earlier version
keyed on `os.getppid()` and fired on EVERY tool call in production, because each invocation
gets a fresh parent.
FILTERED THROUGH AN ALLOWLIST. The session id is arbitrary text going into a filename, so
everything outside `_SAFE` is dropped — no separator, dot or control character can reach the
path. That is an allowlist rather than a search for bad characters, because a list of bad
characters is always incomplete.
@brief Build the marker path from literals and a filtered session key.
@return The marker path.
@version 4
"""
session = os.environ.get(_SESSION_ENV) or str(int(os.getppid()))
safe = "".join(c for c in session if c in _SAFE)[:64] or "nosession"
tmp = next((os.environ[k] for k in _TMP_ENV if os.environ.get(k)), "/tmp")
return os.path.join(tmp, _MARKER_PREFIX + safe)
Activity · 4 steps
Flows
_outside_repo
bool clew_hook._outside_repo(bytes raw, str modality)
Whether the inspected path is PROVABLY outside the repository.
Source · 38 lines
def _outside_repo(raw: bytes, modality: str) -> bool:
"""gh#44. THE TALLY COUNTED INSPECTIONS ANYWHERE ON DISK AND THE NOTE CALLED THEM "in this
repository". A session auditing markdown under `~/.claude/projects/<id>/memory/` accumulated
pressure from reads outside the tree entirely and was told that 45 file-inspection calls in
this repository had gone without an index call. The count was true; the location was not, and
the note fired hardest during work the index categorically cannot serve.
SKIP WHEN PROVABLY OUTSIDE, NEVER REQUIRE INSIDE, which is the same direction every other
uncertainty in this file resolves. A relative path, an unparseable event, a `Glob` pattern or
an oversized payload all return False and are counted exactly as before — a parser gap
degrades to the previous behaviour rather than silencing the hook.
THE PATH IS REPOSITORY-CONTROLLED TEXT AND IS NEVER ECHOED. It is compared against the root
and discarded; the note's own name still comes from `_safe_token`. This is the one question a
basename cannot answer, which is why the raw value is read here and nowhere else.
@brief Test the inspected path against the repository root.
@return True when it is certainly outside.
@version 1
"""
if len(raw) > _MAX_EVENT:
return False
try:
value = _input_value(json.loads(raw), modality)
except Exception:
return False
if not isinstance(value, str) or not os.path.isabs(value):
return False
root = os.environ.get(_PROJECT_DIR_ENV) or os.getcwd()
try:
resolved_root = os.path.realpath(root)
return os.path.commonpath([os.path.realpath(value), resolved_root]) != resolved_root
except Exception:
## Different drives, an empty root, or anything else `commonpath` refuses to compare.
## Not evidence of being outside, so it counts.
return False
Activity · 14 steps
Flows
_payload_for
str clew_hook._payload_for(int pressure, str modality, str|None name)
The complete reply for this pressure, tier chosen by count.
Source · 41 lines
def _payload_for(pressure: int, modality: str, name: str | None) -> str:
"""TWO RUN-TIME VALUES REACH THE MODEL AND BOTH ARE BOUNDED: an `int` through `%d`, and a string
that came out of `_safe_token`. `int()` first, so a corrupted tally can only widen a number; and
`name` is either None or inside `[A-Za-z0-9._-]{1,64}`. There is no third slot, and
`tests/test_hook.py` pins that over the AST.
SERIALISED ONCE, OVER THE WHOLE OBJECT. The reply used to be assembled by concatenating
literals, which was safe only because `%d` on an int cannot emit a `"`. With a string in play,
a filename containing `"}}` would close `additionalContext` and append sibling protocol keys —
so escaping has to be the serialiser's job. The result must never be post-processed: a `+`, a
`.replace()`, or dumping a fragment to paste between literals each reopen the hole. `_HEAD` and
`_TAIL` were DELETED rather than left beside this path, so a later patch cannot reach for them.
`ensure_ascii` is left at its default, which also escapes U+2028/U+2029 — legal in JSON strings
but breaking for JS-adjacent consumers.
THE VARYING SLOTS ARE ALSO THE MECHANISM. A constant string repeats into wallpaper: ~1,900
identical copies were measured changing nothing. The count moves on every fire and now the
basename moves too, so the prompt cache breaks at that point and the note is processed rather
than replayed.
@brief Choose and render the tier.
@return Complete JSON reply.
@version 2
"""
count = int(pressure)
## A modality with no named template (Glob) is treated as fileless: better to say less than to
## invent a sentence about a pattern that is not a path.
if name is not None and modality not in _CAPABILITY_NAMED:
name = None
if name is None:
template = _OPERATOR_FILELESS if count >= _LOUD_AT else _CAPABILITY_FILELESS[modality]
text = template % count
else:
template = _OPERATOR_NAMED if count >= _LOUD_AT else _CAPABILITY_NAMED[modality]
text = template % (name, count)
return json.dumps(
{"hookSpecificOutput": {"hookEventName": "PostToolUse", "additionalContext": text}}
)
Activity · 10 steps
Flows
_quiet
int clew_hook._quiet()
On a call that says nothing else, say the comment count if it changed.
Source · 11 lines
def _quiet() -> int:
"""@brief Silent path. @return 0."""
try:
note = _comment_note()
if note:
_emit(note)
except Exception:
pass
return 0
Activity · 7 steps
Flows
_record
None clew_hook._record(str suffix)
Record one event of a kind for this session.
Source · 12 lines
def _record(suffix: str) -> None:
"""@brief Append one byte to a tally, ignoring any failure.
@return None.
@version 1
"""
try:
with open(_marker_path() + suffix, "ab") as handle:
handle.write(b".")
except Exception:
pass
Activity · 5 steps
Flows
_safe_token
str | None clew_hook._safe_token(object token)
The basename of a path, reduced to the safe alphabet, or None if anything is off.
Source · 33 lines
def _safe_token(token: object) -> str | None:
"""THIS FUNCTION IS THE SECURITY BOUNDARY. Its return set is the complete set of bytes that can
reach a consumer's model from outside this file, so it is written to be read in one sitting and
is proved TOTAL over the input alphabet by `tests/test_hook.py` rather than sampled.
THE SPLIT IS HAND-ROLLED BECAUSE `os.path.basename` IS THE WRONG TOOL HERE. On Linux it is
`posixpath.basename` and splits on `/` alone, so a Windows-shaped `C:\\Users\\bob\\evil.py`
comes back WHOLE — the "basename only, never a full path" rule would be violated on
attacker-chosen input while the code read as though it enforced it. Normalising `\\` first is
platform-invariant, and a security predicate must not vary with the machine it runs on.
REJECT WHOLE, NEVER SCRUB. Stripping bad characters from `IGNORE ALL PREVIOUS` yields
`IGNOREALLPREVIOUS` — still readable, still attacker-authored, and now with a transform the
attacker knows and can pre-compensate for. Rejection leaks exactly one bit: whether the note is
specific or fileless.
Leading `.` is refused, which covers `.`, `..` and dotfiles: a note naming `..` says nothing,
and a traversal-shaped token should never be quoted back at all.
@brief Reduce a candidate path to a safe basename.
@return The name, or None when it cannot be trusted or is not worth saying.
@version 1
"""
if not isinstance(token, str) or not token:
return None
tail = token.replace("\\", "/").rsplit("/", 1)[-1]
if not tail or len(tail) > _NAME_MAX or tail.startswith("."):
return None
if any(c not in _NAME_SAFE for c in tail):
return None
return tail
Activity · 8 steps
Flows
_segment_verb
str clew_hook._segment_verb(str segment)
The command word a shell segment runs, with env assignments skipped and the path stripped.
Source · 11 lines
def _segment_verb(segment: str) -> str:
"""@brief Read a segment's command word.
@return The basenamed verb, or ''.
@version 1
"""
words = segment.split()
while words and "=" in words[0] and not words[0].startswith("-"):
words = words[1:]
return words[0].rsplit("/", 1)[-1] if words else ""
Activity · 4 steps
Flows
_tally
int clew_hook._tally(str suffix)
Count of recorded events of one kind for this session.
Source · 17 lines
def _tally(suffix: str) -> int:
"""SIZE IS THE COUNT. Each event appends one byte, so a tally needs no parsing, no
read-modify-write and no lock — two concurrent tool calls both append and both are counted,
where a read-increment-write would lose one. It also means nothing from the file is ever
interpreted: a corrupted or tampered tally can only make the count wrong, never change what
is emitted, because what is emitted is a constant.
@brief Read one tally by file size.
@return The count, or 0.
@version 1
"""
try:
return os.path.getsize(_marker_path() + suffix)
except Exception:
return 0
Activity · 4 steps
Flows
_target_name
str | None clew_hook._target_name(bytes raw, str modality)
The basename the agent just looked at, from the event, or None.
Source · 37 lines
def _target_name(raw: bytes, modality: str) -> str | None:
"""EVERY RUNG FALLS TO None, AND None IS ALWAYS SAFE — it selects the fileless note, which is
where this component was before 1.0.10. There is no rung that raises and none that returns
partial trust.
`except Exception` IS DELIBERATE AND NARROWING IT WOULD BE A BUG. `RecursionError` from deeply
nested JSON is a `RuntimeError`, NOT a `ValueError`, so `except (ValueError, TypeError)` would
let it escape — and an escape here becomes a traceback on stderr, which `PostToolUse` surfaces
to the model: the second injection channel this file exists to keep shut. `MemoryError` is
reachable the same way. After either, the stack or heap is nearly exhausted, so the handler does
nothing but return.
THE `isinstance(event, dict)` GUARD IS NOT DEFENSIVE PADDING. Valid JSON is not necessarily an
object: `"a string"` parses to `str`, and the test suite's own helper feeds a double-encoded
event that does exactly that. Without this rung the hook would raise `AttributeError` on its own
fixture.
`tool_response` is NEVER read. It is the one bulk repository-authored field.
@brief Extract a safe basename from the event.
@return The name, or None.
@version 1
"""
if len(raw) > _MAX_EVENT:
return None
try:
## BYTES, not a manual decode: `json.loads` does its own UTF-8 handling, while
## `.decode(errors="surrogateescape")` would mint lone surrogates that `json.dumps` happily
## emits as "\\udcff" and strict consumers then reject.
event = json.loads(raw)
except Exception:
return None
if not isinstance(event, dict):
return None
return _safe_token(_input_value(event, modality))
Activity · 9 steps
Flows
main
int clew_hook.main()
Record the call and emit the constant note when one is due; never fail, never block.
Called by none
Tested by
Calls _clear, _drain_stdin, _event_command, _is_due, _is_inspection, _outside_repo, _payload_for, _quiet, _record, _tally, _target_name
Source · 103 lines
def main() -> int:
"""EVERY PATH RETURNS 0, including every error path, and that is a security property rather
than politeness: a non-zero exit on `PostToolUse` surfaces stderr to the model, which is a
second channel into the context this component exists to protect.
WHICH TOOL RAN IS TOLD BY ARGV, NOT BY STDIN. The manifest registers this twice — once for
the search tools and once for the clew tools with `--used` — so the matcher supplies the fact
and no repository-controlled byte is ever examined to obtain it.
@brief Run the hook.
@return 0, always.
@version 2
"""
if os.environ.get(DISABLE_ENV):
return 0
## DRAINED IN FULL, still — the caller writes the event JSON here and would block on a full pipe
## if nobody read it. Truncating the READ would trade a non-problem for a hang or an EPIPE; the
## ceiling that matters is on the PARSE, in `_target_name`.
try:
raw = _drain_stdin()
except Exception:
raw = b""
## ABOVE THE PARSE, DELIBERATELY. A clew call needs nothing from the event, so this path still
## examines not one byte of repository-controlled text — the narrowest possible surface for the
## most frequent case in a session that is already using the index.
if USED_FLAG in sys.argv[1:]:
## The index was used. CLEAR the miss tally and say nothing — a session already reaching
## for the tool must never hear from this, and one call is what earns the silence. The
## old credit-of-3 never reset, so a session that had drifted could not get back under
## the threshold and the loudest tier became permanent.
_clear(_MISS_SUFFIX)
return _quiet()
## THE MODALITY COMES FROM ARGV — our own manifest's flag, never `tool_name`. An unflagged or
## unknown invocation falls back to the read wording, which is the safe generic.
##
## READ BEFORE `_record` NOW, because gh#11's fix is about what gets COUNTED and not only
## about what gets said. A Bash call that inspects nothing is not a file-inspection call, and
## the note's own text claims to count those — so recording it made the number false.
modality = next((flag for flag in MODALITY_FLAGS if flag in sys.argv[1:]), READ_FLAG)
## gh#44, and the same rule as gh#11 one level out: that fix was about what gets COUNTED
## versus what gets SAID for call SHAPE, and this is the split for call LOCATION. An
## inspection outside the repository is not a file-inspection call in this repository, and
## the note's own text claims to count those.
if _outside_repo(raw, modality):
return _quiet()
if modality == SHELL_FLAG and not _is_inspection(_event_command(raw)):
## THE ONE PLACE THE PARSER MOVED ONTO THE HOT PATH, and it buys back more than it costs:
## a session's Bash calls are mostly git, tests and process management, so most of them
## now return here without touching the tally at all — cheaper than the note they used to
## trigger, and the pressure that survives means what it says.
return _quiet()
_record(_MISS_SUFFIX)
pressure = _tally(_MISS_SUFFIX)
if not _is_due(pressure):
## Most invocations are silent, and for every modality but Bash this still keeps the
## parser off the hot path entirely. 2.1: a changed wiki-comment count is said here.
return _quiet()
try:
name = _target_name(raw, modality)
payload = _payload_for(pressure, modality, name)
except Exception:
## Belt and braces: `_target_name` is written not to raise, and if it ever does, silence is
## the correct outcome. A traceback here would reach the model through stderr.
return 0
## FLUSHED INSIDE THE GUARD, AND THE BUFFER DISCARDED IF THAT FAILS. Found by an adversarial
## audit of 1.0.10 and it falsified this file's own central claim. `sys.stdout` is a BUFFERED
## TextIOWrapper, so `write()` alone usually succeeds into the buffer and the real I/O happens
## at interpreter shutdown — AFTER `main()` has returned 0 and outside every `try` in this
## file. When that deferred flush fails, CPython prints "Exception ignored in: <stdout>" to
## stderr and exits 120.
##
## Both triggers are ordinary rather than exotic: the client closing the read end of the pipe
## early (BrokenPipeError) and a full device (ENOSPC). Reproduced deterministically against
## `/dev/full`.
##
## THAT IS THE SECOND INJECTION CHANNEL THIS COMPONENT EXISTS TO KEEP SHUT — a non-zero exit on
## PostToolUse surfaces stderr to the model. Note the wording it emits contains no "Traceback",
## which is why the two tests scanning stderr for that word could not have caught it.
##
## So: flush where it can be caught, and on failure point fd 1 at the null device so the
## shutdown flush has somewhere harmless to go. Retrying the write is pointless — the failure
## means the reader is gone or the disk is full — and the note is advisory, so dropping it is
## the correct outcome.
try:
sys.stdout.write(payload)
sys.stdout.flush()
except Exception:
try:
null = os.open(os.devnull, os.O_WRONLY)
os.dup2(null, sys.stdout.fileno())
os.close(null)
except Exception:
pass
return 0
return 0