Skip to content
Draft
Show file tree
Hide file tree
Changes from all 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
5 changes: 3 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -249,14 +249,15 @@ for example `graphify claude install --project` or `graphify codex install --pro
| Pi coding agent | `graphify install --platform pi`, plus `graphify pi guard install` for the native guard |
| Cursor | `graphify cursor install` |
| Devin CLI | `graphify devin install` |
| DeepSeek Harness (dsh) | `graphify dsh install` or `graphify install --platform dsh` (needs `@deepseek-ai/dsh-hooks-claude-code` in the dsh profile, then `dsh --patch .dsh/graphify.cordis.yml` — see [Make your assistant always use the graph](#make-your-assistant-always-use-the-graph)) |
| Google Antigravity | `graphify antigravity install` |
| Google Antigravity (Windows) | `graphify antigravity install` (auto-detected on Windows) |

Codex users also need `multi_agent = true` under `[features]` in `~/.codex/config.toml` for parallel extraction. CodeBuddy uses the same Agent tool and PreToolUse hook mechanism as Claude Code. Factory Droid uses the `Task` tool for parallel subagent dispatch. OpenClaw and Aider use sequential extraction (parallel agent support is still early on those platforms). Trae uses the Agent tool for parallel subagent dispatch and does **not** support `PreToolUse` hooks, so AGENTS.md is the always-on mechanism.

`--platform agents` (alias `--platform skills`) targets the generic cross-framework [Agent-Skills](https://github.com/anthropics/skills) locations: the spec's user-global `~/.agents/skills/` (read by `npx skills` and spec-compliant frameworks) for a global install, and `./.agents/skills/` for a project (`--project`) install. The bare `graphify install` stays single-platform (Claude Code) by design: use the named `agents` platform when you want the skill discoverable by any framework that reads `.agents/skills`.

Claude Code's `graphify install --project --strict` makes Read and dedicated Grep share one denial per session unless a recent graph query has oriented the agent (default 30 minutes). A Grep over a directory needs no indexed-file match; a Grep pinned to a single file is denied only when the graph indexes that file, as with Read. External and graph-output Grep targets produce neither a deny nor a nudge, in soft mode as well as strict mode, matching Read's scope. A graph marked `needs_update` never triggers a Grep denial. Bash searches and Glob stay advisory. `GRAPHIFY_HOOK_STRICT=1` enables the policy without reinstalling; `GRAPHIFY_HOOK_STRICT=0` disables it even when installed with `--strict`. Existing strict installs need a reinstall to add the search hook's `--strict` flag, or the environment override. Soft nudges are capped per session (`GRAPHIFY_HOOK_NUDGE_CAP`, default 5). After a context compaction, a `SessionStart` hook (matcher `compact`) resets that budget, the subagents' budgets and the strict denial, since the compacted context no longer holds the earlier nudges.
Claude Code's `graphify install --project --strict` makes Read and dedicated Grep share one denial per session unless a recent graph query has oriented the agent (default 30 minutes). A Grep over a directory needs no indexed-file match; a Grep pinned to a single file is denied only when the graph indexes that file, as with Read. External and graph-output Grep targets produce neither a deny nor a nudge, in soft mode as well as strict mode, matching Read's scope. A graph marked `needs_update` never triggers a Grep denial. Bash searches and Glob stay advisory. DeepSeek Harness runs the same policy through `.dsh/hooks.json`: `graphify dsh install --strict` at either scope enables the identical one-shot denial, while a plain dsh install only advises. Neither host gets a repeat-deny mode: the reference host's policy is the policy every host gets. `GRAPHIFY_HOOK_STRICT=1` enables the policy without reinstalling; `GRAPHIFY_HOOK_STRICT=0` disables it even when installed with `--strict`. Existing strict installs need a reinstall to add the search hook's `--strict` flag, or the environment override. Soft nudges are capped per session (`GRAPHIFY_HOOK_NUDGE_CAP`, default 5). After a context compaction, a `SessionStart` hook (matcher `compact`) resets that budget, the subagents' budgets and the strict denial, since the compacted context no longer holds the earlier nudges.

Pi has no `PreToolUse` hook, so `graphify pi guard install` registers a native Pi extension (via Pi's own `pi install <package directory>`) that runs the installed `graphify hook-guard` before Pi's `read`, `grep`, `find` and search-style `bash` calls. Fresh/stale graph decisions and the `GRAPHIFY_HOOK_STRICT=1` once-per-session denial shared by indexed Read and dedicated Grep come from that same policy, so Pi matches Claude Code's hook behavior; Bash and file listing remain advisory. Guidance arrives as a `<system-reminder source="graphify">` steering message. It needs Pi 0.58.4 or newer: earlier versions let a steering message skip the rest of a parallel tool-call batch. The package ships inside the Graphify installation, so install Graphify persistently (`uv tool install graphifyy` or `pipx install graphifyy`, not `uvx`), restart Pi after installing or upgrading, and remove it with `graphify pi guard uninstall`. Only local file targets are inspected; the hook needs `graphify` on an absolute `PATH` entry outside the project, is bounded to a two-second, 256 KiB-in/64 KiB-out call, and fails open. The same package also loads in [Oh My Pi](https://github.com/can1357/oh-my-pi): `omp plugin install "$(graphify pi guard path)"`. The registered path contains the Python version and venv, so re-run `graphify pi guard install` after changing either, and remove the old entry with `pi remove <old path>`.

Expand Down Expand Up @@ -308,7 +309,7 @@ Run `graphify <platform> install` once in your project, for example `graphify cl

