Skip to content

fix(hook): bound the soft read/search nudge per session - #3443

Closed
L4XB wants to merge 3 commits into
Graphify-Labs:v8from
L4XB:fix/cap-soft-hook-nudges
Closed

L4XB wants to merge 3 commits into
Graphify-Labs:v8from
L4XB:fix/cap-soft-hook-nudges

Conversation

@L4XB

@L4XB L4XB commented Sep 9, 2026

Copy link
Copy Markdown
Contributor

Fixes #3435

Problem: _run_hook_guard writes _READ_NUDGE / _SEARCH_NUDGE on every qualifying Read/Glob/Grep/Bash call. There is no dedup, no session cap, and the "recently oriented" query stamp only suppresses the opt-in strict deny, so an agent that just ran graphify query is told on its very next read that it must run graphify query. The issue measured 8,348 injections (~651k tokens) for 339 graphify calls in one project.

Change (graphify/cli.py):

  • _nudge_allowed(session_id) gates both soft nudges. It returns False while _query_stamp_fresh() (the agent ran query/explain/path within GRAPHIFY_HOOK_STRICT_TTL) and after GRAPHIFY_HOOK_NUDGE_CAP nudges in the same session (default 5; 0 or a non-number disables the cap). The count lives in graphify-out/cache/hook_sessions/<sid>.nudges, next to the strict-mode .denied markers, and read + search share one budget.
  • Calls without a session_id are not counted (no key to count on), and the guard keeps its fail-open contract: any error allows the nudge.
  • The 24h marker GC that only ran on the strict path is now _gc_hook_session_markers() and runs when a new session counter is created too.
  • Strict mode is unchanged: the once-per-session deny still fires first; the nudge that follows it is what gets bounded.
  • README: one sentence on the new bound next to the strict-mode note.

Tests: tests/test_hook_guard.py covers stamp suppression (read + search), the per-session cap with independent sessions, the shared read/search budget, the default of 5, the disable values, and uncounted calls without a session id. tests/test_hook_strict.py::test_fresh_query_stamp_suppresses_deny now expects no output at all when the stamp is fresh (previously the soft nudge), which is the intended behaviour change.

pytest tests/test_hook_guard.py tests/test_hook_strict.py tests/test_hook_guard_token_match.py tests/test_hook_out_of_project_paths.py
154 passed, 4 skipped
ruff check: clean

The rest of the suite: 5118 passed locally; the 24 failures are environmental in my checkout (missing optional openai / tree-sitter-hcl, shallow git history for the skillgen tests, a wheel-build test) and don't touch the hook code.

The PreToolUse guard re-injected the MANDATORY read/search nudge on every
qualifying Read/Glob/Grep/Bash call with no cap and no check whether the
agent had just queried the graph. Only the opt-in strict deny was capped.
One project measured 8,348 injections (~651k tokens) for 339 graphify
calls, several times the cost of every query they were asking for.

Skip the soft nudge while the query stamp is fresh (the agent is already
oriented) and cap it at GRAPHIFY_HOOK_NUDGE_CAP nudges per session
(default 5, 0 disables), counted in a per-session marker next to the
strict-mode ones. Calls without a session id are uncounted, the guard
still fails open, and the shared marker GC now runs on both paths.

Fixes Graphify-Labs#3435

@graphify-labs graphify-labs Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Graphify reviewed this change.

Looks safe to merge — no coupling regressions and no blocking issues, checked against the code graph (not a self-assessment).

Formal verification. 2 change(s) tested, no difference found (not proven).


Graphify review — findings

Bounds the soft Read/Grep/Bash nudge so it no longer re-injects on every qualifying tool call: _nudge_allowed skips it while a recent graphify query/explain/path stamp shows the agent is already oriented, and otherwise caps it at GRAPHIFY_HOOK_NUDGE_CAP emissions per session (default 5; 0 or a non-number disables the cap), tracked in a per-session .nudges marker that read and search calls share. Sessions without an id are never counted, marker errors fail open (nudge shown), and stale-marker GC is factored into _gc_hook_session_markers and reused by both the nudge and strict-block paths. A fresh query stamp in strict mode now also suppresses the fallback nudge, so a recently-oriented read produces no output at all.

