@vpxa/aikit 0.1.86 → 0.1.88
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.
- package/package.json +1 -1
- package/packages/cli/dist/index.js +2 -2
- package/packages/cli/dist/{init-CuRXmyD9.js → init-DyXyx-U6.js} +1 -1
- package/packages/cli/dist/{templates-ArdAVWoY.js → templates-C-qED27u.js} +2 -85
- package/packages/cli/dist/{user-C2c_eBDB.js → user-BCQCn7Be.js} +1 -1
- package/packages/server/dist/curated-manager-CXSPygmJ.js +7 -0
- package/packages/server/dist/index.d.ts +45 -0
- package/packages/server/dist/index.js +1 -1
- package/packages/server/dist/{server-DG5jasWR.js → server-CXsoHmuu.js} +145 -140
- package/packages/tools/dist/index.d.ts +133 -6
- package/packages/tools/dist/index.js +69 -68
- package/scaffold/dist/definitions/agents.mjs +37 -1
- package/scaffold/dist/definitions/bodies.mjs +37 -4
- package/scaffold/dist/definitions/protocols.mjs +0 -56
- package/scaffold/dist/definitions/skills.mjs +328 -1
- package/packages/server/dist/curated-manager-DX-_oJg0.js +0 -5
- package/scaffold/claude-code/commands/aikit-ask.md +0 -12
- package/scaffold/claude-code/commands/aikit-debug.md +0 -14
- package/scaffold/claude-code/commands/aikit-design.md +0 -14
- package/scaffold/claude-code/commands/aikit-flow-add.md +0 -83
- package/scaffold/claude-code/commands/aikit-flow-create.md +0 -79
- package/scaffold/claude-code/commands/aikit-flow-manage.md +0 -23
- package/scaffold/claude-code/commands/aikit-implement.md +0 -16
- package/scaffold/claude-code/commands/aikit-plan.md +0 -14
- package/scaffold/claude-code/commands/aikit-review.md +0 -23
|
@@ -1704,7 +1704,334 @@ Notes:
|
|
|
1704
1704
|
- Scripts auto-detect ADR directory and filename strategy.
|
|
1705
1705
|
- Use \`--dir\` and \`--strategy\` to override.
|
|
1706
1706
|
- Use \`--json\` to emit machine-readable output.
|
|
1707
|
-
`}],aikit:[{file:`SKILL.md`,content:'---\nname: aikit\ndescription: "Use the @vpxa/aikit AI Kit MCP server for codebase search, analysis, and persistent memory. Load this skill when using aikit_search, aikit_remember, aikit_analyze_*, or any aikit_* tool. Covers all 82 MCP tools: search (hybrid/semantic/keyword), code analysis (structure, dependencies, symbols, patterns, entry points, diagrams, blast radius), knowledge graph (auto-populated module/symbol/import graph with traversal), context management (worksets, stash, checkpoints, restore, lanes), code manipulation (rename, codemod, eval), knowledge management (remember/read/update/forget), web access (fetch, search, http), FORGE protocol (ground, classify, evidence map, stratum cards, digest), brainstorming (interactive ideation sessions), presentation (rich dashboards via present tool), onboarding (full codebase analysis in one call), and developer utilities (regex, encode, measure, changelog, schema-validate, snippet, env, time)."\nmetadata:\n category: cross-cutting\n domain: general\n applicability: always\n inputs: [codebase]\n outputs: [search-results, analysis, knowledge]\n relatedSkills: [present]\n---\n\n# @vpxa/aikit — AI Kit\n\nLocal-first AI developer toolkit — 82 MCP tools for search, analysis, context compression, FORGE quality gates, knowledge management, code manipulation, execution, web access, brainstorming, presentation, and developer utilities.\n\n## When to Use\n\n- You need long-term memory across coding sessions\n- You want to search a codebase semantically (by meaning, not just keywords)\n- You need to compress large contexts to focus on what matters\n- You want structured output from build tools (tsc, vitest, biome, git)\n- You need to plan which files to read for a task\n- You want to safely explore refactors in isolated lanes\n- You need to rename symbols, apply codemods, or run code transformations\n- You want to fetch and read web pages or search the web\n- You need to make HTTP requests, test APIs, or debug endpoints\n- You want to test regex patterns, encode/decode data, or validate JSON schemas\n- You need code complexity metrics or a git changelog\n- You want to save and reuse code snippets across sessions\n\n## Skills Reference\n\n| Context | Skill | Load when |\n|---------|-------|----------|\n| Repository access recovery | `repo-access` | When encountering git auth failures, accessing private/enterprise repos, or when `web_fetch`/`http` returns auth errors on repository URLs. |\n\n## Architecture\n\n10-package monorepo published as a single npm package:\n\n```\ncore → store → embeddings → chunker → indexer → analyzers → tools → server → cli → tui\n```\n\n- **MCP server**: 82 tools + 2 resources (via `@modelcontextprotocol/sdk`)\n- **CLI**: 45 commands (thin dispatcher + 10 command groups)\n- **Search**: Hybrid vector + keyword + RRF fusion\n- **Embeddings**: ONNX local (mxbai-embed-large-v1, 1024 dimensions)\n- **Vector store**: LanceDB (embedded, zero infrastructure)\n- **Chunking**: Tree-sitter AST (TS/JS/Python/Go/Rust/Java) + regex fallback\n- **TUI**: Ink/React dashboard for human monitoring (search, status, curated, activity log)\n\n## Session Protocol (MANDATORY)\n\n### Start (do ALL)\n```\nflow_status({}) # Check/resume active flow FIRST\n# If flow active → flow_read_instruction({ step }) → follow step instructions\nstatus({}) # Check AI Kit health + onboard state\n# If onboard not run → onboard({ path: "." }) # First-time codebase analysis\nflow_list({}) # See available flows\n# Select flow based on task → flow_start({ flow: "<name>", topic: "<task>" }) # Start — creates .flows/{topic}/\nlist() # See stored knowledge\nsearch({ query: "SESSION CHECKPOINT", origin: "curated" }) # Resume prior work\n```\n\n### During Session\n```\nsearch → scope_map → symbol → trace (orient)\ncheck → test_run (validate changes)\nremember (capture insights)\n```\n\n### End of Session\n```\nsession_digest({ persist: true }) # Auto-capture session activity\nremember({ title: "Session checkpoint: <topic>", content: "<what was done, decisions made, next steps>", category: "conventions" })\n```\n\n## Tool Catalog (82 tools)\n\n### Search & Discovery (8)\n| Tool | CLI | Purpose |\n|------|-----|---------|\n| `search` | `aikit search` | Hybrid/semantic/keyword search with `search_mode` param |\n| `find` | `aikit find` | Federated search: vector + FTS + glob + regex in one call. Use `mode: \'examples\'` to find usage examples. |\n| `symbol` | `aikit symbol` | Resolve symbol definition, imports, and references |\n| `lookup` | `aikit lookup` | Full-file retrieval by path or record ID |\n| `scope_map` | `aikit scope-map` | Task-scoped reading plan with token estimates |\n| `trace` | `aikit trace` | Forward/backward flow tracing through call chains |\n| `dead_symbols` | `aikit dead-symbols` | Find exported symbols never imported — separates source (actionable) from docs (informational). Accepts `path` to scope the search. |\n| `file_summary` | `aikit summarize` | Structural overview of a file (exports, imports, functions) |\n\n### Code Analysis (7)\n| Tool | CLI | Purpose |\n|------|-----|---------|\n| `analyze_structure` | `aikit analyze structure` | Project structure overview |\n| `analyze_dependencies` | `aikit analyze deps` | Dependency graph with confidence |\n| `analyze_symbols` | `aikit analyze symbols` | Symbol extraction and cross-references |\n| `analyze_patterns` | `aikit analyze patterns` | Design pattern detection |\n| `analyze_entry_points` | `aikit analyze entry-points` | Find entry points: handlers, CDK constructs, test suites, package exports (walks workspace packages) |\n| `analyze_diagram` | `aikit analyze diagram` | Generate Mermaid diagrams |\n| `blast_radius` | `aikit analyze blast-radius` | Change impact analysis |\n\n### Context Management (6)\n| Tool | CLI | Purpose |\n|------|-----|---------|\n| `compact` | `aikit compact` | Compress text to relevant sections using embeddings (no LLM). Accepts `path` for server-side file read. |\n| `workset` | `aikit workset` | Named file set management (save/load/add/remove) |\n| `stash` | `aikit stash` | Named key-value store for session data |\n| `checkpoint` | `aikit checkpoint` | Save/restore session checkpoints |\n| `restore` | `aikit restore` | Restore a previously saved checkpoint |\n| `parse_output` | `aikit parse-output` | Parse tsc/vitest/biome/git output → structured JSON |\n\n### Code Manipulation (4)\n| Tool | CLI | Purpose |\n|------|-----|---------|\n| `rename` | `aikit rename` | Smart whole-word symbol rename across files (dry-run supported) |\n| `codemod` | `aikit codemod` | Regex-based code transformations with rules (dry-run supported) |\n| `diff_parse` | `aikit diff` | Parse unified diff → structured changes |\n| `data_transform` | `aikit transform` | JQ-like JSON transformations |\n\n### Execution & Validation (5)\n| Tool | CLI | Purpose |\n|------|-----|---------|\n| `eval` | `aikit eval` | Sandboxed JavaScript/TypeScript execution |\n| `check` | `aikit check` | Incremental typecheck + lint. `detail` param: efficient (default, minimal), normal (parsed errors), full (includes raw) |\n| `test_run` | `aikit test` | Run tests with structured pass/fail results |\n| `batch` | `aikit batch` | Execute multiple operations in parallel |\n| `audit` | `aikit audit` | Unified project audit: structure, deps, patterns, health, dead symbols, check, entry points → synthesized report with score and recommendations. 6 round-trips → 1. |\n\n### Knowledge Management (6)\n| Tool | CLI | Purpose |\n|------|-----|---------|\n| `remember` | `aikit remember` | Store a curated knowledge entry |\n| `update` | `aikit update` | Update an existing entry |\n| `forget` | `aikit forget` | Delete an entry (requires reason) |\n| `read` | `aikit read` | Read a curated entry by path |\n| `list` | `aikit list` | List curated entries |\n| `produce_knowledge` | — | Auto-generate knowledge from analysis |\n\n### Auto-Knowledge (automatic background extraction)\n\nAuto-knowledge runs automatically in the background after every tool completion. It extracts useful facts from tool outputs and stores them in curated memory — no manual action required.\n\n**What gets captured:**\n\n| Extractor | Triggers on | What it stores |\n|-----------|-------------|----------------|\n| Test results | `check`, `test_run` | Framework detection (vitest/jest/mocha), test file naming patterns |\n| Environment | `env`, `config`, `status` | Node.js version, OS, workspace path, store backend, embedding model |\n| Research | `web_search`, `web_fetch`, `search` | Web research findings, fetched page summaries |\n| Conventions | `check`, `analyze_patterns`, `analyze_structure`, `onboard` | Linter/formatter, TypeScript strict mode, package manager, monorepo detection |\n| Build commands | `check`, `test_run` | Verified check results, test summaries, test runner commands |\n| Codebase insights | `analyze_*`, `scope_map`, `blast_radius`, `onboard` | Structure analysis, dependency info, entry points, impact analysis |\n| Tool failures | All tools (global) | Classified actionable errors (filters out transient network/ENOENT errors) |\n\n**Quality controls:**\n- **Quality gate**: Facts scored 0-1; only facts >= 0.3 are stored\n- **Dedup**: Checks existing curated titles + in-memory hash dedup\n- **TTL**: Transient facts (errors, blast radius, search context) automatically expire after 1-2 hours\n- **Session limit**: Maximum 50 auto-knowledge facts per session\n\n**Searching auto-knowledge:**\nAuto-knowledge facts are stored as regular curated entries. Search them with:\n```\nsearch({ query: "error patterns", origin: "curated" })\nsearch({ query: "conventions", origin: "curated" })\nlist({ category: "conventions" })\nlist({ tags: ["errors"] })\n```\n\n### Verified Lanes (1 tool, 6 actions)\n| Tool | CLI | Purpose |\n|------|-----|---------|\n| `lane` | `aikit lane` | Manage isolated file copies for parallel exploration |\n\nLane actions: `create` (copy files to lane), `list`, `status` (modified/added/deleted), `diff` (line-level diff), `merge` (apply back to originals), `discard`.\n\n### Git & Environment (4)\n| Tool | CLI | Purpose |\n|------|-----|---------|\n| `git_context` | `aikit git` | Branch, status, recent commits |\n| `process` | `aikit proc` | Process supervisor (start/stop/logs) |\n| `watch` | `aikit watch` | Filesystem watcher |\n| `delegate` | `aikit delegate` | Delegate subtask to local Ollama model |\n\n### Web & Network (3)\n| Tool | CLI | Purpose |\n|------|-----|---------|\n| `web_fetch` | — | Fetch web page → markdown/raw/links/outline for LLM consumption |\n| `web_search` | — | Search the web via DuckDuckGo (no API key needed) |\n| `http` | — | Make HTTP requests for API testing/debugging |\n\n### Developer Utilities (8)\n| Tool | CLI | Purpose |\n|------|-----|---------|\n| `regex_test` | — | Test regex patterns with match/replace/split modes |\n| `encode` | — | Base64, URL, SHA-256, MD5, hex encode/decode, JWT decode |\n| `measure` | — | Code complexity metrics (cyclomatic, cognitive complexity, lines, functions) |\n| `changelog` | — | Generate changelog from git history (conventional commits) |\n| `schema_validate` | — | Validate JSON data against JSON Schema |\n| `snippet` | — | Save/get/search/delete persistent code snippets |\n| `env` | — | System and runtime environment info (sensitive values redacted) |\n| `time` | — | Date parsing, timezone conversion, duration math |\n\n### FORGE Quality Gates (5)\n| Tool | CLI | Purpose |\n|------|-----|---------|\n| `forge_ground` | — | Full Ground phase: classify tier, scope map, unknowns, constraints |\n| `forge_classify` | — | Quick tier classification (Floor/Standard/Critical) |\n| `evidence_map` | — | CRUD + Gate evaluation for verified/assumed/unknown claims. Safety gate tags (`provenance`/`commitment`/`coverage`) enable mandatory pre-YIELD checks |\n| `stratum_card` | — | Generate T1/T2 compressed context cards from files (10-100x token reduction) |\n| `digest` | — | Compress N text sources into token-budgeted summary |\n\n### System (9)\n| Tool | CLI | Purpose |\n|------|-----|---------|\n| `config` | `aikit config` | View or update project configuration (kb.config.json) |\n| `status` | `aikit status` | Index statistics |\n| `reindex` | `aikit reindex` | Rebuild index |\n| `health` | `aikit health` | Project health checks (package.json, tsconfig, lockfile, circular deps) |\n| `guide` | `aikit guide` | Tool discovery — given a goal, recommends tools and workflow order |\n| `onboard` | `aikit onboard` | Full codebase onboarding in one call (structure + deps + patterns + knowledge) |\n| `graph` | `aikit graph` | Query the auto-populated knowledge graph (modules, symbols, imports) |\n| `queue` | `aikit queue` | Task queue for sequential agent operations (create/push/next/done/fail) |\n| `replay` | `aikit replay` | View or clear the audit trail of tool invocations (action: list/clear) |\n\n### Flows (11)\n| Tool | CLI | Purpose |\n|------|-----|---------|\n| `flow_list` | `aikit flow list` | List available flows and active run |\n| `flow_info` | `aikit flow info` | Get flow details including steps and skill paths |\n| `flow_start` | `aikit flow start` | Start a flow with topic — creates `.flows/{topic-slug}/` run directory |\n| `flow_step` | `aikit flow step` | Advance, skip, or redo the current step |\n| `flow_status` | `aikit flow status` | Check active run including slug, runDir, artifactsPath |\n| `flow_read_instruction` | `aikit flow read-instruction` | Read instruction with `{{artifacts_path}}` and `{{run_dir}}` resolved |\n| `flow_reset` | `aikit flow reset` | Abandon the active flow (preserves run directory) |\n| `flow_runs` | `aikit flow runs` | List all flow runs (current and past) |\n| `flow_add` | `aikit flow add` | Add a custom flow from a directory |\n| `flow_update` | `aikit flow update` | Update an existing custom flow |\n| `flow_remove` | `aikit flow remove` | Remove a custom flow |\n\n### Presentation (1)\n| Tool | CLI | Purpose |\n|------|-----|---------|\n| `present` | — | Rich dashboards, charts, tables, timelines. Use `format: "browser"` then `openBrowserPage` to display. **In CLI mode (no VS Code chat), always use `format: "browser"`** — `html` UIResource is invisible in terminal. |\n\n### Brainstorming (1)\n| Tool | CLI | Purpose |\n|------|-----|---------|\n| `brainstorm` | — | Interactive brainstorming and ideation sessions with structured output |\n\n### Meta-Tools — Tool Discovery (3)\n| Tool | CLI | Purpose |\n|------|-----|---------|\n| `list_tools` | — | List all active AI Kit tools with names, titles, and categories. Accepts optional `category` filter. Use for initial tool discovery. |\n| `describe_tool` | — | Get detailed metadata for a specific tool (title, categories, annotations). Use after `list_tools` to understand a tool before calling it. |\n| `search_tools` | — | Search active tools by keyword across names, titles, and categories. Use when you know what you need but not the tool name. |\n\n### Session Management (1)\n| Tool | CLI | Purpose |\n|------|-----|---------|\n| `session_digest` | — | Generate a compressed digest of session activity (replay log, stash, checkpoints). Options: `scope` (tools/stash/all), `since`, `last`, `focus`, `mode` (deterministic/sampling), `tokenBudget`, `persist`. Use at session end for handoff or mid-session to review what happened. |\n\n## Flow System\n\nFlows are multi-step guided workflows that structure complex tasks. Each step has a skill file with detailed instructions, required artifacts, and agent assignments.\n\n### Built-in Flows\n\n| Flow | Steps | Use When |\n|------|-------|----------|\n| `aikit:basic` | assess → implement → verify | Bug fixes, config changes, small features |\n| `aikit:advanced` | spec → plan → task → execute → verify | New modules, cross-service changes, architectural work |\n\n### Flow Lifecycle\n\n```text\nflow_list() # See available flows\nflow_info({ flow: "aikit:basic" }) # View steps, skills, agents\nflow_start({ flow: "aikit:basic", topic: "Fix login bug" }) # Start — creates .flows/fix-login-bug/\nflow_read_instruction() # Read current step\'s instructions ({{artifacts_path}} resolved)\n# ... do the work described in the instruction ...\nflow_step({ action: "next" }) # Advance to next step\nflow_step({ action: "skip" }) # Skip current step\nflow_step({ action: "redo" }) # Redo current step\nflow_status() # Check progress (includes slug, runDir, artifactsPath, phase, isEpilogue)\nflow_reset() # Abandon active flow\nflow_runs() # List all runs (current + past)\n# Epilogue steps (mandatory, injected after every flow):\n# After last flow step → _docs-sync epilogue runs automatically\n# flow_status() shows phase: \'after\', isEpilogue: true during epilogue\n```\n\nCustom flow lifecycle management:\n\n```text\nflow_add({ source: ".github/flows/my-flow" })\nflow_update({ name: "my-flow" })\nflow_remove({ name: "my-flow" })\n```\n\n### Creating Custom Flows\n\n1. Create a directory under `.github/flows/<flow-name>/`\n2. Add `manifest.yaml`:\n\n```yaml\nname: my-flow\nversion: "1.0.0"\ndescription: "My custom flow"\nartifacts_dir: .spec\nsteps:\n - id: design\n name: Design\n instruction: steps/design/README.md\n description: "Create the design document"\n produces: [design.md]\n requires: []\n agents: [Planner]\n - id: implement\n name: Implement\n instruction: steps/implement/README.md\n description: "Implement the design"\n produces: [code]\n requires: [design]\n agents: [Implementer]\nagents:\n - agents/planner.agent.md\ninstall: []\n```\n\n3. Add skill files under `.github/flows/<flow-name>/skills/<step-id>/SKILL.md`\n4. The flow appears in `flow_list()` automatically\n\n### How Flows Are Delivered\n\n- **Built-in flows** ship with the AI Kit MCP server in `scaffold/flows/`\n- `aikit init` copies them to `.github/flows/` in your workspace\n- At runtime, flow tools resolve paths to `.github/flows/` (workspace-local copies)\n- Custom flows placed in `.github/flows/` are discovered alongside built-in ones\n\n### Agent-Flow Integration\n\n- All code agents have a "Flows" section instructing them to check `flow_status()` first\n- If a flow is active, the agent follows the current step\'s instruction via `flow_read_instruction()`\n- After completing a step\'s work, advance with `flow_step({ action: "next" })`\n- The **Orchestrator** selects and starts flows; other agents follow them\n- The **Orchestrator** specifies `aikit` skill loading — all agents should load `aikit` skill to access flow tools\n\n## CRITICAL: Use AI Kit Tools Instead of Native IDE Tools\n\nAI Kit tools provide **10x richer output** than native IDE tools — with AST-analyzed call graphs, scope context, import classification, and cognitive complexity. **You MUST use AI Kit tools instead of native read/search tools.**\n\n### ⛔ PROHIBITED: Native File Reading\n\n**`read_file` / `read_file_raw` MUST NOT be used to understand code.** They waste tokens and miss structural information.\n\nThe **ONLY** acceptable use of `read_file`: getting exact lines immediately before an edit (to verify the `old_str` for replacement). Even then, use `file_summary` first to identify which lines to read.\n\n### Tool Replacement Table\n\n| ❌ NEVER do this | ✅ Use AI Kit Tool | Why |\n|---|---|---|\n| `read_file` (full file) | `file_summary` | Exports, imports, call edges — **10x fewer tokens** |\n| `read_file` (specific section) | `compact({ path, query })` | Server-side read + extract — **5-20x reduction** |\n| `grep_search` / `textSearch` | `search` | Semantic + keyword hybrid across all indexed content |\n| `grep_search` for a symbol | `symbol` | Definition + references **with scope context** |\n| Multiple `read_file` calls | `digest` | Compresses multiple sources into token-budgeted summary |\n| `listDirectory` + `read_file` | `scope_map` | Identifies relevant files for a task automatically |\n| Manual code tracing | `trace` | AST call-graph traversal with scope context |\n| Line counting / `wc` | `measure` | Lines, complexity, **cognitive complexity**, functions |\n| Grep for unused exports | `dead_symbols` | AST-powered export detection with regex fallback |\n| Repeated file reads | `stratum_card` | Reusable compressed context — **10-100x reduction** |\n| `fetch_webpage` | `web_fetch` | Readability extract + token budget — richer output |\n| Web research / browsing | `web_search` | Structured web results without browser — **unique to KB** |\n\n### Decision Tree — How to Read Code\n\n```\nNeed to understand a file?\n├─ Just structure? → file_summary (exports, imports, call edges — ~50 tokens)\n├─ Specific section? → compact({ path, query }) — 5-20x reduction\n├─ Multiple files? → digest (multi-source compression — token-budgeted)\n├─ Repeated reference? → stratum_card (T1/T2 card — 10-100x reduction)\n├─ Need exact lines to EDIT? → read_file (the ONLY acceptable use)\n└─ "I want to read the whole file" → ⛔ STOP. Use file_summary or compact instead.\n```\n\n### Decision Tree — Need Structural Relationships?\n\nWhen vector search and file reads don\'t answer the question (e.g. "who imports this?",\n"what does this depend on?", "how are these files connected?"), use `graph`:\n\n```\nNeed to understand relationships between code?\n├─ Who imports / calls this? → graph({action:\'find_nodes\', name_pattern}) → graph({action:\'neighbors\', node_id, direction:\'incoming\'})\n├─ What does this depend on? → graph({action:\'neighbors\', node_id, direction:\'outgoing\'})\n├─ Full context for a symbol? → graph({action:\'symbol360\', name})\n├─ Related files within N hops? → graph({action:\'traverse\', node_id, max_depth:2})\n├─ Layer/module isolation check? → graph({action:\'depth_traverse\', node_id, max_depth:3})\n└─ Graph size/health? → graph({action:\'stats\'})\n```\n\n**Use this BEFORE** reaching for `analyze_dependencies` (slower, less precise) or manually\ntracing via `symbol` + `trace` chains. The graph is auto-populated during indexing.\n\n### What AI Kit Tools Return (AST-Enhanced)\n\nThese tools use Tree-sitter WASM to analyze source code at the AST level, providing structured data that raw file reads cannot:\n\n| Tool | Rich Output |\n|------|-------------|\n| `file_summary` | Imports classified as **external vs internal** (`isExternal` flag). **Call edges** between functions (e.g., `handleRequest() → validateInput() @ line 42`). `exported` flag on interfaces and types. Import count breakdown. |\n| `symbol` | References include **scope** — which function/class/method contains each usage (e.g., `referenced in processOrder() at auth-service.ts:55`). |\n| `trace` | **Call-graph edges** discovered via AST syntax tree, not text matching. Supports forward (who does X call?) and backward (who calls X?) tracing. Scope context on each node. |\n| `measure` | **Cognitive complexity** — weights nesting depth (nested `if` inside `for` inside `try` scores higher). More useful than cyclomatic complexity for understanding code difficulty. |\n| `dead_symbols` | **AST export enumeration** — catches `export default`, barrel re-exports (`export { x } from`), `export =`, and `export type`. Regex fallback for non-AST-supported languages. |\n\n### Example: `file_summary` Output\n\n```\nsrc/auth-service.ts\nLanguage: typescript | Lines: 180 | Estimated tokens: ~1400\n\nImports (6): 3 external, 3 internal\n - import { hash } from \'bcrypt\' [external]\n - import { UserRepo } from \'./user-repo\' [internal]\n\nFunctions (4):\n - authenticate @ line 22 [exported]\n - validateToken @ line 55 [exported]\n - hashPassword @ line 90\n - generateJwt @ line 110\n\nCall edges (12 intra-file):\n - authenticate() → hashPassword() @ line 35\n - authenticate() → generateJwt() @ line 42\n - validateToken() → UserRepo.findById() @ line 68\n\nInterfaces (2):\n - AuthResult @ line 8 [exported]\n - TokenPayload @ line 14\n```\n\nCompare: `read_file` would cost ~1400 tokens for raw text. `file_summary` gives structured data in ~120 tokens — **12x reduction** with richer information.\n\n## Token Efficiency\n\n`config.tokenBudget` controls output verbosity globally:\n\n| Level | Output | Compression | Context Strategy |\n|-------|--------|-------------|------------------|\n| `efficient` (default) | Minimal output, score + top issues only | threshold 2000, budget 1000 | `stratum_card(T1)` |\n| `normal` | Standard output with parsed errors/pattern names | threshold 4000, budget 2000 | `compact()` |\n| `full` | Maximum detail with raw output/full tables | No compression | `digest()` |\n\nSet via: `config({ action: \'update\', updates: { tokenBudget: \'normal\' } })`\n\nTools with `detail` param inherit from `config.tokenBudget` when not explicitly set.\nCompression middleware applies to ALL tool responses automatically.\n\n## Search Strategy\n\n1. **Start broad**: `search({ query: "topic", search_mode: "hybrid" })`\n2. **Narrow**: Add `content_type`, `origin`, or `category` filters\n3. **Exact match**: Use `search_mode: "keyword"` for identifiers\n4. **Federated**: Use `find` to combine vector + glob + regex\n\n## Workflow Chains\n\n### Codebase Onboarding\n```\nanalyze_structure({ path: "src/" })\n→ analyze_dependencies({ path: "src/" })\n→ analyze_entry_points({ path: "src/" })\n→ produce_knowledge({ path: "src/" })\n→ remember({ title: "Codebase onboarding complete", ... })\n```\n\n### Planning a Task\n```\nscope_map({ task: "implement user auth" })\n→ compact({ path: "src/auth.ts", query: "auth flow" })\n→ workset({ action: "save", name: "auth-task", files: [...] })\n```\n\n### Bug Investigation\n```\nparse_output({ output: <error> }) → symbol({ name: "failingFn" })\n→ trace({ symbol: "failingFn", direction: "backward" })\n→ blast_radius({ changed_files: ["suspect.ts"] })\n→ eval({ code: "hypothesis test" }) → check({ files: ["suspect.ts"] })\n```\n\n### Safe Refactor with Lanes\n```\nscope_map({ task: "rename UserService" })\n→ lane({ action: "create", name: "refactor", files: [...] })\n→ [make changes in lane files]\n→ lane({ action: "diff", name: "refactor" })\n→ check({}) → test_run({})\n→ lane({ action: "merge", name: "refactor" })\n```\n\n### Lane — isolated read-only exploration\n\n`lane({ action:\'create\', name })` creates an isolated copy of the workspace. Use to try approach A vs B WITHOUT touching canonical source. Other actions: `list`, `diff`, `delete`. Compare with `lane({ action:\'diff\', names:[\'a\',\'b\'] })`. Do NOT use `lane` for actual refactors — use `checkpoint` instead (`checkpoint` = reversible on canonical source; `lane` = isolated copies for comparison).\n\n### After Making Changes\n```\nblast_radius({ changed_files: ["src/auth.ts"] })\n→ check({}) → test_run({ grep: "auth" })\n→ reindex()\n→ remember({ title: "Implemented auth", content: "..." })\n```\n\n### Pre-Commit Validation\n```\ngit_context({ diff: true })\n→ diff_parse({ diff: <staged diff> })\n→ blast_radius({ changed_files: [...] })\n→ check({}) → test_run({})\n```\n\n---\n\n## Persistent Memory (Long-Term Knowledge)\n\nAI Kit provides cross-session persistent memory via a curated knowledge store. Use it to remember decisions, patterns, conventions, and context that should survive beyond the current conversation.\n\n### Writing to Memory\n\n| Tool | Purpose | Example |\n|------|---------|---------|\n| `remember` | Store a new knowledge entry | `remember({ title: "Auth uses JWT RS256", content: "All API auth uses RS256 JWT tokens issued by /auth/token. Refresh via httpOnly cookie.", category: "decisions" })` |\n| `update` | Modify an existing entry | `update({ id: "<entry-id>", content: "Updated: now also supports Ed25519" })` |\n| `produce_knowledge` | Auto-generate analysis entries from code | `produce_knowledge({ path: "src/" })` |\n\n**Categories** — use these to organize entries:\n- `conventions` — coding standards, naming rules, file organization\n- `decisions` — architecture decisions, technology choices, trade-offs made\n- `patterns` — recurring code patterns, design patterns in use\n- `context` — project context, domain knowledge, business rules\n- `session` — session checkpoints for resuming work\n\n### Reading from Memory\n\n| Tool | Purpose | Example |\n|------|---------|---------|\n| `list` | Browse all stored entries | `list()` or `list({ category: "decisions" })` |\n| `read` | Read a specific entry by ID | `read({ id: "<entry-id>" })` |\n| `search` | Find entries by content/query | `search({ query: "authentication", origin: "curated" })` |\n| `forget` | Remove an outdated entry | `forget({ id: "<entry-id>" })` |\n\n### When to Remember\n\n| Situation | What to store | Category |\n|-----------|--------------|----------|\n| Architecture decision made | Decision + rationale + alternatives considered | `decisions` |\n| Pattern discovered in codebase | Pattern description + example locations | `patterns` |\n| Convention established | Rule + enforcement approach | `conventions` |\n| Session ending | Checkpoint: what was done, what\'s next, blockers | `session` |\n| Bug root cause found | Root cause + fix approach + prevention strategy | `context` |\n| External API behavior learned | Behavior quirks, rate limits, gotchas | `context` |\n\n### Session Checkpoint Pattern\n\nAt the END of every meaningful work session:\n```\nremember({\n title: "Session checkpoint: <topic>",\n content: "## Done\\n- <completed items>\\n\\n## Decisions\\n- <key decisions made>\\n\\n## Next\\n- <pending work>\\n\\n## Blockers\\n- <issues encountered>",\n category: "session"\n})\n```\n\nAt the START of the next session:\n```\nsearch({ query: "SESSION CHECKPOINT", origin: "curated" }) # Find last checkpoint\nlist({ category: "session" }) # Browse all checkpoints\n```\n\n### Memory Best Practices\n\n1. **Remember decisions, not code** — store *why*, not *what*. Code changes; rationale persists.\n2. **Search before remembering** — avoid duplicates: `search({ query: "..." })` first.\n3. **Use categories** — structured categories enable filtered `list()` queries.\n4. **Checkpoint regularly** — don\'t wait for session end. Checkpoint at milestones.\n5. **Clean up** — `forget()` outdated entries. Memory is only valuable when accurate.\n6. **Cross-reference** — mention related entry titles in content for discoverability.\n\n## CLI Quick Reference\n\n```bash\naikit init # Scaffold AI Kit in current directory\naikit init --force # Overwrite all scaffold/skill files\naikit init --guide # JSON report of stale files for LLM-driven updates\naikit serve # Start MCP server (stdio or HTTP)\naikit search <q> # Hybrid search\naikit find <q> # Federated search\naikit symbol <name> # Resolve symbol\naikit scope-map <t> # Task reading plan\naikit compact <q> # Context compression (--path file or stdin)\naikit check # Typecheck + lint (--detail efficient|normal|full)\naikit test # Run tests\naikit rename <old> <new> <path> # Rename symbol\naikit lane create <name> --files f1,f2 # Create lane\naikit lane diff <name> # View lane changes\naikit lane merge <name> # Merge lane back\naikit status # Index stats\naikit reindex # Rebuild index\n```\n\n## Configuration\n\n`kb.config.json` in project root:\n```json\n{\n "sources": [{ "path": ".", "excludePatterns": ["node_modules/**", "**/node_modules/**", "dist/**", "coverage/**", ".aikit-data/**"] }],\n "indexing": { "chunkSize": 1500, "chunkOverlap": 200, "minChunkSize": 100, "concurrency": 5 },\n "embedding": { "model": "mixedbread-ai/mxbai-embed-large-v1", "dimensions": 1024 },\n "store": { "backend": "lancedb", "path": ".aikit-data" },\n "curated": { "path": "curated", "adapter": "filesystem" }\n}\n```\n\n## Tool Profiles\n\nTool profiles control which subset of the 82 tools are active. Profiles reduce token overhead by exposing only relevant tools for a given task.\n\n### Built-in Profiles\n\n| Profile | Description | Use When |\n|---------|-------------|----------|\n| `full` | All tools enabled (default) | General development, orchestration |\n| `safe` | Read-only tools — no file/state modifications | Code review, analysis, research |\n| `research` | Search, analysis, knowledge, web access | Investigation, documentation |\n| `minimal` | Essential tools only — search, check, test | Simple tasks, low-token budgets |\n| `discovery` | Full toolset + meta-tools for guided exploration | New users, onboarding, tool learning |\n\n### Activating a Profile\n\nSet `toolProfile` in `kb.config.json`:\n\n```json\n{\n "toolProfile": "research"\n}\n```\n\nBase tools (`status`, `config`, `guide`, `health`) are **always available** regardless of profile.\n\n### Meta-Tool Discovery Pattern (Token Cost Reduction)\n\nInstead of loading all 82 tool descriptions at session start, use the `discovery` profile:\n\n1. `list_tools()` — get a compact list of tool names + categories (~50 tokens)\n2. `search_tools({ query: "what I need" })` — find relevant tools by keyword\n3. `describe_tool({ tool_name: "specific_tool" })` — get full metadata only for tools you\'ll use\n\nThis pattern reduces initial tool-loading cost from ~3000 tokens to ~200 tokens.\n\n## IDE Integration\n\n### VS Code — HTTP mode (recommended for development)\n```json\n// .vscode/mcp.json\n{\n "servers": {\n "kb": {\n "type": "http",\n "url": "http://localhost:3210/mcp"\n }\n }\n}\n```\nStart server: `npx aikit serve --http --port 3210`\n\n### VS Code — stdio mode (no separate server)\n```json\n{\n "servers": {\n "kb": {\n "type": "stdio",\n "command": "npx",\n "args": ["@vpxa/aikit", "serve", "--stdio"]\n }\n }\n}\n```\n\n### Claude Code (`.mcp.json`)\n```json\n{\n "mcpServers": {\n "kb": {\n "command": "npx",\n "args": ["@vpxa/aikit", "serve"]\n }\n }\n}\n```\n\n## Development (Self-Dogfooding)\n\nWhen developing @vpxa/aikit itself, use the tool on its own codebase:\n\n```bash\n# Build → Reindex → Use loop\npnpm build # Build all 10 packages\nnode bin/aikit.mjs reindex # Index own source into LanceDB\nnode bin/aikit.mjs search "query" # Search own code\nnode bin/aikit.mjs symbol "FnName" # Resolve symbols in own code\nnode bin/aikit.mjs check # Typecheck + lint\npnpm test # Run 287+ tests\n\n# Start MCP server for agent use during development\nnode bin/aikit.mjs serve --http --port 3210\n```\n\n**Rules:**\n- Always `pnpm build` before using CLI/server (runs from `dist/`)\n- Always `reindex` after structural code changes\n- LanceDB is single-process — don\'t run CLI and HTTP server simultaneously\n- Curated entries in `curated/` survive reindex and are indexed separately\n\n---\n\n## Flows\n\nFlows are structured multi-step workflows that guide agents through complex tasks. They are the **primary workflow system** — use them instead of ad-hoc planning when a matching flow exists.\n\n### Flow Tools\n\n| Tool | Purpose |\n|------|---------|\n| `flow_status` | Check if a flow is active + current step + phase (before/flow/after) + isEpilogue |\n| `flow_list` | List available flows |\n| `flow_info` | Get flow details including steps and skill paths |\n| `flow_start` | Start a named flow |\n| `flow_step` | Advance: `next`, `skip`, or `redo` current step |\n| `flow_read_instruction` | Read the current step\'s instruction file content directly |\n| `flow_reset` | Clear flow state to start over |\n| `flow_add` | Add a custom flow from a directory |\n| `flow_update` | Update an existing custom flow |\n| `flow_remove` | Remove a custom flow |\n\n### Flow Selection\n\n| Task Type | Flow | Why |\n|-----------|------|-----|\n| Bug fix, config change, small refactor | `aikit:basic` | Known scope, low risk |\n| New feature in existing module | `aikit:basic` | Clear boundaries |\n| New system/service/module | `aikit:advanced` | Needs spec + planning |\n| Cross-service changes | `aikit:advanced` | Multiple boundaries |\n| Architectural change | `aikit:advanced` | High impact |\n| Unclear scope or exploratory | No flow | Use agent\'s native workflow |\n\n### Flow Lifecycle\n\n1. **Start**: `flow_list({})` → choose flow → `flow_start({ flow: "<name>", topic: "<task>" })`\n2. **Each step**: `flow_read_instruction({ step: "<name>" })` → follow step instructions → complete work\n3. **Advance**: `flow_step({ action: "next" })` → repeat from step 2\n4. **Epilogue**: After last flow step, mandatory epilogue steps run (e.g., `_docs-sync` updates `docs/`)\n5. **Resume**: `flow_status({})` → if active, `flow_read_instruction` for current step → continue\n6. **Reset**: `flow_reset({})` if you need to start over\n'}],brainstorming:[{file:`SKILL.md`,content:`---
|
|
1707
|
+
`}],aikit:[{file:`SKILL.md`,content:'---\nname: aikit\ndescription: "Use the @vpxa/aikit AI Kit MCP server for codebase search, analysis, and persistent memory. Load this skill when using aikit_search, aikit_remember, aikit_analyze_*, or any aikit_* tool. Covers all 82 MCP tools: search (hybrid/semantic/keyword), code analysis (structure, dependencies, symbols, patterns, entry points, diagrams, blast radius), knowledge graph (auto-populated module/symbol/import graph with traversal), context management (worksets, stash, checkpoints, restore, lanes), code manipulation (rename, codemod, eval), knowledge management (remember/read/update/forget), web access (fetch, search, http), FORGE protocol (ground, classify, evidence map, stratum cards, digest), brainstorming (interactive ideation sessions), presentation (rich dashboards via present tool), onboarding (full codebase analysis in one call), and developer utilities (regex, encode, measure, changelog, schema-validate, snippet, env, time)."\nmetadata:\n category: cross-cutting\n domain: general\n applicability: always\n inputs: [codebase]\n outputs: [search-results, analysis, knowledge]\n relatedSkills: [present]\n---\n\n# @vpxa/aikit — AI Kit\n\nLocal-first AI developer toolkit — 82 MCP tools for search, analysis, context compression, FORGE quality gates, knowledge management, code manipulation, execution, web access, brainstorming, presentation, and developer utilities.\n\n## When to Use\n\n- You need long-term memory across coding sessions\n- You want to search a codebase semantically (by meaning, not just keywords)\n- You need to compress large contexts to focus on what matters\n- You want structured output from build tools (tsc, vitest, biome, git)\n- You need to plan which files to read for a task\n- You want to safely explore refactors in isolated lanes\n- You need to rename symbols, apply codemods, or run code transformations\n- You want to fetch and read web pages or search the web\n- You need to make HTTP requests, test APIs, or debug endpoints\n- You want to test regex patterns, encode/decode data, or validate JSON schemas\n- You need code complexity metrics or a git changelog\n- You want to save and reuse code snippets across sessions\n\n## Skills Reference\n\n| Context | Skill | Load when |\n|---------|-------|----------|\n| Repository access recovery | `repo-access` | When encountering git auth failures, accessing private/enterprise repos, or when `web_fetch`/`http` returns auth errors on repository URLs. |\n\n## Architecture\n\n10-package monorepo published as a single npm package:\n\n```\ncore → store → embeddings → chunker → indexer → analyzers → tools → server → cli → tui\n```\n\n- **MCP server**: 82 tools + 2 resources (via `@modelcontextprotocol/sdk`)\n- **CLI**: 45 commands (thin dispatcher + 10 command groups)\n- **Search**: Hybrid vector + keyword + RRF fusion\n- **Embeddings**: ONNX local (mxbai-embed-large-v1, 1024 dimensions)\n- **Vector store**: LanceDB (embedded, zero infrastructure)\n- **Chunking**: Tree-sitter AST (TS/JS/Python/Go/Rust/Java) + regex fallback\n- **TUI**: Ink/React dashboard for human monitoring (search, status, curated, activity log)\n\n## Session Protocol (MANDATORY)\n\n### Start (do ALL)\n```\nflow_status({}) # Check/resume active flow FIRST\n# If flow active → flow_read_instruction({ step }) → follow step instructions\nstatus({}) # Check AI Kit health + onboard state\n# If onboard not run → onboard({ path: "." }) # First-time codebase analysis\nflow_list({}) # See available flows\n# Select flow based on task → flow_start({ flow: "<name>", topic: "<task>" }) # Start — creates .flows/{topic}/\nlist() # See stored knowledge\nsearch({ query: "SESSION CHECKPOINT", origin: "curated" }) # Resume prior work\n```\n\n### During Session\n```\nsearch → scope_map → symbol → trace (orient)\ncheck → test_run (validate changes)\nremember (capture insights)\n```\n\n### End of Session\n```\nsession_digest({ persist: true }) # Auto-capture session activity\nremember({ title: "Session checkpoint: <topic>", content: "<what was done, decisions made, next steps>", category: "conventions" })\n```\n\n## Tool Catalog (82 tools)\n\n### Search & Discovery (8)\n| Tool | CLI | Purpose |\n|------|-----|---------|\n| `search` | `aikit search` | Hybrid/semantic/keyword search with `search_mode` param |\n| `find` | `aikit find` | Federated search: vector + FTS + glob + regex in one call. Use `mode: \'examples\'` to find usage examples. |\n| `symbol` | `aikit symbol` | Resolve symbol definition, imports, and references |\n| `lookup` | `aikit lookup` | Full-file retrieval by path or record ID |\n| `scope_map` | `aikit scope-map` | Task-scoped reading plan with token estimates |\n| `trace` | `aikit trace` | Forward/backward flow tracing through call chains |\n| `dead_symbols` | `aikit dead-symbols` | Find exported symbols never imported — separates source (actionable) from docs (informational). Accepts `path` to scope the search. |\n| `file_summary` | `aikit summarize` | Structural overview of a file (exports, imports, functions) |\n\n### Code Analysis (7)\n| Tool | CLI | Purpose |\n|------|-----|---------|\n| `analyze_structure` | `aikit analyze structure` | Project structure overview |\n| `analyze_dependencies` | `aikit analyze deps` | Dependency graph with confidence |\n| `analyze_symbols` | `aikit analyze symbols` | Symbol extraction and cross-references |\n| `analyze_patterns` | `aikit analyze patterns` | Design pattern detection |\n| `analyze_entry_points` | `aikit analyze entry-points` | Find entry points: handlers, CDK constructs, test suites, package exports (walks workspace packages) |\n| `analyze_diagram` | `aikit analyze diagram` | Generate Mermaid diagrams |\n| `blast_radius` | `aikit analyze blast-radius` | Change impact analysis |\n\n### Context Management (6)\n| Tool | CLI | Purpose |\n|------|-----|---------|\n| `compact` | `aikit compact` | Compress text to relevant sections using embeddings (no LLM). Accepts `path` for server-side file read. |\n| `workset` | `aikit workset` | Named file set management (save/load/add/remove) |\n| `stash` | `aikit stash` | Named key-value store for session data |\n| `checkpoint` | `aikit checkpoint` | Save/restore session checkpoints |\n| `restore` | `aikit restore` | Restore a previously saved checkpoint |\n| `parse_output` | `aikit parse-output` | Parse tsc/vitest/biome/git output → structured JSON |\n\n### Code Manipulation (4)\n| Tool | CLI | Purpose |\n|------|-----|---------|\n| `rename` | `aikit rename` | Smart whole-word symbol rename across files (dry-run supported) |\n| `codemod` | `aikit codemod` | Regex-based code transformations with rules (dry-run supported) |\n| `diff_parse` | `aikit diff` | Parse unified diff → structured changes |\n| `data_transform` | `aikit transform` | JQ-like JSON transformations |\n\n### Execution & Validation (5)\n| Tool | CLI | Purpose |\n|------|-----|---------|\n| `eval` | `aikit eval` | Sandboxed JavaScript/TypeScript execution |\n| `check` | `aikit check` | Incremental typecheck + lint. `detail` param: efficient (default, minimal), normal (parsed errors), full (includes raw) |\n| `test_run` | `aikit test` | Run tests with structured pass/fail results |\n| `batch` | `aikit batch` | Execute multiple operations in parallel |\n| `audit` | `aikit audit` | Unified project audit: structure, deps, patterns, health, dead symbols, check, entry points → synthesized report with score and recommendations. 6 round-trips → 1. |\n\n### Knowledge Management (6)\n| Tool | CLI | Purpose |\n|------|-----|---------|\n| `remember` | `aikit remember` | Store a curated knowledge entry |\n| `update` | `aikit update` | Update an existing entry |\n| `forget` | `aikit forget` | Delete an entry (requires reason) |\n| `read` | `aikit read` | Read a curated entry by path |\n| `list` | `aikit list` | List curated entries |\n| `produce_knowledge` | — | Auto-generate knowledge from analysis |\n\n### Auto-Knowledge (automatic)\n\nTool outputs are automatically analyzed after every call. Useful facts (conventions, test patterns, build commands, errors) are extracted and stored as curated entries. Quality gate (score >= 0.3), deduplication, TTL for transient facts, max 50/session.\n\nSearch auto-knowledge with: `search({ query: "...", origin: "curated" })` or `list({ category: "conventions" })`\n\n### Verified Lanes (1 tool, 6 actions)\n| Tool | CLI | Purpose |\n|------|-----|---------|\n| `lane` | `aikit lane` | Manage isolated file copies for parallel exploration |\n\nLane actions: `create` (copy files to lane), `list`, `status` (modified/added/deleted), `diff` (line-level diff), `merge` (apply back to originals), `discard`.\n\n### Git & Environment (4)\n| Tool | CLI | Purpose |\n|------|-----|---------|\n| `git_context` | `aikit git` | Branch, status, recent commits |\n| `process` | `aikit proc` | Process supervisor (start/stop/logs) |\n| `watch` | `aikit watch` | Filesystem watcher |\n| `delegate` | `aikit delegate` | Delegate subtask to local Ollama model |\n\n### Web & Network (3)\n| Tool | CLI | Purpose |\n|------|-----|---------|\n| `web_fetch` | — | Fetch web page → markdown/raw/links/outline for LLM consumption |\n| `web_search` | — | Search the web via DuckDuckGo (no API key needed) |\n| `http` | — | Make HTTP requests for API testing/debugging |\n\n### Developer Utilities (8)\n| Tool | CLI | Purpose |\n|------|-----|---------|\n| `regex_test` | — | Test regex patterns with match/replace/split modes |\n| `encode` | — | Base64, URL, SHA-256, MD5, hex encode/decode, JWT decode |\n| `measure` | — | Code complexity metrics (cyclomatic, cognitive complexity, lines, functions) |\n| `changelog` | — | Generate changelog from git history (conventional commits) |\n| `schema_validate` | — | Validate JSON data against JSON Schema |\n| `snippet` | — | Save/get/search/delete persistent code snippets |\n| `env` | — | System and runtime environment info (sensitive values redacted) |\n| `time` | — | Date parsing, timezone conversion, duration math |\n\n### FORGE Quality Gates (5)\n| Tool | CLI | Purpose |\n|------|-----|---------|\n| `forge_ground` | — | Full Ground phase: classify tier, scope map, unknowns, constraints |\n| `forge_classify` | — | Quick tier classification (Floor/Standard/Critical) |\n| `evidence_map` | — | CRUD + Gate evaluation for verified/assumed/unknown claims. Safety gate tags (`provenance`/`commitment`/`coverage`) enable mandatory pre-YIELD checks |\n| `stratum_card` | — | Generate T1/T2 compressed context cards from files (10-100x token reduction) |\n| `digest` | — | Compress N text sources into token-budgeted summary |\n\n### System (9)\n| Tool | CLI | Purpose |\n|------|-----|---------|\n| `config` | `aikit config` | View or update project configuration (kb.config.json) |\n| `status` | `aikit status` | Index statistics |\n| `reindex` | `aikit reindex` | Rebuild index |\n| `health` | `aikit health` | Project health checks (package.json, tsconfig, lockfile, circular deps) |\n| `guide` | `aikit guide` | Tool discovery — given a goal, recommends tools and workflow order |\n| `onboard` | `aikit onboard` | Full codebase onboarding in one call (structure + deps + patterns + knowledge) |\n| `graph` | `aikit graph` | Query the auto-populated knowledge graph (modules, symbols, imports) |\n| `queue` | `aikit queue` | Task queue for sequential agent operations (create/push/next/done/fail) |\n| `replay` | `aikit replay` | View or clear the audit trail of tool invocations (action: list/clear) |\n\n### Flows (11)\n| Tool | CLI | Purpose |\n|------|-----|---------|\n| `flow_list` | `aikit flow list` | List available flows and active run |\n| `flow_info` | `aikit flow info` | Get flow details including steps and skill paths |\n| `flow_start` | `aikit flow start` | Start a flow with topic — creates `.flows/{topic-slug}/` run directory |\n| `flow_step` | `aikit flow step` | Advance, skip, or redo the current step |\n| `flow_status` | `aikit flow status` | Check active run including slug, runDir, artifactsPath |\n| `flow_read_instruction` | `aikit flow read-instruction` | Read instruction with `{{artifacts_path}}` and `{{run_dir}}` resolved |\n| `flow_reset` | `aikit flow reset` | Abandon the active flow (preserves run directory) |\n| `flow_runs` | `aikit flow runs` | List all flow runs (current and past) |\n| `flow_add` | `aikit flow add` | Add a custom flow from a directory |\n| `flow_update` | `aikit flow update` | Update an existing custom flow |\n| `flow_remove` | `aikit flow remove` | Remove a custom flow |\n\n### Presentation (1)\n| Tool | CLI | Purpose |\n|------|-----|---------|\n| `present` | — | Rich dashboards, charts, tables, timelines. Use `format: "browser"` then `openBrowserPage` to display. **In CLI mode (no VS Code chat), always use `format: "browser"`** — `html` UIResource is invisible in terminal. |\n\n### Brainstorming (1)\n| Tool | CLI | Purpose |\n|------|-----|---------|\n| `brainstorm` | — | Interactive brainstorming and ideation sessions with structured output |\n\n### Meta-Tools — Tool Discovery (3)\n| Tool | CLI | Purpose |\n|------|-----|---------|\n| `list_tools` | — | List all active AI Kit tools with names, titles, and categories. Accepts optional `category` filter. Use for initial tool discovery. |\n| `describe_tool` | — | Get detailed metadata for a specific tool (title, categories, annotations). Use after `list_tools` to understand a tool before calling it. |\n| `search_tools` | — | Search active tools by keyword across names, titles, and categories. Use when you know what you need but not the tool name. |\n\n### Session Management (1)\n| Tool | CLI | Purpose |\n|------|-----|---------|\n| `session_digest` | — | Generate a compressed digest of session activity (replay log, stash, checkpoints). Options: `scope` (tools/stash/all), `since`, `last`, `focus`, `mode` (deterministic/sampling), `tokenBudget`, `persist`. Use at session end for handoff or mid-session to review what happened. |\n\n## Flow System\n\nFlows are multi-step guided workflows that structure complex tasks. Each step has a skill file with detailed instructions, required artifacts, and agent assignments.\n\n### Built-in Flows\n\n| Flow | Steps | Use When |\n|------|-------|----------|\n| `aikit:basic` | assess → implement → verify | Bug fixes, config changes, small features |\n| `aikit:advanced` | spec → plan → task → execute → verify | New modules, cross-service changes, architectural work |\n\n### Flow Lifecycle\n\n```text\nflow_list() # See available flows\nflow_info({ flow: "aikit:basic" }) # View steps, skills, agents\nflow_start({ flow: "aikit:basic", topic: "Fix login bug" }) # Start — creates .flows/fix-login-bug/\nflow_read_instruction() # Read current step\'s instructions ({{artifacts_path}} resolved)\n# ... do the work described in the instruction ...\nflow_step({ action: "next" }) # Advance to next step\nflow_step({ action: "skip" }) # Skip current step\nflow_step({ action: "redo" }) # Redo current step\nflow_status() # Check progress (includes slug, runDir, artifactsPath, phase, isEpilogue)\nflow_reset() # Abandon active flow\nflow_runs() # List all runs (current + past)\n# Epilogue steps (mandatory, injected after every flow):\n# After last flow step → _docs-sync epilogue runs automatically\n# flow_status() shows phase: \'after\', isEpilogue: true during epilogue\n```\n\nCustom flow lifecycle management:\n\n```text\nflow_add({ source: ".github/flows/my-flow" })\nflow_update({ name: "my-flow" })\nflow_remove({ name: "my-flow" })\n```\n\n## CRITICAL: Use AI Kit Tools Instead of Native IDE Tools\n\nAI Kit tools provide **10x richer output** than native IDE tools — with AST-analyzed call graphs, scope context, import classification, and cognitive complexity. **You MUST use AI Kit tools instead of native read/search tools.**\n\n### ⛔ PROHIBITED: Native File Reading\n\n**`read_file` / `read_file_raw` MUST NOT be used to understand code.** They waste tokens and miss structural information.\n\nThe **ONLY** acceptable use of `read_file`: getting exact lines immediately before an edit (to verify the `old_str` for replacement). Even then, use `file_summary` first to identify which lines to read.\n\n### Tool Replacement Table\n\n| ❌ NEVER do this | ✅ Use AI Kit Tool | Why |\n|---|---|---|\n| `read_file` (full file) | `file_summary` | Exports, imports, call edges — **10x fewer tokens** |\n| `read_file` (specific section) | `compact({ path, query })` | Server-side read + extract — **5-20x reduction** |\n| `grep_search` / `textSearch` | `search` | Semantic + keyword hybrid across all indexed content |\n| `grep_search` for a symbol | `symbol` | Definition + references **with scope context** |\n| Multiple `read_file` calls | `digest` | Compresses multiple sources into token-budgeted summary |\n| `listDirectory` + `read_file` | `scope_map` | Identifies relevant files for a task automatically |\n| Manual code tracing | `trace` | AST call-graph traversal with scope context |\n| Line counting / `wc` | `measure` | Lines, complexity, **cognitive complexity**, functions |\n| Grep for unused exports | `dead_symbols` | AST-powered export detection with regex fallback |\n| Repeated file reads | `stratum_card` | Reusable compressed context — **10-100x reduction** |\n| `fetch_webpage` | `web_fetch` | Readability extract + token budget — richer output |\n| Web research / browsing | `web_search` | Structured web results without browser — **unique to KB** |\n\n### Decision Tree — How to Read Code\n\n```\nNeed to understand a file?\n├─ Just structure? → file_summary (exports, imports, call edges — ~50 tokens)\n├─ Specific section? → compact({ path, query }) — 5-20x reduction\n├─ Multiple files? → digest (multi-source compression — token-budgeted)\n├─ Repeated reference? → stratum_card (T1/T2 card — 10-100x reduction)\n├─ Need exact lines to EDIT? → read_file (the ONLY acceptable use)\n└─ "I want to read the whole file" → ⛔ STOP. Use file_summary or compact instead.\n```\n\n### Decision Tree — Need Structural Relationships?\n\nWhen vector search and file reads don\'t answer the question (e.g. "who imports this?",\n"what does this depend on?", "how are these files connected?"), use `graph`:\n\n```\nNeed to understand relationships between code?\n├─ Who imports / calls this? → graph({action:\'find_nodes\', name_pattern}) → graph({action:\'neighbors\', node_id, direction:\'incoming\'})\n├─ What does this depend on? → graph({action:\'neighbors\', node_id, direction:\'outgoing\'})\n├─ Full context for a symbol? → graph({action:\'symbol360\', name})\n├─ Related files within N hops? → graph({action:\'traverse\', node_id, max_depth:2})\n├─ Layer/module isolation check? → graph({action:\'depth_traverse\', node_id, max_depth:3})\n└─ Graph size/health? → graph({action:\'stats\'})\n```\n\n**Use this BEFORE** reaching for `analyze_dependencies` (slower, less precise) or manually\ntracing via `symbol` + `trace` chains. The graph is auto-populated during indexing.\n\n### What AI Kit Tools Return (AST-Enhanced)\n\nThese tools use Tree-sitter WASM to analyze source code at the AST level, providing structured data that raw file reads cannot:\n\n| Tool | Rich Output |\n|------|-------------|\n| `file_summary` | Imports classified as **external vs internal** (`isExternal` flag). **Call edges** between functions (e.g., `handleRequest() → validateInput() @ line 42`). `exported` flag on interfaces and types. Import count breakdown. |\n| `symbol` | References include **scope** — which function/class/method contains each usage (e.g., `referenced in processOrder() at auth-service.ts:55`). |\n| `trace` | **Call-graph edges** discovered via AST syntax tree, not text matching. Supports forward (who does X call?) and backward (who calls X?) tracing. Scope context on each node. |\n| `measure` | **Cognitive complexity** — weights nesting depth (nested `if` inside `for` inside `try` scores higher). More useful than cyclomatic complexity for understanding code difficulty. |\n| `dead_symbols` | **AST export enumeration** — catches `export default`, barrel re-exports (`export { x } from`), `export =`, and `export type`. Regex fallback for non-AST-supported languages. |\n\n### Example: `file_summary` Output\n\n```\nsrc/auth-service.ts\nLanguage: typescript | Lines: 180 | Estimated tokens: ~1400\n\nImports (6): 3 external, 3 internal\n - import { hash } from \'bcrypt\' [external]\n - import { UserRepo } from \'./user-repo\' [internal]\n\nFunctions (4):\n - authenticate @ line 22 [exported]\n - validateToken @ line 55 [exported]\n - hashPassword @ line 90\n - generateJwt @ line 110\n\nCall edges (12 intra-file):\n - authenticate() → hashPassword() @ line 35\n - authenticate() → generateJwt() @ line 42\n - validateToken() → UserRepo.findById() @ line 68\n\nInterfaces (2):\n - AuthResult @ line 8 [exported]\n - TokenPayload @ line 14\n```\n\nCompare: `read_file` would cost ~1400 tokens for raw text. `file_summary` gives structured data in ~120 tokens — **12x reduction** with richer information.\n\n## Token Efficiency\n\n`config.tokenBudget` controls output verbosity globally:\n\n| Level | Output | Compression | Context Strategy |\n|-------|--------|-------------|------------------|\n| `efficient` (default) | Minimal output, score + top issues only | threshold 2000, budget 1000 | `stratum_card(T1)` |\n| `normal` | Standard output with parsed errors/pattern names | threshold 4000, budget 2000 | `compact()` |\n| `full` | Maximum detail with raw output/full tables | No compression | `digest()` |\n\nSet via: `config({ action: \'update\', updates: { tokenBudget: \'normal\' } })`\n\nTools with `detail` param inherit from `config.tokenBudget` when not explicitly set.\nCompression middleware applies to ALL tool responses automatically.\n\n## Search Strategy\n\n1. **Start broad**: `search({ query: "topic", search_mode: "hybrid" })`\n2. **Narrow**: Add `content_type`, `origin`, or `category` filters\n3. **Exact match**: Use `search_mode: "keyword"` for identifiers\n4. **Federated**: Use `find` to combine vector + glob + regex\n\n## Workflow Chains\n\n### Codebase Onboarding\n```\nanalyze_structure({ path: "src/" })\n→ analyze_dependencies({ path: "src/" })\n→ analyze_entry_points({ path: "src/" })\n→ produce_knowledge({ path: "src/" })\n→ remember({ title: "Codebase onboarding complete", ... })\n```\n\n### Planning a Task\n```\nscope_map({ task: "implement user auth" })\n→ compact({ path: "src/auth.ts", query: "auth flow" })\n→ workset({ action: "save", name: "auth-task", files: [...] })\n```\n\n### Bug Investigation\n```\nparse_output({ output: <error> }) → symbol({ name: "failingFn" })\n→ trace({ symbol: "failingFn", direction: "backward" })\n→ blast_radius({ changed_files: ["suspect.ts"] })\n→ eval({ code: "hypothesis test" }) → check({ files: ["suspect.ts"] })\n```\n\n### Multi-Task Orchestration (DAG Queue)\n```\nqueue({ action: "create", name: "my-tasks" })\n→ queue({ action: "push", name: "my-tasks", title: "Task 1", data: { deps: [] } })\n→ queue({ action: "push", name: "my-tasks", title: "Task 2", data: { deps: ["task-1-id"] } })\n→ queue({ action: "next", name: "my-tasks" }) # Gets next ready task\n→ [do work]\n→ queue({ action: "done", name: "my-tasks", id: "<id>" })\n```\n\n### Safe Refactor with Lanes\n```\nscope_map({ task: "rename UserService" })\n→ lane({ action: "create", name: "refactor", files: [...] })\n→ [make changes in lane files]\n→ lane({ action: "diff", name: "refactor" })\n→ check({}) → test_run({})\n→ lane({ action: "merge", name: "refactor" })\n```\n\n### Lane — isolated read-only exploration\n\n`lane({ action:\'create\', name })` creates an isolated copy of the workspace. Use to try approach A vs B WITHOUT touching canonical source. Other actions: `list`, `diff`, `delete`. Compare with `lane({ action:\'diff\', names:[\'a\',\'b\'] })`. Do NOT use `lane` for actual refactors — use `checkpoint` instead (`checkpoint` = reversible on canonical source; `lane` = isolated copies for comparison).\n\n### After Making Changes\n```\nblast_radius({ changed_files: ["src/auth.ts"] })\n→ check({}) → test_run({ grep: "auth" })\n→ reindex()\n→ remember({ title: "Implemented auth", content: "..." })\n```\n\n### Pre-Commit Validation\n```\ngit_context({ diff: true })\n→ diff_parse({ diff: <staged diff> })\n→ blast_radius({ changed_files: [...] })\n→ check({}) → test_run({})\n```\n\n---\n\n## Persistent Memory\n\n| Action | Tool | Category |\n|--------|------|----------|\n| Store | `remember({ title, content, category })` | conventions, decisions, patterns, context, session |\n| Search | `search({ query, origin: "curated" })` | — |\n| Browse | `list()` or `list({ category })` | — |\n| Read | `read({ id })` | — |\n| Update | `update({ id, content })` | — |\n| Remove | `forget({ id })` | — |\n\n**Session checkpoint** (end of session): `remember({ title: "Session checkpoint: <topic>", content: "Done/Decisions/Next/Blockers", category: "session" })`\n\n## CLI Quick Reference\n\n```bash\naikit init # Scaffold AI Kit in current directory\naikit init --force # Overwrite all scaffold/skill files\naikit init --guide # JSON report of stale files for LLM-driven updates\naikit serve # Start MCP server (stdio or HTTP)\naikit search <q> # Hybrid search\naikit find <q> # Federated search\naikit symbol <name> # Resolve symbol\naikit scope-map <t> # Task reading plan\naikit compact <q> # Context compression (--path file or stdin)\naikit check # Typecheck + lint (--detail efficient|normal|full)\naikit test # Run tests\naikit rename <old> <new> <path> # Rename symbol\naikit lane create <name> --files f1,f2 # Create lane\naikit lane diff <name> # View lane changes\naikit lane merge <name> # Merge lane back\naikit status # Index stats\naikit reindex # Rebuild index\n```\n\n## Configuration\n\n`kb.config.json` in project root:\n```json\n{\n "sources": [{ "path": ".", "excludePatterns": ["node_modules/**", "**/node_modules/**", "dist/**", "coverage/**", ".aikit-data/**"] }],\n "indexing": { "chunkSize": 1500, "chunkOverlap": 200, "minChunkSize": 100, "concurrency": 5 },\n "embedding": { "model": "mixedbread-ai/mxbai-embed-large-v1", "dimensions": 1024 },\n "store": { "backend": "lancedb", "path": ".aikit-data" },\n "curated": { "path": "curated", "adapter": "filesystem" }\n}\n```\n\n## Tool Profiles\n\nTool profiles control which subset of the 82 tools are active. Profiles reduce token overhead by exposing only relevant tools for a given task.\n\n### Built-in Profiles\n\n| Profile | Description | Use When |\n|---------|-------------|----------|\n| `full` | All tools enabled (default) | General development, orchestration |\n| `safe` | Read-only tools — no file/state modifications | Code review, analysis, research |\n| `research` | Search, analysis, knowledge, web access | Investigation, documentation |\n| `minimal` | Essential tools only — search, check, test | Simple tasks, low-token budgets |\n| `discovery` | Full toolset + meta-tools for guided exploration | New users, onboarding, tool learning |\n\n### Activating a Profile\n\nSet `toolProfile` in `kb.config.json`:\n\n```json\n{\n "toolProfile": "research"\n}\n```\n\nBase tools (`status`, `config`, `guide`, `health`) are **always available** regardless of profile.\n\n## Development (Self-Dogfooding)\n\nWhen developing @vpxa/aikit itself: always `pnpm build` before using CLI/server (runs from `dist/`), always `reindex` after structural code changes, and don\'t run CLI and HTTP server simultaneously (LanceDB is single-process).\n\n---\n\n## Flows\n\nFlows are structured multi-step workflows that guide agents through complex tasks. They are the **primary workflow system** — use them instead of ad-hoc planning when a matching flow exists.\n\n### Flow Tools\n\n| Tool | Purpose |\n|------|---------|\n| `flow_status` | Check if a flow is active + current step + phase (before/flow/after) + isEpilogue |\n| `flow_list` | List available flows |\n| `flow_info` | Get flow details including steps and skill paths |\n| `flow_start` | Start a named flow |\n| `flow_step` | Advance: `next`, `skip`, or `redo` current step |\n| `flow_read_instruction` | Read the current step\'s instruction file content directly |\n| `flow_reset` | Clear flow state to start over |\n| `flow_add` | Add a custom flow from a directory |\n| `flow_update` | Update an existing custom flow |\n| `flow_remove` | Remove a custom flow |\n\n### Flow Selection\n\n| Task Type | Flow | Why |\n|-----------|------|-----|\n| Bug fix, config change, small refactor | `aikit:basic` | Known scope, low risk |\n| New feature in existing module | `aikit:basic` | Clear boundaries |\n| New system/service/module | `aikit:advanced` | Needs spec + planning |\n| Cross-service changes | `aikit:advanced` | Multiple boundaries |\n| Architectural change | `aikit:advanced` | High impact |\n| Unclear scope or exploratory | No flow | Use agent\'s native workflow |\n\n### Flow Lifecycle\n\n1. **Start**: `flow_list({})` → choose flow → `flow_start({ flow: "<name>", topic: "<task>" })`\n2. **Each step**: `flow_read_instruction({ step: "<name>" })` → follow step instructions → complete work\n3. **Advance**: `flow_step({ action: "next" })` → repeat from step 2\n4. **Epilogue**: After last flow step, mandatory epilogue steps run (e.g., `_docs-sync` updates `docs/`)\n5. **Resume**: `flow_status({})` → if active, `flow_read_instruction` for current step → continue\n6. **Reset**: `flow_reset({})` if you need to start over\n\n---\n\n## Reference Documentation\n\nFor detailed patterns on specific topics, load these reference files:\n\n| Topic | File | When to load |\n|-------|------|-------------|\n| Multi-task orchestration | `references/coordination.md` | Queue, DAG, lanes, worksets, stash, checkpoints |\n| Quality gates (FORGE) | `references/forge-protocol.md` | Complex tasks, evidence maps, tier classification |\n| Search & relationships | `references/search-patterns.md` | Finding code, tracing data flow, graph traversal |\n'},{file:`references/coordination.md`,content:`# Coordination & Multi-Task Orchestration
|
|
1708
|
+
|
|
1709
|
+
Patterns for managing multiple tasks, parallel exploration, and session state.
|
|
1710
|
+
|
|
1711
|
+
## Queue (Task Management)
|
|
1712
|
+
|
|
1713
|
+
| Action | Purpose | Example |
|
|
1714
|
+
|--------|---------|---------|
|
|
1715
|
+
| \`create\` | New queue | \`queue({ action: "create", name: "tasks" })\` |
|
|
1716
|
+
| \`push\` | Add item | \`queue({ action: "push", name: "tasks", title: "Fix auth", data: { deps: [] } })\` |
|
|
1717
|
+
| \`next\` | Get next ready item | \`queue({ action: "next", name: "tasks" })\` |
|
|
1718
|
+
| \`done\` | Mark complete | \`queue({ action: "done", name: "tasks", id: "<id>" })\` |
|
|
1719
|
+
| \`fail\` | Mark failed | \`queue({ action: "fail", name: "tasks", id: "<id>", error: "reason" })\` |
|
|
1720
|
+
| \`get\` | View queue state | \`queue({ action: "get", name: "tasks" })\` |
|
|
1721
|
+
| \`list\` | List all queues | \`queue({ action: "list" })\` |
|
|
1722
|
+
| \`clear\` | Clear all items | \`queue({ action: "clear", name: "tasks" })\` |
|
|
1723
|
+
| \`delete\` | Delete queue | \`queue({ action: "delete", name: "tasks" })\` |
|
|
1724
|
+
|
|
1725
|
+
### DAG Dependencies
|
|
1726
|
+
|
|
1727
|
+
Push items with \`data: { deps: ["item-id-1", "item-id-2"] }\`. The \`next\` action returns items whose dependencies are ALL marked done — automatic topological ordering.
|
|
1728
|
+
|
|
1729
|
+
\`\`\`
|
|
1730
|
+
queue({ action: "create", name: "build-pipeline" })
|
|
1731
|
+
queue({ action: "push", name: "build-pipeline", title: "Compile types", data: { deps: [] } }) // → id: "a"
|
|
1732
|
+
queue({ action: "push", name: "build-pipeline", title: "Bundle JS", data: { deps: ["a"] } }) // → id: "b"
|
|
1733
|
+
queue({ action: "push", name: "build-pipeline", title: "Run tests", data: { deps: ["a"] } }) // → id: "c"
|
|
1734
|
+
queue({ action: "push", name: "build-pipeline", title: "Deploy", data: { deps: ["b", "c"] } }) // → id: "d"
|
|
1735
|
+
queue({ action: "next", name: "build-pipeline" }) // Returns "Compile types" (no deps)
|
|
1736
|
+
queue({ action: "done", name: "build-pipeline", id: "a" })
|
|
1737
|
+
queue({ action: "next", name: "build-pipeline" }) // Returns "Bundle JS" or "Run tests" (deps satisfied)
|
|
1738
|
+
\`\`\`
|
|
1739
|
+
|
|
1740
|
+
## Lanes (Parallel Exploration)
|
|
1741
|
+
|
|
1742
|
+
Isolated file copies for exploring alternatives without affecting the workspace:
|
|
1743
|
+
|
|
1744
|
+
| Action | Purpose |
|
|
1745
|
+
|--------|---------|
|
|
1746
|
+
| \`lane({ action: "create", name: "approach-a", files: ["src/auth.ts"] })\` | Copy files into lane |
|
|
1747
|
+
| \`lane({ action: "status", name: "approach-a" })\` | Check lane state |
|
|
1748
|
+
| \`lane({ action: "diff", name: "approach-a" })\` | See changes vs original |
|
|
1749
|
+
| \`lane({ action: "merge", name: "approach-a" })\` | Apply changes back |
|
|
1750
|
+
| \`lane({ action: "discard", name: "approach-a" })\` | Throw away exploration |
|
|
1751
|
+
| \`lane({ action: "list" })\` | See all active lanes |
|
|
1752
|
+
|
|
1753
|
+
**Use case:** Create lanes for two approaches, explore both, diff to compare, merge the winner.
|
|
1754
|
+
|
|
1755
|
+
## Worksets (Named File Groups)
|
|
1756
|
+
|
|
1757
|
+
Persist named sets of files for repeated reference:
|
|
1758
|
+
|
|
1759
|
+
\`\`\`
|
|
1760
|
+
workset({ action: "save", name: "auth-files", files: ["src/auth.ts", "src/middleware.ts"], description: "Auth module" })
|
|
1761
|
+
workset({ action: "get", name: "auth-files" }) // Returns file list
|
|
1762
|
+
workset({ action: "add", name: "auth-files", files: ["src/session.ts"] })
|
|
1763
|
+
workset({ action: "remove", name: "auth-files", files: ["src/middleware.ts"] })
|
|
1764
|
+
workset({ action: "list" }) // All worksets
|
|
1765
|
+
workset({ action: "delete", name: "auth-files" })
|
|
1766
|
+
\`\`\`
|
|
1767
|
+
|
|
1768
|
+
## Stash (Intermediate Values)
|
|
1769
|
+
|
|
1770
|
+
Key-value store for results between tool calls:
|
|
1771
|
+
|
|
1772
|
+
\`\`\`
|
|
1773
|
+
stash({ action: "set", key: "analysis-result", value: "{ findings: [...] }" })
|
|
1774
|
+
stash({ action: "get", key: "analysis-result" })
|
|
1775
|
+
stash({ action: "list" })
|
|
1776
|
+
stash({ action: "delete", key: "analysis-result" })
|
|
1777
|
+
stash({ action: "clear" })
|
|
1778
|
+
\`\`\`
|
|
1779
|
+
|
|
1780
|
+
## Checkpoints (Session Milestones)
|
|
1781
|
+
|
|
1782
|
+
Save and restore session state:
|
|
1783
|
+
|
|
1784
|
+
\`\`\`
|
|
1785
|
+
checkpoint({ action: "save", label: "before-refactor", notes: "Pre-refactor state" })
|
|
1786
|
+
checkpoint({ action: "list" })
|
|
1787
|
+
checkpoint({ action: "latest" })
|
|
1788
|
+
checkpoint({ action: "load", label: "before-refactor" })
|
|
1789
|
+
\`\`\`
|
|
1790
|
+
`},{file:`references/forge-protocol.md`,content:`# FORGE Protocol — Quality Gates for Complex Tasks
|
|
1791
|
+
|
|
1792
|
+
Fact-Oriented Reasoning with Graduated Evidence. Use for any Standard+ tier task.
|
|
1793
|
+
|
|
1794
|
+
## Tier Classification
|
|
1795
|
+
|
|
1796
|
+
| Tier | Criteria | Ceremony |
|
|
1797
|
+
|------|----------|----------|
|
|
1798
|
+
| **Floor** | Single file, blast_radius ≤ 2, no schema change, no unknowns | Skip Break phase, no evidence map needed |
|
|
1799
|
+
| **Standard** | Multi-file or non-trivial, default for most tasks | Full 4-phase flow |
|
|
1800
|
+
| **Critical** | blast_radius > 5, cross-service, schema change, security code | Comprehensive evidence, extra review |
|
|
1801
|
+
|
|
1802
|
+
When uncertain, round up. Use \`forge_classify({ task, files, root_path })\` for automatic classification.
|
|
1803
|
+
|
|
1804
|
+
## 4-Phase Flow
|
|
1805
|
+
|
|
1806
|
+
### Phase 1 — Ground
|
|
1807
|
+
Read files, classify tier, build Typed Unknown Queue, load constraints.
|
|
1808
|
+
|
|
1809
|
+
\`\`\`
|
|
1810
|
+
forge_ground({ task: "Add user API", files: ["src/routes/user.ts", "src/models/user.ts"], root_path: "." })
|
|
1811
|
+
\`\`\`
|
|
1812
|
+
|
|
1813
|
+
This single call chains: classify → scope_map → unknowns → constraints → file_summaries → evidence_map creation.
|
|
1814
|
+
|
|
1815
|
+
### Phase 2 — Build
|
|
1816
|
+
Generate code with evidence anchoring. Route typed unknowns mid-generation.
|
|
1817
|
+
- Every claim must be backed by a tool receipt (search result, file line, test output)
|
|
1818
|
+
- Add evidence as you go: \`evidence_map({ action: "add", task_id, claim, status: "V", receipt })\`
|
|
1819
|
+
|
|
1820
|
+
### Phase 3 — Break (Standard+ only, skip for Floor)
|
|
1821
|
+
One adversarial round:
|
|
1822
|
+
- Check error paths and edge cases
|
|
1823
|
+
- Verify blast radius hasn't expanded
|
|
1824
|
+
- Check convention violations
|
|
1825
|
+
- Look for missing validation at system boundaries
|
|
1826
|
+
|
|
1827
|
+
### Phase 4 — Gate
|
|
1828
|
+
Binary evaluation: \`evidence_map({ action: "gate", task_id })\`
|
|
1829
|
+
|
|
1830
|
+
| Result | Meaning | Action |
|
|
1831
|
+
|--------|---------|--------|
|
|
1832
|
+
| **YIELD** | All evidence verified | Proceed — task complete |
|
|
1833
|
+
| **HOLD** | Fixable issues | Fix + re-gate (max 3 iterations) |
|
|
1834
|
+
| **HARD_BLOCK** | Contract-type unknowns unresolved | Escalate to user |
|
|
1835
|
+
|
|
1836
|
+
## Evidence Map
|
|
1837
|
+
|
|
1838
|
+
### Creating
|
|
1839
|
+
\`\`\`
|
|
1840
|
+
evidence_map({ action: "create", task_id: "add-user-api", tier: "standard" })
|
|
1841
|
+
\`\`\`
|
|
1842
|
+
|
|
1843
|
+
### Adding Claims
|
|
1844
|
+
\`\`\`
|
|
1845
|
+
evidence_map({
|
|
1846
|
+
action: "add",
|
|
1847
|
+
task_id: "add-user-api",
|
|
1848
|
+
claim: "User schema matches existing patterns",
|
|
1849
|
+
status: "V", // V=Verified, A=Assumed, U=Unresolved
|
|
1850
|
+
receipt: "search → models/user.ts#L12",
|
|
1851
|
+
safety_gate: "provenance" // Optional: provenance | commitment | coverage
|
|
1852
|
+
})
|
|
1853
|
+
\`\`\`
|
|
1854
|
+
|
|
1855
|
+
### Status Values
|
|
1856
|
+
| Status | Meaning | Requirements |
|
|
1857
|
+
|--------|---------|-------------|
|
|
1858
|
+
| **V** (Verified) | Proven by tool output | Must have non-empty receipt |
|
|
1859
|
+
| **A** (Assumed) | Reasonable assumption | Must have reasoning in receipt |
|
|
1860
|
+
| **U** (Unresolved) | Unknown, needs investigation | Blocks gate if on critical path |
|
|
1861
|
+
|
|
1862
|
+
### Safety Gates (Standard+ only)
|
|
1863
|
+
Three mandatory checks evaluated during \`gate\`:
|
|
1864
|
+
|
|
1865
|
+
| Gate | Rule | Failure |
|
|
1866
|
+
|------|------|---------|
|
|
1867
|
+
| **Provenance** | Every V claim has a non-empty receipt | HOLD |
|
|
1868
|
+
| **Commitment** | Every commitment-tagged entry is V | HOLD |
|
|
1869
|
+
| **Coverage** | No coverage-tagged entry is U | HOLD |
|
|
1870
|
+
|
|
1871
|
+
### Gating
|
|
1872
|
+
\`\`\`
|
|
1873
|
+
evidence_map({ action: "gate", task_id: "add-user-api" })
|
|
1874
|
+
// Returns: { verdict: "YIELD" | "HOLD" | "HARD_BLOCK", ... }
|
|
1875
|
+
\`\`\`
|
|
1876
|
+
|
|
1877
|
+
## Score-Driven Iteration
|
|
1878
|
+
|
|
1879
|
+
For quality-sensitive tasks:
|
|
1880
|
+
|
|
1881
|
+
1. Execute task (Build phase)
|
|
1882
|
+
2. Score: \`check({})\` + \`test_run({})\` + \`evidence_map({ action: "gate" })\`
|
|
1883
|
+
3. If gate ≠ YIELD → fix issues → re-score (max 3 iterations)
|
|
1884
|
+
4. Track progress: \`stash({ action: "set", key: "iteration-N", value: "{ score, issues }" })\`
|
|
1885
|
+
|
|
1886
|
+
## Quick Reference
|
|
1887
|
+
|
|
1888
|
+
\`\`\`
|
|
1889
|
+
// Classify
|
|
1890
|
+
forge_classify({ task: "...", files: ["..."], root_path: "." })
|
|
1891
|
+
|
|
1892
|
+
// Full Ground phase (single call)
|
|
1893
|
+
forge_ground({ task: "...", files: ["..."], root_path: "." })
|
|
1894
|
+
|
|
1895
|
+
// Evidence lifecycle
|
|
1896
|
+
evidence_map({ action: "create", task_id: "my-task", tier: "standard" })
|
|
1897
|
+
evidence_map({ action: "add", task_id: "my-task", claim: "...", status: "V", receipt: "..." })
|
|
1898
|
+
evidence_map({ action: "gate", task_id: "my-task" })
|
|
1899
|
+
\`\`\`
|
|
1900
|
+
`},{file:`references/search-patterns.md`,content:`# Search Patterns & Code Discovery
|
|
1901
|
+
|
|
1902
|
+
How to find code, understand relationships, and trace data flow.
|
|
1903
|
+
|
|
1904
|
+
## Decision Tree: Which Tool?
|
|
1905
|
+
|
|
1906
|
+
\`\`\`
|
|
1907
|
+
What do you need?
|
|
1908
|
+
├─ Understand a file's structure? → file_summary({ path })
|
|
1909
|
+
├─ Find specific content in a file? → compact({ path, query })
|
|
1910
|
+
├─ Find code across the codebase? → search({ query })
|
|
1911
|
+
├─ Find a specific symbol? → symbol({ name })
|
|
1912
|
+
├─ Trace data flow? → trace({ start, direction })
|
|
1913
|
+
├─ Understand module relationships? → graph({ action: "find_nodes" }) → graph({ action: "neighbors" })
|
|
1914
|
+
├─ Plan what to read for a task? → scope_map({ task })
|
|
1915
|
+
├─ Multi-strategy precision search? → find({ query, pattern, glob })
|
|
1916
|
+
└─ Compress multiple files? → digest({ sources, query })
|
|
1917
|
+
\`\`\`
|
|
1918
|
+
|
|
1919
|
+
## Search Modes
|
|
1920
|
+
|
|
1921
|
+
| Mode | When | Example |
|
|
1922
|
+
|------|------|---------|
|
|
1923
|
+
| \`hybrid\` (default) | General queries, combines vector + full-text | \`search({ query: "error handling" })\` |
|
|
1924
|
+
| \`semantic\` | Conceptual similarity, find related patterns | \`search({ query: "retry with backoff", search_mode: "semantic" })\` |
|
|
1925
|
+
| \`keyword\` | Exact identifiers, class/function names | \`search({ query: "CircuitBreaker", search_mode: "keyword" })\` |
|
|
1926
|
+
|
|
1927
|
+
## Search Filters
|
|
1928
|
+
|
|
1929
|
+
| Filter | Values | Purpose |
|
|
1930
|
+
|--------|--------|---------|
|
|
1931
|
+
| \`content_type\` | code-typescript, code-javascript, documentation, config-json, test-code, etc. | Restrict to file types |
|
|
1932
|
+
| \`origin\` | indexed, curated, produced | Source of knowledge |
|
|
1933
|
+
| \`source_type\` | source, documentation, test, config, generated | Coarse file category |
|
|
1934
|
+
| \`tags\` | string[] | Match any tag |
|
|
1935
|
+
| \`category\` | conventions, decisions, patterns, context, session | Curated knowledge category |
|
|
1936
|
+
| \`dedup\` | chunk (default), file | Collapse results from same file |
|
|
1937
|
+
|
|
1938
|
+
## Symbol Lookup
|
|
1939
|
+
|
|
1940
|
+
Find where a symbol is defined, imported, and used:
|
|
1941
|
+
|
|
1942
|
+
\`\`\`
|
|
1943
|
+
symbol({ name: "AuthService" })
|
|
1944
|
+
// Returns: definition location, all imports, all references with context
|
|
1945
|
+
\`\`\`
|
|
1946
|
+
|
|
1947
|
+
## Data Flow Tracing
|
|
1948
|
+
|
|
1949
|
+
Follow data forward (who uses this?) or backward (where does this come from?):
|
|
1950
|
+
|
|
1951
|
+
\`\`\`
|
|
1952
|
+
trace({ start: "handleRequest", direction: "forward" }) // What does handleRequest call?
|
|
1953
|
+
trace({ start: "src/db.ts:42", direction: "backward" }) // What calls this line?
|
|
1954
|
+
trace({ start: "validateInput", direction: "both" }) // Full call chain
|
|
1955
|
+
\`\`\`
|
|
1956
|
+
|
|
1957
|
+
## Knowledge Graph
|
|
1958
|
+
|
|
1959
|
+
The graph is auto-populated with modules, symbols, and import relationships. Two-step pattern:
|
|
1960
|
+
|
|
1961
|
+
\`\`\`
|
|
1962
|
+
// Step 1: Find nodes
|
|
1963
|
+
graph({ action: "find_nodes", name_pattern: "auth" })
|
|
1964
|
+
// Returns: nodes with IDs
|
|
1965
|
+
|
|
1966
|
+
// Step 2: Explore connections
|
|
1967
|
+
graph({ action: "neighbors", node_id: "<id-from-step-1>", direction: "incoming" })
|
|
1968
|
+
// Returns: what imports/depends on this module
|
|
1969
|
+
\`\`\`
|
|
1970
|
+
|
|
1971
|
+
### Graph Actions
|
|
1972
|
+
|
|
1973
|
+
| Action | Purpose |
|
|
1974
|
+
|--------|---------|
|
|
1975
|
+
| \`find_nodes\` | Search nodes by name pattern or type |
|
|
1976
|
+
| \`neighbors\` | Direct connections (incoming/outgoing/both) |
|
|
1977
|
+
| \`traverse\` | Multi-hop traversal (max_depth: 1-5) |
|
|
1978
|
+
| \`symbol360\` | Full context for a named symbol |
|
|
1979
|
+
| \`stats\` | Graph size and health |
|
|
1980
|
+
| \`cohesion\` | Module cohesion score |
|
|
1981
|
+
|
|
1982
|
+
## Scope Map (Reading Plans)
|
|
1983
|
+
|
|
1984
|
+
Generate a task-scoped reading plan:
|
|
1985
|
+
|
|
1986
|
+
\`\`\`
|
|
1987
|
+
scope_map({ task: "Add rate limiting to API routes" })
|
|
1988
|
+
// Returns: prioritized file list with relevance scores, token estimates, reading order
|
|
1989
|
+
\`\`\`
|
|
1990
|
+
|
|
1991
|
+
## Find (Multi-Strategy)
|
|
1992
|
+
|
|
1993
|
+
Combines vector search, full-text search, glob matching, and regex in one call:
|
|
1994
|
+
|
|
1995
|
+
\`\`\`
|
|
1996
|
+
find({ query: "rate limit", glob: "src/middleware/**", limit: 10 })
|
|
1997
|
+
find({ pattern: "new RateLimiter\\(", mode: "search" })
|
|
1998
|
+
find({ query: "handleRequest", mode: "examples" }) // Find real usage examples
|
|
1999
|
+
\`\`\`
|
|
2000
|
+
|
|
2001
|
+
## Context Compression
|
|
2002
|
+
|
|
2003
|
+
| Tool | Purpose | Token Reduction |
|
|
2004
|
+
|------|---------|----------------|
|
|
2005
|
+
| \`file_summary\` | Structure only (imports, exports, functions) | ~10x |
|
|
2006
|
+
| \`compact\` | Query-relevant content from a file | 5-20x |
|
|
2007
|
+
| \`digest\` | Compress multiple sources with budget | configurable |
|
|
2008
|
+
| \`stratum_card\` | Reusable T1/T2 context cards | 10-100x |
|
|
2009
|
+
|
|
2010
|
+
## Example Workflows
|
|
2011
|
+
|
|
2012
|
+
### Bug Investigation
|
|
2013
|
+
\`\`\`
|
|
2014
|
+
symbol({ name: "failingFunction" }) // Find definition
|
|
2015
|
+
→ trace({ start: "failingFunction", direction: "backward" }) // Who calls it?
|
|
2016
|
+
→ compact({ path: "src/caller.ts", query: "error handling around failingFunction" })
|
|
2017
|
+
→ blast_radius({ path: ".", files: ["src/caller.ts"] }) // What else is affected?
|
|
2018
|
+
\`\`\`
|
|
2019
|
+
|
|
2020
|
+
### Dependency Analysis
|
|
2021
|
+
\`\`\`
|
|
2022
|
+
graph({ action: "find_nodes", name_pattern: "auth-module" })
|
|
2023
|
+
→ graph({ action: "neighbors", node_id: "<id>", direction: "incoming" }) // Who depends on auth?
|
|
2024
|
+
→ graph({ action: "traverse", node_id: "<id>", max_depth: 2 }) // Deep dependency tree
|
|
2025
|
+
\`\`\`
|
|
2026
|
+
|
|
2027
|
+
### Codebase Onboarding
|
|
2028
|
+
\`\`\`
|
|
2029
|
+
scope_map({ task: "Understand the authentication system" })
|
|
2030
|
+
→ [read each file with file_summary or compact based on relevance]
|
|
2031
|
+
→ graph({ action: "find_nodes", name_pattern: "auth" })
|
|
2032
|
+
→ graph({ action: "neighbors", node_id: "<id>" })
|
|
2033
|
+
\`\`\`
|
|
2034
|
+
`}],brainstorming:[{file:`SKILL.md`,content:`---
|
|
1708
2035
|
name: brainstorming
|
|
1709
2036
|
description: "You MUST use this before any creative work - creating features, building components, adding functionality, or modifying behavior. Explores user intent, requirements and design before implementation."
|
|
1710
2037
|
metadata:
|
|
@@ -1,5 +0,0 @@
|
|
|
1
|
-
import{dirname as e,isAbsolute as t,join as n}from"node:path";import{createLogger as r,serializeError as i}from"../../core/dist/index.js";import{createHash as a}from"node:crypto";import{mkdir as o,readFile as s,readdir as c,stat as l,unlink as u,writeFile as d}from"node:fs/promises";var f=class{constructor(e){this.baseDir=e}async initialize(){await o(this.baseDir,{recursive:!0})}async read(e){let t=n(this.baseDir,e);try{return await s(t,`utf-8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}}async write(t,r,i){let a=n(this.baseDir,t);await o(e(a),{recursive:!0}),await d(a,r,{encoding:`utf-8`,flag:i?.exclusive?`wx`:`w`})}async delete(e){let t=n(this.baseDir,e);try{return await u(t),!0}catch(e){if(e.code===`ENOENT`)return!1;throw e}}async list(e){let t=[],r=e?[e]:await this.listDirectories();for(let e of r){let r=n(this.baseDir,e),i;try{i=await c(r)}catch{continue}for(let r of i){if(!r.endsWith(`.md`))continue;let i=`${e}/${r}`,a=n(this.baseDir,i);try{let e=await l(a);t.push({path:i,size:e.size})}catch{}}}return t}async exists(e){let t=n(this.baseDir,e);try{return await l(t),!0}catch{return!1}}async listDirectories(){try{return(await c(this.baseDir,{withFileTypes:!0})).filter(e=>e.isDirectory()&&/^[a-z][a-z0-9-]*$/.test(e.name)).map(e=>e.name)}catch{return[]}}async close(){}};const p=50*1024,m=r(`server`);var h=class{constructor(e,t,n,r=new f(e)){this.curatedDir=e,this.store=t,this.embedder=n,this.adapter=r}async remember(e,t,n,r=[]){this.validateCategoryName(n),this.validateContentSize(t);let i=this.slugify(e),a=await this.uniqueRelativePath(n,i),o=new Date().toISOString(),s={title:e,category:n,tags:r,created:o,updated:o,version:1,origin:`curated`,changelog:[{version:1,date:o,reason:`Initial creation`}]},c=this.serializeFile(t,s);try{await this.adapter.write(a,c,{exclusive:!0})}catch(e){throw e.code===`EEXIST`?Error(`Concurrent write collision for "${a}" — retry the operation`):e}try{await this.indexCuratedFile(a,t,s)}catch(e){throw await this.adapter.delete(a).catch(()=>{}),Error(`Remember failed: wrote file but indexing failed — rolled back. ${e.message}`)}return{path:a}}async update(e,t,n){e=this.guardPath(e),this.validateContentSize(t);let r=await this.adapter.read(e);if(r==null)throw Error(`Curated entry not found: ${e}`);let{frontmatter:i}=this.parseFile(r),a=(i.version??1)+1,o=new Date().toISOString();i.version=a,i.updated=o,i.changelog=[...i.changelog??[],{version:a,date:o,reason:n}];let s=this.serializeFile(t,i);return await this.adapter.write(e,s),await this.indexCuratedFile(e,t,i),{path:e,version:a}}async forget(e,t){if(e=this.guardPath(e),!await this.adapter.delete(e))throw Error(`Curated entry not found: ${e}`);let n=`.ai/curated/${e}`;return await this.store.deleteBySourcePath(n).catch(e=>{m.warn(`File deleted but vector cleanup failed`,{sourcePath:n,...i(e)})}),{path:e}}async read(e){e=this.guardPath(e);let t=await this.adapter.read(e);if(t==null)throw Error(`Curated entry not found: ${e}`);let{frontmatter:n,content:r}=this.parseFile(t),i=e.split(`/`)[0];return{path:e,title:n.title??e,category:i,tags:n.tags??[],version:n.version??1,created:n.created??``,updated:n.updated??``,contentPreview:r.slice(0,200),content:r}}async list(e){let t=[],n=e?.category?[e.category]:await this.discoverCategories();for(let r of n){let n=await this.adapter.list(r);for(let i of n){let n=await this.adapter.read(i.path);if(n==null)continue;let{frontmatter:a,content:o}=this.parseFile(n);e?.tag&&!(a.tags??[]).includes(e.tag)||t.push({path:i.path,title:a.title??i.path,category:r,tags:a.tags??[],version:a.version??1,created:a.created??``,updated:a.updated??``,contentPreview:o.slice(0,200)})}}return t}async reindexAll(){let e=await this.discoverCategories(),t=[],n=[];for(let r of e){let e=await this.adapter.list(r);for(let r of e){let e=r.path;try{let r=await this.adapter.read(e);if(r==null){t.push(`${e}: read failed`);continue}let{frontmatter:i,content:a}=this.parseFile(r);n.push({relativePath:e,content:a,frontmatter:i})}catch(n){m.error(`Failed to read curated file`,{relativePath:e,...i(n)}),t.push(`${e}: read failed`)}}}if(n.length===0)return{indexed:0,errors:t};let r=await this.embedder.embedBatch(n.map(e=>e.content)),a=new Date().toISOString(),o=n.map(e=>{let t=`.ai/curated/${e.relativePath}`;return{id:this.hashId(t,0),content:e.content,sourcePath:t,contentType:`curated-knowledge`,headingPath:e.frontmatter.title,chunkIndex:0,totalChunks:1,startLine:1,endLine:e.content.split(`
|
|
2
|
-
`).length,fileHash:this.hash(e.content),indexedAt:a,origin:`curated`,tags:e.frontmatter.tags,category:e.frontmatter.category,version:e.frontmatter.version}});return await this.store.upsert(o,r),{indexed:n.length,errors:t}}async indexCuratedFile(e,t,n){let r=await this.embedder.embed(t),i=`.ai/curated/${e}`,a=new Date().toISOString(),o={id:this.hashId(i,0),content:t,sourcePath:i,contentType:`curated-knowledge`,headingPath:n.title,chunkIndex:0,totalChunks:1,startLine:1,endLine:t.split(`
|
|
3
|
-
`).length,fileHash:this.hash(t),indexedAt:a,origin:`curated`,tags:n.tags,category:n.category,version:n.version};await this.store.upsert([o],[r])}async discoverCategories(){return this.adapter.listDirectories()}guardPath(e){let n=e.replace(/^\.ai\/curated\//,``);if(n.endsWith(`.md`)||(n+=`.md`),n.includes(`..`)||t(n))throw Error(`Invalid path: ${n}. Must be relative within .ai/curated/ directory.`);let r=n.split(`/`)[0];return this.validateCategoryName(r),n}validateCategoryName(e){if(!/^[a-z][a-z0-9-]*$/.test(e))throw Error(`Invalid category name: "${e}". Must be lowercase kebab-case (e.g., "decisions", "api-contracts").`)}validateContentSize(e){if(Buffer.byteLength(e,`utf-8`)>p)throw Error(`Content exceeds maximum size of ${p/1024}KB`)}slugify(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-|-$/g,``).slice(0,80)}async uniqueRelativePath(e,t){let n=`${e}/${t}.md`;if(!await this.adapter.exists(n))return n;for(let n=2;n<=100;n++){let r=`${e}/${t}-${n}.md`;if(!await this.adapter.exists(r))return r}throw Error(`Too many entries with slug "${t}" in category "${e}"`)}hash(e){return a(`sha256`).update(e).digest(`hex`).slice(0,16)}hashId(e,t){return this.hash(`${e}::${t}`)}serializeFile(e,t){return`${[`---`,`title: "${t.title.replace(/"/g,`\\"`)}"`,`category: ${t.category}`,`tags: [${t.tags.map(e=>`"${e}"`).join(`, `)}]`,`created: ${t.created}`,`updated: ${t.updated}`,`version: ${t.version}`,`origin: ${t.origin}`,`changelog:`,...t.changelog.map(e=>` - version: ${e.version}\n date: ${e.date}\n reason: "${e.reason.replace(/"/g,`\\"`)}"`),`---`].join(`
|
|
4
|
-
`)}\n\n${e}\n`}parseFile(e){let t=e.match(/^---\n([\s\S]*?)\n---\n\n?([\s\S]*)$/);if(!t)return{frontmatter:{title:`Untitled`,category:`notes`,tags:[],created:``,updated:``,version:1,origin:`curated`,changelog:[]},content:e};let n=t[1],r=t[2].trim(),i={},a=[],o=n.split(`
|
|
5
|
-
`),s=!1,c={};for(let e of o){if(/^changelog:\s*$/.test(e)){s=!0;continue}if(s){let t=e.match(/^\s+-\s+version:\s*(\d+)$/);if(t){c.version!=null&&a.push(c),c={version:parseInt(t[1],10)};continue}let n=e.match(/^\s+date:\s*(.+)$/);if(n){c.date=n[1].trim();continue}let r=e.match(/^\s+reason:\s*"?(.*?)"?\s*$/);if(r){c.reason=r[1];continue}/^\w/.test(e)&&(s=!1,c.version!=null&&a.push(c),c={});continue}let t=e.match(/^(\w+):\s*(.*)$/);if(t){let e=t[1],n=t[2];typeof n==`string`&&n.startsWith(`[`)&&n.endsWith(`]`)?n=n.slice(1,-1).split(`,`).map(e=>e.trim().replace(/^"|"$/g,``)).filter(e=>e.length>0):typeof n==`string`&&/^\d+$/.test(n)?n=parseInt(n,10):typeof n==`string`&&n.startsWith(`"`)&&n.endsWith(`"`)&&(n=n.slice(1,-1)),i[e]=n}}return c.version!=null&&a.push(c),{frontmatter:{title:i.title??`Untitled`,category:i.category??`notes`,tags:i.tags??[],created:i.created??``,updated:i.updated??``,version:i.version??1,origin:`curated`,changelog:a},content:r}}};export{f as n,h as t};
|
|
@@ -1,12 +0,0 @@
|
|
|
1
|
-
# aikit ask
|
|
2
|
-
|
|
3
|
-
> Quick research question — find answer using AI Kit + web search
|
|
4
|
-
|
|
5
|
-
## Quick Research
|
|
6
|
-
|
|
7
|
-
1. **AI Kit Recall** — Search knowledge base for existing answers
|
|
8
|
-
2. **Web Search** — If AI Kit has no relevant results, search the web
|
|
9
|
-
3. **Synthesize** — Combine findings into a clear, concise answer
|
|
10
|
-
4. **Remember** — If the answer is broadly useful, persist it to KB
|
|
11
|
-
|
|
12
|
-
**Always cite sources** — AI Kit entries, file paths, or URLs.
|
|
@@ -1,14 +0,0 @@
|
|
|
1
|
-
# aikit debug
|
|
2
|
-
|
|
3
|
-
> Systematic error diagnosis: reproduce → trace → diagnose → fix → verify
|
|
4
|
-
|
|
5
|
-
## Debug Workflow
|
|
6
|
-
|
|
7
|
-
1. **Parse Error** — Use `parse_output` on the error message/stack trace
|
|
8
|
-
2. **AI Kit Recall** — Search for known issues matching this pattern
|
|
9
|
-
3. **Reproduce** — Run the failing command/test to confirm
|
|
10
|
-
4. **Trace** — Use `symbol` and `trace` to follow the call chain
|
|
11
|
-
5. **Diagnose** — Form hypothesis, gather evidence
|
|
12
|
-
6. **Fix** — Implement minimal fix
|
|
13
|
-
7. **Verify** — `check` + `test_run` to confirm fix and no regressions
|
|
14
|
-
8. **Remember** — Persist the fix with category `troubleshooting`
|
|
@@ -1,14 +0,0 @@
|
|
|
1
|
-
# aikit design
|
|
2
|
-
|
|
3
|
-
> Collaborative design session — explore ideas, refine requirements, produce a design spec
|
|
4
|
-
|
|
5
|
-
## Design Session
|
|
6
|
-
|
|
7
|
-
Enter Phase 0 (Design Gate) directly — the user is requesting a design session.
|
|
8
|
-
|
|
9
|
-
1. **Invoke the brainstorming skill** — interactive design dialogue with user
|
|
10
|
-
2. Follow the skill's full process (auto-selects Simple or Advanced mode)
|
|
11
|
-
3. If Advanced Mode, use Decision Protocol for unresolved technical choices
|
|
12
|
-
4. Terminal state: brainstorming skill invokes writing-plans skill
|
|
13
|
-
|
|
14
|
-
**🛑 HARD GATE** — Do NOT skip brainstorming. Do NOT write code. Design first.
|
|
@@ -1,83 +0,0 @@
|
|
|
1
|
-
# aikit flow-add
|
|
2
|
-
|
|
3
|
-
> Install a new flow from a git URL or local path — with interactive error recovery
|
|
4
|
-
|
|
5
|
-
## Flow Installation Assistant
|
|
6
|
-
|
|
7
|
-
Install a development flow from a git repository or local directory.
|
|
8
|
-
|
|
9
|
-
### Usage
|
|
10
|
-
Provide a git URL or local path:
|
|
11
|
-
- `https://github.com/org/my-flow.git`
|
|
12
|
-
- `git@github.com:org/my-flow.git`
|
|
13
|
-
- `./path/to/local/flow`
|
|
14
|
-
- `C:\Users\name\flows\my-flow`
|
|
15
|
-
|
|
16
|
-
### Workflow
|
|
17
|
-
|
|
18
|
-
1. **Attempt Install** — Call `flow_add` with the provided source
|
|
19
|
-
2. **On Success** — Show installed flow info with `flow_info`, present summary to user
|
|
20
|
-
3. **On Failure** — Classify the error and enter the appropriate recovery path:
|
|
21
|
-
|
|
22
|
-
### Error Recovery Paths
|
|
23
|
-
|
|
24
|
-
#### Git Authentication Failure
|
|
25
|
-
If the error mentions authentication, credentials, 401, 403, permission denied, or SAML:
|
|
26
|
-
|
|
27
|
-
1. Present the error clearly to the user
|
|
28
|
-
2. Ask which auth method they prefer:
|
|
29
|
-
- **SSH key**: Walk through `ssh-keygen -t ed25519`, adding the public key to their git host, and retrying with the SSH URL
|
|
30
|
-
- **Personal Access Token (PAT)**: Guide them to create a PAT in their git host settings, configure `git credential.helper store`, and retry
|
|
31
|
-
- **Git Credential Manager**: Check if GCM is installed, help install if needed, then retry (GCM opens a browser for auth)
|
|
32
|
-
3. After credentials are configured, retry `flow_add`
|
|
33
|
-
|
|
34
|
-
#### Network / Connectivity Failure
|
|
35
|
-
If the error mentions timeout, host not found, SSL, or proxy:
|
|
36
|
-
|
|
37
|
-
1. Present diagnostics: Is VPN needed? Is the URL correct? Is there a proxy?
|
|
38
|
-
2. Guide the user through resolution
|
|
39
|
-
3. Retry after the issue is resolved
|
|
40
|
-
|
|
41
|
-
#### Format Not Recognized
|
|
42
|
-
If `flow_add` succeeds cloning but returns a format/structure error:
|
|
43
|
-
|
|
44
|
-
1. Explain that the source was fetched but doesn't match any supported format
|
|
45
|
-
2. List the 3 supported formats:
|
|
46
|
-
- **Native**: Has a `flow.json` manifest in the root
|
|
47
|
-
- **Claude Plugin**: Has `.claude-plugin/plugin.json` with skills as steps
|
|
48
|
-
- **Copilot Agents**: Has `.github/agents/` with agent .md files as steps
|
|
49
|
-
3. Analyze the source structure to understand what's there
|
|
50
|
-
4. Offer to help migrate:
|
|
51
|
-
- If it has README files or markdown docs → propose creating a `flow.json` that maps them as steps
|
|
52
|
-
- If it has a different workflow format → propose conversion
|
|
53
|
-
- If it's missing key parts → guide user to fill them in
|
|
54
|
-
5. Create the missing `flow.json` manifest and step structure
|
|
55
|
-
6. Retry `flow_add` with the fixed source
|
|
56
|
-
|
|
57
|
-
### Native flow.json Format Reference
|
|
58
|
-
```json
|
|
59
|
-
{
|
|
60
|
-
"name": "my-flow",
|
|
61
|
-
"version": "1.0.0",
|
|
62
|
-
"description": "Description of the flow",
|
|
63
|
-
"steps": [
|
|
64
|
-
{
|
|
65
|
-
"id": "step-id",
|
|
66
|
-
"name": "Step Name",
|
|
67
|
-
"instruction": "steps/step-id/README.md",
|
|
68
|
-
"produces": ["output.md"],
|
|
69
|
-
"requires": [],
|
|
70
|
-
"agents": [],
|
|
71
|
-
"description": "What this step does"
|
|
72
|
-
}
|
|
73
|
-
],
|
|
74
|
-
"agents": [],
|
|
75
|
-
"artifacts_dir": ".spec",
|
|
76
|
-
"install": []
|
|
77
|
-
}
|
|
78
|
-
```
|
|
79
|
-
|
|
80
|
-
### Post-Install
|
|
81
|
-
After successful installation:
|
|
82
|
-
- Show the flow name, steps, and description via `present`
|
|
83
|
-
- Remind user they can start it with `flow_start`
|