This writes a small config file that tells your assistant to consult the knowledge graph for codebase questions, preferring scoped queries like `graphify query "<question>"` over reading the full report or grepping raw files.

- **Hook platforms** (Claude Code, Gemini CLI): a hook fires automatically before search-style tool calls (and, on Claude Code, before reading source files one by one via the Read/Glob tools, or via `cat`, `head`, `tail`, `sed -n` and similar readers in Bash) and nudges your assistant toward the graph path.
- **Hook platforms** (Claude Code, Gemini CLI, DeepSeek Harness): a hook fires automatically before search-style tool calls (and, on Claude Code and DeepSeek Harness, before reading source files one by one via the Read/Glob tools, or via `cat`, `head`, `tail`, `sed -n` and similar readers in Bash) and nudges your assistant toward the graph path. DeepSeek Harness reads no hook file by itself: `graphify dsh install` also writes `.dsh/hooks.json` and a cordis overlay that mounts the `@deepseek-ai/dsh-hooks-claude-code` bridge, so a session only sees the guard after `dsh --patch .dsh/graphify.cordis.yml` and a restart. Blocking is opt-in on both hosts: a plain `graphify dsh install` only advises, and `--strict` (accepted at either scope) enables the same one-shot denial a strict Claude Code install gets - no host gets a second, stricter policy.
- **Instruction-file platforms** (Codex, OpenCode, Cursor, etc.): persistent instruction files (`AGENTS.md`, `.cursor/rules/`, etc.) provide the same query-first guidance.