No blocking issues surfaced. 6 lower-confidence candidates did not survive cross-model review.

Analysis details — impact, health, verification

Impact & health

Graphify review

Impact — 338 functions depend on the 146 functions this change touches.

Health — this change adds coupling hotspots:

  • new: dispatch_command() — 2 callers, 124 callees
  • new: _stale_graph_sources() — 7 callers, 6 callees
  • new: _run_hook_guard() — 4 callers, 9 callees
  • new: test_poisoned_manifest_is_healed() — 0 callers, 6 callees

Verification — 338 functions in the blast radius were not formally verified this run (proofs are advisory here).

Gate & verification

graphify gate

PASS — objectively clean (no health regressions, tests not run — proofs not run this pass (advisory)). Grounded, not self-assessed.

Advisory (not blocking):

  • verification_scope: 284 function(s) in the blast radius were not formally verified this run

Test selection

Test selection

262 of 262 test file(s) selected (100%) via static blast radius.

Escalated to a full run for safety — the selection is not trustworthy on its own (see below). CI should run the whole suite.

  • tests/test_affected_cli.py — impact, full-run-safety
  • tests/test_affected_member_seed.py — full-run-safety
  • tests/test_agents_platform.py — impact, full-run-safety
  • tests/test_analyze.py — full-run-safety
  • tests/test_anthropic_custom_endpoint.py — full-run-safety
  • tests/test_antigravity_install.py — full-run-safety
  • tests/test_apm_fallback_version.py — full-run-safety
  • tests/test_architecture_doc.py — full-run-safety
  • tests/test_astro_extraction.py — full-run-safety
  • tests/test_astro_import_ids.py — full-run-safety
  • tests/test_atomic_canvas_export.py — full-run-safety
  • tests/test_atomic_version_stamp.py — full-run-safety
  • tests/test_atomic_writes.py — full-run-safety
  • tests/test_backend_extras.py — full-run-safety
  • tests/test_benchmark.py — full-run-safety
  • tests/test_benchmark_raw_graph.py — full-run-safety
  • tests/test_build.py — full-run-safety
  • tests/test_build_merge_hyperedges_and_prune.py — full-run-safety
  • tests/test_build_merge_shrink_guard.py — full-run-safety
  • tests/test_builtin_global_type_refs.py — full-run-safety
  • tests/test_cache.py — full-run-safety
  • tests/test_callflow_html.py — full-run-safety
  • tests/test_cargo_introspect.py — full-run-safety
  • tests/test_carried_hyperedge_remap.py — full-run-safety
  • tests/test_case_sensitive_resolution.py — full-run-safety
  • tests/test_charmap_encoding.py — full-run-safety
  • tests/test_chunking.py — full-run-safety
  • tests/test_cjs_module_extension.py — full-run-safety
  • tests/test_claude_cli_backend.py — full-run-safety
  • tests/test_claude_md.py — full-run-safety
  • tests/test_cli_broken_pipe.py — full-run-safety
  • tests/test_cli_export.py — full-run-safety
  • tests/test_cli_help.py — full-run-safety
  • tests/test_cluster.py — full-run-safety
  • tests/test_codebuddy.py — impact, full-run-safety
  • tests/test_community_hub_labels.py — full-run-safety
  • tests/test_community_labels_skill.py — full-run-safety
  • tests/test_confidence.py — full-run-safety
  • tests/test_corrupt_graph_json.py — full-run-safety
  • tests/test_cpp_nested_and_cli.py — full-run-safety
  • tests/test_cpp_objc_cross_file_calls.py — full-run-safety
  • tests/test_cpp_preprocess.py — full-run-safety
  • tests/test_cross_extension_reexport_self_cycle.py — full-run-safety
  • tests/test_cross_language_call_resolution.py — full-run-safety
  • tests/test_cross_repo_member_calls.py — full-run-safety
  • tests/test_cross_repo_shared_types.py — full-run-safety
  • tests/test_csharp_call_site_generic_args.py — full-run-safety
  • tests/test_csharp_enum_members.py — full-run-safety
  • tests/test_csharp_field_generic_args.py — full-run-safety
  • tests/test_csharp_generic_callsites.py — full-run-safety
  • … and 212 more

