Skip to content

SI: hook robustness, context intelligence for Claude 5, statusline fixes - #9

Open
dayakarreddyn wants to merge 67 commits into
mainfrom
fix/si-hook-robustness
Open

dayakarreddyn wants to merge 67 commits into
mainfrom
fix/si-hook-robustness

Conversation

@dayakarreddyn

@dayakarreddyn dayakarreddyn commented Oct 19, 2026 •

Copy link
Copy Markdown
Owner

Summary

Three tiers of Session Intelligence work, stacked on one branch (59 commits over main):

  1. Hook robustness (24acf0b) — lib/sqlite-driver.js falls back from better-sqlite3 to node:sqlite on an ABI mismatch (PRAGMA busy_timeout = 5000, SAVEPOINT nesting, SI_SQLITE_DRIVER override); SessionStart bootstrap timeout 5 s → 15 s; npm test runs on Node 20 and 22.
  2. Context intelligence for Claude 5 (38 commits, plan docs/superpowers/plans/2026-10-19-si-context-intelligence.md, research reports/Context rot optimisation for Claude 5.md) — per-call context size from the transcript replaces the cumulative chars/4 estimate; a model-aware context-window resolver; fill % on compact/zone rows (schema v3) and adaptive zones that learn from it; zones as fractions of the window (0.20/0.30/0.40); a PreToolUse/PostToolUse pruner that replaces ≥50K-char tool results with an archived excerpt in the tool's own output shape (command rewriting ships off by default, prune.rewriteInput); duplicate-read / re-run / large-result signals; a typed constraint registry emitted first in the PreCompact block under a 10K cap and re-injected through the SessionStart handoff; a PostCompact hook measuring retention (compact_outcomes); Claude 5 pricing + schema v4 reprice; /si doctor window advice; cold-resume advice and a cache-hit series; telemetry hygiene (JSONL/DB reconcile, canonical project keys).
  3. Statusline fixes (17 commits, plan docs/superpowers/plans/2026-10-21-si-statusline-fixes.md, spec docs/superpowers/specs/2026-10-21-si-statusline-fixes-design.md) — the 2,132-line statusline split into six modules behind golden renders of seven captured payloads; the tools cell reads the state dir the hook writes to; fabricated per-model weekly-remaining (wr:) removed; exact output_tokens_details.thinking_tokens deduped per message; one chunked, bounded transcript scanner (4 MiB chunks, 64 MiB per render) with state-dir caches; session-average tps fallback removed; spend_limit rendered as a budget, usage poller only on builds older than 2.1.90 or without rate_limits; absolute-mode zones never replaced by the learner; honest used/? cell for unknown caps; ~s$ labelling of calibrated savings; dead code, per-render driver log, stale-file sweep, test litter and the CLAUDE.md injection template path fixed; README statusline section regenerated from the golden render with a drift test; the entry never blanks on a failed sibling require.

Behaviour changes you will notice

  • Status line: tools count renders; wr: gone; thinking counts drop to the exact value (the old residual was ~5× high); c$…/~s$…; sl:$used/$limit<period> for gateway accounts; 200k/1M formatting; used/? for unknown models.
  • Hooks (new Claude Code sessions only): PreToolUse pruner, PostCompact retention probe, registry-first PreCompact block.
  • Zones are fractions of the window by default; set "zoneMode": "absolute" beside zones to keep fixed thresholds.
  • Economics caches now live in ~/.claude/state (claude-cost-<sid>.v5.json, claude-cost-sincecompact-<sid>.v4.json); old tmpdir files are ignored and swept after 7 days.

