@vpxa/aikit 0.1.85 → 0.1.87
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-BCQCn7Be.js +5 -0
- 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-CRBcgUPU.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/bodies.mjs +8 -2
- package/scaffold/dist/definitions/skills.mjs +328 -1
- package/packages/cli/dist/user-C05ypatU.js +0 -5
- package/packages/server/dist/curated-manager-DX-_oJg0.js +0 -5
|
@@ -358,6 +358,8 @@ If a flow is active, follow the current step's instructions. Advance with \`flow
|
|
|
358
358
|
Use \`flow_list\` to see available flows and \`flow_start\` to begin one.
|
|
359
359
|
`,Planner:`**Read \`AGENTS.md\`** in the workspace root for project conventions and AI Kit protocol.
|
|
360
360
|
|
|
361
|
+
Load the \`aikit\` skill for full tool documentation, workflow chains, and session protocol.
|
|
362
|
+
|
|
361
363
|
## MANDATORY FIRST ACTION
|
|
362
364
|
|
|
363
365
|
1. Run \`status({})\` — if onboard shows ❌, run \`onboard({ path: "." })\` and wait for completion
|
|
@@ -453,7 +455,9 @@ When subagents complete, their visual outputs (from \`present\`) are NOT visible
|
|
|
453
455
|
| \`c4-architecture\` | When the plan involves architectural changes — generate C4 diagrams |
|
|
454
456
|
| \`adr-skill\` | When the plan involves non-trivial technical decisions — create executable ADRs |
|
|
455
457
|
| \`session-handoff\` | When context window is filling up, planning session ending, or major milestone completed |
|
|
456
|
-
| \`repo-access\` | When the plan involves accessing private, enterprise, or self-hosted repositories |`,Implementer:"**Read `AGENTS.md`** in the workspace root for project conventions and AI Kit protocol.\n\n## Implementation Protocol\n\n1. **Understand scope** — Read the phase objective, identify target files\n2. **Write test first** (Red) — Create failing tests that define expected behavior\n3. **Implement** (Green) — Write minimal code to make tests pass\n4. **Refactor** — Clean up while keeping tests green\n5. **Validate** — `check`, `test_run`, `blast_radius`\n6. **Persist** — `remember` any decisions or patterns discovered\n\n## Rules\n\n- **Test-first always** — No implementation without a failing test\n- **Minimal code** — Don't build what isn't asked for\n- **Follow existing patterns** — Search AI Kit for conventions before creating new ones (`search(\"convention\")`, `list({ category: \"conventions\" })`)\n- **Never modify tests to make them pass** — Fix the implementation instead\n- **Run `check` after every change** — Catch errors early\n- **Loop-break** — If the same test fails 3 times with the same error after your fixes, STOP. Re-read the error from scratch, check your assumptions with `trace` or `symbol`, and try a fundamentally different approach. Do not attempt a 4th fix in the same direction\n- **Think-first for complex tasks** — If a task involves 3+ files or non-obvious logic, outline your approach before writing code. Check existing patterns with `search` first. Design, then implement\n\n## Pre-Edit Checklist (before modifying any file)\n\n1. **Understand consumers** — `graph({action:'find_nodes', name_pattern:'<target>'})` → `graph({action:'neighbors', node_id, direction:'incoming'})`. See who calls/imports before changing a contract.\n2. **Compress, don't raw-read** — `file_summary` then `compact({path, query})` for the specific area. Only `read_file` when you need exact lines for `replace_string_in_file`.\n3. **Snapshot risky edits** — `checkpoint({action:'save', label:'pre-<scope>'})` before cross-cutting changes. `checkpoint({action:'restore', ...})` if `check`/`test_run` fails.\n4. **Estimate blast radius** — `blast_radius({changed_files:[...]})` BEFORE editing when changing a public/shared symbol; re-run AFTER to confirm actual impact matches.\n5. **TDD when tests exist** — write/extend the failing test first, then minimum code to pass.\n\n## Post-Edit Checklist\n\n1. `check({})` — typecheck + lint must pass clean\n2. `test_run({})` — full suite or targeted pattern\n3. If Orchestrator passed a `task_id`: `evidence_map({action:'add', task_id, claim, status:'V', receipt:'file.ts#Lxx'})` for each verified contract/acceptance claim. Do NOT run the gate — Orchestrator owns it.",Frontend:"**Read `AGENTS.md`** in the workspace root for project conventions and AI Kit protocol.\n\n## Frontend Protocol\n\n1. **Search KB** for existing component patterns and design tokens\n2. **Write component tests first** — Accessibility, rendering, interaction\n3. **Implement** — Follow existing component patterns, use design system tokens\n4. **Validate** — `check`, `test_run`, visual review\n5. **Persist** — `remember` new component patterns\n\n## Rules\n\n- **Accessibility first** — ARIA attributes, keyboard navigation, screen reader support\n- **Follow design system** — Use existing tokens, don't create one-off values\n- **Responsive by default** — Mobile-first, test all breakpoints\n- **Test-first** — Component tests before implementation\n\n## Frontend Exploration Mode\n\n| Need | Tool |\n|------|------|\n| Component dependency graph | `graph({action:'neighbors', node_id:'src/components/X.tsx', direction:'incoming'})` |\n| Stale / unused components | `dead_symbols({ path:'src/components' })` |\n| React / a11y / library API research | `web_search({ query })`, `web_fetch({ urls })` |\n| Component complexity hotspots | `measure({ path:'src/components' })` |\n| Verify a component's callers | `graph({action:'find_nodes', name_pattern})` → `neighbors` |\n\n## Visual Validation Protocol (post `test_run`)\n\n**Pre-flight (MANDATORY before any browser step):**\n1. Read `package.json` scripts — identify dev command (e.g. `dev`, `start`, `vite`)\n2. Determine default port (check script args, `vite.config.*`, or env)\n3. Check if dev server already running on port (attempt `http({ url:'http://localhost:<port>' })`)\n4. If NOT running, delegate to a helper or use `createAndRunTask` to start `npm run dev`\n in the background; wait for ready signal\n5. Capture the base URL\n\n**Validation:**\n6. `open_browser_page({ url })` — render target component page\n7. `screenshot_page` + `read_page` — capture visual + DOM\n8. Keyboard-only navigation check: simulate Tab/Enter/Escape via `type_in_page` —\n verify focus ring, activation, dismiss\n9. Compare against design tokens / Figma URL if supplied\n10. Fail fast if color contrast < 4.5:1 (WCAG AA) or focus indicator missing\n\nIf the pre-flight dev server cannot be started (e.g. sandbox), fall back to\n`compact` inspection of the component source + describe expected visual behavior.",Debugger:"**Read `AGENTS.md`** in the workspace root for project conventions and AI Kit protocol.\n\n## Debugging Protocol\n\n1. **AI Kit Recall** — `search(\"error patterns\")` to find auto-captured error patterns; `list({ tags: [\"errors\"] })` for all error entries; search for known issues matching this error pattern\n2. **Reproduce** — Confirm the error, use `parse_output` on stack traces and build errors for structured analysis\n3. **Verify targets exist** — Before tracing, confirm the files and functions mentioned in the error actually exist. Use `find` or `symbol` to verify paths and signatures. **Never trace into a file you haven't confirmed exists**\n4. **Trace** — `graph` (module imports), `symbol` (definitions/references), `trace` (call chains) — start with `graph` to understand module relationships, then drill into symbols\n5. **Diagnose** — Form hypothesis, gather evidence, identify root cause\n6. **Fix** — Implement the fix, verify with tests\n7. **Validate** — `check`, `test_run` to confirm no regressions\n8. **Persist** — `remember` the fix with category `troubleshooting`\n\n## Rules\n\n- **Never guess** — Always trace the actual execution path\n- **Reproduce first** — Confirm the error before attempting a fix\n- **Minimal fix** — Fix the root cause, don't add workarounds\n- **Test the fix** — Every fix must have a test that would have caught the bug\n- **Verify before asserting** — Don't claim a function has a certain signature without checking via `symbol`. Don't reference a config option without confirming it exists in the codebase\n- **Break debug loops** — If you apply a fix, test, and get the same error 3 times: your hypothesis is wrong. STOP, discard your current theory, re-examine the error output and trace from a different entry point. Return `ESCALATE` if a fresh approach also fails",Refactor:"**Read `AGENTS.md`** in the workspace root for project conventions and AI Kit protocol.\n\n## Refactoring Protocol\n\n1. **AI Kit Recall** — Search for established patterns and conventions\n2. **Analyze** — `graph` (module dependency map), `analyze_structure`, `analyze_patterns`, `dead_symbols`, `trace` (impact chains)\n3. **Ensure test coverage** — Run existing tests, add coverage for untested paths\n4. **Refactor in small steps** — Each step must keep tests green\n5. **Validate** — `check`, `test_run`, `blast_radius` after each step\n6. **Persist** — `remember` new patterns established\n\n## Rules\n\n- **Tests must pass at every step** — Never break behavior\n- **Smaller is better** — Prefer many small refactors over one big one\n- **Follow existing patterns** — Consolidate toward established conventions\n- **Don't refactor what isn't asked** — Scope discipline\n\n## Reversible Refactor Protocol\n\nRefactors modify the canonical source, so use `checkpoint` (NOT `lane`) for safety:\n\n1. **Before starting:** `checkpoint({ action:'save', label:'pre-refactor-<scope>' })`\n — captures a snapshot of the relevant files\n2. **Baseline metrics:** `measure({ path })` on target files — record\n `cognitiveComplexity` values BEFORE refactor\n3. **Apply changes** — use `rename({ old, new })` for symbol rename (dry_run first),\n or `codemod({ pattern, replacement })` for structural transforms (dry_run first).\n Never hand-edit what `rename`/`codemod` can do safely.\n4. **Verify:** `check({})` + `test_run({})` must both pass with zero new failures\n5. **Post-metrics:** `measure({ path })` again — confirm cognitive complexity\n delta is negative (or justify if zero)\n6. **If validation fails:** `checkpoint({ action:'restore', label:'pre-refactor-<scope>' })`\n\nFor multi-approach uncertainty (A vs B), do NOT create lanes. Instead:\n- Delegate to `Researcher-Delta` with a feasibility question — they can use `lane`\n for read-only exploration and return a recommendation\n- You then apply the winning approach under the checkpoint protocol above\n\n## Skills (load on demand)\n\n| Skill | When to load |\n|-------|--------------|\n| `lesson-learned` | After completing a refactor — extract principles from the before/after diff |\n| `typescript` | When refactoring TypeScript code — type patterns, generics, utility types |",Security:`**Read \`AGENTS.md\`** in the workspace root for project conventions and AI Kit protocol.
|
|
458
|
+
| \`repo-access\` | When the plan involves accessing private, enterprise, or self-hosted repositories |`,Implementer:"**Read `AGENTS.md`** in the workspace root for project conventions and AI Kit protocol.\n\nLoad the `aikit` skill for full tool documentation, workflow chains, and session protocol.\n\n## Implementation Protocol\n\n1. **Understand scope** — Read the phase objective, identify target files\n2. **Write test first** (Red) — Create failing tests that define expected behavior\n3. **Implement** (Green) — Write minimal code to make tests pass\n4. **Refactor** — Clean up while keeping tests green\n5. **Validate** — `check`, `test_run`, `blast_radius`\n6. **Persist** — `remember` any decisions or patterns discovered\n\n## Rules\n\n- **Test-first always** — No implementation without a failing test\n- **Minimal code** — Don't build what isn't asked for\n- **Follow existing patterns** — Search AI Kit for conventions before creating new ones (`search(\"convention\")`, `list({ category: \"conventions\" })`)\n- **Never modify tests to make them pass** — Fix the implementation instead\n- **Run `check` after every change** — Catch errors early\n- **Loop-break** — If the same test fails 3 times with the same error after your fixes, STOP. Re-read the error from scratch, check your assumptions with `trace` or `symbol`, and try a fundamentally different approach. Do not attempt a 4th fix in the same direction\n- **Think-first for complex tasks** — If a task involves 3+ files or non-obvious logic, outline your approach before writing code. Check existing patterns with `search` first. Design, then implement\n\n## Pre-Edit Checklist (before modifying any file)\n\n1. **Understand consumers** — `graph({action:'find_nodes', name_pattern:'<target>'})` → `graph({action:'neighbors', node_id, direction:'incoming'})`. See who calls/imports before changing a contract.\n2. **Compress, don't raw-read** — `file_summary` then `compact({path, query})` for the specific area. Only `read_file` when you need exact lines for `replace_string_in_file`.\n3. **Snapshot risky edits** — `checkpoint({action:'save', label:'pre-<scope>'})` before cross-cutting changes. `checkpoint({action:'restore', ...})` if `check`/`test_run` fails.\n4. **Estimate blast radius** — `blast_radius({changed_files:[...]})` BEFORE editing when changing a public/shared symbol; re-run AFTER to confirm actual impact matches.\n5. **TDD when tests exist** — write/extend the failing test first, then minimum code to pass.\n\n## Post-Edit Checklist\n\n1. `check({})` — typecheck + lint must pass clean\n2. `test_run({})` — full suite or targeted pattern\n3. If Orchestrator passed a `task_id`: `evidence_map({action:'add', task_id, claim, status:'V', receipt:'file.ts#Lxx'})` for each verified contract/acceptance claim. Do NOT run the gate — Orchestrator owns it.",Frontend:"**Read `AGENTS.md`** in the workspace root for project conventions and AI Kit protocol.\n\nLoad the `aikit` skill for full tool documentation, workflow chains, and session protocol.\n\n## Frontend Protocol\n\n1. **Search KB** for existing component patterns and design tokens\n2. **Write component tests first** — Accessibility, rendering, interaction\n3. **Implement** — Follow existing component patterns, use design system tokens\n4. **Validate** — `check`, `test_run`, visual review\n5. **Persist** — `remember` new component patterns\n\n## Rules\n\n- **Accessibility first** — ARIA attributes, keyboard navigation, screen reader support\n- **Follow design system** — Use existing tokens, don't create one-off values\n- **Responsive by default** — Mobile-first, test all breakpoints\n- **Test-first** — Component tests before implementation\n\n## Frontend Exploration Mode\n\n| Need | Tool |\n|------|------|\n| Component dependency graph | `graph({action:'neighbors', node_id:'src/components/X.tsx', direction:'incoming'})` |\n| Stale / unused components | `dead_symbols({ path:'src/components' })` |\n| React / a11y / library API research | `web_search({ query })`, `web_fetch({ urls })` |\n| Component complexity hotspots | `measure({ path:'src/components' })` |\n| Verify a component's callers | `graph({action:'find_nodes', name_pattern})` → `neighbors` |\n\n## Visual Validation Protocol (post `test_run`)\n\n**Pre-flight (MANDATORY before any browser step):**\n1. Read `package.json` scripts — identify dev command (e.g. `dev`, `start`, `vite`)\n2. Determine default port (check script args, `vite.config.*`, or env)\n3. Check if dev server already running on port (attempt `http({ url:'http://localhost:<port>' })`)\n4. If NOT running, delegate to a helper or use `createAndRunTask` to start `npm run dev`\n in the background; wait for ready signal\n5. Capture the base URL\n\n**Validation:**\n6. `open_browser_page({ url })` — render target component page\n7. `screenshot_page` + `read_page` — capture visual + DOM\n8. Keyboard-only navigation check: simulate Tab/Enter/Escape via `type_in_page` —\n verify focus ring, activation, dismiss\n9. Compare against design tokens / Figma URL if supplied\n10. Fail fast if color contrast < 4.5:1 (WCAG AA) or focus indicator missing\n\nIf the pre-flight dev server cannot be started (e.g. sandbox), fall back to\n`compact` inspection of the component source + describe expected visual behavior.",Debugger:"**Read `AGENTS.md`** in the workspace root for project conventions and AI Kit protocol.\n\nLoad the `aikit` skill for full tool documentation, workflow chains, and session protocol.\n\n## Debugging Protocol\n\n1. **AI Kit Recall** — `search(\"error patterns\")` to find auto-captured error patterns; `list({ tags: [\"errors\"] })` for all error entries; search for known issues matching this error pattern\n2. **Reproduce** — Confirm the error, use `parse_output` on stack traces and build errors for structured analysis\n3. **Verify targets exist** — Before tracing, confirm the files and functions mentioned in the error actually exist. Use `find` or `symbol` to verify paths and signatures. **Never trace into a file you haven't confirmed exists**\n4. **Trace** — `graph` (module imports), `symbol` (definitions/references), `trace` (call chains) — start with `graph` to understand module relationships, then drill into symbols\n5. **Diagnose** — Form hypothesis, gather evidence, identify root cause\n6. **Fix** — Implement the fix, verify with tests\n7. **Validate** — `check`, `test_run` to confirm no regressions\n8. **Persist** — `remember` the fix with category `troubleshooting`\n\n## Rules\n\n- **Never guess** — Always trace the actual execution path\n- **Reproduce first** — Confirm the error before attempting a fix\n- **Minimal fix** — Fix the root cause, don't add workarounds\n- **Test the fix** — Every fix must have a test that would have caught the bug\n- **Verify before asserting** — Don't claim a function has a certain signature without checking via `symbol`. Don't reference a config option without confirming it exists in the codebase\n- **Break debug loops** — If you apply a fix, test, and get the same error 3 times: your hypothesis is wrong. STOP, discard your current theory, re-examine the error output and trace from a different entry point. Return `ESCALATE` if a fresh approach also fails",Refactor:"**Read `AGENTS.md`** in the workspace root for project conventions and AI Kit protocol.\n\nLoad the `aikit` skill for full tool documentation, workflow chains, and session protocol.\n\n## Refactoring Protocol\n\n1. **AI Kit Recall** — Search for established patterns and conventions\n2. **Analyze** — `graph` (module dependency map), `analyze_structure`, `analyze_patterns`, `dead_symbols`, `trace` (impact chains)\n3. **Ensure test coverage** — Run existing tests, add coverage for untested paths\n4. **Refactor in small steps** — Each step must keep tests green\n5. **Validate** — `check`, `test_run`, `blast_radius` after each step\n6. **Persist** — `remember` new patterns established\n\n## Rules\n\n- **Tests must pass at every step** — Never break behavior\n- **Smaller is better** — Prefer many small refactors over one big one\n- **Follow existing patterns** — Consolidate toward established conventions\n- **Don't refactor what isn't asked** — Scope discipline\n\n## Reversible Refactor Protocol\n\nRefactors modify the canonical source, so use `checkpoint` (NOT `lane`) for safety:\n\n1. **Before starting:** `checkpoint({ action:'save', label:'pre-refactor-<scope>' })`\n — captures a snapshot of the relevant files\n2. **Baseline metrics:** `measure({ path })` on target files — record\n `cognitiveComplexity` values BEFORE refactor\n3. **Apply changes** — use `rename({ old, new })` for symbol rename (dry_run first),\n or `codemod({ pattern, replacement })` for structural transforms (dry_run first).\n Never hand-edit what `rename`/`codemod` can do safely.\n4. **Verify:** `check({})` + `test_run({})` must both pass with zero new failures\n5. **Post-metrics:** `measure({ path })` again — confirm cognitive complexity\n delta is negative (or justify if zero)\n6. **If validation fails:** `checkpoint({ action:'restore', label:'pre-refactor-<scope>' })`\n\nFor multi-approach uncertainty (A vs B), do NOT create lanes. Instead:\n- Delegate to `Researcher-Delta` with a feasibility question — they can use `lane`\n for read-only exploration and return a recommendation\n- You then apply the winning approach under the checkpoint protocol above\n\n## Skills (load on demand)\n\n| Skill | When to load |\n|-------|--------------|\n| `lesson-learned` | After completing a refactor — extract principles from the before/after diff |\n| `typescript` | When refactoring TypeScript code — type patterns, generics, utility types |",Security:`**Read \`AGENTS.md\`** in the workspace root for project conventions and AI Kit protocol.
|
|
459
|
+
|
|
460
|
+
Load the \`aikit\` skill for full tool documentation, workflow chains, and session protocol.
|
|
457
461
|
|
|
458
462
|
## MANDATORY FIRST ACTION
|
|
459
463
|
|
|
@@ -496,6 +500,8 @@ When subagents complete, their visual outputs (from \`present\`) are NOT visible
|
|
|
496
500
|
1. **[SEVERITY]** Title — Description, file:line, remediation
|
|
497
501
|
\`\`\``,Documenter:`**Read \`AGENTS.md\`** in the workspace root for project conventions and AI Kit protocol.
|
|
498
502
|
|
|
503
|
+
Load the \`aikit\` skill for full tool documentation, workflow chains, and session protocol.
|
|
504
|
+
|
|
499
505
|
## MANDATORY FIRST ACTION
|
|
500
506
|
|
|
501
507
|
1. Run \`status({})\` — if onboard shows ❌, run \`onboard({ path: "." })\` and wait for completion
|
|
@@ -569,4 +575,4 @@ Rules adapted from *The Elements of Agent Style* (CC BY 4.0, Yue Zhao) and class
|
|
|
569
575
|
| \`present\` | When presenting documentation previews, API tables, or architecture visuals to the user |
|
|
570
576
|
| \`c4-architecture\` | When documenting system architecture — generate C4 Mermaid diagrams |
|
|
571
577
|
| \`adr-skill\` | When documenting architecture decisions — create or update ADRs |
|
|
572
|
-
| \`typescript\` | When documenting TypeScript APIs — type signatures, JSDoc patterns |`,Explorer:"**Read `AGENTS.md`** in the workspace root for project conventions and AI Kit protocol.\n\n## MANDATORY FIRST ACTION\n\n1. Run `status({})` — if onboard shows ❌, run `onboard({ path: \".\" })` and wait for completion\n2. Note the **Onboard Directory** path from status output\n3. **Before exploring**, read relevant onboard artifacts using `compact({ path: \"<dir>/<file>\" })`:\n - `synthesis-guide.md` — project overview and architecture\n - `structure.md` — file tree and module purposes\n - `symbols.md` + `api-surface.md` — exported symbols\n - `dependencies.md` — import relationships\n - `code-map.md` — module graph\n4. Only use `find`, `symbol`, `trace`, `graph` for details NOT covered by artifacts\n\n## Exploration Protocol\n\n1. **AI Kit Recall** — `search` for existing analysis on this area\n2. **Discover** — Use `find`, `symbol`, `scope_map` to locate relevant files\n3. **Analyze** — Use `analyze_structure`, `analyze_dependencies`, `file_summary`\n4. **Compress** — Use `compact` for targeted file sections, `digest` when synthesizing 3+ sources, `stratum_card` for files you'll reference repeatedly\n5. **Map** — Build a picture of the subsystem: files, exports, dependencies, call chains\n6. **Report** — Structured findings with file paths and key observations\n\n## Exploration Modes\n\n| Goal | Tools |\n|------|-------|\n| Find files for a feature | `find`, `scope_map` |\n| Map a symbol's usage | `symbol`, `trace` |\n| Map module relationships | `graph({ action: 'neighbors' })` — import/export edges across packages |\n| Understand a package | `analyze_structure`, `analyze_dependencies`, `file_summary` |\n| Check impact of a change | `blast_radius` |\n\n## Output Format\n\n```markdown\n## Exploration: {topic}\n\n### Files Found\n- path/to/file.ts — purpose, key exports\n\n### Dependencies\n- package A → package B (via import)\n\n### Key Observations\n- Notable patterns, potential issues, architectural notes\n```\n\n## Rules\n\n- **Speed over depth** — Provide a useful map quickly, not an exhaustive analysis\n- **Read-only** — Never create, edit, or delete files\n- **Structured output** — Always return findings in the format above"};export{e as AGENT_BODIES};
|
|
578
|
+
| \`typescript\` | When documenting TypeScript APIs — type signatures, JSDoc patterns |`,Explorer:"**Read `AGENTS.md`** in the workspace root for project conventions and AI Kit protocol.\n\nLoad the `aikit` skill for full tool documentation, workflow chains, and session protocol.\n\n## MANDATORY FIRST ACTION\n\n1. Run `status({})` — if onboard shows ❌, run `onboard({ path: \".\" })` and wait for completion\n2. Note the **Onboard Directory** path from status output\n3. **Before exploring**, read relevant onboard artifacts using `compact({ path: \"<dir>/<file>\" })`:\n - `synthesis-guide.md` — project overview and architecture\n - `structure.md` — file tree and module purposes\n - `symbols.md` + `api-surface.md` — exported symbols\n - `dependencies.md` — import relationships\n - `code-map.md` — module graph\n4. Only use `find`, `symbol`, `trace`, `graph` for details NOT covered by artifacts\n\n## Exploration Protocol\n\n1. **AI Kit Recall** — `search` for existing analysis on this area\n2. **Discover** — Use `find`, `symbol`, `scope_map` to locate relevant files\n3. **Analyze** — Use `analyze_structure`, `analyze_dependencies`, `file_summary`\n4. **Compress** — Use `compact` for targeted file sections, `digest` when synthesizing 3+ sources, `stratum_card` for files you'll reference repeatedly\n5. **Map** — Build a picture of the subsystem: files, exports, dependencies, call chains\n6. **Report** — Structured findings with file paths and key observations\n\n## Exploration Modes\n\n| Goal | Tools |\n|------|-------|\n| Find files for a feature | `find`, `scope_map` |\n| Map a symbol's usage | `symbol`, `trace` |\n| Map module relationships | `graph({ action: 'neighbors' })` — import/export edges across packages |\n| Understand a package | `analyze_structure`, `analyze_dependencies`, `file_summary` |\n| Check impact of a change | `blast_radius` |\n\n## Output Format\n\n```markdown\n## Exploration: {topic}\n\n### Files Found\n- path/to/file.ts — purpose, key exports\n\n### Dependencies\n- package A → package B (via import)\n\n### Key Observations\n- Notable patterns, potential issues, architectural notes\n```\n\n## Rules\n\n- **Speed over depth** — Provide a useful map quickly, not an exhaustive analysis\n- **Read-only** — Never create, edit, or delete files\n- **Structured output** — Always return findings in the format above"};export{e as AGENT_BODIES};
|
|
@@ -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{a as e,n as t,r as n}from"./constants-B8_CApx0.js";import{n as r,t as i}from"./templates-ArdAVWoY.js";import{loadAdapter as a,n as o,r as s,smartCopyFromMemory as c,t as l}from"./scaffold-WMQ2uQ48.js";import{existsSync as u,mkdirSync as d,readFileSync as f,rmSync as p,unlinkSync as m,writeFileSync as h}from"node:fs";import{dirname as g,join as _,resolve as v}from"node:path";import{fileURLToPath as y}from"node:url";import{getGlobalDataDir as b,saveRegistry as x}from"../../core/dist/index.js";import{execFileSync as S}from"node:child_process";import{homedir as C}from"node:os";function w(e){let t=e;for(let e=0;e<10;e++){try{let e=_(t,`package.json`);if(u(e)&&JSON.parse(f(e,`utf8`)).name===`@vpxa/aikit`)return t}catch{}let e=g(t);if(e===t)break;t=e}return v(e,`..`,`..`,`..`)}function T(){let e={...t};if(process.platform!==`win32`){let t=process.env.PATH;t&&(e.env={PATH:t});try{let t=S(`which`,[`npx`],{encoding:`utf-8`,timeout:3e3}).trim();t&&u(t)&&(e.command=t)}catch{}}return e}function E(){let e=C(),t=process.platform,n=[],r=v(e,`.copilot`),i=v(r,`instructions`),a=v(e,`.claude`),o=v(e,`.cursor`),s=v(e,`.windsurf`);if(t===`win32`){let t=process.env.APPDATA??v(e,`AppData`,`Roaming`);n.push({ide:`VS Code`,configDir:v(t,`Code`,`User`),mcpConfigPath:v(t,`Code`,`User`,`mcp.json`),globalScaffoldRoot:r,instructionsRoot:i},{ide:`VS Code Insiders`,configDir:v(t,`Code - Insiders`,`User`),mcpConfigPath:v(t,`Code - Insiders`,`User`,`mcp.json`),globalScaffoldRoot:r,instructionsRoot:i},{ide:`VSCodium`,configDir:v(t,`VSCodium`,`User`),mcpConfigPath:v(t,`VSCodium`,`User`,`mcp.json`),globalScaffoldRoot:r,instructionsRoot:i},{ide:`Cursor`,configDir:v(t,`Cursor`,`User`),mcpConfigPath:v(t,`Cursor`,`User`,`mcp.json`),globalScaffoldRoot:o,instructionsRoot:null},{ide:`Cursor Nightly`,configDir:v(t,`Cursor Nightly`,`User`),mcpConfigPath:v(t,`Cursor Nightly`,`User`,`mcp.json`),globalScaffoldRoot:o,instructionsRoot:null},{ide:`Windsurf`,configDir:v(t,`Windsurf`,`User`),mcpConfigPath:v(t,`Windsurf`,`User`,`mcp.json`),globalScaffoldRoot:s,instructionsRoot:null})}else if(t===`darwin`){let t=v(e,`Library`,`Application Support`);n.push({ide:`VS Code`,configDir:v(t,`Code`,`User`),mcpConfigPath:v(t,`Code`,`User`,`mcp.json`),globalScaffoldRoot:r,instructionsRoot:i},{ide:`VS Code Insiders`,configDir:v(t,`Code - Insiders`,`User`),mcpConfigPath:v(t,`Code - Insiders`,`User`,`mcp.json`),globalScaffoldRoot:r,instructionsRoot:i},{ide:`VSCodium`,configDir:v(t,`VSCodium`,`User`),mcpConfigPath:v(t,`VSCodium`,`User`,`mcp.json`),globalScaffoldRoot:r,instructionsRoot:i},{ide:`Cursor`,configDir:v(t,`Cursor`,`User`),mcpConfigPath:v(t,`Cursor`,`User`,`mcp.json`),globalScaffoldRoot:o,instructionsRoot:null},{ide:`Cursor Nightly`,configDir:v(t,`Cursor Nightly`,`User`),mcpConfigPath:v(t,`Cursor Nightly`,`User`,`mcp.json`),globalScaffoldRoot:o,instructionsRoot:null},{ide:`Windsurf`,configDir:v(t,`Windsurf`,`User`),mcpConfigPath:v(t,`Windsurf`,`User`,`mcp.json`),globalScaffoldRoot:s,instructionsRoot:null})}else{let t=process.env.XDG_CONFIG_HOME??v(e,`.config`);n.push({ide:`VS Code`,configDir:v(t,`Code`,`User`),mcpConfigPath:v(t,`Code`,`User`,`mcp.json`),globalScaffoldRoot:r,instructionsRoot:i},{ide:`VS Code Insiders`,configDir:v(t,`Code - Insiders`,`User`),mcpConfigPath:v(t,`Code - Insiders`,`User`,`mcp.json`),globalScaffoldRoot:r,instructionsRoot:i},{ide:`VSCodium`,configDir:v(t,`VSCodium`,`User`),mcpConfigPath:v(t,`VSCodium`,`User`,`mcp.json`),globalScaffoldRoot:r,instructionsRoot:i},{ide:`Cursor`,configDir:v(t,`Cursor`,`User`),mcpConfigPath:v(t,`Cursor`,`User`,`mcp.json`),globalScaffoldRoot:o,instructionsRoot:null},{ide:`Cursor Nightly`,configDir:v(t,`Cursor Nightly`,`User`),mcpConfigPath:v(t,`Cursor Nightly`,`User`,`mcp.json`),globalScaffoldRoot:o,instructionsRoot:null},{ide:`Windsurf`,configDir:v(t,`Windsurf`,`User`),mcpConfigPath:v(t,`Windsurf`,`User`,`mcp.json`),globalScaffoldRoot:s,instructionsRoot:null})}if(n.push({ide:`Claude Code`,configDir:v(e,`.claude`),mcpConfigPath:v(e,`.claude`,`mcp.json`),globalScaffoldRoot:a,instructionsRoot:null}),n.push({ide:`Copilot CLI`,configDir:r,mcpConfigPath:v(r,`mcp-config.json`),globalScaffoldRoot:null,instructionsRoot:null}),t===`darwin`){let e={"VS Code":`/Applications/Visual Studio Code.app`,"VS Code Insiders":`/Applications/Visual Studio Code - Insiders.app`,VSCodium:`/Applications/VSCodium.app`,Cursor:`/Applications/Cursor.app`,"Cursor Nightly":`/Applications/Cursor Nightly.app`,Windsurf:`/Applications/Windsurf.app`};return n.filter(t=>u(t.configDir)||e[t.ide]&&u(e[t.ide]))}return n.filter(e=>u(e.configDir))}function D(e,t,n=!1){let{mcpConfigPath:r,configDir:i}=e,a=T(),o={};if(u(r)){try{let e=f(r,`utf-8`);o=JSON.parse(e)}catch{let e=`${r}.bak`;h(e,f(r,`utf-8`),`utf-8`),console.log(` Backed up invalid ${r} to ${e}`),o={}}if((o.servers??o.mcpServers??{})[t]&&!n){console.log(` ${e.ide}: ${t} already configured (use --force to update)`);return}}let s=new Set([`VS Code`,`VS Code Insiders`,`VSCodium`,`Windsurf`]).has(e.ide)?`servers`:`mcpServers`,c=o[s]??{};e.ide===`Copilot CLI`?c[t]={...a,tools:[`*`]}:c[t]=a,o[s]=c,d(i,{recursive:!0}),h(r,`${JSON.stringify(o,null,2)}\n`,`utf-8`),console.log(` ${e.ide}: configured ${t} in ${r}`)}const O=new Set([`VS Code`,`VS Code Insiders`,`VSCodium`]);function k(t,n=!1){if(!O.has(t.ide))return;let r=v(t.configDir,`settings.json`),i={};if(u(r))try{let e=f(r,`utf-8`);i=JSON.parse(e)}catch{console.log(` ${t.ide}: skipped settings.json (invalid JSON)`);return}let a=!1;for(let[t,r]of Object.entries(e))if(typeof r==`object`&&r){let e=typeof i[t]==`object`&&i[t]!==null?i[t]:{},n={...e,...r};JSON.stringify(n)!==JSON.stringify(e)&&(i[t]=n,a=!0)}else (n||!(t in i))&&(i[t]=r,a=!0);a&&(h(r,`${JSON.stringify(i,null,2)}\n`,`utf-8`),console.log(` ${t.ide}: updated settings.json`))}async function A(e,t,n,f,m=!1){let g=new Set;for(let e of t)e.globalScaffoldRoot&&g.add(e.globalScaffoldRoot);if(g.size===0){console.log(` No IDEs with global scaffold support detected.`);return}let _=await a(e,`copilot`),y=new Map;for(let e of _){let t=e.path.indexOf(`/`);if(t===-1)continue;let n=e.path.substring(0,t);if(n!==`agents`&&n!==`prompts`)continue;let r=y.get(n)??[];r.push({path:e.path.substring(t+1),content:e.content}),y.set(n,r)}let b=await a(e,`skills`),x=new Map;for(let e of b){let t=e.path.indexOf(`/`);if(t===-1)continue;let n=e.path.substring(0,t),r=x.get(n)??[];r.push({path:e.path.substring(t+1),content:e.content}),x.set(n,r)}let S=await a(e,`flows`),w=new Map;for(let e of S){let t=e.path.indexOf(`/`);if(t===-1)continue;let n=e.path.substring(0,t),r=w.get(n)??[];r.push({path:e.path.substring(t+1),content:e.content}),w.set(n,r)}let T=(e,t)=>{let n=y.get(t);if(!n||n.length===0)return;let r=v(e,`.aikit-scaffold.json`),i=o(r)??l(f);i.version=f,c(n,v(e,t),i,t,m),s(r,i)};for(let e of g){T(e,`agents`),T(e,`prompts`);{let t=v(e,`.aikit-scaffold.json`),n=o(t)??l(f);n.version=f;for(let[t,r]of x)c(r,v(e,`skills`,t),n,`skills/${t}`,m);s(t,n)}{let t=v(e,`.aikit-scaffold.json`),n=o(t)??l(f);n.version=f;for(let t of w.keys()){let n=v(e,`flows`,t,`skills`);u(n)&&(p(n,{recursive:!0,force:!0}),console.log(` ${e}: migrated ${t} flow to steps/ layout`))}for(let[t,r]of w)c(r,v(e,`flows`,t),n,`flows/${t}`,m);s(t,n)}console.log(` ${e}: scaffold updated (${x.size} skills)`)}let E=new Set,D=r(`aikit`,n),O=i(`aikit`,n);for(let e of t){if(!e.globalScaffoldRoot)continue;let t=e.globalScaffoldRoot;if(e.ide===`Claude Code`){let e=v(t,`CLAUDE.md`);h(e,`${D}\n---\n\n${O}`,`utf-8`),E.add(e)}else if(e.ide===`VS Code`||e.ide===`VS Code Insiders`||e.ide===`VSCodium`){let n=e.instructionsRoot??t;d(n,{recursive:!0});let r=v(n,`copilot-instructions.md`);E.has(r)||(h(r,`---\napplyTo: "**"\n---\n\n${D}\n---\n\n${O}`,`utf-8`),E.add(r));let i=v(C(),`.github`),a=v(i,`copilot-instructions.md`);E.has(a)||(d(i,{recursive:!0}),h(a,`${D}\n---\n\n${O}`,`utf-8`),E.add(a)),T(e.configDir,`prompts`)}else if(e.ide===`Cursor`||e.ide===`Cursor Nightly`){let e=v(t,`rules`);d(e,{recursive:!0});let n=v(e,`aikit.mdc`);E.has(n)||(h(n,`${D}\n---\n\n${O}`,`utf-8`),E.add(n))}else if(e.ide===`Windsurf`){let e=v(t,`rules`);d(e,{recursive:!0});let n=v(e,`aikit.md`);E.has(n)||(h(n,`${D}\n---\n\n${O}`,`utf-8`),E.add(n))}}E.size>0&&console.log(` Instruction files: ${[...E].join(`, `)}`)}function j(e){let t=[];for(let n of e){if(!n.globalScaffoldRoot)continue;let e=n.globalScaffoldRoot;if(n.ide===`VS Code`||n.ide===`VS Code Insiders`||n.ide===`VSCodium`){let r=n.instructionsRoot??e;t.push(v(r,`kb.instructions.md`)),t.push(v(r,`aikit.instructions.md`))}else n.ide===`Cursor`||n.ide===`Cursor Nightly`?t.push(v(e,`rules`,`kb.mdc`)):n.ide===`Windsurf`&&t.push(v(e,`rules`,`kb.md`))}for(let e of t)u(e)&&(m(e),console.log(` Removed legacy file: ${e}`))}async function M(e){let t=n,r=w(g(y(import.meta.url))),i=JSON.parse(f(v(r,`package.json`),`utf-8`)).version;console.log(`Initializing @vpxa/aikit v${i}...\n`);let a=b();d(a,{recursive:!0}),console.log(` Global data store: ${a}`),x({version:1,workspaces:{}}),console.log(` Created registry.json`);let o=E();if(o.length===0)console.log(`
|
|
2
|
-
No supported IDEs detected. You can manually add the MCP server config.`);else{console.log(`\n Detected ${o.length} IDE(s):`);for(let n of o)D(n,t,e.force),k(n,e.force)}console.log(`
|
|
3
|
-
Installing scaffold files:`),await A(r,o,t,i,e.force),j(o),console.log(`
|
|
4
|
-
User-level AI Kit installation complete!`),console.log(`
|
|
5
|
-
Next steps:`),console.log(` 1. Open any workspace in your IDE`),console.log(` 2. The AI Kit server will auto-start and index the workspace`),console.log(` 3. Agents, prompts, skills & instructions are available globally`),console.log(` 4. No per-workspace init needed — just open a project and start coding`)}export{M as initUser};
|