`GRAPH_REPORT.md` is still available for broad architecture review.
Expand Down
144 changes: 96 additions & 48 deletions graphify/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,35 +92,8 @@ def _valid_price(value: float) -> float:
),
}
}, ensure_ascii=False, separators=(",", ":")) + "\n"
# Strict-mode block (opt-in). Claude Code PreToolUse honors
# hookSpecificOutput.permissionDecision == "deny" and shows permissionDecisionReason
# to the model. Fires at most once per session (see _mark_session_denied) so it can
# never strand an agent: the very next read proceeds with the soft nudge.
_READ_DENY = json.dumps({
"hookSpecificOutput": {
"hookEventName": "PreToolUse",
"permissionDecision": "deny",
"permissionDecisionReason": (
'graphify strict mode: this project has a fresh knowledge graph that covers '
'this file. Run `graphify query "<your question>"` (or `graphify explain` / '
'`graphify path`) FIRST to orient yourself, then re-issue this Read — it '
'will be allowed. This block fires at most once per session; after one '
'query, read raw files for the exact lines the graph pointed you to.'
),
}
}, ensure_ascii=False, separators=(",", ":")) + "\n"
_SEARCH_DENY = json.dumps({
"hookSpecificOutput": {
"hookEventName": "PreToolUse",
"permissionDecision": "deny",
"permissionDecisionReason": (
'graphify strict mode: this project has a knowledge graph. Run '
'`graphify query "<your question>"` (or `graphify explain` / '
'`graphify path`) FIRST to orient yourself, then re-issue this Grep — '
'it will be allowed. This block fires at most once per session.'
),
}
}, ensure_ascii=False, separators=(",", ":")) + "\n"
# (the strict-mode deny payloads live further down, next to the tool-name
# vocabulary the guard branches on)
_HOOK_SOURCE_EXTS = (
'.py', '.js', '.cjs', '.ts', '.tsx', '.jsx', '.astro', '.vue', '.svelte', '.ejs', '.go',
'.rs', '.java', '.rb', '.c', '.h', '.cpp', '.hpp', '.cc', '.cs', '.kt',
Expand Down Expand Up @@ -1140,6 +1113,57 @@ def _hook_strict_enabled(flag: bool) -> bool:
return flag


# Tool names each supported harness registers for the SAME operation. Claude Code
# capitalizes (Read/Grep/Bash); DeepSeek Harness registers lowercase
# (read/grep/glob/bash). The guard branches on the operation, never on the host,
# so one policy module serves every harness the installer supports.
_TOOL_READ_NAMES = frozenset({"Read", "read"})
_TOOL_SEARCH_NAMES = frozenset({"Grep", "grep"})
_TOOL_BASH_NAMES = frozenset({"Bash", "bash"})


def _tool_is(payload: dict, names: "frozenset[str]") -> bool:
"""True when the payload's tool is one of *names*, or the payload names none.

An absent or null ``tool_name`` keeps the legacy bare-payload behaviour: the
guard is also driven directly (tests, hosts whose pre-tool event carries no
name), and those payloads must be examined rather than silently skipped.
"""
name = payload.get("tool_name")
return name is None or name in names


# Strict-mode deny, one payload per kind. The text is unchanged from before dsh
# support: Claude Code and dsh both honour permissionDecision == "deny" and show
# permissionDecisionReason to the model, and both get the same one block per
# session (see _mark_session_denied) so a deny can never strand an agent.
_READ_DENY = json.dumps({
"hookSpecificOutput": {
"hookEventName": "PreToolUse",
"permissionDecision": "deny",
"permissionDecisionReason": (
'graphify strict mode: this project has a fresh knowledge graph that covers '
'this file. Run `graphify query "<your question>"` (or `graphify explain` / '
'`graphify path`) FIRST to orient yourself, then re-issue this Read — it '
'will be allowed. This block fires at most once per session; after one '
'query, read raw files for the exact lines the graph pointed you to.'
),
}
}, ensure_ascii=False, separators=(",", ":")) + "\n"
_SEARCH_DENY = json.dumps({
"hookSpecificOutput": {
"hookEventName": "PreToolUse",
"permissionDecision": "deny",
"permissionDecisionReason": (
'graphify strict mode: this project has a knowledge graph. Run '
'`graphify query "<your question>"` (or `graphify explain` / '
'`graphify path`) FIRST to orient yourself, then re-issue this Grep — '
'it will be allowed. This block fires at most once per session.'
),
}
}, ensure_ascii=False, separators=(",", ":")) + "\n"


def _touch_query_stamp(graph_path: "Path") -> None:
"""Record that graphify oriented the agent recently, next to the queried graph.
The strict guard suppresses its block while this stamp is fresh. Fail-silent."""
Expand Down Expand Up @@ -1566,12 +1590,10 @@ def _run_hook_guard(kind: str, strict: bool = False) -> None:

In strict mode (opt-in), the FIRST raw Read of indexed, fresh code or dedicated
Grep in the project is DENIED with a redirect to `graphify query`, then
downgrades to the soft nudge. The two tools share one block per session.
Bash and Glob stay nudge-only: a compound shell command has no single
parseable target and blocking file listing would strand navigation. A Bash
command that prints an in-project code file (cat/head/tail/sed -n/nl/less/
more/bat, see _bash_read_target) gets the Read nudge for that file, through
the same budget, and is never denied.
downgrades to the soft nudge. Claude Code and dsh share that one-shot
contract; neither host gets a second, stricter policy. A Bash command that
prints an in-project code file is routed through the read policy and is never
denied.
Out-of-project and graph-output targets are ignored; stale graphs never block.
"""
from graphify.paths import out_path
Expand Down Expand Up @@ -1607,15 +1629,41 @@ def _run_hook_guard(kind: str, strict: bool = False) -> None:
except Exception:
pass
return
# Host-neutral SessionStart guard: orient a fresh session with the same one
# line the Claude Code compaction hook restates, and reset the budget when the
# source IS a compaction. Hosts whose start event carries startup/resume/clear
# sources (DeepSeek Harness) use this instead of `compact`, which only fires on
# a compaction; Claude Code keeps `compact` so its behaviour is unchanged.
if kind == "session":
try:
if d.get("hook_event_name", "SessionStart") != "SessionStart":
return
if d.get("source") == "compact":
_reset_hook_session(str(d.get("session_id") or ""))
if out_path("graph.json").is_file():
sys.stdout.write(_nudge_for_out(_COMPACT_CONTEXT))
except Exception:
pass
return
t = d.get("tool_input", d)
if isinstance(t, str):
# Some hosts hand the tool arguments through as the JSON text the model
# emitted instead of a parsed object (DeepSeek Harness's Claude-Code
# bridge does exactly this: `tool_input` is the raw argument string).
# Parsing it here is what keeps the read/search policy applying there;
# an unparseable string still fails open below.
try:
t = json.loads(t) if t.strip() else {}
except (ValueError, TypeError):
return
if not isinstance(t, dict):
return
try:
# A Bash file read is a Read by another name: route it through the read
# guard below with the file as its target. A reader wins over a search
# in the same command, since the read nudge names the file's symbols.
bash_read = False
if kind == "search" and d.get("tool_name") in (None, "Bash"):
if kind == "search" and _tool_is(d, _TOOL_BASH_NAMES):
target = _bash_read_target(str(t.get("command", "") or ""), str(d.get("cwd") or ""))
if target:
kind, t, bash_read = "read", {"file_path": target}, True
Expand All @@ -1630,7 +1678,7 @@ def _run_hook_guard(kind: str, strict: bool = False) -> None:
# outside the project emits no project hint (#4961).
pattern = t.get("pattern")
is_grep_tool = not cmd_str and isinstance(pattern, str) and bool(pattern) \
and d.get("tool_name") in (None, "Grep")
and _tool_is(d, _TOOL_SEARCH_NAMES)
is_bash_search = bool(cmd_str) and _bash_invokes_search(cmd_str)
if not (is_grep_tool or is_bash_search) or not out_path("graph.json").is_file():
return
Expand Down Expand Up @@ -1799,10 +1847,9 @@ def _is_under_out(target: str) -> bool:
if _nudge_allowed(d):
sys.stdout.write(_nudge_for_out(_READ_NUDGE_STALE))
return
# Strict block: Read tool only, first time per session, not recently
# oriented, and the file is demonstrably indexed. Bash stays advisory.
tool_name = d.get("tool_name")
if not bash_read and _hook_strict_enabled(strict) and tool_name in (None, "Read") \
# Strict block: Read tool only, not recently oriented, and the file is
# demonstrably indexed. Bash stays advisory.
if not bash_read and _hook_strict_enabled(strict) and _tool_is(d, _TOOL_READ_NAMES) \
and not _query_stamp_fresh() \
and _target_is_indexed(fp, root) \
and _mark_session_denied(str(d.get("session_id") or "")):
Expand Down Expand Up @@ -3585,14 +3632,15 @@ def _clear_html_stale_marker() -> None:
# tool calls. Graph guidance reaches the agent via AGENTS.md / skill instead.
sys.exit(0)
elif cmd == "hook-guard":
# Shell-agnostic Claude/Codebuddy PreToolUse guard (#522). Replaces the old
# inline-bash hooks that failed on Windows. Prints an additionalContext nudge
# toward graphify when a fresh in-project graph exists; always exits 0. In
# strict mode (opt-in, `hook-guard <read|search> --strict`) it blocks the
# first raw Read or dedicated Grep per session via the JSON permissionDecision
# Shell-agnostic PreToolUse guard (#522). Replaces the old inline-bash
# hooks that failed on Windows. Prints an additionalContext nudge toward
# graphify when a fresh in-project graph exists; always exits 0. In strict
# mode (opt-in, `hook-guard <read|search> --strict`) it blocks the first
# raw Read or dedicated Grep per session via the JSON permissionDecision
# payload — never via exit code — and downgrades to the nudge thereafter.
# `hook-guard compact` is the SessionStart (matcher "compact") hook that
# resets the session's nudge budget after a context compaction.
# `hook-guard compact` is the Claude Code SessionStart (matcher "compact")
# hook; `hook-guard session` is the host-neutral SessionStart hook that
# also fires on startup/resume/clear.
_run_hook_guard(
sys.argv[2] if len(sys.argv) > 2 else "",
strict="--strict" in sys.argv[3:],
Expand Down
11 changes: 10 additions & 1 deletion graphify/detect.py
Original file line number Diff line number Diff line change
Expand Up @@ -1064,11 +1064,20 @@ def is_resolution_input(path: "Path | str") -> bool:
(".opencode", "plugins", "graphify.js"), # opencode
(".windsurf", "rules", "graphify.md"), # devin
})
# Two-component files graphify writes whole. They cannot match the three-part
# tail test below, so they get their own set: `.dsh/hooks.json` is the merged
# Claude-shaped hook config and `graphify.cordis.yml` the bridge overlay, and
# neither is source a graph should ever describe.
_GRAPHIFY_INSTALLED_ROOT_FILES = frozenset({
(".dsh", "hooks.json"),
(".dsh", "graphify.cordis.yml"),
})


def _is_installed_graphify_file(path: "Path") -> bool:
"""True for a single file `graphify install` wrote into the project (#4057)."""
return path.parts[-3:] in _GRAPHIFY_INSTALLED_FILES
parts = path.parts
return parts[-3:] in _GRAPHIFY_INSTALLED_FILES or parts[-2:] in _GRAPHIFY_INSTALLED_ROOT_FILES

# Files a coverage tool writes into its own output dir. Any one of them is proof
# the directory is generated: lcov (lcov.info), nyc/Istanbul (coverage-final.json,
Expand Down
Loading
Loading