graphflow · diff
git:20261002.58d8365 to git:20261014.fd39fe4
15 added, 711 removed. Audit A to A.
---
- name: "graphflow"
- description: "图谱上下文压缩、任务规划与知识图谱编排(10 个 MCP 工具)。任何读代码、改代码、排错、中文问题之前必须先调 graphflow_context。DeepSeek Harness / Kimi Code 下工具名为 mcp__graphflow__graphflow_*。"
- ---
-
- # GraphFlow Skill
-
- GraphFlow is a graph-based context and planning service backed by a persistent MCP server. It turns codebases into queryable knowledge graphs, delivering token-efficient compressed context, task planning, and orchestration.
-
- ## Architecture
-
- ```
- ┌─────────────────────────────────────────────────┐
- │ GraphFlow Skill (this file) │
- │ - Quick entry points & workflows │
- │ - Tool selection logic │
- │ - Output interpretation guides │
- └──────────────────┬──────────────────────────────┘
- │
- ▼
- ┌─────────────────────────────────────────────────┐
- │ GraphFlow MCP Server (persistent backend) │
- │ 10 tools: context, plan, index, insight, run, │
- │ report_outcome, skill_insights, diagnose, │
- │ artifact, skill_guide │
- └──────────────────┬──────────────────────────────┘
- │
- ▼
- ┌─────────────────────────────────────────────────┐
- │ GraphFlow Core Engine │
- │ - Graph index & context compression │
- │ - Task planning & DAG │
- │ - Skill learning flywheel │
- │ - Artifact import/export │
- └─────────────────────────────────────────────────┘
- ```
-
- ## When to Use
-
- **ALWAYS invoke this skill BEFORE:**
- - Multi-step edits, refactors, or architecture changes
- - Large codebase-wide questions or exploration
- - Debugging across multiple files
- - Any task where you would otherwise read many files
- - Token budget is a concern
- - You need structured task planning
-
- **DO NOT:**
- - Scan the whole repository recursively before trying GraphFlow
- - Read large files before checking GraphFlow anchors
- - Skip GraphFlow for complex tasks
- - Use grep for codebase exploration before `graphflow_context`
-
- ## Workspace root (`rootDir`)
-
- Every tool resolves its workspace from, in order: the `rootDir` argument, `GRAPHFLOW_WORKSPACE_ROOT`, project config, then discovery from the process cwd.
-
- - Pass `rootDir` = the **absolute path of the project you are working in**.
- - **Never** pass your home directory, AppData, a bundled runtime directory, or an unexpanded `${workspaceFolder}` placeholder. GraphFlow refuses unsafe roots (`unsafe workspace root`) instead of indexing them, so the call fails.
- - On `unsafe workspace root`: retry the **same call without `rootDir`** (the server then uses its configured workspace / discovery) or with the session's project path. Do not retry the same unsafe path.
- - If the host started the MCP server from your home directory, set `GRAPHFLOW_WORKSPACE_ROOT` to the project path in its MCP server config.
-
- ### Trae / Trae CN setup (Rules + Skill + MCP)
-
- Trae loads **Rules every turn** and **Skills on demand**. GraphFlow `install` writes:
-
- | Path | Role |
- |------|------|
- | `.trae/rules/graphflow.md` | `alwaysApply: true` — **must** call `graphflow_context` first |
- | `.trae/skills/graphflow/SKILL.md` | Full workflows; trigger with `#graphflow` |
- | `User/mcp.json` | GraphFlow MCP server |
-
- If Rules are missing, type `#graphflow` at the start of a chat. Pass `rootDir` = current project absolute path on every context call.
-
- ### Antigravity IDE setup (Rules + Skill + MCP)
-
- | Path | Role |
- |------|------|
- | `~/.gemini/antigravity/mcp_config.json` | Global MCP (`mcpServers.graphflow`) |
- | `~/.gemini/antigravity/skills/graphflow/SKILL.md` | Global Skill |
- | `.agent/rules/graphflow.md` | Project rules (always loaded in workspace) |
- | `.agent/skills/graphflow/SKILL.md` | Project Skill |
- | `GEMINI.md` (project root) | Managed token-first block |
-
- Run `npx @roarpeng/graphflow install` from the project root. Do **not** hardcode `GRAPHFLOW_WORKSPACE_ROOT` in MCP env.
-
- ### Gemini CLI setup
-
- | Path | Role |
- |------|------|
- | `~/.gemini/settings.json` | MCP (`mcpServers.graphflow`) |
- | `~/.gemini/GEMINI.md` | Global managed instruction block |
- | `GEMINI.md` (project root) | Project managed block (with `install --scope all`) |
-
- ### GitHub Copilot (VS Code) setup
-
- | Path | Role |
- |------|------|
- | `~/.config/Code/User/mcp.json` | User MCP (`servers.graphflow`) |
- | `.vscode/mcp.json` | Project MCP (optional, team-shared) |
- | `.github/copilot-instructions.md` | Repo-level Copilot instructions |
-
- ### Kimi Code CLI setup
-
- | Path | Role |
- |------|------|
- | `~/.kimi-code/mcp.json` (or `$KIMI_CODE_HOME/mcp.json`) | User MCP (`mcpServers.graphflow`) |
- | `~/.kimi-code/skills/graphflow/SKILL.md` | User Skill (`/skill:graphflow`) |
- | `~/.kimi-code/AGENTS.md` | Global token-first instruction block |
-
- Run `npx @roarpeng/graphflow install`. Kimi Code does not expand `${workspaceFolder}`; GraphFlow omits that env placeholder. Tools appear as `mcp__graphflow__graphflow_*`. HostAdapter id: `kimi-code`.
-
- ### DeepSeek Harness(`dsh`)插件:用法与能力
-
- GraphFlow 是 DeepSeek Harness 的 `dsh-plugin`。装入后模型看到的工具名带前缀 `mcp__graphflow__`。
-
- **能力**
-
- | 能力 | 工具(dsh 名) |
- |------|----------------|
- | 压缩上下文(先调用) | `mcp__graphflow__graphflow_context` |
- | 任务规划 DAG | `mcp__graphflow__graphflow_plan` |
- | 桥接执行包 | `mcp__graphflow__graphflow_run` |
- | 回填飞轮 | `mcp__graphflow__graphflow_report_outcome` |
- | ATP insight | `mcp__graphflow__graphflow_insight` |
- | 增量/全量建图 | `mcp__graphflow__graphflow_index` |
- | 技能洞察 | `mcp__graphflow__graphflow_skill_insights` |
- | 诊断 | `mcp__graphflow__graphflow_diagnose` |
- | 图谱产物 | `mcp__graphflow__graphflow_artifact` |
- | 技能指南 | `mcp__graphflow__graphflow_skill_guide` |
-
- **安装**
-
- ```sh
- dsh plugin --profile web add @roarpeng/graphflow
- npx @deepseek-ai/dsh web
- # 或已有 ~/.dsh 时写 home overlay + skill 文件:
- npx @roarpeng/graphflow install
- ```
-
- | 路径 | 作用 |
- |------|------|
- | 包内 `cordis.patch.yml` | `dsh plugin add` 插入的 bundle 层:MCP(`cwd: process.cwd()`)+ `@roarpeng/graphflow/dsh` glue |
- | `$DSH_HOME/cordis.patch.yml`(默认 `~/.dsh`) | `graphflow install` 写的 home overlay |
- | `$DSH_HOME/skills/graphflow/SKILL.md` | 本 Skill(install 复制);glue 也会在运行时 `ctx.skills.register` |
-
- **用法:** 第一轮先 `mcp__graphflow__graphflow_context`(`rootDir` = 仓库绝对路径)。不要在 patch 里写死 `GRAPHFLOW_WORKSPACE_ROOT`。走了 `graphflow_run` 后必须 `graphflow_report_outcome`。会话结束时 glue 会 best-effort 关闭 pending episode(`GRAPHFLOW_AUTO_CAPTURE=0` 可关)。VS Code 图谱面板 / Workbench Tree 不在 dsh 上。
-
- ---
-
- ## Tool Inventory (10 MCP Tools)
-
- ### Core Context Tools (Highest Frequency)
-
- | Tool | Purpose | Call Frequency |
- |------|---------|---------------|
- | `graphflow_context` | Preview compressed context (query), expand anchor (anchorId), or archive/recall oversized outputs (content/handle) | **Highest** - default first step |
-
- ### Planning Tools (High Frequency)
-
- | Tool | Purpose | Call Frequency |
- |------|---------|---------------|
- | `graphflow_plan` | Multi-step task decomposition & DAG (mode='simple' or 'insight') | High - before complex work |
- | `graphflow_run` | Plan + context package (bridge mode) | Medium - full task packaging |
- | `graphflow_report_outcome` | Report bridge-mode execution outcome back | Medium - close the learning loop |
- | `graphflow_insight` | Submit or merge agent insights | Medium - no external LLM API |
-
- ### Graph Management Tools (Medium Frequency)
-
- | Tool | Purpose | Call Frequency |
- |------|---------|---------------|
- | `graphflow_index` | Incremental workspace re-index, single-file, or full rebuild | Medium - after file changes |
-
- ### Collaboration & Insights Tools (Low Frequency)
-
- | Tool | Purpose | Call Frequency |
- |------|---------|---------------|
- | `graphflow_artifact` | Export or import graph artifact | Low - team sharing |
- | `graphflow_skill_insights` | Learned skill patterns | Low - leverage prior learning |
- | `graphflow_skill_guide` | Skill usage guide for connected agents | Low - onboarding |
- | `graphflow_diagnose` | Provider health, graph stats, and token savings | Low - ROI tracking / config issues |
-
- ---
-
- ## Standard Workflows
-
- ### Workflow 1: Context First (90% of tasks)
-
- **Use when:** Answering code questions, exploring codebase, understanding modules
-
- ```
- Step 1: graphflow_context(query: "<your question>")
- Step 2: Read summary + anchors as primary context
- Step 3: Expand specific anchors with graphflow_context(anchorId: "...") when needed
- Step 4: Read full files only when exact edits required
- Step 5: After answering the user, call graphflow_context({ assistantReply: "<original answer>" })
- (query optional). This fills the pending turn/topic. Store original text, not an extracted abstract.
- ```
-
- Complex tasks: `graphflow_plan` seeds a **workbench** of topic containers (function nodes on the canvas). Pass `topicId` to refine a node or return to the mainline. Drift auto-forks an isolated side node; messages stay inside the topic — the canvas is not one-turn-one-node. Without a workbench, previews still record as dialogue-turn nodes (`resumeFromTurnId`). Workbench titles/Path labels are **display only**; next-turn context is Goal + path titles + local original Q/A.
-
- The response echoes workbench/dialogue history only as **message previews** (each clipped to ~160 chars with a `truncated` flag; every turn keeps its `id` for `resumeFromTurnId`). Full text stays in the graph store — expand with `graphflow_context(anchorId)` or view the whole history in the VS Code panel (Workbench Tree / `workbench tree`). Pass `recordDialogue: false` to disable the echo AND the recording for that call entirely.
-
- **Input - context (preview):**
- ```typescript
- {
- query?: string; // User question (Chinese OK). Omit when only filling assistantReply.
- englishQuery?: string; // Agent-translated English code search terms (recommended for CJK)
- topicId?: string; // Click a workbench function node to refine / return to mainline
- sessionId?: string; // Dialogue session name (default "main")
- resumeFromTurnId?: string; // Continue from a clicked dialogue-turn node (legacy, no workbench)
- assistantReply?: string; // Original assistant answer to store on the pending turn/topic
- recordDialogue?: boolean; // false = no workbench/dialogue echo AND no recording (per-call opt-out)
- configPath?: string;
- rootDir?: string;
- }
- ```
-
- **Input - context (expand):**
- ```typescript
- {
- anchorId: string; // Required for expand - anchor id from preview
- configPath?: string;
- rootDir?: string;
- }
- ```
-
- **Output structure (preview):**
- ```typescript
- {
- summary: string[];
- anchors: Array<{ id: string; type: string; layer: "L1" | "L2" | "L3" }>;
- tokenBudget: {
- maxContextTokens: number;
- estimatedRawTokens: number;
- compressedTokens: number;
- estimatedSavingsPercent: number;
- budgetUsedPercent: number;
- };
- unbudgetedTokens: number; // out-of-package payloads also delivered (dialogueHits, workbench/dialogue preview echoes)
- accountedTokens: number; // compressedTokens + unbudgetedTokens = the true delivered total
- agentWorkItems?: Array<{ id: string; kind: string; prompt: string }>; // CJK low-match delegation
- englishQuery?: string;
- }
- ```
-
- **Where these fields live (U2 stable text copy):** the legacy `content[].text` copy of a preview carries only the stable face — `query`, `summary`, `anchors`, the `dialogueThread` echo — in that fixed order, closed by `"volatile-metrics": "see structuredContent"`. The numeric fields above (`tokenBudget`, `unbudgetedTokens`, `accountedTokens`, `contextPressure`) moved out of the text copy into **structuredContent** only: they change every call and one moved byte re-prices the host's whole cached prefix. If your host shows only `content[].text`, read the numbers from structuredContent before reporting savings; `anchors` order inside the package is (layer, id), not relevance rank — the relevance score rides on each anchor.
-
- **Always report to user:** `accountedTokens` (= `compressedTokens` + `unbudgetedTokens`) with the savings %, anchor count, key summary findings. Savings % alone understates the true delivered payload — quote the accounted total.
-
- ### Workflow 1b: Chinese / CJK queries (agent translates → English search)
-
- **Use when:** User asks in Chinese but the codebase uses English symbols
-
- GraphFlow tokenizes CJK and expands workspace path hints. When that is not enough, **YOU must translate** to English code keywords.
-
- **Preferred (proactive):**
- ```
- Step 1: Translate user intent to English file/symbol terms with YOUR model
- Step 2: graphflow_context({ query: "<Chinese>", englishQuery: "PoseDetectionPage avatarMode BattlePage shieldEffect", rootDir })
- Step 3: Use summary + anchors
- ```
-
- Use **exact file/class/component names** (PascalCase stems). Avoid generic words like `exercise` when the user means camera/pose UI — that word often hits data/types layers instead of pages.
-
- For **module families** (Zustand store + `slices/`): put file stems in `englishQuery` (`useGameStore companionSlice dailySlice inventorySlice`), not bare domain words like `monster` (often ranks `data/monsters` over `monsterSlice`).
-
- **Fallback:** If `anchorCount < 3` and `agentWorkItems` includes `query-translate-en`, answer JSON prompt and retry with `englishQuery`.
-
- ---
-
- ### Workflow 2: Plan Before Coding (complex tasks)
-
- **Use when:** Multi-step changes, refactors, features with unclear scope
-
- ```
- Step 1: graphflow_context(query: "<task>")
- Step 2: graphflow_plan(task: "<task description>")
- - Without GraphFlow LLM: returns mode=agent-delegated + agentWorkItems
- (simple-plan-intent, simple-plan-decomposition) and optional suggestedNodes.
- MUST submit/merge via graphflow_insight before treating the DAG as final.
- - The merge response may carry `challenges[]`: pre-execution challenge questions
- grounded in graph facts (external-caller compatibility / deleted symbols /
- requirement links). The agent MUST answer these challenges before executing;
- any step it cannot answer is a plan blind spot — revisit the plan, do not
- execute around it. Missing/empty `challenges` means no graph-grounded risk
- was found (or the gate failed open) — not a green light to skip review.
- - Local suggestedNodes are heuristic hints only.
- - Result includes workbench.topics and workbench.outline (mainline DAG + side branches).
- Step 3: Review workbench.outline (function nodes), not chat turns. Wake later with graphflow workbench tree or graphflow_diagnose (graph.workbenchOutline).
- Step 4: Refine a node: graphflow_context({ query, topicId: "<topic:...>" })
- Step 5: If the conversation drifted, click a 主线 node (same topicId) to restore trunk context
- Step 6: graphflow_index() after major changes
- ```
-
- **Input:**
- ```typescript
- {
- task: string; // Required - task description to plan
- mode?: "simple" | "insight"; // 'simple' (default) for quick planning, 'insight' for Six Hats + 5-Why
- configPath?: string;
- }
- ```
-
- **Output structure:**
- ```typescript
- {
- ideas: string[]; // Brainstorming ideas
- plan: {
- steps: Array<{
- id: string;
- title: string;
- description: string;
- dependsOn: string[];
- estimate: string;
- }>;
- dag: object; // Task dependency graph
- };
- }
- ```
-
- ---
-
- ### Workflow 3: Deep Analysis (complex/ambiguous tasks)
-
- **Use when:** High-stakes changes, root-cause analysis, ambiguous requirements
-
- ```
- Step 1: graphflow_context(query: "<task>")
- Step 2: graphflow_plan(task: "<task description>", mode: "insight")
- Step 3: Review Six Hats analysis and 5-Why chains
- Step 4: Use insights to inform implementation plan
- Step 5: Execute with regular context previews
- ```
-
- ---
-
- ### Workflow 4: Full Task Packaging (bridge mode)
-
- **Use when:** You want a complete execution descriptor with context packaged
-
- ```
- Step 1: graphflow_run(task: "<full task description>")
- Step 2: Receive executionDescriptor with phases + compressed context
- Step 3: Execute the plan (GraphFlow does NOT execute code)
- Step 4: graphflow_report_outcome(episodeId, success, lessons)
- ```
-
- **Input:**
- ```typescript
- {
- task: string; // Required - full task description
- configPath?: string; // Optional - config path
- }
- ```
-
- **Input - report_outcome:**
- ```typescript
- {
- episodeId: string; // Required - from graphflow_run
- success: boolean; // Required - whether task completed
- lessons?: string[]; // Optional - up to 4 lessons learned
- configPath?: string; // Optional - config path
- }
- ```
-
- ---
-
- ### Workflow 5: Graph Maintenance
-
- **Use when:** Graph is stale, or after significant project changes
-
- #### Incremental Index (fast)
- ```
- graphflow_index(rootDir?: string, configPath?: string)
- ```
- - Only indexes new/changed files
- - Safe to call frequently
- - Use after saving multiple files
-
- #### Single File Index (fastest)
- ```
- graphflow_index(filePath: string, configPath?: string)
- ```
- - Index just one file
- - Perfect for onSave hooks
- - Skips unchanged files automatically
-
- #### Full Rebuild (slow but clean)
- ```
- graphflow_index(mode: "full", rootDir?: string, configPath?: string)
- ```
- - Clears ALL cached data
- - Full re-index from scratch
- - Use only when graph is corrupted or very stale
-
- #### Inspect Graph State
- ```
- graphflow_diagnose(nodeLimit?, edgeLimit?, rootDir?)
- ```
- - Check graph size, file count, symbol count
- - Verify indexing worked correctly
- - Sample nodes to verify quality
- - Also shows provider health and token savings
-
- ---
-
- ### Workflow 6: Team Collaboration
-
- **Use when:** Sharing graph state with teammates
-
- #### Export Artifact
- ```
- graphflow_artifact(mode: "export", outputPath?, compression?)
- ```
- - Export graph to portable gzip artifact
- - Share with team to skip full indexing
- - Can be committed to git
-
- #### Import Artifact
- ```
- graphflow_artifact(mode: "import", inputPath?)
- ```
- - Import teammate's graph artifact
- - Skip initial full workspace index
- - Great for onboarding new team members
-
- ---
-
- ### Workflow 7: Advanced Capabilities
-
- #### Skill Insights (learning flywheel)
- ```
- graphflow_skill_insights(limit?, rootDir?)
- ```
- - Returns learned skill patterns from prior runs
- - Can accelerate similar tasks
- - Part of the skill evolution flywheel
-
- #### Token Savings Stats
- ```
- graphflow_diagnose(configPath?, rootDir?)
- ```
- - Check the `stats` field for cumulative token savings across all runs
- - ROI tracking
- - See how much GraphFlow has saved
-
- #### Diagnostics
- ```
- graphflow_diagnose(configPath?)
- ```
- - Check provider health
- - Verify model routing
- - Debug configuration issues
- - Also returns graph stats and token savings
-
- ---
-
- ### Workflow 8: Large-output observations & efficiency mechanisms
-
- Every efficiency mechanism is **ON by default** — the default is the best
- configuration (`efficiencyPolicy` in `graphflow.config.json`; switch any of
- them off from the **GraphFlow: Settings** page or with an explicit `false`).
- Switching one off never gates an explicit call: passing `content`/`handle`,
- `reduce:true`, or reading a returned `executionDescriptor` is explicit intent
- and always works.
-
- #### Observation handles (ObservationPack)
-
- Archive a large tool output or log instead of replaying it in every later request:
-
- ```
- Step 1: graphflow_context({ content: "<full output>", rootDir })
- → { handle: "gfo:…", head, tail, sizeBytes, lines }
- Step 2: Keep the handle + head/tail excerpt in context; drop the full body.
- Step 3: Recall exact bytes when needed:
- graphflow_context({ handle: "gfo:…", page: 0 }) # 200 lines/page
- graphflow_context({ handle: "gfo:…", range: [start, end] }) # inclusive 1-based
- Step 4: Reduce a long diagnostic log to a verified receipt:
- graphflow_context({ handle: "gfo:…", reduce: true, maxReceiptTokens: 400 })
- ```
-
- The receipt's retained lines are each re-read from the archive and checked
- **verbatim**; any mismatch returns a bounded excerpt (`fallback: true`) instead
- of the receipt. `efficiencyPolicy.observations` controls the inline threshold,
- head/tail sizes, TTL, redaction, and whether reduction is local (`fingerprint`)
- or an explicit remote model (`strategy: "llm"` requires `provider` + `model`;
- without them the resolver stays local and a strategy-`llm` reduce fails open).
-
- #### Observed-pressure budget & compaction signal (Online Context Compact)
-
- ```
- graphflow_context({
- query: "<question>",
- contextPressure: { usedTokens: 120000, maxTokens: 200000, remainingTurnsEstimate: 8 }
- })
- ```
-
- Online Context Compact is enabled by default: GraphFlow packs against a
- budget scaled by the observed pressure (`maxContextTokens: "auto"`) and returns a
- `contextPressure` block with `effectiveMaxContextTokens` and, when
- `remainingTurnsEstimate` is supplied, an economic `compaction` recommendation
- (set `efficiencyPolicy.contextPressure.enabled: false` to disable).
- Omit `contextPressure` when unknown — GraphFlow never fabricates it.
-
- #### Fused action steps (Action Fusion)
-
- Action Fusion is enabled by default: `graphflow_run`'s
- `executionDescriptor` carries `steps` (`fused: true`) where an edit and its
- immediately following validation command collapse into one action. Execute the
- edit and its `command` in a single tool call to save one model round trip
- (set `efficiencyPolicy.actionFusion.enabled: false` to disable).
-
- These are the defaults — every mechanism ships ON; override any field in
- `graphflow.config.json` (or toggle per mechanism in **GraphFlow: Settings**):
-
- ```json
- {
- "efficiencyPolicy": {
- "observations": { "enabled": true, "inlineThresholdBytes": 8192 },
- "contextPressure": { "enabled": true, "maxContextTokens": "auto", "cacheWriteReadRatio": 12.5 },
- "actionFusion": { "enabled": true }
- }
- }
- ```
-
- ---
-
- ## Tool Selection Decision Tree
-
- ```
- Start
- │
- ├─ Is this a codebase question/exploration?
- │ └─ YES → graphflow_context ← START HERE
- │ │
- │ └─ Need more detail on specific item?
- │ └─ YES → graphflow_context(anchorId)
- │
- ├─ Is this a multi-step coding task?
- │ ├─ Simple (2-3 files) → context + implement
- │ ├─ Complex → context → graphflow_plan → implement
- │ └─ Ambiguous/high-stakes → context → graphflow_plan(mode="insight") → implement
- │
- ├─ Do you need a complete packaged task?
- │ └─ YES → graphflow_run (bridge mode) → execute → report_outcome
- │
- ├─ Did you just make file changes?
- │ ├─ Single file → graphflow_index(filePath)
- │ └─ Multiple files → graphflow_index (incremental)
- │
- ├─ Is the graph giving bad results?
- │ ├─ First → graphflow_diagnose (check state)
- │ ├─ Then → graphflow_index (try incremental)
- │ └─ Last resort → graphflow_index(mode="full") (full rebuild)
- │
- ├─ Sharing with teammates?
- │ ├─ Export → graphflow_artifact(mode="export")
- │ └─ Import → graphflow_artifact(mode="import")
- │
- ├─ Do you want to leverage prior learning?
- │ └─ YES → graphflow_skill_insights
- │
- ├─ Tracking ROI?
- │ └─ graphflow_diagnose (check stats field)
- │
- └─ Is routing/models misbehaving?
- └─ YES → graphflow_diagnose
- ```
-
- ---
-
- ## Output Interpretation Guide
-
- ### Reading Compressed Context
-
- The `summary` array contains compressed context lines. Each line is one of:
-
- | Prefix | Meaning | Example |
- |--------|---------|---------|
- | `Module:` | Module-level summary | `Module: src/graph/context-slicer` |
- | `File:` | File-level summary | `File: src/graph/context-slicer.ts # exports: buildLayeredContextPackage` |
- | `Symbol:` | Function/class symbol | `Symbol: function buildLayeredContextPackage (exported) @src/graph/context-slicer.ts:42` |
-
- **Priority order:** Symbols (L1) > Files (L1) > Modules (L2) > Overview (L3)
-
- ### Token Budget
-
- Always pay attention to `tokenBudget`:
-
- | Field | Meaning |
- |-------|---------|
- | `maxContextTokens` | The configured budget (default 1500) |
- | `estimatedRawTokens` | What reading all relevant files raw would cost (floored at the actual delivered size — never reported below it) |
- | `compressedTokens` | What GraphFlow's compressed output uses |
- | `estimatedSavingsPercent` | Percentage saved, computed on `accountedTokens` (typically 70-95%) |
- | `budgetUsedPercent` | How much of the budget is used |
- | `unbudgetedTokens` | Out-of-package payloads the response also carries (dialogue recall hits, workbench/dialogue preview echoes) — counted outside `tokenBudget`, never hidden |
- | `accountedTokens` | `compressedTokens` + `unbudgetedTokens`: the true delivered total the savings % is computed on |
- | `contextPressure` | Present only when observed-pressure budgeting is enabled: `effectiveMaxContextTokens` plus an optional `compaction` signal |
-
- **Rule of thumb:** If `budgetUsedPercent < 50%`, you can safely expand more anchors. When reporting savings, quote `accountedTokens` too — savings % alone understates the real payload you received.
-
- ---
-
- ## Best Practices
-
- ### 1. Context First, Always
- - Start EVERY coding task with `graphflow_context`
- - Only read full files when compressed context is insufficient
- - Never grep the whole repo before trying GraphFlow
-
- ### 2. Plan Before Complex Work
- - Use `graphflow_plan` for anything beyond 2-3 files
- - Use `graphflow_plan(mode="insight")` for ambiguous tasks
- - Follow the DAG order (respect dependencies)
- - Use context from GraphFlow at each step
-
- ### 3. Keep Graph Fresh
- - Call `graphflow_index(filePath)` after saving individual files
- - Call `graphflow_index` after significant changes
- - Prefer incremental index over full rebuild
- - Check `graphflow_diagnose` if results seem off
-
- ### 4. Close the Learning Loop
- - After bridge-mode runs, call `graphflow_report_outcome`
- - Include lessons learned to improve future planning
- - This feeds the skill evolution flywheel
-
- ### 5. Report Token Savings (honest accounting)
- - Report `accountedTokens` = `compressedTokens` + `unbudgetedTokens`, together with `estimatedSavingsPercent`
- - Savings % is computed on the accounted total (it includes out-of-package payloads like dialogue hits and preview echoes); quoting only savings % understates the true delivered payload
- - Include raw (`estimatedRawTokens`) vs accounted token counts
-
- ### 6. Bridge Mode Mindset
- - `graphflow_run` returns plans, it doesn't execute them
- - YOU are the execution agent (bridge mode)
- - Use the packaged context to accelerate your work
-
- ---
-
- ## Troubleshooting
-
- ### "0 anchors found" or empty results
- 1. **Chinese/CJK:** translate to English keywords; pass `englishQuery` or answer `agentWorkItems` id `query-translate-en`
- 2. Check if graph exists: `graphflow_diagnose`
- 3. If empty: run `graphflow_index`
- 4. If still empty: verify `rootDir` points to correct project
-
- ### Results seem stale
- 1. Run `graphflow_index` (incremental, fast)
- 2. If still stale: `graphflow_index(mode="full")` (full, slow)
-
- ### Context quality is poor
- 1. Try more specific query terms
- 2. Check if symbols are indexed (diagnose)
- 3. Run `graphflow_index(mode="full")` if the graph may be stale
-
- ### Tool errors / configuration issues
- 1. Run `graphflow_diagnose` to check provider health
- 2. Verify config file exists at specified path
- 3. Check workspace root is correct
-
- ### Want to share graph with teammates
- 1. Export: `graphflow_artifact(mode="export")`
- 2. Send the artifact file
- 3. Teammate imports: `graphflow_artifact(mode="import")`
-
+ name: graphflow
+ description: Token-First Surgical Code Engine (gf_read, gf_edit, gf_exec, gf_macro) across TS/JS, Python, Go, Rust, C/C++, and C#.
---
- ## Quick Reference Cheat Sheet
-
- ```typescript
- // 90% of the time - start here
- await graphflow_context({ query: "what you're looking for" });
-
- // Need more detail on a specific anchor?
- await graphflow_context({ anchorId: "symbol:src/foo.ts:abc123" });
-
- // Before complex tasks
- await graphflow_plan({ task: "describe the task" });
-
- // Deep analysis with Six Thinking Hats + 5-Why
- await graphflow_plan({ task: "complex ambiguous task", mode: "insight" });
-
- // Full packaged task (bridge mode)
- const result = await graphflow_run({ task: "full task description" });
- // ... execute the task ...
- await graphflow_report_outcome({
- episodeId: result.episodeId,
- success: true,
- lessons: ["lesson 1", "lesson 2"]
- });
-
- // After making changes - single file
- await graphflow_index({ filePath: "src/foo.ts" });
-
- // After making changes - workspace
- await graphflow_index({ rootDir: "/path/to/project" });
-
- // Check graph health + stats + savings
- await graphflow_diagnose({ nodeLimit: 20 });
-
- // When graph is broken
- await graphflow_index({ mode: "full", rootDir: "/path/to/project" });
-
- // Team collaboration
- await graphflow_artifact({ mode: "export", outputPath: "graph-artifact.gz" });
- await graphflow_artifact({ mode: "import", inputPath: "graph-artifact.gz" });
+ # GraphFlow 3.1 — Token-First Surgical Engine
- // Leverage prior learning
- await graphflow_skill_insights({ limit: 5 });
+ Always prefer the 4 surgical `gf_*` MCP tools over raw full-file reads or verbose test runs:
- // Diagnose issues
- await graphflow_diagnose();
- ```
+ 1. **`gf_read`** (`targets`, `q`, `skeleton`, `dedup`):
+ - Read exact symbols (`"src/file.ts#symbol"`) with automatic **Cross-File Type Closure** and 3-line **`[Blast Radius]`** caller micro-snippets.
+ - Fold large files into AST skeletons (`"src/file.ts"`, `skeleton: true`) cutting token cost by 93%.
+ - Pass `dedup: true` in long sessions to skip re-reading unchanged files (SHA-256 cache).
+ 2. **`gf_edit`** (`file`, `symbol`, `newCode`, `edits`, `renameTo`):
+ - Edit symbols or line ranges in-place, apply multi-file atomic batch `edits` bottom-up with zero line drift, or run zero-LLM cross-repo symbol rename (`renameTo`).
+ - Enforces instant AST syntax rollback, caller-arity checks, and struct/interface field deletion guards.
+ 3. **`gf_exec`** (`cmd`, `changedFiles`, `handle`, `run`):
+ - Run `cmd: "affected-tests"` (2-hop reverse import router) or any command with output dehydration (passing runs = 1-line `PASS` receipt; failures inline exact 5-line source context; 3 consecutive failures trigger the loop circuit breaker).
+ 4. **`gf_macro`** (`action: "list" | "run" | "save" | "mine" | "mine-git"`):
+ - Mine git history co-change coupling (`action: "mine-git"`) or run auto-compiled `.graphflow/macros/*.mjs` scripts and isomorphic codemods with zero LLM turns.