non-code file(s) changed (README.md) → running the full suite for safety (a code graph can't see config/fixture/data deps)

changed code file(s) with no mapped test (README.md) — a coverage gap or a missing link — running the full suite rather than only the selected tests

Selection is safe under the controlled-regression assumption; always-run tests + a periodic full run are the backstops. Advisory — it never changes the check verdict.

Formal verification

No difference found (not proven): No behavior difference found in \_mark\_session\_denied (not a proof).

The verifier ran both versions of \_mark\_session\_denied on many inputs and saw identical behavior every time. Strong evidence the change is safe, but evidence, not a proof.

Guarantee: Empirical: differential testing (both versions run on many generated inputs). A divergence on an untested input remains possible, so this is 'no counterexample found', not 'proven equivalent'.

Note: An input the sampler did not try could still differ.

No difference found (not proven): No behavior difference found in \_run\_hook\_guard (not a proof).

The verifier ran both versions of \_run\_hook\_guard on many inputs and saw identical behavior every time. Strong evidence the change is safe, but evidence, not a proof.

Guarantee: Empirical: differential testing (both versions run on many generated inputs). A divergence on an untested input remains possible, so this is 'no counterexample found', not 'proven equivalent'.

Note: An input the sampler did not try could still differ.

· 4 more finding(s) on lines outside this diff (see the check run).

@andrebrait

Copy link
Copy Markdown
Contributor

Thanks for this. I'm carrying it in a downstream build and hit three gaps in practice. A follow-up commit on top of this branch (rebased onto current v8) addresses them: pfBlockerNG@e8f4119

  1. Claude Code subagents share the parent's budget. Subagent tool calls carry the parent's session_id and are distinguished only by agent_id (hooks docs). Keying the counter on session_id alone lets the parent exhaust the budget before a subagent, which starts with an empty context, ever sees the nudge. The commit keys the marker on session_id plus a short SHA-256 of agent_id when present (hashed so long ids cannot truncate two agents into one key).
  2. The query stamp silences agents that never queried. last_query_stamp is project-wide and cannot say which agent ran query/explain/path, so one agent's query currently suppresses the nudge for every other session and subagent, including a fresh one. The commit lets each agent's first nudge fire regardless of the stamp; the stamp then silences the later ones. Calls without a session_id keep the current stamp-only behavior.
  3. The stale-graph notice is still unbounded. _READ_NUDGE_STALE fires on every read of a file edited after the last build, which in an editing session is most reads. The commit draws it from the same per-agent budget.

test_fresh_query_stamp_suppresses_deny changes accordingly: with a fresh stamp there is still no deny, the session's first nudge fires, and the second read is silent. New tests cover per-agent budgets (including 64-character session ids), a subagent's first nudge after the parent queried, the stamp without a session_id, and the stale notice sharing the budget. tests/test_hook_guard.py, tests/test_hook_strict.py, tests/test_hook_guard_token_match.py, tests/test_hook_out_of_project_paths.py, and tests/test_install_strings.py pass (165 passed, 4 skipped), and ruff check is clean.

@L4XB, if you'd like to include this, I can open a PR against L4XB/graphify targeting fix/cap-soft-hook-nudges so it lands in this PR rather than as a separate one.

@andrebrait

Copy link
Copy Markdown
Contributor

Opened #3893 so the follow-up doesn't get lost if this merges first: it carries this PR's commit unchanged (authorship and message kept) onto current v8, plus the follow-up commit described above. If you'd rather take the follow-up here, the PR offer against L4XB/graphify stands, and #3893 can be closed.

andrebrait added a commit to pfBlockerNG/graphify that referenced this pull request Sep 28, 2026
…Graphify-Labs#3443)

Squashed from origin/fix/per-agent-hook-nudges (17a2822) onto upstream/v8.
andrebrait added a commit to pfBlockerNG/graphify that referenced this pull request Sep 28, 2026
…Graphify-Labs#3443)

Squashed from origin/fix/per-agent-hook-nudges (17a2822) onto upstream/v8.
andrebrait added a commit to pfBlockerNG/graphify that referenced this pull request Sep 29, 2026
…Graphify-Labs#3443)

Squashed from origin/fix/per-agent-hook-nudges (158f035) onto upstream/v8.
L4XB and others added 2 commits October 5, 2026 14:04
Subagents start with an empty context, but Claude Code gives them the
parent's session_id; keying the nudge budget on session_id alone let a
parent exhaust a subagent's budget. Key it on session_id plus a hash of
agent_id when present.

The query stamp is project-wide and cannot say which agent queried, so it
no longer silences an agent's first nudge; it silences later ones. The
stale-graph notice now draws on the same budget instead of firing on every
read of an edited file.
@L4XB

L4XB commented Oct 5, 2026

Copy link
Copy Markdown
Contributor Author

@andrebrait thanks for running this downstream and for the follow-up. All three gaps are real, and your commit is now on this branch with your authorship kept (093421d), on top of a merge of current v8. The merge adds v8's _nudge_for_out wrapper to each nudge your commit budgets: the search nudge, the read nudge and the stale notice. tests/test_hook_guard.py and tests/test_hook_strict.py pass (112), and the full suite shows the same environment-only failures as v8 (optional grammars I don't have installed) with 12 more passes. So #3893 can be closed if you agree; it carries the same two commits.