Verification

  • Node 20 npm test: 514 pass, 0 fail, 4 skipped · Node 22: 518 pass · Node 22 + SI_SQLITE_DRIVER=node:sqlite: 518 pass.
  • TMPDIR=<empty dir> npm test leaves 0 claude-* files; two tests that ran a hook against the real $HOME / spawned the real usage-refresh worker are isolated.
  • Live: si-statusline-chain.sh renders five lines, exit 0, on a 56 MB transcript (entry 163 ms for the verbose preset); the entry alone prints claude and exits 0; a session-start payload without rate_limits on 2.1.303 spawns no poller; PreToolUse pruning of a 60,085-char Read verified in-session.
  • Every task had a scoped review; each tier had a whole-branch review on the most capable model plus one fix wave and a re-review (rulings recorded in the plans' SDD ledgers; summarised in the session notes).

Test plan

  • Full matrix green on the merged branch
  • Live statusline render through the real chain script
  • New session: confirm PostCompact fires and stamps compact_outcomes
  • New session with prune.rewriteInput: true: confirm the rewritten test command shows in the permission prompt and still matches Bash(...) allow rules
  • Watch /si stats fill-at-compact and retention columns over a few CSM sessions before tuning zones

Follow-ups (shippable, tracked in session notes)

partial totals under-count until a cold 550 MB transcript is absorbed over a few renders (~ marks them); prune.tools lists Grep/Glob/WebFetch but the extractor handles string/Bash/Read shapes only; shape chars are recorded before pruning; lib/context-shape.js is 930 lines (pre-existing); cmp: and emoji still colour against a fallback cap; some other process on the dev machine runs a pre-fix events.js and logs driver lines.

CI and golden fixtures (2026-10-31)

  • CI had never been green on any branch. setup-node caches npm against plugins/session-intelligence/package-lock.json, which was gitignored, so every run aborted in ~15 s with "Some specified paths were not resolved" before npm ci. The lockfile is now committed (in sync with package.json, registry.npmjs.org only) and tests/ci-workflow.test.js asserts every cache-dependency-path is a git-tracked file. (c9514ea)
  • Golden statusline renders rotted after four days. The captured payloads carry real resets_at epochs; once the seven-day reset (2026-10-26) passed, format.js correctly dropped the r:<dur> cell and six goldens failed. Spawned renders now run with the wall clock pinned to 2026-10-21 09:01 UTC via a node -r tests/helpers/freeze-clock.js preload (test-only, gated on SI_TEST_FROZEN_NOW_MS). Golden files unchanged. (ef8d31c)
  • Closes the gap PR fix(si): drop fabricated per-model weekly-remaining; tighten statusline line 5 #8 addressed (ported as aee9316); fix(si): drop fabricated per-model weekly-remaining; tighten statusline line 5 #8 closed as superseded.

…tstrap timeout 15s

Hooks run under whatever `node` the project directory resolves to. ReelCuts
pins Node 22 via mise, so the plugin's prebuilt better-sqlite3 binary
(NODE_MODULE_VERSION 115) failed to load there: lib/events.js logged
"sqlite open failed" 450-745x/day and silently dropped all telemetry.

- lib/sqlite-driver.js: pick better-sqlite3 when it loads, else wrap the
  built-in node:sqlite (Node >= 22.13) in a better-sqlite3-shaped facade
  (prepare/run/get/all, exec, pragma incl. { simple }, nested transactions
  via SAVEPOINT, busy_timeout 5000 to match better-sqlite3's default).
  The ExperimentalWarning is filtered only for the duration of the require.
  SI_SQLITE_DRIVER=better-sqlite3|node:sqlite overrides selection.
- lib/events.js opens through the driver and logs which one it picked.
- hooks/hooks.json: si-bootstrap timeout 5s -> 15s. 87 hook_cancelled
  records since 2026-08-15 at exactly 5s, median run 5.1s, nearly all in
  teammate launch storms.
- package.json: `node --test tests/*.test.js` (Node 22 rejects a directory
  argument); add test:node22 and test:matrix.
- tests: seed sandbox DBs through the driver instead of requiring
  better-sqlite3 directly; add sqlite-driver (incl. cross-process lock wait
  and savepoint nesting) and hooks-config tests. 246/246 on Node 20 and 22.
…le sweep, stop test litter, fix the CLAUDE.md template path
…ssion, never blank on failed require, mark partial token totals
@dayakarreddyn dayakarreddyn changed the title fix(si): node:sqlite fallback on ABI mismatch; bootstrap timeout 15s SI: hook robustness, context intelligence for Claude 5, statusline fixes Oct 21, 2026
…path

The test workflow caches npm against plugins/session-intelligence/package-lock.json, but that file was gitignored. setup-node aborted every run in about 15 seconds with "Some specified paths were not resolved, unable to cache dependencies", before npm ci ever ran, so the workflow had never been green on any branch. Commit the lockfile (in sync with package.json, registry.npmjs.org only) and add a guard test that every cache-dependency-path in the workflow is a git-tracked file.
… stop rotting

The golden payloads carry real resets_at epochs from the day they were captured (seven_day reset 2026-10-26). statusline/format.js drops the r:<dur> cell once a reset is past, so from 2026-10-26 all six rate-limited goldens failed on w:20% vs w:20% r:<dur>. The fixture helper now preloads tests/helpers/freeze-clock.js via node -r, which replaces Date with a subclass frozen at 2026-10-21 09:01 UTC when SI_TEST_FROZEN_NOW_MS is set, and seeds the usage cache at that same instant. Golden files are unchanged. tests/README.md replaces the stale "statusline not covered" note.
…tually lives

lib/context-shape.js moved the shape log to getStateDir() but the doctor kept
checking os.tmpdir(), so every live session reported "SI is dark" (exit 1)
while the file sat in the state dir. Check the state dir first and keep the
temp dir as the fallback for sessions that predate the move.
…DROP labels, reports null retention when empty

47 of 49 recorded compacts had an empty registry: most projects' On Compact
and Key Decisions sections are still the seeded template, and the registry
read nothing else. Add the autofilled Current Task block as the lowest
priority source so the registry is never empty for that reason alone. A bare
"PRESERVE:" or "DROP:" line is a label, not a constraint; lines under a DROP
label are the opposite of one and are skipped; "issue: none" is ignored.

retentionOf returns ratio null for an empty registry, so compact_outcomes
stores NULL instead of the 0% that dragged the reported mean down to 1%.
…s a day ledger and backfills blind subagent rows

The daily and weekly trend bucketed total_cost_usd by session start day, so
every later day of a week-long session showed $0.00 while compacts kept
landing. New session_cost_days table (sid, day, cost, t): si-stop upserts the
session's running total under the local day on every turn, and aggregateStats
turns consecutive rows into day-over-day deltas. Sessions recorded before the
ledger existed keep start-day attribution; the first ledger row of a session
that started earlier stays on its start day. %TOT now sums to 100 over the
rendered series.

Retention (mean) averages only compacts that registered constraints (legacy
rows stored an empty registry as 0.0) and says how many of them did.

37% of agent_invocations in the last 14 days had NULL usage: background Agent
calls are recorded before their transcript flushes, and reconcileSubagentUsage
ran only at SessionStart, which a session open for days never reaches. si-stop
now runs it too, throttled to once per 10 minutes per session through a
claude-agent-reconcile marker that the stale sweep also cleans up.
The two corrupt-handoff cases log at WARN through intel-debug, which writes to
~/.claude/logs even under the test runner. Quiet that process so test runs
stop leaving "handoff parse failed" lines in the live daily log.
…-attributed trend and Stop hook

Compaction section lists the CONSTRAINT REGISTRY as the fifth injected block
with its sources in priority order. Doctor section names ~/.claude/state as
the shape-log location. Stats section explains the session_cost_days ledger
and that retention is NULL, not 0, when nothing was registered. Hooks table
gains the missing si-stop row and the backfill paths for blind agent rows.
…arlier than the static 20%

Zone thresholds are learned per cwd while the zone state is per session, so a
session whose hooks run from two directories read one token count as yellow in
one and green in the other. Each green reading re-armed the state and the next
yellow reading re-emitted the callout, on every tool call.

A lower zone now re-arms only once the context has shrunk 15% below the last
emit level. Adaptive yellow is floored at the static yellow, still below orange.
…g subagents by model and effort

The model cell appends stdin effort.level ("Fable 5.2 · high"). A new agents
cell, on its own last row of the verbose preset, groups the subagents still
working by the model and effort recorded in their transcripts; an agent counts
while its meta.json is not finished and its transcript was written in the last
15 minutes.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant