Skip to content

Commit 42aec88

Browse files
feat(code-intel): RegistryProvider + hook-runtime + doctor checks + agent improvements [Story INS-4.11] (#489)
* chore(code-intel): QA re-review NOG-3 + entity-registry updates [Epic NOGIC] - QA re-review NOG-3 (2026-02-20): PASS confirmed, 31/31 tests, 123/123 suite - Updated gate file with correct test counts - Entity registry sync Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat(code-intel): QA gate enhancement with blast radius + coverage [Story NOG-4] - Add qa-helper.js with 4 public functions (getBlastRadius, getTestCoverage, getReferenceImpact, suggestGateInfluence) - Add qa-helper.test.js with 40 tests (156/156 suite passing) - Modify qa-gate.md with optional Code Intelligence Enhancement section - Modify qa-review-story.md with step 0b Reference Impact - Register qa-helper in entity-registry.yaml - QA Gate: PASS (100/100, all 5 ACs verified, 94.91% coverage) Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat(code-intel): planning helper for brownfield & PRD workflows [Story NOG-5] Add planning-helper.js with 5 functions for @pm/@architect code intelligence: - getCodebaseOverview, getDependencyGraph, getComplexityAnalysis, getImplementationContext, getImplementationImpact - Integrate code intelligence steps into 5 task markdown files - 41 tests covering all 15 scenarios (T1-T15), 0 regressions - QA gate: PASS (all ACs met, pattern compliant with dev/qa helpers) Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat(code-intel): story creation awareness with duplicate detection [Story NOG-6] Add story-helper.js with 3 functions for @sm/@po agent tasks: - detectDuplicateStory: advisory duplicate warning during story creation - suggestRelevantFiles: file suggestions via findReferences + analyzeCodebase - validateNoDuplicates: boolean checklist item for story validation Integrate into create-next-story.md (step 1.2) and validate-next-story.md (step 8.1) with graceful fallback when no provider available. 24 tests passing, 98% coverage. QA gate: PASS. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix(cli): correct aios info paths and YAML parse errors (#173, #104) - Fix `aios info` showing 0 agents/tasks/templates/workflows by using correct `development/` subdirectory paths (#173) - Fix YAML parse errors in oalanicolas.md by wrapping strings containing arrow character (→) in single quotes (#104) Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat(code-intel): devops pre-push impact analysis and PR enrichment [Story NOG-7] - Create devops-helper.js with 4 functions (assessPrePushImpact, generateImpactSummary, classifyRiskLevel, _formatImpactReport) - Add Step 9.1 to pre-push quality gate (advisory impact analysis, never blocks) - Add Step 5.1 to PR automation (enrich description with blast radius) - 25 tests passing, 100% stmts/fns/lines coverage - Register devops-helper entity in entity-registry.yaml - QA gate: PASS (100/100) by Quinn Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat(code-intel): squad creator codebase awareness and integration pattern [Story NOG-8] Add creation-helper.js with 3 functions (getCodebaseContext, checkDuplicateArtefact, enrichRegistryEntry) for code intelligence in artefact creation workflows. Integrate auto-enrichment into registry-updater.js, add optional Code Intelligence sections to agent/task templates via Handlebars conditionals, and create standardized integration pattern template. QA review PASS — all 5 ACs met, 68/68 tests pass, 0 regressions. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * chore: sync pending changes (synapse, installer, pro-cli, story updates, tests) Includes synapse engine improvements, installer i18n expansion, pro-cli recovery fixes, license auth tests, story status updates for NOG-4/5/6/7, and activation pipeline enhancements. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat(graph-dashboard): CLI Graph Dashboard MVP — PRD, architecture, stories, and GD-1 implementation - Add PRD with 3 epics (MVP ASCII, Interactive TUI, Real-time) - Add detailed architecture document (16-file module structure) - Add deep research (5 files) for CLI graph visualization - Implement Story GD-1: CLI entrypoint, CodeIntelSource, tree-renderer - Add 3 story drafts for Epic 1 MVP (GD-1, GD-2, GD-3) - Register aios-graph bin entrypoint in package.json - Add unit tests for cli, code-intel-source, tree-renderer - Disable Synapse UserPromptSubmit hook (redundant with .claude/rules/) - Update entity-registry metadata Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * test(graph-dashboard): QA review pass — resolve coverage observations [Story GD-1] - Added tests for flat object normalization and registry fallback error paths - Created index.test.js for public API wrapper (5 tests) - Coverage improved: code-intel-source 57%→71% branch, index.js 0%→100% - QA gate: PASS (95/100), 43 tests total, 0 issues - Updated story status, QA results, and gate file Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix(updater): use correct package name aios-core instead of @synkra/aios-core (#174) The npm package was renamed from @synkra/aios-core to aios-core but the updater still referenced the old scoped name, causing: - npm registry lookup returning 404 (version=null) - npm install command failing with E404 Fixed references in: - updater/index.js: registry URL, install command, fallback path, error msg - aios-init.js: error message, node_modules fallback path - validate/index.js: repair source path - i18n.js: "try again" messages in EN/PT/ES Closes #174 Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat(graph-dashboard): entity stats and cache metrics ASCII view [Story GD-2] Add --stats flag to aios-graph CLI with entity statistics table, cache performance sparklines, and latency chart via asciichart. QA review PASS (95/100), all observations resolved. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix: rename @synkra/aios-core to aios-core across entire codebase (#159) Complete rename of legacy scoped package name @synkra/aios-core to the current unscoped name aios-core across 136 files including source code, documentation (EN/PT/ES), agent definitions, IDE configs, CI/CD workflows, tests, and configuration files. Preserves backward-compat check in updater/index.js line 183. Fixes malformed security email addresses in security-best-practices docs. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix(docs): remove non-existent email references, redirect to GitHub Issues Replace all security@synkra.ai, support@synkra.ai and security@aios-core.dev references with GitHub Issues/Security Advisories links since no AIOS email exists yet. Affects docs (EN/PT/ES), installer i18n, and pro-setup. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat(graph-dashboard): provider status and output formats [Story GD-3] Add provider status renderer (TTY/non-TTY), JSON/DOT/Mermaid formatters, summary view combining tree+stats+status, and format validation in CLI router. 56 new tests, QA PASS (97/100). Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix(ide-sync): implement GitHub Copilot custom agents format (#138) Create dedicated GitHub Copilot transformer that generates .agent.md files with proper YAML frontmatter (name, description, tools) as required by the Copilot specification. Replaces the identity transform that was copying raw agent files without frontmatter. - Create github-copilot.js transformer with YAML frontmatter generation - Update ide-sync index.js to register new transformer - Update core-config.yaml format from full-markdown-yaml to github-copilot - Update installer to apply Copilot transformer during installation - Rename .github/agents/*.md to *.agent.md (12 agents) - Add research documentation for Copilot format specification Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs(graph-dashboard): research + stories GD-4/5/6 for dynamic visualization Research: blessed-contrib abandoned, recommending 3-phase approach: - GD-4: Live DOT watch mode (Graphviz VS Code ext) - GD-5: vis-network HTML web viewer (--format=html) - GD-6: Custom VS Code extension with Cytoscape.js Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat(devops): add GitHub issues triage and resolve tasks Add two new operational tasks for @devops agent: - *triage-issues: analyze open issues, classify by type/severity/effort, prioritize with scoring formula, identify quick wins - *resolve-issue {number}: end-to-end workflow from investigation to close, with research phase, parallel execution patterns, and lessons learned from past sessions (#138, #159, #174) Update devops agent definition with new commands and dependencies. Sync agent files across all 6 IDEs. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat(graph-dashboard): live DOT watch mode with QA pass [Story GD-4] - handleWatch() with setInterval + fs.watch + 300ms debounce - --watch and --interval=N flags in parseArgs - .aios/graph.dot (default) or .aios/graph.mmd (--format=mermaid) - process.once('SIGINT') for clean listener management - 14 unit tests (watch-mode.test.js), 158/158 total passing - QA gate: PASS 9.5/10 (zero CRITICAL/HIGH issues) - Sync: entity-registry, agent IDE configs, story updates Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat(github): implement issue management system [Story GHIM-001] Cherry-picked from feat/nog-3-dev-task-enhancement branch. Adds GitHub issue templates (YAML forms), auto-labeling workflow, stale issue management, and DevOps triage task. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat(code-intel): UAP & SYNAPSE deep research + Wave 6 stories [Story NOG-9] Complete NOG-9 research deliverables: - 21 research reports across 4 waves (UAP loaders, UAP steps, SYNAPSE core, cross-IDE) - Comparative matrix, optimization roadmap, output taxonomy, code-intel helpers - Research summary consolidating all findings - Codex QA review handoff and architect response with revised plan - 5 new stories (NOG-10 to NOG-14) for Wave 6 hardening phase - Updated INDEX.md with Wave 5-6 and dependency graph Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat(code-intel): add Wave 6 performance journey log system Observador externo que captura UAP + SYNAPSE + code-intel metrics como snapshots tagueados, compara entre stories e gera report markdown acumulativo. Baseline capturado. Stories NOG-10 a NOG-13 atualizadas com journey tasks pos-QA. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat(code-intel): safe quick wins — session wiring, token estimation, git detection [Story NOG-10] - QW-1: Wire updateSession() in synapse hook for bracket state persistence - QW-3: Apply 1.2x XML_SAFETY_MULTIPLIER to token estimation - QW-5: Direct .git/HEAD read with fallback chain (52ms → <2ms branch detection) - 17 new tests (git-config-detector, bracket return, XML multiplier) - QA gate: PASS — all ACs met, 273 suites, 6625 tests, 0 failures Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat(graph-dashboard): HTML web viewer with vis-network, QA pass [Story GD-5] - html-formatter.js: vis-network CDN, XSS sanitization, category colors, legend - cli.js: --format=html, handleHtmlOutput, openInBrowser (cross-platform) - Watch mode: --watch --format=html with meta-refresh auto-reload - Node deduplication fix for entity-registry duplicate IDs - Large graph optimization: smooth=false, hideEdgesOnDrag, status indicator - 29 unit tests (HTML gen, sanitization, nodes, edges, XSS prevention) - QA gate: PASS (8.5/10) — 526 unique nodes rendering correctly Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs(research): graph taxonomy, filtering & query capabilities Tech search covering 3 areas for graph dashboard evolution: - Entity taxonomy expansion (4 → 10+ categories, script subtypes) - vis-network filtering UI (DataView pattern, search, clustering) - Graph query API (graphology library, impact analysis, Synapse integration) 26 sources analyzed, 3-phase implementation plan documented. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs(code-intel): close Story NOG-10 — Phase 0A Safe Quick Wins [Done] QA PASS (score 90). All 3 quick wins implemented and validated. Updated epic INDEX.md with completion status. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs(code-intel): NOG-11 token usage source discovery — research complete, QA PASS [Story NOG-11] Research spike: 4 sources investigated, viable solution found (Stop hook + JSONL tail read, 0.2ms). Includes: research report, ADR, Codex QA review (GO condicionado), mini-design for NOG-15 conditions, handoff docs, QA gate PASS (95/100), and journey snapshot. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat(graph-dashboard): improve code-intel source, HTML formatter, and entity registry Enhanced code-intel data source, HTML formatter improvements, and entity registry enrichment with populate script updates. Tests updated accordingly. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat(code-intel): NOG-15 tests + QA PASS, NOG-16A/B/C stories, registry governance research - NOG-15: +12 tests (32/32 pass), QA review PASS 9/10, story Ready for Review - NOG-16A: Scan Config expansion (4 dirs) + sentinel/noise filter [Draft] - NOG-16B: Dependency classification + entity lifecycle tags [Draft] - NOG-16C: Graph filtering + focus mode with vis-network DataView [Draft] - Research: registry governance patterns (Nx, Backstage, DataHub, Rush) - Registry regenerated: 563 entities with enriched graph [Story NOG-15] Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat(synapse): atomic writes + session cleanup wiring [Story NOG-12] - Create atomicWriteSync() utility (write-to-tmp + rename, Windows compat) - Apply atomic writes to all 5 persistence points (session-manager, context-detector, unified-activation-pipeline x2, createSession) - Wire cleanStaleSessions() into hook-runtime on first prompt - Add staleTTLHours config (168h default) to core-config.yaml - 10 new atomic-write tests, 2 new hook-runtime cleanup tests - QA PASS — 97/97 tests passing, zero regressions - Journey snapshot NOG-12 captured (no code-caused regressions) Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat(doctor): git fsmonitor detection + opt-in suggestion [Story NOG-13] Add fsmonitor check (Check 3b) to aios doctor with three states: enabled, available (Git 2.37+), unavailable. Shared detectFsmonitor() module in bin/utils/. UAP hints fsmonitor when projectStatus > 100ms. 11 tests, QA PASS (100/100), journey snapshot captured. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * chore(registry): regenerate entity-registry after QA concern fixes [Story NOG-16A] Registry regenerated after removing double-filtering in scanCategory merge and adding verbose logging to extractMarkdownCrossReferences. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat(code-intel): dependency classification and entity lifecycle [Story NOG-16B] Add dependency classification (internal/external/planned) and entity lifecycle states (production/orphan/experimental/deprecated) to the entity registry scanner. EXTERNAL_TOOLS set (21 tools), DEPRECATED_PATTERNS (4 regexes), lifecycle override from YAML frontmatter. Registry now at 712 entities with 100% resolution rate. QA gate: PASS (68/68 tests). Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs(architecture): ADR memory self-editing security model [Story NOG-14] ADR-SYNAPSE-001 defines security guardrails for AI memory self-editing: - Threat model: 4 threats (persistence poisoning, context degradation, agent impersonation, rollback failure) - Decision: Option C (Hybrid) — auto-validation + escalation - 6 guardrails: field allowlist, content validation, versioning, audit log, approval gate, TTL - QA security review: PASS (95/100) - PM approval: ACCEPTED Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat(code-intel): graph filtering, focus mode, and lifecycle styling [Story NOG-16C] Add interactive filtering controls to the graph dashboard: - DataView-based filtering (category, lifecycle, search) - Sidebar with 11 category + 4 lifecycle toggle checkboxes - Visual lifecycle differentiation (opacity, border, color) - Focus mode on double-click (1-hop neighborhood) - Search input with live filtering (200ms debounce) - Metrics display (visible/total entities) - Reset/Show All button - hideEdgesOnDrag always enabled for performance - 32 new tests (229 graph-dashboard total, all passing) Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * chore: sync pending changes (synapse, installer, pro-cli, story updates, tests) Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat(code-intel): E2E pipeline audit with QA pass [Story NOG-17] Comprehensive audit of UAP + SYNAPSE + Session + Git Detection pipeline. Key findings: git _isGitRepository() bottleneck (34ms vs 0.05ms direct read), projectStatus impossible at 20ms budget (164ms total), SYNAPSE efficient (70 rules, <2ms), 85% tokens ESSENTIAL. All 3 QA concerns fixed in-session: calibrated bracket prompt_counts, bracket-filter vs no-content distinction, corrected classification logic. QA gate: PASS. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat(graph-dashboard): tooltip redesign and physics control panel [Story GD-10, GD-11] GD-10: Tooltip & Interaction Redesign - Redesigned tooltip with category-colored header and structured layout - Added entity type filters with gold-line separators and section-label pattern - Implemented focus mode with direct neighbor highlighting on double-click - Lifecycle badge, dependencies/dependants count, and used-by section in tooltip GD-11: Physics Control Panel (Obsidian-style) - 4 force sliders: Center Force, Repel Force, Link Force, Link Distance - Real-time physics via network.setOptions() with 50ms debounce - Reset button restores defaults, Pause/Resume toggles physics.enabled - Collapsible PHYSICS section with THEME token governance (zero hardcoded hex) - Cross-browser range input CSS (webkit + moz) - ARIA labels on all sliders Tests: 257 graph-dashboard tests passing (84 html-formatter) Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * chore: sync graph dashboard stories, research, and pending changes - Stories GD-11 through GD-15 (physics controls, depth expansion, metrics, export, clustering) - Research: graph-dashboard-controls tech-search results - Entity registry updates - NOG-16C and NOG index minor updates Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs(code-intel): NOG-18 story + native-first research [Story NOG-18] Create SYNAPSE Native-First Migration story based on NOG-17 audit metrics and 4 parallel tech-search research streams validating Claude Code 2.1.50 native features as replacements for custom SYNAPSE/UAP machinery. Target: <20ms activation (from ~95ms). Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat(graph-dashboard): multi-level depth expansion with BFS neighborhood exploration [Story GD-12] - Iterative BFS algorithm (getNeighborsAtDepth) with depth-limited graph traversal - Depth selector UI with 1/2/3/All buttons, node count display - Visual differentiation per depth level (opacity, border color, node size) - Keyboard shortcuts (1/2/3/A) for quick depth switching - Fixed QA observations: removed dead code (O-1), Reset button depth cleanup (O-3) - 9 new tests, 93/93 passing. QA gate: PASS (21/21 AC) Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat(graph-dashboard): node sizing by degree centrality and layout switching [Story GD-13] - Add computeDegrees() for O(E) degree centrality (total, in, out) - Add applySizing() with 10-40px normalization via DataSet batch update - Add switchLayout() with Force/Hierarchical/Circular modes - Fix hierarchical layout by rebuilding network (vis-network limitation) - Dim physics controls when layout != force (risk mitigation) - 12 new tests, 105/105 pass Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat(code-intel): SYNAPSE native-first migration — UAP streamlined, L3-L7 disabled, agent memory [Story NOG-18] - Remove projectStatus loader from UAP (native gitStatus replaces it) - Replace _isGitRepository() execSync (~34ms) with fs.existsSync (~0.05ms) - Add DEFAULT_ACTIVE_LAYERS [0,1,2] — L3-L7 disabled (0 rules produced) - Add SYNAPSE_LEGACY_MODE=true env var for full rollback to 8-layer processing - Create 6 agent MEMORY.md seed files (dev, qa, architect, devops, pm, po) - Create @import bridge rule for agent memory access - Add paths: frontmatter to 3 rules (60% unconditional rule reduction) - Update CLAUDE.md with context management guidance - QA: PASS with descope — 776 tests pass, zero regressions - Deferred: pipeline audit (NOG-19), frontmatter extras (NOG-20), greeting migration (NOG-21) Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat(graph-dashboard): export PNG/JSON and minimap navigation overview [Story GD-14] Add graph export (PNG via canvas toDataURL, JSON with metadata) and minimap panel (200x150px canvas with viewport rectangle, click-to-pan, throttled updates). Fix hierarchical layout via network rebuild pattern. 10 new tests, 115/115 pass. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat(graph-dashboard): category clustering and statistics panel [Story GD-15] Add vis-network clustering by category with toggle, double-click expand, and filter-aware joinCondition. Statistics panel shows node/edge count, graph density, avg degree, and top-5 connected entities with dynamic updates on filter changes. QA PASS 17/17 ACs, 123/123 tests. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs(code-intel): pipeline audit validation — benchmarks and QA gate [Story NOG-19] - Story NOG-19: Tasks 1-4 completed, AC 12/12 PASS (2 documented deviations) - UAP improvements: dev 79%, qa 93%, architect 69%, devops 81%, sm 68%, po 77% - SYNAPSE improvements: p50 47%, p95 33%, rules 70→59 (L3-L7 deactivated) - QA gate: PASS (quality score 100, zero regressions) - core-config.yaml reviewed — no changes needed Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat(code-intel): agent frontmatter validation — hooks, skills, memory sync [Story NOG-20] - Hook enforce-git-push-authority.sh: node-based JSON parsing, fail-closed - Skills equalized: diagnose-synapse for all 10 native agents + role-specific - Agent Memory section added to all 12 command path files - QA gate PASS (95/100), zero regressions - Story NOG-22 (skill discovery) added to backlog Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat(boundary): permission deny rules and toggleable framework protection [Story BM-1] - Create .claude/settings.json with 18 deny rules (L1/L2 core paths) and 5 allow rules (L3/L4 exceptions) - Add boundary.frameworkProtection toggle to core-config.yaml with documentation - Fix .gitignore: change .claude to .claude/* so settings.json can be committed - Add Epic Boundary Mapping with 6 stories (BM-1 through BM-6) - QA gate: PASS (100/100) by Quinn Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * refactor(code-intel): native greeting migration — replace UAP/GreetingBuilder with markdown instructions [Story NOG-21] Replace unified-activation-pipeline.js execution in all 12 agent command files with native markdown instructions for zero-JS agent activation. Native greeting uses gitStatus from system prompt, active story detection, and persona data directly from YAML. UAP preserved as commented fallback. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs(boundary): close story BM-2 — CLAUDE.md boundary section [Story BM-2] Story closed by @po (Pax). QA PASS (Round 2) by @qa (Quinn). All 7 acceptance criteria met. Status: Done. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat(boundary): pre-commit framework guard with dynamic config [Story BM-3] Add pre-commit hook that blocks commits to L1/L2 framework core files. Paths read dynamically from core-config.yaml boundary.protected/exceptions (single source of truth). Includes globToRegex converter, fallback safety, and Windows backslash normalization. 35/35 tests passed, QA PASS Round 2. Files: - bin/utils/framework-guard.js (new) — guard script with dynamic config - .husky/pre-commit (modified) — guard runs before manifest check - .aios-core/core-config.yaml (modified) — boundary.protected + exceptions lists Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs(code-intel): QA review NOG-22 — expand checklist-runner to all 8 agents [Story NOG-22] QA gate PASS (100/100). Added checklist-runner skill to pm, po, sm, data-engineer, ux agents to match the 8-agent execute-checklist usage pattern identified in the research. Story QA Results section updated. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat(boundary): config schema enrichment and template customization surface [Story BM-4] Enrich L1/L2 JSON schemas with all documented keys, add template override consumer helper, refactor deny rules for granular framework protection, and create config override guide documentation. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs(code-intel): close stories NOG-8, NOG-17→NOG-22 — epic 25/25 complete Updated status to Done for 7 stories completing the NOGIC epic. All QA gates passed, zero regressions confirmed. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs(code-intel): post-migration validation & benchmark — QA PASS 100/100 [Story NOG-23] - Pipeline-audit rerun: @dev -17%, @architect -74%, zero regressions - Agent smoke test: 10/10 agents validated (memory, hooks, skills) - Fresh install simulation: 3 key agents verified in isolated env - Test suite: 275 pass, 0 new failures, validate:agents 0 errors - Created MEMORY.md for analyst, sm, data-engineer, ux agents Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * chore: sync boundary-mapping stories, agent configs, rules and utilities - Boundary mapping stories BM-1,3,4,5 status updates - Agent frontmatter updates (dev, devops, qa) with memory/skills sync - New rules: agent-authority, coderabbit-integration, ids-principles, story-lifecycle, workflow-execution - Entity registry enrichment, CLAUDE.md updates - New utility: detect-fsmonitor.js, performance-tips docs Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat(boundary): entity registry layer classification L1-L4 [Story BM-5] Add classifyLayer() pure function that assigns boundary layers to all 715 registry entities. L1=Core(201), L2=Templates(504), L3=Config(10). Integrated with populate-entity-registry.js and registry-updater.js. 40 tests (31 unit + 9 integration), zero regression. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat(boundary): agent memory lifecycle and CLAUDE.md ownership annotations [Story BM-6] Structured MEMORY.md format (Active Patterns / Promotion Candidates / Archived), migrated all 10 agent files, annotated 14 CLAUDE.md sections with ownership comments, created memory-audit-checklist. Epic Boundary Mapping complete (6/6 stories, 21 points). Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * chore: force-track gitignored .claude files for worktree compatibility Files that were created after .gitignore blocked .claude/ directory were never tracked, causing worktrees to miss skills, agents, and agent memory. Force-added 11 files: - 3 skills: tech-search, checklist-runner, coderabbit-review - 5 agents: brad-frost, dan-mall, dave-malouf, nano-banana-generator, squad-chief - 2 agent memories: aios-po, aios-qa Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat(token-opt): unified tool registry — 34 tools, 10 profiles, 5 bindings [Story TOK-1] - Create .aios-core/data/tool-registry.yaml with 3-Tier Tool Mesh (Always/Deferred/External) - 12 Tier 1 (native), 17 Tier 2 (agent/deferred), 5 Tier 3 (MCP external) tools cataloged - 10 agent profiles with always_loaded/frequently_used/deferred arrays - 5 task bindings mapped to real tasks in .aios-core/development/tasks/ - Squad override pattern documented with example at squads/_example/tool-overrides.yaml - QA PASS 21/21 acceptance criteria verified Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs(token-opt): baseline metrics & full epic token-optimization setup [Story TOK-1.5] - TOK-1.5: baseline token measurements for 4 workflows (SDC, QA Loop, Spec Pipeline, Interactive) - Framework overhead: 26,143 tokens before user interaction - Adjustment factor 0.75 (30 tools vs Anthropic 50+ benchmark) - Revised targets: conservative 25-35%, ceiling 35-45% - QA PASS 15/15 ACs, variance corrected to CV method - Epic INDEX, blueprint, codex analysis, handoffs, and all 8 story drafts included - TOK-1 status updated to Done Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat(doctor): rewrite aios doctor with 12 modular checks, --fix, --json, --dry-run [Story INS-4.1] - Fix contract bug: runDoctor(options) now properly receives and uses options object - 12 modular check modules in .aios-core/core/doctor/checks/ (settings-json, rules-files, agent-memory, entity-registry, git-hooks, core-config, claude-md, ide-sync, graph-dashboard, code-intel, node-version, npm-packages) - Text and JSON output formatters with summary line - Fix handler with dry-run support for auto-correcting WARN/FAIL items - Boundary path comparison: settings-json validates deny rules cover core-config protected paths - 40 tests passing (28 unit + 12 integration) - Epic INS-4 (Installation Health) setup with 8 stories drafted Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat(token-opt): capability-aware deferred loading with 3-level fallback [Story TOK-2] Implement runtime capability detection (Tool Search, MCP servers, Docker Gateway) with ADR-7 strategy hierarchy: tool-search-auto > mcp-discipline > claudemd-guidance. 18/18 ACs pass. QA gate: PASS. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat(boundary): deterministic settings.json generator from core-config boundary [Story INS-4.2] Generator at .aios-core/infrastructure/scripts/generate-settings-json.js reads boundary config from core-config.yaml and produces idempotent .claude/settings.json with deny/allow rules. Includes path traversal validation, frameworkProtection toggle, and user section preservation. 12 unit tests, QA gate PASS. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs(installation-health): close INS-4.2, approve INS-4.3 with validation fixes - INS-4.2: marked Done in INDEX, updated DoD checkboxes - INS-4.3: fixed Gap #13 accuracy (hooks copy works, registration is the bug), rewrote AC4/Task 5, status Draft → Approved - INDEX: updated progress 10/33 pts done Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat(installer): full artifact copy pipeline — skills, commands, hooks, generator wiring [Story INS-4.3] Wire INS-4.2 boundary generator into wizard flow, add copySkillFiles (7 skills), copyExtraCommandFiles (~11 .md files excluding AIOS/agents/), and rewrite createClaudeSettingsLocal to dynamically register ALL .cjs hooks instead of hardcoding synapse-engine only. All copy functions have source===dest guards and graceful degradation via try/catch. 9 unit tests covering real exported functions with _sourceRoot injection for testability. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat(token-opt): PTC batch templates, execution_mode schema, 21-task inventory [Story TOK-3] - Add ptc_eligible:true to 12 Tier 1 native tools, ptc_eligible:false to 5 MCP tools - Annotate 3 tasks with execution_mode:programmatic (qa-gate, validate-agents, spec-research) - Create 3 Bash batch PTC templates (qa-gate, entity-validation, research-aggregation) - Add execution_mode field to task-v3-schema.json (enum: direct|programmatic) - Token comparison: 74.9% avg reduction across 3 workflows (target >= 20%) - Exhaustive PTC candidate inventory: 21 tasks (88+ calls → ~23 batches) - QA Gate: PASS 17/17 ACs Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat(installer): CLAUDE.md template v5 — 4 new AIOS-MANAGED sections [Story INS-4.4] - Add framework-boundary, rules-system, code-intelligence, graph-dashboard sections - Template now has 9 AIOS-MANAGED sections total (5 original + 4 new) - 15 tests: marker presence, content quality, upgrade safety, section order - Close INS-4.3 (Done), update epic INDEX progress (18/33 points) - QA PASS with all ACs verified Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat(token-opt): agent handoff context compaction — 65% reduction in SDC [Story TOK-4A] Rules-based handoff protocol: on agent switch, previous agent persona (~3-5K tokens) compacted to ~379-token artifact. SDC workflow: 18.7K → 6.5K tokens (65.4% reduction). Phase 1 complete (ACs 1-13). Phase 2 (SYNAPSE) deferred pending NOG-18. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat(installer): IDE sync integration via adapter pattern after artifact copy [Story INS-4.5] Calls commandSync and commandValidate programmatically in the installer wizard after skills/commands are copied. Uses adapter pattern (save cwd, chdir to target, finally restore) since both functions read process.cwd() internally. Graceful failure — sync errors log warning and continue install. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat(token-opt): input examples registry + client-layer injection for top-10 tools [Story TOK-4B] - Create mcp-tool-examples.yaml with 10 tools, 23 examples (ADR-4 compliant) - Create tool-examples.md rules for client-layer injection (ADR-5 compliant) - Extend entity-registry with invocationExamples for 5 tool entities - Update populate-entity-registry.js to preserve invocationExamples on re-population - Update CLAUDE.md Tool Selection Guidance with TOK-4B reference Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat(publish): publish safety gate — submodule + file count validation [Story INS-4.10] Prevent incomplete npm publishes by validating pro/ submodule and package file count before publish. Addresses v4.2.14 incident (empty pro/). Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat(installer): entity registry bootstrap on install [Story INS-4.6] - Call populate-entity-registry.js after .aios-core/ copy during install - Sync execution (measured 0.67s on 734 entities, well under 15s threshold) - Three-state outcome: populated/skipped/failed with entity count reporting - 30s timeout guard, try/catch for non-blocking failure - 19 unit tests covering all 5 acceptance criteria - QA PASS: 17/17 AC items verified, 0 new test failures Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat(token-opt): tool usage analytics pipeline with promote/demote engine [Story TOK-5] - collect-tool-usage.js: session-based data collection, schema validation, sanitization (no user content), 30-day retention pruning - generate-optimization-report.js: baseline comparison (static overhead vs dynamic usage), promote/demote recommendations with configurable thresholds - tool-registry.yaml: analytics.thresholds section for promote/demote config - 27 unit tests covering both scripts (schema, retention, comparison, recs) - QA concerns resolved: C1 apples-to-apples comparison, C2 precise demote rate, C3 formal test suite Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat(token-opt): dynamic filtering engine with 3 filter types and SYNAPSE rule [Story TOK-6] Rules-based dynamic filtering for MCP tool responses via SYNAPSE rule + standalone filter utility scripts. Filter configs for 5 tools in tool-registry.yaml (exa, apify, context7, WebFetch, playwright). - content-filter: HTML stripping, entity decoding, token-boundary truncation - schema-filter: JSON field whitelisting with safe array truncation - field-filter: array column projection + row limiting (SQL-like) - index.js: registry-driven dispatcher with YAML fallback - constants.js: shared CHARS_PER_TOKEN constant - SYNAPSE rule: zero-overhead self-filtering instructions - 46 unit tests passing, payload reduction verified (-46%/-81%/-86%) - QA gate: PASS (quality score 100/100) Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat(installer): YAML merger strategy + config smart merge Phase 1 [Story INS-4.7] - Add YamlMerger strategy with target-wins deep merge for .yaml/.yml files - Integrate smart merge into brownfield upgrader for core-config.yaml - Backup + restore safety on merge failure, conflict warnings in report - 26 tests covering merge rules, edge cases, and upgrader integration Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs(token-opt): close TOK-6 and mark Epic Token Optimization complete [Story TOK-6] Story TOK-6 status → Done. Epic INDEX updated: 8/8 stories Done, Definition of Done checkbox marked, Change Log v3.0 added. Epic Token Optimization delivered across 3 waves with payload reduction exceeding all targets (-46% content, -81% schema, -86% field). Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat(doctor): unify health-check task + 3 new checks (skills, commands, hooks) [Story INS-4.8] - Add skills-count, commands-count, hooks-claude-count doctor checks (12→15) - Rewrite health-check.yaml v3.0: delegates to `aios doctor --json` with governance map - Remove *doctor alias from task (avoid confusion with CLI `aios doctor`) - Document core/health-check/ as separate HCS-2 system (not used by task) - Add 15 new tests (46/46 passing) Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs(stories): create story CODEINTEL-RP-001 — Code-Intel RegistryProvider Native provider using Entity Registry (737 entities) as data source for code-intel, implementing 5/8 primitives without MCP dependency. T1 always loaded, PTC-eligible (ADR-3). Backlog item 1740200000001 promoted to story. PO validation: GO (9.6/10). SF-1 and SF-2 applied (YAML safe schema, expanded CodeRabbit section). Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs(epic): close INS-4.8 and mark Epic INS-4 Installation Health complete (9/9 stories, 33 pts) - Story INS-4.8: Status → Done, changelog entries added (QA, DevOps, PO) - Epic INDEX: INS-4.8 Done, DoD all items checked, Epic Status COMPLETE - Wave 3 complete (3/3), all 3 waves done Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix(doctor): update orchestrator tests from 12 to 15 checks [Story INS-4.8] Stale assertions in doctor-orchestrator.test.js still expected 12 checks after INS-4.8 added 3 new ones (skills-count, commands-count, hooks-claude-count). Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat(devops): wire *health-check command and task dependency [Story INS-4.8] - Add health-check command to @devops commands list (visibility: full, quick, key) - Add health-check.yaml to @devops dependencies.tasks - Add to Quick Commands and Guide sections - Sync skill file (.claude/commands/AIOS/agents/devops.md) Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * chore(release): bump version to 4.3.0 5 epics complete: Code Intelligence (NOG), Graph Dashboard (GD), Boundary Mapping (BM), Token Optimization (TOK), Installation Health (INS-4). 82 commits, 51 features, 0 breaking changes. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix: resolve CI failures — lint errors and test drift from NOG-18 merge - Fix no-regex-spaces ESLint errors in capability-detection.js and tool-search-validation.js - Update unified-activation-pipeline tests for NOG-18 loader changes (projectStatus removed) - Update claude-md-ownership test for new TOK-2 section count (5→6 PROJECT-CUSTOMIZED) - Update git-config-detector tests for fs-based _isGitRepository refactor - Fix generate-settings-json test to force frameworkProtection=true - Fix config-resolver tests for schema validation edge cases Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * chore: regenerate manifest and sync IDE command files for CI Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * chore: update entity-registry and regenerate manifest for CI parity Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * chore: sync IDE command files for all IDEs (devops health-check) Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * chore: add review-contributor-pr task, sync github-copilot agent, regen manifest Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat(code-intel): implement RegistryProvider — native T1 code intelligence [Story CODEINTEL-RP-001] Add native RegistryProvider using entity-registry.yaml (737+ entities, 14 categories) as T1 code-intel provider, enabling zero-latency code intelligence without MCP dependency. - Implement 5 core primitives (findDefinition, findReferences, analyzeDependencies, analyzeCodebase, getProjectStats) with lazy loading and mtime-based cache - Add polymorphic isAvailable() to provider interface for detection contract - Refactor _detectProvider() to use provider.isAvailable() instead of mcpCallFn check - Register RegistryProvider first in priority chain (Registry > MCP fallback) - Support entity name disambiguation (35 duplicates) via scoring: exact+type > layer > path - Handle unresolved dependencies (~10.6%) with resolved:false markers and unresolvedCount - Safe YAML parsing (JSON_SCHEMA) and path traversal defense - Add tool-registry.yaml entry (tier:1, ptc_eligible:true, mcp_required:false) - QA gate: PASS (100/100) — all 14 ACs validated, 351 tests passing Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * docs(code-intel): update architecture flowcharts and rewrite doctor check for RegistryProvider - CODE-INTEL-FLOWCHARTS.md v2.0: reflect dual-provider architecture (T1 Registry + T3 MCP) - SYNAPSE-FLOWCHARTS-v3.md v3.1: update Code-Intel status from DESABILITADO to ATIVO - Doctor check rewritten to actually test provider detection (was only checking config string) - Fix entity count: read metadata.entityCount (739) instead of regex (~19) [Story CODEINTEL-RP-001] Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix(installer): v4.3.0 post-release installer fixes and open-source audit [Story INS-4.11] - AC1: copyExtraCommandFiles allowlist prevents private content leak (squads, stories) - AC2: core-config-template includes boundary section with frameworkProtection: true - AC3: generate-settings-json cascade fix (boundary section now present) - AC4: CLAUDE.md template includes Constitution + Sistema de Agentes sections - AC5: hooks-claude-count parses nested Claude Code hooks schema correctly - AC6: ide-sync uses homogeneous .md file comparison on both sides - AC7: 12 agent source files migrated to native greeting (zero JS execution) - AC8: 522/522 tests pass, E2E deferred to post-publish - AC9: SynapseMemoryProvider moved from pro/ to open-source, feature gate removed - Fix: code-intel doctor test rewritten for RegistryProvider (was pre-existing failure) - Regenerated IDE command files for claude-code, codex, gemini (12 agents x 3 IDEs) Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * chore: regenerate manifest after merge with main Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix(manifest): regenerate install-manifest from clean git state The previous manifest was generated with uncommitted local changes (code-intel workflow-chains, agent handoff additions) causing hash mismatches in CI where those changes don't exist. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat(workflow): workflow-aware greeting suggestions & task handoff metadata [Story WIS-16] Add workflow chain data, agent greeting step 5.5 for contextual next-command suggestions, and ## Handoff sections to 21 core tasks for explicit workflow continuation metadata. 40 tests covering schema, resolution, and snapshots. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix(manifest): remove untracked workflow-chains.yaml from manifest File exists locally but is not committed to Git, causing CI validation to fail with "REMOVED FILES" error. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix(manifest): regenerate from clean HEAD state (include workflow-chains) Previous regeneration excluded workflow-chains.yaml (already committed in WIS-16) and had stale entity-registry hash from local modifications. Stash all local changes before regeneration for exact match with CI. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix: address CodeRabbit review issues (9 Major findings) Code robustness: - code-intel-client: try/catch in _detectProvider() for isAvailable() exceptions - hook-runtime: wrap resolveCodeIntel() in try/catch to prevent unhandled rejections - ide-sync doctor check: try/catch on both readdirSync calls Agent docs: - squad-creator: fix stale STEP 4 GreetingBuilder reference, normalize HALT instruction - ux-design-expert: fix stale STEP 4 GreetingBuilder reference - Sync corrected agents to all IDE directories (claude, codex, gemini) Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * chore(manifest): regenerate after IDS hook entity-registry sync Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * chore: sync corrected agent IDE files (npm run sync:ide) Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix: address remaining CodeRabbit Major issues (round 2) - hook-runtime: fix singleton to reset when projectRoot changes - All 12 agents: reorder handoff consumed timing — mark consumed only after STEP 4 displays successfully, not during assembly - Sync all IDE agent copies via npm run sync:ide Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * chore(manifest): regenerate after IDS hook sync Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix(agents): resolve CodeRabbit round 3 — grammar, STEP 4 duplication, handoff exception - Fix "deviance" → "deviation" across 11 agent activation instructions - Change STEP 4 to no-op in squad-creator and ux-design-expert (avoid duplicate greeting) - Add STEP 5.5 handoff activation exception in squad-creator - Sync all 6 IDE targets, regenerate manifest Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix(manifest): regenerate without transient healing backup file The IDS hook created a registry healing backup that was captured by the manifest generator but is gitignored and not present in CI. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
1 parent a58be64 commit 42aec88

File tree

109 files changed

+7780
-1653
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

109 files changed

+7780
-1653
lines changed

.aios-core/core/code-intel/code-intel-client.js

Lines changed: 19 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
'use strict';
22

33
const { CodeGraphProvider } = require('./providers/code-graph-provider');
4+
const { RegistryProvider } = require('./providers/registry-provider');
45

56
// --- Constants (adjustable, not hardcoded magic numbers) ---
67
const CIRCUIT_BREAKER_THRESHOLD = 3;
@@ -51,10 +52,19 @@ class CodeIntelClient {
5152

5253
/**
5354
* Register default providers based on configuration.
55+
* Provider priority: RegistryProvider FIRST (native, T1), then CodeGraphProvider (MCP, T3).
56+
* First provider with isAvailable() === true wins.
5457
* @private
5558
*/
5659
_registerDefaultProviders(options) {
57-
// Code Graph MCP is the primary (and currently only) provider
60+
// RegistryProvider — native, T1, always available when registry exists
61+
const registryProvider = new RegistryProvider({
62+
registryPath: options.registryPath || null,
63+
projectRoot: options.projectRoot || null,
64+
});
65+
this._providers.push(registryProvider);
66+
67+
// Code Graph MCP — T3, available when mcpCallFn is configured
5868
const codeGraphProvider = new CodeGraphProvider({
5969
mcpServerName: options.mcpServerName || 'code-graph',
6070
mcpCallFn: options.mcpCallFn || null,
@@ -74,17 +84,21 @@ class CodeIntelClient {
7484

7585
/**
7686
* Detect and return the first available provider.
87+
* Uses polymorphic isAvailable() — first provider that returns true wins.
7788
* @returns {import('./providers/provider-interface').CodeIntelProvider|null}
7889
* @private
7990
*/
8091
_detectProvider() {
8192
if (this._activeProvider) return this._activeProvider;
8293

8394
for (const provider of this._providers) {
84-
// A provider is considered "available" if it has a configured mcpCallFn
85-
if (provider.options && typeof provider.options.mcpCallFn === 'function') {
86-
this._activeProvider = provider;
87-
return provider;
95+
try {
96+
if (typeof provider.isAvailable === 'function' && provider.isAvailable()) {
97+
this._activeProvider = provider;
98+
return provider;
99+
}
100+
} catch (_err) {
101+
// Provider threw during availability check — treat as unavailable
88102
}
89103
}
90104

Lines changed: 186 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,186 @@
1+
'use strict';
2+
3+
const path = require('path');
4+
const { RegistryProvider } = require('./providers/registry-provider');
5+
6+
/** Cached provider instance (survives across hook invocations in same process). */
7+
let _provider = null;
8+
let _providerRoot = null;
9+
10+
/**
11+
* Get or create a RegistryProvider singleton.
12+
* Resets if projectRoot changes between calls.
13+
* @param {string} projectRoot - Project root directory
14+
* @returns {RegistryProvider}
15+
*/
16+
function getProvider(projectRoot) {
17+
if (!_provider || _providerRoot !== projectRoot) {
18+
_provider = new RegistryProvider({ projectRoot });
19+
_providerRoot = projectRoot;
20+
}
21+
return _provider;
22+
}
23+
24+
/**
25+
* Resolve code intelligence context for a file being written/edited.
26+
*
27+
* Queries RegistryProvider for:
28+
* - Entity definition (path, layer, purpose, type)
29+
* - References (files that use this entity)
30+
* - Dependencies (entities this file depends on)
31+
*
32+
* @param {string} filePath - Absolute or relative path to the target file
33+
* @param {string} cwd - Project root / working directory
34+
* @returns {{ entity: Object|null, references: Array|null, dependencies: Object|null }|null}
35+
*/
36+
async function resolveCodeIntel(filePath, cwd) {
37+
if (!filePath || !cwd) return null;
38+
39+
try {
40+
const provider = getProvider(cwd);
41+
if (!provider.isAvailable()) return null;
42+
43+
// Normalize to relative path (registry uses relative paths)
44+
let relativePath = filePath;
45+
if (path.isAbsolute(filePath)) {
46+
relativePath = path.relative(cwd, filePath).replace(/\\/g, '/');
47+
} else {
48+
relativePath = filePath.replace(/\\/g, '/');
49+
}
50+
51+
// Run all three queries in parallel
52+
const [definition, references, dependencies] = await Promise.all([
53+
provider.findDefinition(relativePath),
54+
provider.findReferences(relativePath),
55+
provider.analyzeDependencies(relativePath),
56+
]);
57+
58+
// Treat empty dependency graph as no data
59+
const hasUsefulDeps = dependencies && dependencies.nodes && dependencies.nodes.length > 0;
60+
61+
// If nothing found at all, try searching by the file basename
62+
if (!definition && !references && !hasUsefulDeps) {
63+
const basename = path.basename(relativePath, path.extname(relativePath));
64+
const fallbackDef = await provider.findDefinition(basename);
65+
if (!fallbackDef) return null;
66+
67+
const [fallbackRefs, fallbackDeps] = await Promise.all([
68+
provider.findReferences(basename),
69+
provider.analyzeDependencies(basename),
70+
]);
71+
72+
return {
73+
entity: fallbackDef,
74+
references: fallbackRefs,
75+
dependencies: fallbackDeps,
76+
};
77+
}
78+
79+
return {
80+
entity: definition,
81+
references,
82+
dependencies,
83+
};
84+
} catch (_err) {
85+
// Guard against provider exceptions to avoid unhandled rejections in hook runtime
86+
return null;
87+
}
88+
}
89+
90+
/**
91+
* Format code intelligence data as XML for injection into Claude context.
92+
*
93+
* @param {Object|null} intel - Result from resolveCodeIntel()
94+
* @param {string} filePath - Target file path (for display)
95+
* @returns {string|null} XML string or null if no data
96+
*/
97+
function formatAsXml(intel, filePath) {
98+
if (!intel) return null;
99+
100+
const { entity, references, dependencies } = intel;
101+
102+
// At least one piece of data must exist
103+
if (!entity && !references && !dependencies) return null;
104+
105+
const lines = ['<code-intel-context>'];
106+
lines.push(` <target-file>${escapeXml(filePath)}</target-file>`);
107+
108+
// Entity definition
109+
if (entity) {
110+
lines.push(' <existing-entity>');
111+
if (entity.file) lines.push(` <path>${escapeXml(entity.file)}</path>`);
112+
if (entity.context) lines.push(` <purpose>${escapeXml(entity.context)}</purpose>`);
113+
lines.push(' </existing-entity>');
114+
}
115+
116+
// References
117+
if (references && references.length > 0) {
118+
// Deduplicate by file path
119+
const uniqueRefs = [];
120+
const seen = new Set();
121+
for (const ref of references) {
122+
if (ref.file && !seen.has(ref.file)) {
123+
seen.add(ref.file);
124+
uniqueRefs.push(ref);
125+
}
126+
}
127+
128+
lines.push(` <referenced-by count="${uniqueRefs.length}">`);
129+
for (const ref of uniqueRefs.slice(0, 15)) {
130+
const ctx = ref.context ? ` context="${escapeXml(ref.context)}"` : '';
131+
lines.push(` <ref file="${escapeXml(ref.file)}"${ctx} />`);
132+
}
133+
if (uniqueRefs.length > 15) {
134+
lines.push(` <!-- ...and ${uniqueRefs.length - 15} more -->`);
135+
}
136+
lines.push(' </referenced-by>');
137+
}
138+
139+
// Dependencies
140+
if (dependencies && dependencies.nodes && dependencies.nodes.length > 1) {
141+
// First node is the target itself, rest are dependencies
142+
const depNodes = dependencies.nodes.slice(1);
143+
lines.push(` <dependencies count="${depNodes.length}">`);
144+
for (const dep of depNodes.slice(0, 10)) {
145+
const layer = dep.layer ? ` layer="${dep.layer}"` : '';
146+
lines.push(` <dep name="${escapeXml(dep.name)}"${layer} />`);
147+
}
148+
if (depNodes.length > 10) {
149+
lines.push(` <!-- ...and ${depNodes.length - 10} more -->`);
150+
}
151+
lines.push(' </dependencies>');
152+
}
153+
154+
lines.push('</code-intel-context>');
155+
return lines.join('\n');
156+
}
157+
158+
/**
159+
* Escape special XML characters.
160+
* @param {string} str
161+
* @returns {string}
162+
*/
163+
function escapeXml(str) {
164+
if (!str) return '';
165+
return String(str)
166+
.replace(/&/g, '&amp;')
167+
.replace(/</g, '&lt;')
168+
.replace(/>/g, '&gt;')
169+
.replace(/"/g, '&quot;');
170+
}
171+
172+
/**
173+
* Reset cached provider (for testing).
174+
*/
175+
function _resetForTesting() {
176+
_provider = null;
177+
_providerRoot = null;
178+
}
179+
180+
module.exports = {
181+
resolveCodeIntel,
182+
formatAsXml,
183+
escapeXml,
184+
getProvider,
185+
_resetForTesting,
186+
};

.aios-core/core/code-intel/index.js

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ const { CodeIntelClient } = require('./code-intel-client');
44
const { CodeIntelEnricher } = require('./code-intel-enricher');
55
const { CodeIntelProvider, CAPABILITIES } = require('./providers/provider-interface');
66
const { CodeGraphProvider, TOOL_MAP } = require('./providers/code-graph-provider');
7+
const { RegistryProvider } = require('./providers/registry-provider');
78

89
// Singleton client instance (lazily initialized)
910
let _defaultClient = null;
@@ -127,6 +128,7 @@ module.exports = {
127128
CodeIntelEnricher,
128129
CodeIntelProvider,
129130
CodeGraphProvider,
131+
RegistryProvider,
130132

131133
// Constants
132134
CAPABILITIES,

.aios-core/core/code-intel/providers/code-graph-provider.js

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,14 @@ class CodeGraphProvider extends CodeIntelProvider {
2929
this._mcpServerName = options.mcpServerName || 'code-graph';
3030
}
3131

32+
/**
33+
* Code Graph provider is available when mcpCallFn is configured.
34+
* @returns {boolean}
35+
*/
36+
isAvailable() {
37+
return typeof this.options.mcpCallFn === 'function';
38+
}
39+
3240
/**
3341
* Execute an MCP tool call via the configured server.
3442
* This method is the single point of MCP communication — all capabilities route through here.

.aios-core/core/code-intel/providers/provider-interface.js

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,15 @@ class CodeIntelProvider {
1414
this.options = options;
1515
}
1616

17+
/**
18+
* Check if this provider is available and can serve requests.
19+
* Subclasses MUST override this to indicate availability.
20+
* @returns {boolean}
21+
*/
22+
isAvailable() {
23+
return false;
24+
}
25+
1726
/**
1827
* Locate the definition of a symbol.
1928
* @param {string} symbol - Symbol name to find

0 commit comments

Comments
 (0)