@andrebrait

Copy link
Copy Markdown
Contributor

Thanks for taking the follow-up. One more on top of this branch: L4XB#1 makes a firing nudge (and the strict deny) name the graph nodes behind the call plus a ready command, and narrows the "modify/debug specific lines" wording that let agents skip it. Your budget decides when it fires; this changes what it says. Happy to adjust or split it.

andrebrait added a commit to pfBlockerNG/graphify that referenced this pull request Oct 11, 2026
Squashed carry of carry source pfBlockerNG/graphify feat/nudge-hints (7c1c4d7), which merges v8 into L4XB:fix/cap-soft-hook-nudges.
andrebrait added a commit to pfBlockerNG/graphify that referenced this pull request Oct 11, 2026
…r session

Squashed from origin/carry/pr-3443 (80ee89b) onto upstream/v8.
andrebrait added a commit to pfBlockerNG/graphify that referenced this pull request Oct 11, 2026
Squashed carry of pfBlockerNG/graphify feat/nudge-hints (093dc19), which merges v8 into L4XB:fix/cap-soft-hook-nudges.
andrebrait added a commit to pfBlockerNG/graphify that referenced this pull request Oct 11, 2026
…r session

Squashed from origin/carry/pr-3443 (0e1dab5) onto upstream/v8.
@andrebrait

Copy link
Copy Markdown
Contributor

@L4XB here is exactly what L4XB#1 proposes on top of this branch. Each item can be taken or dropped on its own.

1. Call-specific hint on a firing nudge (graphify/cli.py: _search_hint_terms, _graph_hint, _with_hint)
Your _nudge_allowed budget decides when a nudge fires. When it does, the nudge (and the strict-mode deny) now ends with a ready command and up to five graph nodes:

Start with: `graphify explain "load_config()"`
What the graph already has for this call:
- load_config() (src/app.py L10)
  • Search: the terms come from the Grep pattern, or the pattern argument of grep/rg/ag/ack. Value-taking flags such as -t/-g/-A are skipped. find/fd are excluded because they match file names, not content.
  • Read: the hint lists the file's symbols in line order and suggests graphify explain "<file>".
  • Ranking: labels only. Exact matches come first and suggest explain; otherwise it suggests query. Terms shorter than 5 characters only match exactly, so src does not list every path.
  • Cost and safety: it scans graph.json labels directly (0.3–0.5 s on 3k–15k-node graphs) instead of loading the query stack (~1.5 s). Graphs over 24 MiB, a malformed graph, no match, or any error all return your nudge unchanged. Graph text is one line, with no control characters or backticks, and capped in length, since graph.json is repository content.

