context-mcp-server 1.0.8 → 1.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. package/README.md +29 -7
  2. package/codegraph/__pycache__/affected.cpython-313.pyc +0 -0
  3. package/codegraph/__pycache__/cache.cpython-313.pyc +0 -0
  4. package/codegraph/__pycache__/callflow_html.cpython-313.pyc +0 -0
  5. package/codegraph/__pycache__/export.cpython-313.pyc +0 -0
  6. package/codegraph/__pycache__/report.cpython-313.pyc +0 -0
  7. package/codegraph/__pycache__/server.cpython-313.pyc +0 -0
  8. package/codegraph/__pycache__/tree_html.cpython-313.pyc +0 -0
  9. package/codegraph/affected.py +233 -0
  10. package/codegraph/cache.py +51 -2
  11. package/codegraph/callflow_html.py +273 -0
  12. package/codegraph/export.py +544 -0
  13. package/codegraph/extractors/__pycache__/ast_extractor.cpython-313.pyc +0 -0
  14. package/codegraph/extractors/ast_extractor.py +143 -16
  15. package/codegraph/graph/__pycache__/builder.cpython-313.pyc +0 -0
  16. package/codegraph/graph/__pycache__/clustering.cpython-313.pyc +0 -0
  17. package/codegraph/graph/__pycache__/query.cpython-313.pyc +0 -0
  18. package/codegraph/graph/__pycache__/symbol_resolution.cpython-313.pyc +0 -0
  19. package/codegraph/graph/builder.py +10 -0
  20. package/codegraph/graph/clustering.py +247 -10
  21. package/codegraph/graph/query.py +99 -0
  22. package/codegraph/graph/symbol_resolution.py +112 -0
  23. package/codegraph/report.py +53 -0
  24. package/codegraph/server.py +112 -20
  25. package/codegraph/tree_html.py +241 -0
  26. package/package.json +2 -2
  27. package/pyproject.toml +4 -1
  28. package/src/cli.js +329 -227
  29. package/src/db.js +79 -102
  30. package/src/search.js +73 -9
  31. package/src/server.js +7 -1
  32. package/src/templates/antigravity/GEMINI.md +96 -0
  33. package/src/templates/antigravity/hooks/context-mcp-post-tool-use.js +62 -0
  34. package/src/templates/antigravity/workflows/context-resume.md +20 -0
  35. package/src/templates/antigravity/workflows/graph-build.md +23 -0
  36. package/src/templates/antigravity/workflows/save-context.md +29 -0
  37. package/src/templates/claude/CLAUDE.md +140 -0
  38. package/src/templates/claude/commands/graph-build.md +9 -0
  39. package/src/templates/claude/commands/save-context.md +19 -0
  40. package/src/templates/claude/hooks/context-mcp-post-tool-use.js +59 -0
  41. package/src/templates/claude/hooks/context-mcp-pre-tool-use.js +26 -0
  42. package/src/templates/claude/skills/SKILL.md +144 -0
  43. package/src/templates/codex/AGENTS.md +107 -0
  44. package/src/templates/codex/hooks/context-mcp-post-tool-use.js +46 -0
  45. package/src/templates/codex/hooks/context-mcp-pre-tool-use.js +23 -0
  46. package/src/templates/codex/prompts/context-resume.md +15 -0
  47. package/src/templates/codex/prompts/graph-build.md +14 -0
  48. package/src/templates/codex/prompts/save-context.md +24 -0
  49. package/src/templates/cursor/commands/context-resume.md +7 -0
  50. package/src/templates/cursor/commands/graph-build.md +7 -0
  51. package/src/templates/cursor/commands/save-context.md +12 -0
  52. package/src/templates/{cursor-rules.mdc → cursor/cursor-rules.mdc} +13 -3
  53. package/src/templates/cursor/hooks/context-mcp-post-tool-use.js +55 -0
  54. package/src/templates/gemini/GEMINI.md +92 -0
  55. package/src/templates/gemini/commands/context-resume.toml +15 -0
  56. package/src/templates/gemini/commands/graph-build.toml +14 -0
  57. package/src/templates/gemini/commands/save-context.toml +24 -0
  58. package/src/templates/gemini/hooks/context-mcp-after-tool.js +59 -0
  59. package/src/templates/gemini/hooks/context-mcp-before-tool.js +26 -0
  60. package/src/templates/vscode/commands/context-resume.prompt.md +15 -0
  61. package/src/templates/vscode/commands/graph-build.prompt.md +10 -0
  62. package/src/templates/vscode/commands/save-context.prompt.md +16 -0
  63. package/src/templates/vscode/hooks/context-mcp-post-tool-use.js +58 -0
  64. package/src/templates/windsurf/hooks/context-mcp-post-run-command.js +57 -0
  65. package/src/templates/windsurf/windsurf-rules.md +86 -0
  66. package/src/templates/windsurf/workflows/context-resume.md +11 -0
  67. package/src/templates/windsurf/workflows/graph-build.md +11 -0
  68. package/src/templates/windsurf/workflows/save-context.md +18 -0
  69. package/src/tools/codegraph.js +83 -43
  70. package/src/tools/context.js +42 -24
  71. package/src/tools/plan.js +14 -11
  72. package/uv.lock +1101 -4
  73. package/src/migrator.js +0 -124
  74. package/src/templates/AGENTS.md +0 -80
  75. package/src/templates/CLAUDE.md +0 -103
  76. package/src/templates/GEMINI.md +0 -80
  77. package/src/templates/commands/graph-build.md +0 -5
  78. package/src/templates/commands/save-context.md +0 -9
  79. package/src/templates/skills/SKILL.md +0 -108
  80. package/src/templates/windsurf-rules.md +0 -35
  81. /package/src/templates/{commands → claude/commands}/context-resume.md +0 -0
@@ -0,0 +1,23 @@
1
+ # graph-build
2
+
3
+ Build or refresh the codebase knowledge graph for the current project.
4
+
5
+ ## Steps
6
+
7
+ 1. Identify the project root — use the workspace path or ask if ambiguous.
8
+ 2. Call `codegraph_build` with `path: "<absolute project root>"`.
9
+ - This scans all source files using AST extraction (16+ languages).
10
+ - Incremental: only changed files are re-processed.
11
+ 3. When complete, call `context` with `action:"save"`:
12
+ ```
13
+ type: "note"
14
+ title: "CodeGraph built — <project>"
15
+ content: "nodes: N | edges: E | communities: C | time: Xms"
16
+ project: "<project>"
17
+ tags: ["codegraph"]
18
+ ```
19
+ 4. Report: node count, edge count, communities, any warnings.
20
+ 5. Suggest next steps:
21
+ - `codegraph_arch` — module map
22
+ - `codegraph_report` — god nodes, surprising connections
23
+ - `codegraph_query` — ask structural questions
@@ -0,0 +1,29 @@
1
+ # save-context
2
+
3
+ Save the current work state to persistent memory.
4
+
5
+ ## Steps
6
+
7
+ 1. Ask (or infer from context):
8
+ - **Title** — one-line summary of what was done
9
+ - **Why** — motivation or trigger
10
+ - **Outcome** — result, decision, or current state
11
+ - **Files** — list of files touched (if applicable)
12
+ 2. Call `context` MCP tool with `action: "save"`:
13
+ ```
14
+ type: "note"
15
+ title: "<title>"
16
+ why: "<why>"
17
+ outcome: "<outcome>"
18
+ files: ["<file1>", "<file2>"]
19
+ project: "<project>"
20
+ ```
21
+ 3. Confirm: report the saved entry ID and title.
22
+
23
+ ## When to use
24
+
25
+ - After completing a task, fix, or feature
26
+ - After making a significant decision
27
+ - When discovering a constraint or gotcha
28
+ - When the user says "save this" or "remember this"
29
+ - After a graph build (use `graph-build` workflow instead)
@@ -0,0 +1,140 @@
1
+ ---
2
+ name: context-mcp
3
+ description: >
4
+ Persistent memory + ContextGraph for Claude.
5
+ Use at the START of every conversation to resume project context.
6
+ Use whenever the user mentions a project, asks to remember/save something,
7
+ references past work, or says "pick up where we left off".
8
+ Also use when the user asks about code structure — query ContextGraph before reading any files.
9
+ ---
10
+
11
+ # Context-MCP — Claude Usage Guide
12
+
13
+ Persistent memory + codebase knowledge graph across every conversation.
14
+ `context.resume` starts every session. `codegraph_arch` shows module structure. `codegraph_query` finds specific symbols. Files only for bugs/logic.
15
+
16
+ ---
17
+
18
+ ## 1. Start of Every Conversation (MANDATORY)
19
+
20
+ Call `context` tool **before any tool or response**:
21
+ - `action: "resume"`
22
+ - `project: "<basename of git repo root>"` — infer from cwd
23
+ - `rootPath: "<absolute path to git repo root>"` — required
24
+
25
+ Returns:
26
+ - `recentEntries` — last 15 entries; newest 5 have full content, rest have 200-char preview
27
+ - `activePlans` — in-progress plans; read them before starting any new work
28
+ - `codegraph` — `{ built: true/false, nodes, edges }`
29
+ - `stats.totalEntries` — if ≥ 20, write a compaction summary before proceeding (see Rule 4)
30
+
31
+ Then:
32
+ - `codegraph.built: true` → use `codegraph_arch` for structure overview, `codegraph_query` for specific lookups
33
+ - `codegraph.built: false` → call `codegraph_build(path)` first
34
+
35
+ ---
36
+
37
+ ## 2. When to Save Context (MANDATORY TRIGGERS)
38
+
39
+ Call `context.save` with `type: "note"` whenever you finish something or discover something worth keeping:
40
+
41
+ ```
42
+ context.save
43
+ project: "<project>"
44
+ title: "<what was done — up to 120 chars>"
45
+ why: "<why it mattered>"
46
+ outcome: "<what the result was>"
47
+ files: ["src/file.js", ...]
48
+ ```
49
+
50
+ **Save immediately after:**
51
+ - Task / fix / feature complete
52
+ - Decision made (architecture, library, approach)
53
+ - Discovery — non-obvious behavior, constraint, gotcha
54
+ - Config / env / deploy info
55
+ - Graph build complete — include nodes/edges count in content
56
+ - User says "save this" / "remember this"
57
+
58
+ **Manual compaction** — "compact now", "compress memory", "clean up context":
59
+ Save a full session summary as `type: "compaction"`. Server removes old entries using it.
60
+
61
+ **Do NOT save:** routine reads, search results, explanations of existing code, dead-end debugging.
62
+
63
+ ---
64
+
65
+ ## 3. Plans (MANDATORY for multi-file work)
66
+
67
+ **Create a plan when:** editing 2+ files, multi-step implementation, refactor, multi-file bug fix.
68
+
69
+ **Skip plan for:** single-file edits, questions, simple config tweaks.
70
+
71
+ 1. Call `plan.save` with `name`, `content` (full plan in markdown), `project`, `planDir` before starting
72
+ 2. Work through the plan
73
+ 3. Call `plan.update status:"done"` when complete — this deletes the plan
74
+
75
+ On `resume`, if `activePlans` is non-empty — read them before starting new work. Do not create a duplicate.
76
+
77
+ ---
78
+
79
+ ## 4. Auto-Summary Rule (MANDATORY)
80
+
81
+ When `resume` returns `stats.totalEntries ≥ 20`, call `context.save` **before doing anything else**:
82
+
83
+ ```
84
+ context.save
85
+ type: "compaction"
86
+ title: "Session summary — <YYYY-MM-DD>"
87
+ content: "<what was built, decided, broke, current state>"
88
+ project: "<project>"
89
+ ```
90
+
91
+ ---
92
+
93
+ ## 5. Search Before Asking
94
+
95
+ If the user references past work → call `search` first:
96
+ ```
97
+ search query: "<what they're referencing>" project: "<project>"
98
+ ```
99
+
100
+ ---
101
+
102
+ ## 6. ContextGraph Pipeline
103
+
104
+ ### Build (once per project)
105
+ ```
106
+ codegraph_build(path)
107
+ ```
108
+
109
+ ### Query tools
110
+ ```
111
+ codegraph_arch(path, limit?) → module map: every file, its exports, its imports
112
+ codegraph_query(path, question?, node?) → find function/class/file or answer structural question
113
+ codegraph_nodes(path, type) → list all nodes of a type
114
+ codegraph_report(path) → god nodes, clusters, structural analysis
115
+ codegraph_affected(path, node, depth?) → blast radius BFS — what breaks if X changes?
116
+ codegraph_html(path, formats?) → regenerate visualizations (auto-runs on every build)
117
+ ```
118
+
119
+ | Question | Tool |
120
+ |---|---|
121
+ | What files exist and what do they export? | `codegraph_arch` |
122
+ | Where is function X defined? | `codegraph_query node:"X"` |
123
+ | What does module Y depend on? | `codegraph_query question:"what does Y import?"` |
124
+ | What are all the classes? | `codegraph_nodes type:"class"` |
125
+ | Most connected files? | `codegraph_report` |
126
+ | What breaks if I change X? | `codegraph_affected node:"X"` |
127
+
128
+ **Never read files for structure questions — use graph tools first.**
129
+
130
+ ---
131
+
132
+ ## 7. Rules
133
+
134
+ 1. `context.resume` first — before any tool or response
135
+ 2. Always pass `project`
136
+ 3. Save on task complete — `why` + `outcome` + `files`
137
+ 4. Compaction at ≥ 20 entries — before starting the task
138
+ 5. Plan for multi-file work — save before starting, `status:"done"` deletes it
139
+ 6. Search before asking about past work
140
+ 7. Graph tools before files
@@ -0,0 +1,9 @@
1
+ Call `codegraph_build` with the path `$ARGUMENTS`.
2
+
3
+ If no argument is given, use the current working directory.
4
+
5
+ This builds the ContextGraph for the project by parsing source files into an AST
6
+ knowledge graph. Once built, use `codegraph_query` to answer structural questions
7
+ about the codebase before reading files directly.
8
+
9
+ After the build completes, report total nodes, edges, and communities.
@@ -0,0 +1,19 @@
1
+ Call the `context` MCP tool with `action: "save"` to store a note for the
2
+ current project.
3
+
4
+ Parse `$ARGUMENTS` to determine:
5
+
6
+ - `project`: infer from current working directory name if not specified.
7
+ - `title`: first sentence or phrase, up to 120 chars.
8
+ - `why`: why it mattered, what problem it solved, or what constraint it revealed.
9
+ - `outcome`: what changed, what was verified, what shipped, and which files were affected.
10
+ - `files`: list of files changed, required for task/bug types.
11
+ - `content`: full argument text.
12
+ - `type`: auto-detect:
13
+ - bug/fix/error -> `"bug"`
14
+ - task/done/complete/shipped/implemented -> `"task"`
15
+ - decision/chose/decided/approach -> `"decision"`
16
+ - config/env/secret/deploy -> `"config"`
17
+ - otherwise -> `"note"`
18
+
19
+ Confirm to the user: title, type, why, outcome, and project.
@@ -0,0 +1,59 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * Claude Code PostToolUse hook for context-mcp.
5
+ *
6
+ * Input (stdin JSON): { session_id, cwd, hook_event_name: "PostToolUse",
7
+ * tool_name, tool_input: { command }, tool_response | tool_output }
8
+ *
9
+ * Saves failed Bash commands to context-mcp so the next session can see
10
+ * what broke. Exits silently when the command succeeded or the exit code
11
+ * cannot be determined.
12
+ */
13
+
14
+ import { spawnSync } from 'node:child_process';
15
+
16
+ process.stdin.resume();
17
+ process.stdin.setEncoding('utf8');
18
+
19
+ let input = '';
20
+ process.stdin.on('data', chunk => { input += chunk; });
21
+ process.stdin.on('end', () => {
22
+ let event = {};
23
+ try {
24
+ event = input.trim() ? JSON.parse(input) : {};
25
+ } catch {
26
+ return;
27
+ }
28
+
29
+ const toolInput = event.tool_input || {};
30
+ const toolResult = typeof event.tool_response === 'object' && event.tool_response !== null
31
+ ? event.tool_response
32
+ : {};
33
+ const command = toolInput.command || '';
34
+ const exitCode = toolResult.exit_code ?? toolResult.exitCode ?? toolResult.code;
35
+
36
+ if (!command || exitCode === undefined || Number(exitCode) === 0) return;
37
+
38
+ const output = String(
39
+ toolResult.stderr || toolResult.stdout || toolResult.output || event.tool_output || '',
40
+ ).trim();
41
+
42
+ const content = [
43
+ `Command: ${command}`,
44
+ `Exit code: ${exitCode}`,
45
+ output ? `Output:\n${output.slice(0, 4000)}` : null,
46
+ ].filter(Boolean).join('\n\n');
47
+
48
+ spawnSync('ctx', [
49
+ 'save',
50
+ '--project', (event.cwd || process.cwd()).split(/[\\/]/).pop() || 'default',
51
+ '--type', 'bug',
52
+ '--title', `Failed shell command: ${command.slice(0, 80)}`,
53
+ '--content', content,
54
+ ], {
55
+ encoding: 'utf8',
56
+ shell: true,
57
+ stdio: 'ignore',
58
+ });
59
+ });
@@ -0,0 +1,26 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * Claude Code PreToolUse hook for context-mcp.
5
+ *
6
+ * Input (stdin JSON): { session_id, cwd, hook_event_name: "PreToolUse",
7
+ * tool_name, tool_input, permission_mode }
8
+ *
9
+ * This hook is intentionally conservative. It validates the hook pipeline
10
+ * runs before Bash commands but never blocks or rewrites them (exit 0 =
11
+ * allow). Keep policy decisions in CLAUDE.md or a dedicated security hook
12
+ * if your team needs command blocking (exit 2 + stderr blocks the call).
13
+ */
14
+
15
+ process.stdin.resume();
16
+ process.stdin.setEncoding('utf8');
17
+
18
+ let input = '';
19
+ process.stdin.on('data', chunk => { input += chunk; });
20
+ process.stdin.on('end', () => {
21
+ try {
22
+ if (input.trim()) JSON.parse(input);
23
+ } catch {
24
+ // Do not interrupt the user's command because hook input changed.
25
+ }
26
+ });
@@ -0,0 +1,144 @@
1
+ ---
2
+ name: context-mcp
3
+ description: >
4
+ Persistent memory + ContextGraph (codebase knowledge graph) for Claude.
5
+ Use at the START of every conversation to resume project context. Use
6
+ whenever the user mentions a project, asks to remember/save something,
7
+ references past work, or says "pick up where we left off". Also use
8
+ when the user asks about code structure, dependencies, or what exists
9
+ in a codebase — query the ContextGraph before reading any files.
10
+ ---
11
+
12
+ # Context-MCP
13
+
14
+ Persistent memory + codebase knowledge graph across every conversation.
15
+ `context.resume` starts every session. `codegraph_arch` shows module structure. `codegraph_query` finds specific symbols. Files only for bugs/logic.
16
+
17
+ ---
18
+
19
+ ## Subcommands
20
+
21
+ When invoked with an argument, act immediately:
22
+
23
+ **`/context-mcp resume`** — call `context` tool with `action:"resume"`, infer `project` from cwd, pass `rootPath`. Report what was returned.
24
+
25
+ **`/context-mcp save`** — call `context` tool with `action:"save"` to save the most recent thing worth keeping from this conversation. Use `type:"note"`, fill in `title`, `why`, `outcome`, `files` from context. Confirm what was saved.
26
+
27
+ ---
28
+
29
+ ## MANDATORY: Start of Every Conversation
30
+
31
+ Call `context` tool **before any tool or response** with:
32
+ - `action: "resume"`
33
+ - `project: "<basename of git repo root dir>"` — infer from `cwd` if not stated
34
+ - `rootPath: "<absolute path to git repo root>"` — required for sandbox + graph lookup
35
+
36
+ Returns:
37
+ - `recentEntries` — last 15 entries; newest 5 have full content, rest have 200-char preview
38
+ - `activePlans` — in-progress plans; read them before starting any new work
39
+ - `codegraph` — `{ built: true/false, nodes, edges, communities }`
40
+ - `stats.totalEntries` — if ≥ 20, write a compaction summary before proceeding (see Rule 4)
41
+
42
+ Then:
43
+ - `codegraph.built: true` → use `codegraph_arch` for structure overview, `codegraph_query` for specific lookups
44
+ - `codegraph.built: false` → call `codegraph_build(path)` first
45
+
46
+ ---
47
+
48
+ ## When to Save Context (MANDATORY TRIGGERS)
49
+
50
+ Call `context.save` with `type: "note"` after finishing anything worth keeping:
51
+
52
+ ```
53
+ context.save
54
+ project: "<project>"
55
+ title: "<what was done — up to 120 chars>"
56
+ why: "<why it mattered>"
57
+ outcome: "<what the result was>"
58
+ files: ["src/file.js", ...]
59
+ ```
60
+
61
+ **Save immediately after:**
62
+ - Task / fix / feature complete
63
+ - Decision made (architecture, library, approach)
64
+ - Discovery — non-obvious behavior, constraint, gotcha
65
+ - Config / env / deploy info
66
+ - Graph build complete — include nodes/edges count in content
67
+ - User says "save this" / "remember this"
68
+
69
+ **Manual compaction** — "compact now", "compress memory", "clean up context":
70
+ Save a full session summary as `type: "compaction"`. Server removes old entries using it.
71
+
72
+ **Do NOT save:** routine reads, search results, explanations of existing code, dead-end debugging.
73
+
74
+ ---
75
+
76
+ ## Plans (MANDATORY for multi-file work)
77
+
78
+ **Create a plan when:** editing 2+ files, multi-step implementation, refactor, multi-file bug fix.
79
+
80
+ **Skip plan for:** single-file edits, questions, simple config tweaks.
81
+
82
+ 1. `plan.save` with name, content, project, planDir — before starting work
83
+ 2. Work through plan
84
+ 3. `plan.update status:"done"` when complete — deletes the plan
85
+
86
+ On `resume`, check `activePlans` — do not duplicate in-progress work.
87
+
88
+ ---
89
+
90
+ ## Auto-Summary Rule (MANDATORY)
91
+
92
+ When `resume` returns `stats.totalEntries ≥ 20`, call `context.save` **before the user's task**:
93
+
94
+ ```
95
+ type: "compaction" title: "Session summary — <date>"
96
+ content: "<what was built, decided, broke, current state>"
97
+ project: "<project>"
98
+ ```
99
+
100
+ ---
101
+
102
+ ## Search Before Asking
103
+
104
+ If user references past work → `search` first. Never ask user to re-explain saved information.
105
+
106
+ ---
107
+
108
+ ## ContextGraph Pipeline
109
+
110
+ ### Build (once per project)
111
+ ```
112
+ codegraph_build(path) → AST graph: functions, classes, imports, edges
113
+ ```
114
+
115
+ ### Query tools
116
+ ```
117
+ codegraph_arch(path) → module map: every file, exports, imports
118
+ codegraph_query(path, question?, node?) → find symbol or answer structural question
119
+ codegraph_nodes(path, type) → list all nodes of a type
120
+ codegraph_report(path) → god nodes, clusters, structural analysis
121
+ codegraph_affected(path, node, depth?) → blast radius BFS — what breaks if X changes?
122
+ codegraph_html(path, formats?) → regenerate visualizations (auto-runs on every build)
123
+ ```
124
+
125
+ | Question | Tool |
126
+ |---|---|
127
+ | Architecture overview / what files exist | `codegraph_arch` |
128
+ | Where is function/class X defined? | `codegraph_query node:"X"` |
129
+ | What does module Y import? | `codegraph_query question:"..."` |
130
+ | List all classes/functions | `codegraph_nodes type:"class"` |
131
+ | Most connected / central files | `codegraph_report` |
132
+ | What breaks if I change X? | `codegraph_affected node:"X"` |
133
+
134
+ ---
135
+
136
+ ## Rules
137
+
138
+ 1. `context.resume` first — before any tool or response
139
+ 2. Always pass `project`
140
+ 3. Save on task complete — `why` + `outcome` + `files`
141
+ 4. Compaction at ≥ 20 entries — before starting task
142
+ 5. Plan for multi-file work — `status:"done"` deletes it
143
+ 6. Search before asking about past work
144
+ 7. Graph tools before files
@@ -0,0 +1,107 @@
1
+ # Context-MCP - Codex CLI Usage Guide
2
+
3
+ Persistent memory + codebase knowledge graph.
4
+ `context.resume` starts every session. `codegraph_query` finds specific symbols.
5
+ Read files only for bugs or implementation logic.
6
+
7
+ ---
8
+
9
+ ## 1. Start of Every Conversation (MANDATORY)
10
+
11
+ Call the `context` MCP tool before any other action:
12
+
13
+ ```json
14
+ {
15
+ "action": "resume",
16
+ "project": "<project>",
17
+ "rootPath": "<absolute path to the project root>"
18
+ }
19
+ ```
20
+
21
+ Returns: `recentEntries`, `activePlans`, `codegraph`, `stats.totalEntries`.
22
+
23
+ - `codegraph.built: true` -> use graph tools before reading files.
24
+ - `codegraph.built: false` -> call `codegraph_build(path)` first.
25
+ - `stats.totalEntries >= 20` -> write a compaction summary first.
26
+ - `activePlans` non-empty -> read them before starting new work.
27
+
28
+ ---
29
+
30
+ ## 2. Save Triggers (MANDATORY)
31
+
32
+ Call `context.save` with `type: "note"` after finishing anything worth keeping:
33
+
34
+ | Trigger | Required fields |
35
+ |---|---|
36
+ | Task / fix / feature complete | title, why, outcome, files[] |
37
+ | Decision made | title, why, outcome |
38
+ | Discovery / constraint / gotcha | title, content |
39
+ | Config / env / deploy info | title, content |
40
+ | Graph build complete | title, content with nodes/edges count |
41
+ | User says "save this" | title, content |
42
+ | "compact now" / "compress memory" | `type: "compaction"`, full session summary |
43
+
44
+ Do not save routine reads, search results, or explanations of existing code.
45
+
46
+ ---
47
+
48
+ ## 3. Plans (MANDATORY for multi-file work)
49
+
50
+ Create a plan when editing 2+ files, doing a multi-step implementation, refactor,
51
+ or multi-file bug fix.
52
+
53
+ 1. Call `plan.save` with name, content, and project before starting.
54
+ 2. Call `plan.update status: "done"` when complete.
55
+
56
+ Check `activePlans` on resume. Do not create duplicates.
57
+
58
+ ---
59
+
60
+ ## 4. Auto-Summary at >= 20 Entries (MANDATORY)
61
+
62
+ When `totalEntries >= 20`, call `context.save` before the user's task:
63
+
64
+ ```json
65
+ {
66
+ "type": "compaction",
67
+ "title": "Session summary - <YYYY-MM-DD>",
68
+ "content": "<what was built, decided, broke, current state>",
69
+ "project": "<project>"
70
+ }
71
+ ```
72
+
73
+ ---
74
+
75
+ ## 5. Search Before Asking
76
+
77
+ Call `search` before asking the user to re-explain past work.
78
+
79
+ ---
80
+
81
+ ## 6. ContextGraph Tools
82
+
83
+ ```text
84
+ codegraph_build(path) -> build AST graph + auto-generate all visualizations
85
+ codegraph_arch(path, limit?) -> module map: files, exports, imports
86
+ codegraph_query(path, question?, node?) -> find symbol or answer structural question
87
+ codegraph_nodes(path, type) -> list all nodes of a type
88
+ codegraph_report(path) -> structural analysis
89
+ codegraph_affected(path, node, depth?) -> blast radius BFS — what breaks if X changes?
90
+ codegraph_html(path, formats?) -> regenerate visualizations on demand
91
+ ```
92
+
93
+ Use `codegraph_arch` first. Read files only when you need exact bug or
94
+ implementation details.
95
+
96
+ ---
97
+
98
+ ## 7. Rules
99
+
100
+ 1. `context.resume` first, before any tool or response.
101
+ 2. Always pass `project`.
102
+ 3. Pass `rootPath` whenever the current project root is known.
103
+ 4. Save on task complete with why, outcome, and files.
104
+ 5. Compact at >= 20 entries before starting the task.
105
+ 6. Plan before multi-file work.
106
+ 7. Search before asking about past work.
107
+ 8. Use graph tools before files.
@@ -0,0 +1,46 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { spawnSync } from 'node:child_process';
4
+
5
+ process.stdin.resume();
6
+ process.stdin.setEncoding('utf8');
7
+
8
+ let input = '';
9
+ process.stdin.on('data', chunk => { input += chunk; });
10
+ process.stdin.on('end', () => {
11
+ let event = {};
12
+ try {
13
+ event = input.trim() ? JSON.parse(input) : {};
14
+ } catch {
15
+ return;
16
+ }
17
+
18
+ const toolInput = event.tool_input || event.toolInput || {};
19
+ const toolResult = event.tool_response || event.toolResponse || event.result || {};
20
+ const command = toolInput.command || toolInput.cmd || event.command || '';
21
+ const exitCode = toolResult.exit_code ?? toolResult.exitCode ?? event.exit_code ?? event.exitCode;
22
+
23
+ if (!command || exitCode === undefined || Number(exitCode) === 0) return;
24
+
25
+ const output = String(
26
+ toolResult.stderr || toolResult.stdout || toolResult.output || event.output || '',
27
+ ).trim();
28
+
29
+ const content = [
30
+ `Command: ${command}`,
31
+ `Exit code: ${exitCode}`,
32
+ output ? `Output:\n${output.slice(0, 4000)}` : null,
33
+ ].filter(Boolean).join('\n\n');
34
+
35
+ spawnSync('ctx', [
36
+ 'save',
37
+ '--project', process.cwd().split(/[\\/]/).pop() || 'default',
38
+ '--type', 'bug',
39
+ '--title', `Failed shell command: ${command.slice(0, 80)}`,
40
+ '--content', content,
41
+ ], {
42
+ encoding: 'utf8',
43
+ shell: true,
44
+ stdio: 'ignore',
45
+ });
46
+ });
@@ -0,0 +1,23 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * Codex PreToolUse hook for context-mcp.
5
+ *
6
+ * This hook is intentionally conservative. It validates that Codex can run the
7
+ * project-local hook pipeline before Bash commands, but it does not block or
8
+ * rewrite commands. Keep policy decisions in AGENTS.md or a dedicated security
9
+ * hook if your team needs command blocking.
10
+ */
11
+
12
+ process.stdin.resume();
13
+ process.stdin.setEncoding('utf8');
14
+
15
+ let input = '';
16
+ process.stdin.on('data', chunk => { input += chunk; });
17
+ process.stdin.on('end', () => {
18
+ try {
19
+ if (input.trim()) JSON.parse(input);
20
+ } catch {
21
+ // Do not interrupt the user's command because hook input changed.
22
+ }
23
+ });
@@ -0,0 +1,15 @@
1
+ ---
2
+ description: "Resume project memory + ContextGraph from context-mcp"
3
+ argument-hint: [project]
4
+ ---
5
+
6
+ Call the `context` MCP tool with `action: "resume"`, `project: "$ARGUMENTS"` (if no argument given, infer the project name from the current working directory name), and `rootPath: "<absolute path to the project root / git repo root>"`.
7
+
8
+ Both `project` and `rootPath` are required: `project` names the memory bucket, `rootPath` enables exact graph lookup and file sandboxing.
9
+
10
+ This loads:
11
+ - Recent decisions, bugs, and notes from past sessions
12
+ - Active plans
13
+ - ContextGraph status (built or not)
14
+
15
+ If `codegraph.built` is false in the response, immediately call `codegraph_build` on the project path before proceeding.
@@ -0,0 +1,14 @@
1
+ ---
2
+ description: "Build the ContextGraph (AST knowledge graph) for a project"
3
+ argument-hint: [path]
4
+ ---
5
+
6
+ Call `codegraph_build` with the path `$ARGUMENTS`.
7
+
8
+ If no argument is given, use the current working directory.
9
+
10
+ This builds the ContextGraph for the project by parsing source files into an AST
11
+ knowledge graph. Once built, use `codegraph_query` to answer structural questions
12
+ about the codebase before reading files directly.
13
+
14
+ After the build completes, report total nodes, edges, and communities.