2. Narrower nudge wording (_SEARCH_NUDGE, _READ_NUDGE, _READ_DENY)
"…or to modify/debug specific lines" excused almost every targeted read in practice. Raw reads are now allowed "only once you know the exact file and lines you need, from the graph or an earlier read".

3. Always-on rule (Claude, AGENTS.md and Gemini blocks; recorded as a sanctioned edit _QUERY_FIRST_EDIT in tools/skillgen/gen.py)
"For codebase questions, first run graphify query…" becomes "…before your first grep, search or source-file read for a codebase question, and put this rule in every subagent prompt that explores code. Read raw files only for lines the graph or an earlier read already located." The Kiro and Antigravity blocks are unchanged.

Why: in our downstream build, agents still skipped the nudge within the budget. In session logs, a reminder got 28–41 deliveries per session against 0–2 graphify calls, and the model's reasoning never mentioned it. The hint shows what the graph has instead of only asking. Smoke on a real repo: rg 'stripHiddenWrappers' now gets graphify explain "stripHiddenWrappers()" plus its file and line.

Branch notes: it first merges current v8, as you did in d7ba4af. The README conflict was resolved to v8's side, because the strict-mode note moved to the docs site. Tests in tests/test_hook_guard.py and tests/test_hook_strict.py cover hints, ranking, the 5-node cap, flag parsing, hostile and malformed graphs, the size cap and the deny hint. The skillgen guards pass. We carry this downstream until it lands. If you'd rather keep this PR to the budget, I can open it upstream as a separate PR stacked on this one.

andrebrait added a commit to pfBlockerNG/graphify that referenced this pull request Oct 11, 2026
Squashed carry of pfBlockerNG/graphify feat/nudge-hints (7897b71), which merges v8 into L4XB:fix/cap-soft-hook-nudges.
andrebrait added a commit to pfBlockerNG/graphify that referenced this pull request Oct 11, 2026
…r session

Squashed from origin/carry/pr-3443 (dca722c) onto upstream/v8.
andrebrait added a commit to pfBlockerNG/graphify that referenced this pull request Oct 11, 2026
…r session

Squashed from origin/carry/pr-3443 (dca722c) onto upstream/v8.
safishamsi pushed a commit that referenced this pull request Oct 12, 2026
The read/search nudge was re-injected on every qualifying Read/Glob/Grep/Bash
call with no dedup or session cap (issue #3435 measured ~8,348 injections,
~651k tokens, for 339 graphify calls), and an agent that just ran
`graphify query` was still nudged on its very next read. `_nudge_allowed`
now gates all three soft-nudge sites with a per-session + per-agent counter
(first nudge always fires; later ones suppressed while the query stamp is
fresh; hard cap via GRAPHIFY_HOOK_NUDGE_CAP, default 5), with 24h GC and
fail-open preserved. Subagents get independent budgets. The strict deny path
is unchanged.

Landed from PR #3443 (squashed). The README strict-mode note is omitted here
because that prose moved to docs.graphify.com in the README trim.

Co-Authored-By: Andre Brait <[email protected]>
Co-Authored-By: Claude Opus 4.8 <[email protected]>
@safishamsi

Copy link
Copy Markdown
Member

Shipped in v0.9.87, just released to PyPI as graphifyy 0.9.87. Landed via an authorship-preserving cherry-pick (so the commit keeps your name and counts on your contributor graph) rather than a branch merge, which is why GitHub marks this closed rather than merged. Thanks @L4XB!

@safishamsi safishamsi closed this Oct 12, 2026
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.

PreToolUse soft nudge has no session cap — measured 8,348 injections (~651k tokens) in a single project

3 participants