project-athena 0.1.0
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/LICENSE +21 -0
- package/README.md +247 -0
- package/dist/cli.js +8614 -0
- package/dist/cli.js.map +1 -0
- package/dist/web/assets/Editor-DmFaONG7.js +39 -0
- package/dist/web/assets/_basePickBy-QJXUw_pr.js +1 -0
- package/dist/web/assets/_baseUniq-DR4vVjyC.js +1 -0
- package/dist/web/assets/abnfDiagram-O67JEVCF-BEaDGLKl.js +1 -0
- package/dist/web/assets/arc-DgcGdgmL.js +1 -0
- package/dist/web/assets/architecture-7GRP2DOG-CHNxu4zI.js +1 -0
- package/dist/web/assets/architectureDiagram-NJMV4G6O-Cr_YqU4C.js +36 -0
- package/dist/web/assets/array-BifhSqXX.js +1 -0
- package/dist/web/assets/blockDiagram-BEXU5L5S-NA64lNxM.js +140 -0
- package/dist/web/assets/c4Diagram-YGBWAQC7-C9OZTI8T.js +38 -0
- package/dist/web/assets/channel-D_T5GGJX.js +1 -0
- package/dist/web/assets/chunk-2Q5K7J3B-C1jixKkw.js +1 -0
- package/dist/web/assets/chunk-3FUC2YCW-PivwegVV.js +2 -0
- package/dist/web/assets/chunk-5DYCD2WN-DH_dVKgx.js +1 -0
- package/dist/web/assets/chunk-5VM5RSS4-ZNzvKenW.js +15 -0
- package/dist/web/assets/chunk-742MDFTN-DTR6iTOw.js +1 -0
- package/dist/web/assets/chunk-7INBJB4K-XeJOzIDQ.js +62 -0
- package/dist/web/assets/chunk-7M6MHVWA-Bn-cXg0l.js +213 -0
- package/dist/web/assets/chunk-7PRAP22T-CPe5zfLc.js +1 -0
- package/dist/web/assets/chunk-DUW6YSOI-Dgx8z5s3.js +1 -0
- package/dist/web/assets/chunk-FOHPRMQF-DzxwRta7.js +161 -0
- package/dist/web/assets/chunk-GTNCS2PH-DSn-mpqy.js +88 -0
- package/dist/web/assets/chunk-GWA4HPMP-DE4DJkth.js +1 -0
- package/dist/web/assets/chunk-J5ZVWO5B-oDCd-gWO.js +1 -0
- package/dist/web/assets/chunk-JWPE2WC7-DVXcaiue.js +1 -0
- package/dist/web/assets/chunk-MBY4JIJT-9uaOqseW.js +72 -0
- package/dist/web/assets/chunk-NETBCI7D-bxqe7jPe.js +1 -0
- package/dist/web/assets/chunk-O7XYJQB3-CjZQSnt8.js +126 -0
- package/dist/web/assets/chunk-UA2S7LBM-BfYbPxwY.js +1 -0
- package/dist/web/assets/chunk-WEXAMYUT-CT8bG5L7.js +1 -0
- package/dist/web/assets/chunk-XXDRQBXY-BvKO0v-W.js +1 -0
- package/dist/web/assets/chunk-Y2CYZVJY-DsF7k-Jl.js +1 -0
- package/dist/web/assets/chunk-Z7XXMR3K-CHWuLoFG.js +10 -0
- package/dist/web/assets/chunk-ZIGJFQKS-C6SOqBs6.js +2 -0
- package/dist/web/assets/classDiagram-v2-NBCMYWYE-CrSxkUNF.js +217 -0
- package/dist/web/assets/cose-bilkent-JH36ORCC-COXSdE6a.js +1 -0
- package/dist/web/assets/cynefin-OW5HDTMX-CMbTYwga.js +1 -0
- package/dist/web/assets/cynefinDiagram-VND7K2PF-B8wb03CF.js +62 -0
- package/dist/web/assets/cytoscape.esm-Yq6u8L66.js +321 -0
- package/dist/web/assets/dagre-6A5THRUB-Bz-BHtjW.js +4 -0
- package/dist/web/assets/defaultLocale-BFoDCU3G.js +1 -0
- package/dist/web/assets/diagram-22UHCM2B-C9M-mcex.js +200 -0
- package/dist/web/assets/diagram-3UASUU5V-q18RgATq.js +24 -0
- package/dist/web/assets/diagram-ATOU4E4O-zywdDXPc.js +3 -0
- package/dist/web/assets/diagram-CDSNMT55-BGMdofKO.js +30 -0
- package/dist/web/assets/diagram-MLGK6HIB-BdT0J6Xl.js +24 -0
- package/dist/web/assets/diagram-MPIPVDR6-BXdFmdOp.js +41 -0
- package/dist/web/assets/dist-B_J_HbC0.js +1 -0
- package/dist/web/assets/ebnfDiagram-ZINNZB2B-B7Mz8zd0.js +1 -0
- package/dist/web/assets/elk-276RUBZZ-CQ4lVw-r.js +27 -0
- package/dist/web/assets/erDiagram-OPXOYQCR-DmmZBLvC.js +99 -0
- package/dist/web/assets/eventmodeling-NTZA5JFV-BgPhBkRf.js +1 -0
- package/dist/web/assets/flowDiagram-KWPJA3E3-C3wNriu7.js +1 -0
- package/dist/web/assets/ganttDiagram-FUAMR5RP-B0egPzgH.js +292 -0
- package/dist/web/assets/gitGraph-4MIJSDKK-BdShI4JY.js +1 -0
- package/dist/web/assets/gitGraphDiagram-X574FWY7-jwG6nUmP.js +106 -0
- package/dist/web/assets/graphlib-C9Tl7QrK.js +1 -0
- package/dist/web/assets/index-BSiW3yI1.js +45 -0
- package/dist/web/assets/index-DKE3ojTe.css +1 -0
- package/dist/web/assets/info-A6RAGUB7-Hm3KO-lX.js +1 -0
- package/dist/web/assets/infoDiagram-VRGFBTTK-CdcggvNW.js +2 -0
- package/dist/web/assets/init-C-OQMol4.js +1 -0
- package/dist/web/assets/ishikawaDiagram-OU5B5YK6-C8x3tV6X.js +70 -0
- package/dist/web/assets/journeyDiagram-ZHPQQLJL-CLXIkiwl.js +139 -0
- package/dist/web/assets/kanban-definition-PNTS6WVX-P94klDAy.js +89 -0
- package/dist/web/assets/katex-ZlcWpGUi.js +257 -0
- package/dist/web/assets/line-DtGZCXZs.js +1 -0
- package/dist/web/assets/linear-BUnzfXgk.js +1 -0
- package/dist/web/assets/mermaid-parser.core-Du2mcMMx.js +7 -0
- package/dist/web/assets/mermaid.core-B4zgSyXF.js +44 -0
- package/dist/web/assets/mindmap-definition-NLK3R4M7-C0EF7lWr.js +96 -0
- package/dist/web/assets/ordinal-BDEzSJ7C.js +1 -0
- package/dist/web/assets/packet-AYTQ26CC-SJ1tKR5t.js +1 -0
- package/dist/web/assets/path-fybaL0A-.js +1 -0
- package/dist/web/assets/pegDiagram-GJSIUBJH-Dek_S7Z0.js +1 -0
- package/dist/web/assets/pie-WAS4IAKB-C0wgWLu4.js +1 -0
- package/dist/web/assets/pieDiagram-5QR66LMP-Dy1jV_P-.js +39 -0
- package/dist/web/assets/quadrantDiagram-O4NWA36T-Df6Jl4OG.js +7 -0
- package/dist/web/assets/radar-RG4KPBEZ-BCtk017a.js +1 -0
- package/dist/web/assets/railroad-74A4TZTK-_ZAooQok.js +1 -0
- package/dist/web/assets/railroad-abnf-HS5TGJTU-Bacbbg7g.js +1 -0
- package/dist/web/assets/railroad-ebnf-LZEXJU2U-Cb23oOsU.js +1 -0
- package/dist/web/assets/railroad-peg-WCYAUIDC-EPh5LyCw.js +1 -0
- package/dist/web/assets/railroadDiagram-XR7U4H2S-DNraioKj.js +1 -0
- package/dist/web/assets/requirementDiagram-PLB6GJNP-C09s8xl6.js +84 -0
- package/dist/web/assets/rolldown-runtime-Dd_uD5pT.js +1 -0
- package/dist/web/assets/rough.esm-Dy-Kn_BL.js +1 -0
- package/dist/web/assets/sankeyDiagram-IPEJSGJF-cwVwdash.js +40 -0
- package/dist/web/assets/sequenceDiagram-PO4LG4MO-Uz6m2m-d.js +169 -0
- package/dist/web/assets/sizeCapture-INFHLROL-3uHXrFqA.js +1 -0
- package/dist/web/assets/src-oBChb5qS.js +1 -0
- package/dist/web/assets/stateDiagram-v2-GCMORJYK-DASY_MN7.js +291 -0
- package/dist/web/assets/swimlanes-2SLR337P-DjbxDj0Z.js +1 -0
- package/dist/web/assets/swimlanesDiagram-TC7HE7FX-Bv90z5my.js +8 -0
- package/dist/web/assets/timeline-definition-EJHVYXUP-Dffxj5AG.js +120 -0
- package/dist/web/assets/treeView-Q6P3EWNA-CXAvuG6A.js +1 -0
- package/dist/web/assets/treemap-WGGIJYW6-D_BSE2GX.js +1 -0
- package/dist/web/assets/usecaseDiagram-POWQR4AR-CKcfbpDB.js +328 -0
- package/dist/web/assets/vennDiagram-UO4OBE2U-DkJknm_I.js +34 -0
- package/dist/web/assets/wardley-WFR3VGLG-Drx6WB-t.js +1 -0
- package/dist/web/assets/wardleyDiagram-VNRHLVJA-fdjd5am3.js +78 -0
- package/dist/web/assets/xychartDiagram-PMCCYNJV-DCWTWMv0.js +7 -0
- package/dist/web/favicon.svg +1 -0
- package/dist/web/index.html +17 -0
- package/package.json +77 -0
package/dist/cli.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/cli/index.ts","../src/services/version.ts","../src/services/errors.ts","../src/cli/ui/term.ts","../src/cli/commands/init.ts","../src/core/state/state.ts","../src/core/config.ts","../src/core/util/fs.ts","../src/agents/registry.ts","../src/core/util/paths.ts","../src/agents/claude-code/adapter.ts","../src/core/knowledge/documents.ts","../src/agents/common/instructions.ts","../src/agents/common/files.ts","../src/core/knowledge/managed-blocks.ts","../src/agents/common/hooks.ts","../src/agents/common/hook-events.ts","../src/agents/cursor/adapter.ts","../src/agents/antigravity/adapter.ts","../src/agents/agents-md/adapter.ts","../src/services/pipeline.ts","../src/core/analyzer/analyze.ts","../src/core/fs/walker.ts","../src/core/fs/ignore.ts","../src/core/model/project-model.ts","../src/core/model/fact.ts","../src/core/analyzer/context.ts","../src/core/analyzer/detectors/structure.ts","../src/core/analyzer/detectors/manifests.ts","../src/core/analyzer/catalog.ts","../src/core/analyzer/detectors/dependencies.ts","../src/core/analyzer/detectors/env.ts","../src/core/security/secrets.ts","../src/core/analyzer/detectors/infra.ts","../src/core/analyzer/detectors/tests.ts","../src/core/analyzer/detectors/database.ts","../src/core/analyzer/detectors/routes.ts","../src/core/analyzer/detectors/auth.ts","../src/core/analyzer/detectors/entrypoints.ts","../src/core/analyzer/detectors/secrets.ts","../src/core/git/git.ts","../src/core/knowledge/generate.ts","../src/core/knowledge/md.ts","../src/core/knowledge/renderers/project.ts","../src/core/knowledge/renderers/architecture.ts","../src/core/knowledge/renderers/data.ts","../src/core/knowledge/renderers/security.ts","../src/core/knowledge/renderers/quality.ts","../src/core/knowledge/renderers/deployment.ts","../src/core/knowledge/rules-seed.ts","../src/core/model/security-scan.ts","../src/cli/context.ts","../src/services/project.ts","../src/cli/commands/analyze.ts","../src/services/status.ts","../src/core/impact/impact.ts","../src/cli/commands/status.ts","../src/services/doctor.ts","../src/core/knowledge/rules.ts","../src/services/time.ts","../src/services/instance.ts","../src/services/which.ts","../src/services/agent-activity.ts","../src/cli/commands/doctor.ts","../src/services/rules.ts","../src/services/knowledge.ts","../src/cli/commands/rules.ts","../src/cli/commands/clean.ts","../src/cli/commands/open.ts","../src/server/instance.ts","../src/server/app.ts","../src/services/agents.ts","../src/services/overview.ts","../src/services/sync.ts","../src/core/impact/model-diff.ts","../src/services/security.ts","../src/services/review.ts","../src/services/context.ts","../src/core/graph/graph.ts","../src/core/context/context-engine.ts","../src/services/ai.ts","../src/ai/provider.ts","../src/ai/providers.ts","../src/services/watch.ts","../src/server/events.ts","../src/server/security.ts","../src/server/static.ts","../src/server/port.ts","../src/cli/commands/sync.ts","../src/cli/commands/event.ts","../src/cli/commands/activity.ts","../src/cli/commands/security.ts","../src/cli/commands/review.ts","../src/cli/commands/context.ts","../src/cli/commands/ai.ts","../src/mcp/server.ts","../src/cli/commands/mcp.ts","../src/cli/commands/watch.ts","../src/cli/commands/agents.ts"],"sourcesContent":["import { Command, Option } from 'commander';\nimport { ATHENA_VERSION } from '../services/version.js';\nimport { AthenaError, EXIT } from '../services/errors.js';\nimport * as ui from './ui/term.js';\nimport type { GlobalOptions } from './context.js';\nimport { initCommand } from './commands/init.js';\nimport { analyzeCommand } from './commands/analyze.js';\nimport { statusCommand } from './commands/status.js';\nimport { doctorCommand } from './commands/doctor.js';\nimport { rulesAddCommand, rulesDisableCommand, rulesEditCommand, rulesEnableCommand, rulesListCommand, rulesRemoveCommand } from './commands/rules.js';\nimport { cleanCommand } from './commands/clean.js';\nimport { openCommand } from './commands/open.js';\nimport { syncCommand } from './commands/sync.js';\nimport { eventCommand } from './commands/event.js';\nimport { activityCommand } from './commands/activity.js';\nimport { securityCommand } from './commands/security.js';\nimport { reviewCommand } from './commands/review.js';\nimport { architectureCommand, contextCommand, graphCommand } from './commands/context.js';\nimport { aiEnrichCommand, aiStatusCommand } from './commands/ai.js';\nimport { mcpCommand } from './commands/mcp.js';\nimport { watchCommand } from './commands/watch.js';\nimport { agentsAddCommand, agentsListCommand, agentsRemoveCommand } from './commands/agents.js';\n\nconst controller = new AbortController();\nlet interrupted = false;\n\nfunction onSignal(): void {\n if (interrupted) process.exit(EXIT.INTERRUPTED); // second Ctrl+C: exit immediately\n interrupted = true;\n controller.abort(new Error('Interrupted'));\n if (process.stdout.isTTY) process.stdout.write('\\x1b[?25h');\n if (!ui.isJson()) process.stderr.write(`\\n${ui.c.yellow('Interrupted.')} ${ui.dim(ui.getInterruptMessage())}\\n`);\n}\nprocess.on('SIGINT', onSignal);\nprocess.on('SIGTERM', onSignal);\n\nconst PLANNED: Array<{ name: string; description: string; phase: number }> = [\n];\n\nfunction globals(cmd: Command): GlobalOptions {\n return cmd.optsWithGlobals() as GlobalOptions;\n}\n\nfunction run<A extends unknown[]>(fn: (...args: A) => Promise<void | number>) {\n return async (...args: A) => {\n const cmd = args[args.length - 1] as Command;\n const g = globals(cmd);\n ui.setOutputMode({ json: g.json, quiet: g.quiet });\n const code = await fn(...args);\n if (typeof code === 'number') process.exitCode = code;\n };\n}\n\nexport function buildProgram(): Command {\n const program = new Command();\n program\n .name('athena')\n .description('Athena — local-first project intelligence for AI coding agents')\n .version(ATHENA_VERSION, '-v, --version', 'Print the Athena version')\n .addOption(new Option('-C, --cwd <dir>', 'Run as if started in <dir>'))\n .option('--json', 'Machine-readable JSON output')\n .option('-q, --quiet', 'Only print warnings, errors and results')\n .option('--no-color', 'Disable colors (also respects NO_COLOR)')\n .showHelpAfterError('(run `athena --help` for usage)')\n .configureHelp({ sortSubcommands: false });\n\n program\n .command('init')\n .description('Analyze the project and create .athena/ knowledge')\n .option('--agents <list>', 'Agents to configure: comma-separated ids (claude-code, cursor, antigravity, agents-md), \"all\" or \"none\". Default: detected agents + AGENTS.md')\n .option('--no-agents', 'Do not configure any agent integration')\n .option('--dry-run', 'Analyze and show what would be written, without writing')\n .action(\n run(async (cmdOpts: { agents?: string | boolean; dryRun?: boolean }, cmd: Command) => {\n const g = globals(cmd);\n await initCommand({ ...g, agents: typeof cmdOpts.agents === 'string' ? cmdOpts.agents : undefined, noAgents: cmdOpts.agents === false, dryRun: cmdOpts.dryRun, signal: controller.signal });\n }),\n );\n\n program\n .command('analyze')\n .description('Re-analyze the project and refresh generated knowledge (developer edits are preserved)')\n .option('--force', 'Regenerate sections even if they were edited by hand')\n .option('--agents <list>', 'Reconfigure these agent integrations')\n .action(run(async (o: { force?: boolean; agents?: string }, cmd: Command) => analyzeCommand({ ...globals(cmd), ...o, signal: controller.signal })));\n\n program\n .command('sync')\n .description('Review and apply knowledge updates for changes since the last analysis')\n .option('-y, --yes', 'Apply without asking')\n .option('--dry-run', 'Show the plan without writing')\n .option('--check', 'Exit with code 1 if knowledge is out of date (for CI/hooks)')\n .option('--diff', 'Print full diffs of proposed document changes')\n .option('--force', 'Also regenerate sections that were edited by hand')\n .action(run(async (o: { yes?: boolean; dryRun?: boolean; check?: boolean; diff?: boolean; force?: boolean }, cmd: Command) => syncCommand({ ...globals(cmd), ...o, signal: controller.signal })));\n\n program\n .command('watch')\n .description('Watch the project and propose knowledge updates as files change')\n .option('--auto-apply', 'Apply updates automatically instead of proposing them')\n .option('--debounce <ms>', 'Quiet period before checking changes (default 1500)')\n .action(run(async (o: { autoApply?: boolean; debounce?: string }, cmd: Command) => watchCommand({ ...globals(cmd), ...o, signal: controller.signal })));\n\n program\n .command('context <task>')\n .description('Show which knowledge an agent should read for a task (deterministic)')\n .option('--full', 'Print the full context an agent would receive')\n .option('--max-chars <n>', 'Character budget for selected sections')\n .action(run(async (task: string, o: { full?: boolean; maxChars?: string }, cmd: Command) => contextCommand(task, { ...globals(cmd), ...o, signal: controller.signal })));\n\n program\n .command('graph')\n .description('Inspect the project graph (packages, files, routes, entities and their relationships)')\n .option('--build', 'Rebuild the graph from the current code')\n .option('--node <id>', 'Show one node and its relationships')\n .option('--kind <kind>', 'Filter by node kind (package, file, route, entity, framework, command, infra)')\n .option('--search <term>', 'Filter nodes by name or path')\n .action(run(async (o: { build?: boolean; node?: string; kind?: string; search?: string }, cmd: Command) => graphCommand({ ...globals(cmd), ...o, signal: controller.signal })));\n\n program\n .command('architecture')\n .description('Summarize the project graph')\n .action(run(async (_o: unknown, cmd: Command) => architectureCommand({ ...globals(cmd), signal: controller.signal })));\n\n program\n .command('mcp')\n .description('Serve Athena project intelligence over MCP (stdio) for AI agents')\n .option('--allow-write', 'Permit the update_knowledge tool to apply changes (read-only by default)')\n .action(run(async (o: { allowWrite?: boolean }, cmd: Command) => mcpCommand({ ...globals(cmd), ...o, signal: controller.signal })));\n\n const ai = program.command('ai').description('Optional AI provider integration (never required)');\n ai.command('status', { isDefault: true }).description('Show configured and available AI providers').action(run(async (_o: unknown, cmd: Command) => aiStatusCommand(globals(cmd))));\n ai.command('enrich')\n .description('Ask the configured provider for INFERRED suggestions based on your knowledge documents')\n .option('--docs <list>', 'Documents to send (default: project,architecture,database,api)')\n .option('--consent', 'Consent to sending redacted knowledge to a remote provider for this run')\n .option('--dry-run', 'Show exactly what would be sent, and send nothing')\n .action(run(async (o: { docs?: string; consent?: boolean; dryRun?: boolean }, cmd: Command) => aiEnrichCommand({ ...globals(cmd), ...o, signal: controller.signal })));\n\n program\n .command('security')\n .description('Scan dependencies with the audit tools installed for this project, and report secret findings')\n .option('--no-audit', 'Skip dependency audits (report secrets only)')\n .option('--fail-on <severity>', 'Exit 1 when a finding at or above this severity exists (critical, high, moderate, low)')\n .option('--last', 'Show the last scan instead of running a new one')\n .action(run(async (o: { audit?: boolean; failOn?: string; last?: boolean }, cmd: Command) => securityCommand({ ...globals(cmd), noAudit: o.audit === false, failOn: o.failOn, last: o.last, signal: controller.signal })));\n\n program\n .command('review')\n .description('Check the current diff for facts worth reviewing, and list the project rules and checklist')\n .option('--base <ref>', 'Compare against this Git ref instead of the working tree')\n .option('--no-sync', 'Skip the knowledge freshness check')\n .option('--no-fail', 'Always exit 0, even when blockers are found')\n .action(run(async (o: { base?: string; sync?: boolean; fail?: boolean }, cmd: Command) => reviewCommand({ ...globals(cmd), base: o.base, noSync: o.sync === false, noFail: o.fail === false, signal: controller.signal })));\n\n program\n .command('status')\n .description('Show knowledge health and changes since the last analysis')\n .action(run(async (_o: unknown, cmd: Command) => statusCommand({ ...globals(cmd), signal: controller.signal })));\n\n program\n .command('doctor')\n .description('Check the Athena installation, project and integrations')\n .action(run(async (_o: unknown, cmd: Command) => doctorCommand(globals(cmd))));\n\n const rules = program.command('rules').description('List and edit project rules (.athena/rules.md)');\n rules.command('list', { isDefault: true }).description('List rules with their numbers').action(run(async (_o: unknown, cmd: Command) => rulesListCommand(globals(cmd))));\n rules.command('add <text>').description('Add a rule').option('-s, --section <name>', 'Section heading', 'General').action(run(async (text: string, o: { section?: string }, cmd: Command) => rulesAddCommand(text, { ...globals(cmd), ...o })));\n rules.command('edit <number> <text>').description('Replace the text of a rule').action(run(async (n: string, text: string, _o: unknown, cmd: Command) => rulesEditCommand(n, text, globals(cmd))));\n rules.command('enable <number>').description('Enable a rule').action(run(async (n: string, _o: unknown, cmd: Command) => rulesEnableCommand(n, globals(cmd))));\n rules.command('disable <number>').description('Disable a rule without deleting it').action(run(async (n: string, _o: unknown, cmd: Command) => rulesDisableCommand(n, globals(cmd))));\n rules.command('remove <number>').description('Delete a rule').action(run(async (n: string, _o: unknown, cmd: Command) => rulesRemoveCommand(n, globals(cmd))));\n\n const agents = program.command('agents').description('Manage AI agent integrations');\n agents.command('list', { isDefault: true }).description('Show supported agents and integration status').action(run(async (_o: unknown, cmd: Command) => agentsListCommand(globals(cmd))));\n agents.command('add <agents...>').description('Configure integrations (claude-code, cursor, antigravity, agents-md, or \"all\")').action(run(async (names: string[], _o: unknown, cmd: Command) => agentsAddCommand(names, globals(cmd))));\n agents.command('remove <agents...>').description('Remove Athena-managed integration files/blocks').action(run(async (names: string[], _o: unknown, cmd: Command) => agentsRemoveCommand(names, globals(cmd))));\n\n program\n .command('open')\n .description('Start (or reuse) the local web UI and open it in your browser')\n .option('-p, --port <port>', 'Port to bind (default: first free port from 7432)')\n .option('--host <host>', 'Interface to bind (default: 127.0.0.1)')\n .option('--allow-remote', 'Allow binding to a non-loopback interface')\n .option('--no-open', 'Do not launch a browser')\n .option('--no-watch', 'Do not watch the project for changes')\n .action(run(async (o: { port?: string; host?: string; open?: boolean; allowRemote?: boolean; watch?: boolean }, cmd: Command) => openCommand({ ...globals(cmd), ...o, signal: controller.signal })));\n\n program\n .command('activity')\n .description('Show AI agent activity observed through hooks')\n .option('-n, --limit <count>', 'Number of events to show (default 30)')\n .option('--agent <id>', 'Only show events from this agent')\n .action(run(async (o: { limit?: string; agent?: string }, cmd: Command) => activityCommand({ ...globals(cmd), ...o })));\n\n program\n .command('event')\n .description('Record an agent hook event (called by AI coding agents, reads JSON on stdin)')\n .option('--agent <id>', 'Agent that fired the hook')\n .option('--hook <name>', 'Hook event name')\n .option('--athena-hook', 'Marker used to identify Athena-managed hook entries')\n .option('--verbose-errors', 'Print errors to stderr (hooks stay silent by default)')\n .action(\n run(async (o: { agent?: string; hook?: string; verboseErrors?: boolean }, cmd: Command) => {\n const g = globals(cmd);\n await eventCommand({ agent: o.agent, hook: o.hook, cwd: g.cwd, verbose: o.verboseErrors });\n }),\n );\n\n program\n .command('clean')\n .description('Remove .athena/ and Athena agent integrations')\n .option('-y, --yes', 'Skip confirmation')\n .option('--keep-agents', 'Keep agent integration files/blocks')\n .action(run(async (o: { yes?: boolean; keepAgents?: boolean }, cmd: Command) => cleanCommand({ ...globals(cmd), ...o })));\n\n program\n .command('version')\n .description('Print the Athena version')\n .action(run(async (_o: unknown, cmd: Command) => {\n if (globals(cmd).json) ui.json({ version: ATHENA_VERSION, node: process.versions.node, platform: process.platform });\n else ui.line(ATHENA_VERSION);\n }));\n\n for (const p of PLANNED) {\n program\n .command(p.name)\n .description(`${p.description} ${ui.dim(`(planned — Phase ${p.phase})`)}`)\n .allowUnknownOption()\n .allowExcessArguments()\n .action(\n run(async (_o: unknown, cmd: Command) => {\n if (globals(cmd).json) ui.json({ available: false, command: p.name, plannedPhase: p.phase });\n else ui.line(`${ui.c.yellow('Not available yet')} — \\`athena ${p.name}\\` is planned for Phase ${p.phase}.`);\n return EXIT.NOT_AVAILABLE;\n }),\n );\n }\n return program;\n}\n\nasync function main(): Promise<void> {\n const program = buildProgram();\n try {\n await program.parseAsync(process.argv);\n } catch (err) {\n if (process.stdout.isTTY) process.stdout.write('\\x1b[?25h');\n if (controller.signal.aborted) {\n process.exitCode = EXIT.INTERRUPTED;\n return;\n }\n if (err instanceof AthenaError) {\n if (ui.isJson()) ui.json({ error: err.message, hint: err.hint });\n else {\n process.stderr.write(`${ui.c.red(`${ui.sym.err} ${err.message}`)}\\n`);\n if (err.hint) process.stderr.write(` ${ui.dim(err.hint)}\\n`);\n }\n process.exitCode = err.exitCode;\n return;\n }\n process.stderr.write(`${ui.c.red(`${ui.sym.err} Unexpected error: ${(err as Error).message}`)}\\n`);\n if (process.env.ATHENA_DEBUG) process.stderr.write(`${(err as Error).stack}\\n`);\n else process.stderr.write(` ${ui.dim('Set ATHENA_DEBUG=1 for a stack trace. Please report this issue.')}\\n`);\n process.exitCode = EXIT.ERROR;\n }\n}\n\nawait main();\n","import { createRequire } from 'node:module';\n\n/** Must match package.json \"name\" — the version lookup checks it to avoid reading the wrong manifest. */\nexport const PACKAGE_NAME = 'project-athena';\n\nfunction readVersion(): string {\n try {\n const require = createRequire(import.meta.url);\n // dist/cli.js → ../package.json ; src/cli/version.ts (tests) → ../../package.json\n for (const p of ['../package.json', '../../package.json']) {\n try {\n const pkg = require(p) as { name?: string; version?: string };\n if (pkg.name === PACKAGE_NAME && pkg.version) return pkg.version;\n } catch {\n /* try next */\n }\n }\n } catch {\n /* fall through */\n }\n return '0.0.0-unknown';\n}\n\nexport const ATHENA_VERSION = readVersion();\n","export const EXIT = {\n OK: 0,\n ERROR: 1,\n NOT_AVAILABLE: 2,\n NOT_INITIALIZED: 3,\n INTERRUPTED: 130,\n} as const;\n\n/** Error category, mapped to exit codes by the CLI and HTTP statuses by the server. */\nexport type ErrorKind = 'invalid' | 'not-found' | 'conflict' | 'not-initialized' | 'busy' | 'unprocessable' | 'forbidden' | 'internal';\n\n/** An expected, user-facing error with an actionable hint. No stack trace is shown. */\nexport class AthenaError extends Error {\n readonly kind: ErrorKind;\n constructor(\n message: string,\n readonly hint?: string,\n readonly exitCode: number = EXIT.ERROR,\n kind?: ErrorKind,\n /** Structured details safe to return to clients. */\n readonly details?: Record<string, unknown>,\n ) {\n super(message);\n this.name = 'AthenaError';\n this.kind = kind ?? (exitCode === EXIT.NOT_INITIALIZED ? 'not-initialized' : 'invalid');\n }\n}\n\nexport const notFound = (message: string) => new AthenaError(message, undefined, EXIT.ERROR, 'not-found');\nexport const conflict = (message: string, hint?: string, details?: Record<string, unknown>) => new AthenaError(message, hint, EXIT.ERROR, 'conflict', details);\n","import pc from 'picocolors';\n\nconst out = process.stdout;\nconst isTTY = Boolean(out.isTTY) && process.env.TERM !== 'dumb' && !process.env.CI;\nconst unicode = process.platform !== 'win32' || Boolean(process.env.WT_SESSION) || process.env.TERM_PROGRAM === 'vscode' || Boolean(process.env.TERMINAL_EMULATOR);\n\nexport const sym = {\n ok: unicode ? '✓' : '√',\n warn: unicode ? '⚠' : '!',\n err: unicode ? '✗' : '×',\n info: unicode ? '•' : '*',\n dot: unicode ? '●' : '*',\n ring: unicode ? '○' : 'o',\n arrow: unicode ? '→' : '->',\n};\n\nexport const c = pc;\n\nlet quiet = false;\nlet jsonMode = false;\nexport function setOutputMode(opts: { quiet?: boolean; json?: boolean }): void {\n quiet = Boolean(opts.quiet);\n jsonMode = Boolean(opts.json);\n}\nexport const isJson = () => jsonMode;\nexport const isQuiet = () => quiet;\n\nlet interruptMessage = 'No partial knowledge was written.';\nexport const setInterruptMessage = (m: string) => (interruptMessage = m);\nexport const getInterruptMessage = () => interruptMessage;\n\nexport function line(s = ''): void {\n if (jsonMode) return;\n out.write(`${s}\\n`);\n}\nexport function info(s: string): void {\n if (!quiet) line(s);\n}\nexport const ok = (s: string) => line(`${c.green(sym.ok)} ${s}`);\nexport const warn = (s: string) => line(`${c.yellow(sym.warn)} ${s}`);\nexport const fail = (s: string) => line(`${c.red(sym.err)} ${s}`);\nexport const bullet = (s: string) => line(`${c.dim(sym.info)} ${s}`);\nexport const heading = (s: string) => line(c.bold(s));\nexport const dim = (s: string) => c.dim(s);\n\nexport function json(value: unknown): void {\n out.write(`${JSON.stringify(value, null, 2)}\\n`);\n}\n\nexport function banner(): void {\n if (jsonMode || quiet) return;\n const title = 'ATHENA';\n const sub = 'Project Intelligence for AI Coding';\n const w = sub.length + 4;\n const pad = (s: string) => {\n const left = Math.floor((w - s.length) / 2);\n return ' '.repeat(left) + s + ' '.repeat(w - s.length - left);\n };\n if (unicode) {\n line(c.dim(`╭${'─'.repeat(w)}╮`));\n line(`${c.dim('│')}${c.bold(c.cyan(pad(title)))}${c.dim('│')}`);\n line(`${c.dim('│')}${c.dim(pad(sub))}${c.dim('│')}`);\n line(c.dim(`╰${'─'.repeat(w)}╯`));\n } else {\n line(c.bold(c.cyan(title)));\n line(c.dim(sub));\n }\n line();\n}\n\n/** Render a list of paths as a tree under a root label. */\nexport function tree(rootLabel: string, items: string[]): void {\n line(rootLabel);\n items.forEach((item, i) => {\n const last = i === items.length - 1;\n line(`${c.dim(unicode ? (last ? '└── ' : '├── ') : last ? '`-- ' : '|-- ')}${item}`);\n });\n}\n\nexport interface Spinner {\n update(text: string): void;\n succeed(text?: string): void;\n warn(text?: string): void;\n fail(text?: string): void;\n stop(): void;\n}\n\nconst FRAMES = unicode ? ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'] : ['-', '\\\\', '|', '/'];\n\nexport function spinner(text: string): Spinner {\n let current = text;\n let timer: NodeJS.Timeout | null = null;\n let frame = 0;\n const clear = () => {\n if (isTTY) out.write('\\r\\x1b[2K');\n };\n const done = (symbol: string, msg?: string, suppressible = false) => {\n const wasSpinning = timer !== null;\n if (timer) clearInterval(timer);\n timer = null;\n if (jsonMode) return;\n if (wasSpinning) {\n clear();\n out.write('\\x1b[?25h');\n }\n if (!(suppressible && quiet)) line(`${symbol} ${msg ?? current}`);\n };\n if (!jsonMode && !quiet && isTTY) {\n out.write('\\x1b[?25l');\n timer = setInterval(() => {\n clear();\n out.write(`${c.cyan(FRAMES[(frame = (frame + 1) % FRAMES.length)]!)} ${current}`);\n }, 80);\n timer.unref();\n }\n return {\n update(t) {\n current = t;\n },\n succeed: (msg) => done(c.green(sym.ok), msg, true),\n warn: (msg) => done(c.yellow(sym.warn), msg),\n fail: (msg) => done(c.red(sym.err), msg),\n stop() {\n if (!timer) return;\n clearInterval(timer);\n timer = null;\n clear();\n out.write('\\x1b[?25h');\n },\n };\n}\n\nexport function relativeTime(iso: string): string {\n const ms = Date.now() - Date.parse(iso);\n if (Number.isNaN(ms)) return 'unknown';\n const s = Math.round(ms / 1000);\n if (s < 60) return `${s}s ago`;\n const m = Math.round(s / 60);\n if (m < 60) return `${m} min ago`;\n const h = Math.round(m / 60);\n if (h < 48) return `${h} h ago`;\n return `${Math.round(h / 24)} days ago`;\n}\n","import path from 'node:path';\nimport { readState } from '../../core/state/state.js';\nimport { resolveAdapters, ADAPTERS } from '../../agents/registry.js';\nimport type { AgentAdapter } from '../../core/agents/adapter.js';\nimport { runPipeline, type PipelineResult } from '../../services/pipeline.js';\nimport { resolveCwd, type GlobalOptions } from '../context.js';\nimport { AthenaError } from '../../services/errors.js';\nimport * as ui from '../ui/term.js';\n\nexport interface InitOptions extends GlobalOptions {\n agents?: string;\n noAgents?: boolean;\n dryRun?: boolean;\n signal?: AbortSignal;\n}\n\nexport function parseAgentsOption(value: string | undefined, disabled: boolean | undefined): AgentAdapter[] | undefined {\n if (disabled) return [];\n if (value === undefined) return undefined;\n if (value.trim().toLowerCase() === 'all') return [...ADAPTERS];\n if (value.trim().toLowerCase() === 'none') return [];\n try {\n return resolveAdapters(value.split(','));\n } catch (err) {\n throw new AthenaError((err as Error).message);\n }\n}\n\nexport async function initCommand(opts: InitOptions): Promise<void> {\n const root = await resolveCwd(opts);\n const existing = await readState(path.join(root, '.athena'));\n if (existing.kind === 'ok') {\n throw new AthenaError('Athena is already initialized in this project.', 'Run `athena analyze` to refresh knowledge, or `athena clean` to start over.');\n }\n const agents = parseAgentsOption(opts.agents, opts.noAgents);\n\n ui.banner();\n const result = await runWithProgress(root, { mode: 'init', dryRun: opts.dryRun, agents, signal: opts.signal });\n\n if (ui.isJson()) {\n ui.json(summarize(result, root, Boolean(opts.dryRun)));\n return;\n }\n printSummary(result, Boolean(opts.dryRun), 'init');\n}\n\nexport async function runWithProgress(root: string, o: { mode: 'init' | 'analyze'; dryRun?: boolean; force?: boolean; agents?: AgentAdapter[]; signal?: AbortSignal }): Promise<PipelineResult> {\n const sp = ui.spinner('Scanning project files...');\n const started = Date.now();\n try {\n const result = await runPipeline({\n root,\n mode: o.mode,\n dryRun: o.dryRun,\n force: o.force,\n agents: o.agents,\n signal: o.signal,\n onStage: (stage) => {\n const labels: Record<string, string> = { analyze: 'Scanning project files...', scan: 'Scanning project files...', detect: 'Detecting technologies, schema, routes and infrastructure...', git: 'Reading Git metadata...', finalize: 'Redacting and validating...', write: 'Writing knowledge...', agents: 'Configuring AI agents...' };\n sp.update(labels[stage] ?? stage);\n },\n });\n sp.succeed(`Analyzed ${result.analysis.model.stats.filesScanned} files in ${((Date.now() - started) / 1000).toFixed(1)}s`);\n return result;\n } catch (err) {\n sp.stop();\n throw err;\n }\n}\n\nfunction detectionLine(label: string, count: number, detail?: string): void {\n if (count > 0) ui.ok(`${label}${detail ? ui.dim(` — ${detail}`) : ''}`);\n else ui.line(`${ui.c.dim(ui.sym.ring)} ${ui.c.dim(`${label} — not detected`)}`);\n}\n\nexport function printSummary(result: PipelineResult, dryRun: boolean, mode: 'init' | 'analyze'): void {\n const m = result.analysis.model;\n if (ui.isQuiet()) {\n for (const w of m.warnings) ui.warn(w);\n for (const n of result.notes) ui.warn(n);\n for (const d of result.docs.filter((x) => x.preservedModified.length)) ui.warn(`${d.file}: kept your edits in ${d.preservedModified.join(', ')}`);\n const changed = result.docs.filter((d) => d.status !== 'unchanged').map((d) => d.file);\n ui.line(dryRun ? 'Dry run: nothing written.' : changed.length ? `Updated: ${changed.join(', ')}` : 'Knowledge up to date.');\n return;\n }\n ui.line();\n const uniq = (xs: string[]) => [...new Set(xs)];\n detectionLine('Project', m.stats.filesScanned, `${m.name}${m.languages[0] ? ` · ${m.languages.slice(0, 3).map((l) => l.name).join(', ')}` : ''}`);\n detectionLine('Frameworks', m.frameworks.length, uniq(m.frameworks.map((f) => f.name)).slice(0, 5).join(', '));\n detectionLine('Workspace', m.workspace.isMonorepo ? m.workspace.packages.length : 0, m.workspace.isMonorepo ? `monorepo · ${m.workspace.packages.length} packages` : undefined);\n detectionLine('Database', m.databases.length + m.dbEntities.length, `${uniq(m.databases.map((d) => d.name)).slice(0, 3).join(', ')}${m.dbEntities.length ? ` · ${m.dbEntities.length} entities` : ''}`);\n detectionLine('API', m.routes.length + m.apiSpecs.length, `${m.routes.length} route${m.routes.length === 1 ? '' : 's'}${m.apiSpecs.length ? ` · ${m.apiSpecs.length} specs` : ''}`);\n detectionLine('Authentication', m.auth.length, uniq(m.auth.map((a) => a.name)).slice(0, 3).join(', '));\n detectionLine('Testing', m.tests.frameworks.length + m.tests.testFileCount, `${uniq(m.tests.frameworks.map((f) => f.name)).slice(0, 3).join(', ')} · ${m.tests.testFileCount} test files`);\n detectionLine('Deployment', m.containers.dockerfiles.length + m.ci.length + m.infrastructure.length, [m.containers.dockerfiles.length ? 'Docker' : '', m.ci.length ? uniq(m.ci.map((j) => j.system)).join(', ') : '', ...uniq(m.infrastructure.filter((i) => i.kind === 'hosting').map((i) => i.name))].filter(Boolean).slice(0, 4).join(', '));\n if (m.security.secrets.length) ui.warn(`Security — ${m.security.secrets.length} potential hardcoded secret(s); see .athena/security.md (values not stored)`);\n else ui.ok(`Security${ui.dim(' — no likely secrets matched')}`);\n\n if (m.warnings.length) {\n ui.line();\n for (const w of m.warnings.slice(0, 5)) ui.warn(ui.c.yellow(w));\n if (m.warnings.length > 5) ui.line(ui.dim(` +${m.warnings.length - 5} more warnings (see .athena/project.md)`));\n }\n\n ui.line();\n if (dryRun) {\n ui.heading('Dry run — nothing was written.');\n ui.line('Would create .athena/ with 12 knowledge files, model.json and state.json.');\n for (const { adapter, changes } of result.agentChanges) for (const ch of changes) ui.bullet(`${adapter.displayName}: would ${ch.action} ${ch.path}`);\n return;\n }\n\n if (mode === 'init') {\n ui.tree(ui.c.bold('.athena/'), [...result.docs.map((d) => d.file), 'model.json', 'state.json']);\n } else {\n const changed = result.docs.filter((d) => d.status !== 'unchanged');\n if (changed.length) {\n ui.heading('Knowledge updated:');\n for (const d of changed) ui.bullet(`${d.file} ${ui.dim(`(${d.status})`)}`);\n } else ui.ok('Knowledge already up to date.');\n }\n const preserved = result.docs.filter((d) => d.preservedModified.length);\n if (preserved.length) {\n ui.line();\n for (const d of preserved) ui.warn(`${d.file}: kept your edits in ${d.preservedModified.join(', ')} ${ui.dim('(use --force to regenerate)')}`);\n }\n\n ui.line();\n if (result.agentChanges.length) {\n for (const { adapter, changes } of result.agentChanges) {\n const touched = changes.filter((c) => c.action !== 'unchanged').map((c) => `${c.path} (${c.action})`);\n ui.ok(`${adapter.displayName} integration${ui.dim(` — ${touched.length ? touched.join(', ') : changes.map((c) => c.path).join(', ') + ' (unchanged)'}`)}`);\n }\n } else if (mode === 'init') {\n ui.line(ui.dim('No agent integrations configured. Use `athena init --agents claude,cursor,antigravity` or `athena agents` later.'));\n }\n for (const n of result.notes) ui.warn(n);\n if (mode === 'init') {\n const unconfigured = ADAPTERS.filter((a) => !result.agentChanges.some((c) => c.adapter.id === a.id));\n if (unconfigured.length) ui.line(ui.dim(`Not configured: ${unconfigured.map((a) => a.displayName).join(', ')} (not detected in this project). Add with --agents.`));\n }\n\n ui.line();\n ui.line(ui.c.bold(ui.c.green(mode === 'init' ? 'Athena ready.' : 'Analysis complete.')));\n if (mode === 'init') {\n ui.line(ui.dim('Next: review .athena/rules.md and enable the rules that apply, then run `athena open` for the web UI.'));\n }\n}\n\nexport function summarize(result: PipelineResult, root: string, dryRun: boolean) {\n const m = result.analysis.model;\n return {\n root,\n dryRun,\n project: m.name,\n filesScanned: m.stats.filesScanned,\n durationMs: result.analysis.durationMs,\n languages: m.languages.slice(0, 5).map((l) => l.name),\n frameworks: [...new Set(m.frameworks.map((f) => f.name))],\n monorepo: m.workspace.isMonorepo,\n databases: m.databases.map((d) => d.name),\n entities: m.dbEntities.length,\n routes: m.routes.length,\n testFiles: m.tests.testFileCount,\n potentialSecrets: m.security.secrets.length,\n documents: result.docs.map((d) => ({ file: d.file, status: d.status, preservedModified: d.preservedModified })),\n agents: result.agentChanges.map((a) => ({ id: a.adapter.id, files: a.changes.map((c) => ({ path: c.path, action: c.action })) })),\n warnings: m.warnings,\n notes: result.notes,\n };\n}\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { z } from 'zod';\nimport { ATHENA_DIR } from '../config.js';\nimport { writeFileAtomic } from '../util/fs.js';\nimport type { FileEntry } from '../fs/walker.js';\n\nexport const STATE_SCHEMA_VERSION = 1;\n\nexport const DocumentState = z.object({\n file: z.string(),\n blocks: z.array(z.string()),\n lastGeneratedAt: z.string(),\n /** When the file content last changed due to Athena. */\n lastChangedAt: z.string(),\n contentHash: z.string(),\n preservedModified: z.array(z.string()),\n});\n\nexport const AgentState = z.object({\n configured: z.boolean(),\n files: z.array(z.string()),\n configuredAt: z.string().optional(),\n});\n\nexport const AthenaState = z.object({\n schemaVersion: z.literal(STATE_SCHEMA_VERSION),\n athenaVersion: z.string(),\n projectName: z.string(),\n createdAt: z.string(),\n analyzedAt: z.string(),\n analysisDurationMs: z.number(),\n git: z.object({ isRepo: z.boolean(), head: z.string().optional(), branch: z.string().optional() }),\n /** Repo-relative path → content hash/size/mtime. Basis for incremental analysis. */\n fileIndex: z.record(z.string(), z.object({ h: z.string(), s: z.number(), m: z.number(), b: z.literal(1).optional() })),\n documents: z.record(z.string(), DocumentState),\n detectors: z.record(z.string(), z.number()),\n agents: z.record(z.string(), AgentState),\n warnings: z.array(z.string()),\n});\nexport type AthenaState = z.infer<typeof AthenaState>;\nexport type DocumentState = z.infer<typeof DocumentState>;\n\nexport function athenaDir(root: string): string {\n return path.join(root, ATHENA_DIR);\n}\n\nexport type StateReadResult =\n | { kind: 'missing' }\n | { kind: 'ok'; state: AthenaState }\n | { kind: 'corrupted'; reason: string };\n\nexport async function readState(dir: string): Promise<StateReadResult> {\n let raw: string;\n try {\n raw = await fs.readFile(path.join(dir, 'state.json'), 'utf8');\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') return { kind: 'missing' };\n return { kind: 'corrupted', reason: `unreadable (${(err as NodeJS.ErrnoException).code})` };\n }\n let json: unknown;\n try {\n json = JSON.parse(raw);\n } catch {\n return { kind: 'corrupted', reason: 'invalid JSON' };\n }\n const parsed = AthenaState.safeParse(json);\n if (!parsed.success) {\n const issue = parsed.error.issues[0];\n return { kind: 'corrupted', reason: `schema mismatch at ${issue?.path.join('.') || '(root)'}: ${issue?.message}` };\n }\n return { kind: 'ok', state: parsed.data };\n}\n\nexport async function writeState(dir: string, state: AthenaState): Promise<void> {\n await writeFileAtomic(path.join(dir, 'state.json'), `${JSON.stringify(state, null, 2)}\\n`);\n}\n\n/** Move a corrupted state.json aside so it can be inspected; never delete it. */\nexport async function backupCorruptedState(dir: string): Promise<string | null> {\n const src = path.join(dir, 'state.json');\n const backupDir = path.join(dir, '.backup');\n const dest = path.join(backupDir, `state.${new Date().toISOString().replace(/[:.]/g, '-')}.json`);\n try {\n await fs.mkdir(backupDir, { recursive: true });\n await fs.rename(src, dest);\n return dest;\n } catch {\n return null;\n }\n}\n\nexport function buildFileIndex(files: FileEntry[]): AthenaState['fileIndex'] {\n const idx: AthenaState['fileIndex'] = {};\n for (const f of files) idx[f.path] = { h: f.hash.startsWith('meta:') ? f.hash : f.hash.slice(0, 16), s: f.size, m: f.mtimeMs, ...(f.binary ? { b: 1 as const } : {}) };\n return idx;\n}\n\nexport interface IndexDiff {\n added: string[];\n modified: string[];\n deleted: string[];\n}\n\nexport function diffFileIndex(prev: AthenaState['fileIndex'], next: AthenaState['fileIndex']): IndexDiff {\n const diff: IndexDiff = { added: [], modified: [], deleted: [] };\n for (const [p, v] of Object.entries(next)) {\n const old = prev[p];\n if (!old) diff.added.push(p);\n else if (old.h !== v.h) diff.modified.push(p);\n }\n for (const p of Object.keys(prev)) if (!(p in next)) diff.deleted.push(p);\n return diff;\n}\n","import path from 'node:path';\nimport { z } from 'zod';\nimport { readTextIfExists } from './util/fs.js';\n\nexport const ATHENA_DIR = '.athena';\n\nexport const DEFAULT_IGNORES = [\n '.git',\n '.hg',\n '.svn',\n 'node_modules',\n 'bower_components',\n 'dist',\n 'build',\n 'out',\n '.next',\n '.nuxt',\n '.svelte-kit',\n '.turbo',\n '.cache',\n '.parcel-cache',\n '.dart_tool',\n '.venv',\n 'venv',\n '.tox',\n '__pycache__',\n '.pytest_cache',\n '.mypy_cache',\n 'target',\n 'coverage',\n '.gradle',\n '.idea',\n 'vendor',\n 'Pods',\n '.terraform',\n '.serverless',\n ATHENA_DIR,\n `${ATHENA_DIR}.tmp-*`,\n];\n\nexport const AthenaConfig = z.object({\n /** Additional gitignore-style patterns to exclude. */\n ignore: z.array(z.string()).default([]),\n /** Patterns (gitignore-style) to force-include even if a default ignore matches. */\n include: z.array(z.string()).default([]),\n /** Files larger than this are indexed by metadata only. */\n maxFileBytes: z.number().int().positive().default(1_000_000),\n /** Hard cap on files scanned; beyond this analysis stops and warns. */\n maxFiles: z.number().int().positive().default(200_000),\n /** Agent adapters to configure. Empty = auto. */\n agents: z.array(z.string()).optional(),\n /** Optional AI provider settings (see `athena ai status`). AI is never required. */\n ai: z\n .object({\n provider: z.enum(['anthropic', 'openai', 'google', 'ollama']).optional(),\n model: z.string().optional(),\n mode: z.enum(['cloud', 'local']).optional(),\n consent: z.boolean().optional(),\n maxChars: z.number().int().min(500).max(200_000).optional(),\n baseUrl: z.string().optional(),\n })\n .optional(),\n});\nexport type AthenaConfig = z.infer<typeof AthenaConfig>;\n\nexport interface LoadedConfig {\n config: AthenaConfig;\n warning?: string;\n}\n\nexport async function loadConfig(root: string): Promise<LoadedConfig> {\n const file = path.join(root, ATHENA_DIR, 'config.json');\n const raw = await readTextIfExists(file);\n if (raw === null) return { config: AthenaConfig.parse({}) };\n try {\n const parsed = AthenaConfig.safeParse(JSON.parse(raw));\n if (parsed.success) return { config: parsed.data };\n return { config: AthenaConfig.parse({}), warning: `.athena/config.json is invalid (${parsed.error.issues[0]?.message}); using defaults` };\n } catch {\n return { config: AthenaConfig.parse({}), warning: '.athena/config.json is not valid JSON; using defaults' };\n }\n}\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport crypto from 'node:crypto';\n\n/** Write a file atomically: write to a temp file in the same dir, then rename. */\nexport async function writeFileAtomic(file: string, data: string): Promise<void> {\n await fs.mkdir(path.dirname(file), { recursive: true });\n const tmp = `${file}.${process.pid}.${crypto.randomBytes(4).toString('hex')}.tmp`;\n try {\n await fs.writeFile(tmp, data, 'utf8');\n await fs.rename(tmp, file);\n } catch (err) {\n await fs.rm(tmp, { force: true }).catch(() => {});\n throw err;\n }\n}\n\nexport async function exists(p: string): Promise<boolean> {\n try {\n await fs.access(p);\n return true;\n } catch {\n return false;\n }\n}\n\nexport async function readTextIfExists(p: string): Promise<string | null> {\n try {\n return await fs.readFile(p, 'utf8');\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') return null;\n throw err;\n }\n}\n\nexport function sha256(data: string | Buffer): string {\n return crypto.createHash('sha256').update(data).digest('hex');\n}\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport type { AgentAdapter, PlannedFileChange } from '../core/agents/adapter.js';\nimport { writeFileAtomic } from '../core/util/fs.js';\nimport { resolveInside } from '../core/util/paths.js';\nimport { claudeCodeAdapter } from './claude-code/adapter.js';\nimport { cursorAdapter } from './cursor/adapter.js';\nimport { antigravityAdapter } from './antigravity/adapter.js';\nimport { agentsMdAdapter } from './agents-md/adapter.js';\n\nexport const ADAPTERS: AgentAdapter[] = [claudeCodeAdapter, cursorAdapter, antigravityAdapter, agentsMdAdapter];\n\n/** Accepts ids and friendly aliases. */\nexport function resolveAdapters(names: string[]): AgentAdapter[] {\n const alias: Record<string, string> = { claude: 'claude-code', claudecode: 'claude-code', agents: 'agents-md', 'agents.md': 'agents-md', gemini: 'antigravity' };\n const out: AgentAdapter[] = [];\n for (const raw of names) {\n const n = raw.trim().toLowerCase();\n if (!n) continue;\n const id = alias[n] ?? n;\n const a = ADAPTERS.find((x) => x.id === id);\n if (!a) throw new Error(`Unknown agent \"${raw}\". Supported: ${ADAPTERS.map((x) => x.id).join(', ')}`);\n if (!out.includes(a)) out.push(a);\n }\n return out;\n}\n\nexport async function applyChanges(root: string, changes: PlannedFileChange[]): Promise<PlannedFileChange[]> {\n const applied: PlannedFileChange[] = [];\n for (const c of changes) {\n if (c.action === 'unchanged') continue;\n const abs = resolveInside(root, c.path);\n if (!abs) throw new Error(`Refusing to write outside the project: ${c.path}`);\n // Don't follow a symlink planted at an integration path.\n const st = await fs.lstat(abs).catch(() => null);\n if (st?.isSymbolicLink()) throw new Error(`Refusing to write through symlink: ${c.path}`);\n await fs.mkdir(path.dirname(abs), { recursive: true });\n await writeFileAtomic(abs, c.content);\n if (abs.endsWith('.sh')) await fs.chmod(abs, 0o755).catch(() => {});\n applied.push(c);\n }\n return applied;\n}\n","import path from 'node:path';\n\n/** Convert an OS path to a POSIX-style path (stable across Windows/macOS/Linux). */\nexport function toPosix(p: string): string {\n return p.split(path.sep).join('/').replace(/\\\\/g, '/');\n}\n\n/** Repo-relative POSIX path. */\nexport function relPosix(root: string, abs: string): string {\n return toPosix(path.relative(root, abs)) || '.';\n}\n\n/**\n * Resolve `candidate` inside `root`, rejecting anything that escapes it\n * (path traversal, absolute paths, drive letters).\n */\nexport function resolveInside(root: string, candidate: string): string | null {\n if (candidate.includes('\\0')) return null;\n const resolvedRoot = path.resolve(root);\n const resolved = path.resolve(resolvedRoot, candidate);\n const rel = path.relative(resolvedRoot, resolved);\n if (rel === '' ) return resolved;\n if (rel.startsWith('..') || path.isAbsolute(rel)) return null;\n return resolved;\n}\n\nexport function dirOf(posixPath: string): string {\n const i = posixPath.lastIndexOf('/');\n return i === -1 ? '.' : posixPath.slice(0, i);\n}\n\nexport function baseName(posixPath: string): string {\n const i = posixPath.lastIndexOf('/');\n return i === -1 ? posixPath : posixPath.slice(i + 1);\n}\n","import path from 'node:path';\nimport type { AgentAdapter, PlannedFileChange } from '../../core/agents/adapter.js';\nimport { readTextIfExists } from '../../core/util/fs.js';\nimport { athenaInstructions } from '../common/instructions.js';\nimport { checkBlock, planBlock, removeBlockFrom, userEvidence } from '../common/files.js';\nimport { CLAUDE_HOOK_EVENTS } from '../common/hook-events.js';\nimport { hookArgs, hookCommand, isAthenaEntry, mergeMcpServers, planJsonChange, pruneEmpty, removeJsonHooks, stripMcpServers } from '../common/hooks.js';\n\nconst SETTINGS = '.claude/settings.json';\nconst MCP_FILE = '.mcp.json';\n\ninterface HookEntry {\n matcher?: string;\n hooks?: Array<Record<string, unknown>>;\n}\n\n/**\n * Claude Code:\n * - project memory: a marked block in CLAUDE.md, importing .athena/rules.md\n * - activity: hooks in .claude/settings.json calling `athena event`\n * Format per https://code.claude.com/docs/en/hooks (checked 2026-09):\n * hooks.<EventName>[] = { matcher, hooks: [{ type: \"command\", command, args, async, timeout }] }\n * `args` uses exec form (no shell) and `async: true` keeps the agent unblocked.\n */\nexport const claudeCodeAdapter: AgentAdapter = {\n id: 'claude-code',\n displayName: 'Claude Code',\n capabilities: { instructionsFile: true, scopedRules: false, hooks: true, mcp: true },\n supportNote: 'Uses CLAUDE.md with an @-import of .athena/rules.md, hooks in .claude/settings.json that report activity, and an MCP server entry in .mcp.json.',\n async detectPresence(root) {\n const evidence = await userEvidence(root, { files: ['CLAUDE.md', 'CLAUDE.local.md'], dirs: ['.claude'], athenaOwnedJson: [SETTINGS, MCP_FILE] });\n return { detectedInProject: evidence.length > 0, evidence };\n },\n async plan(ctx) {\n const changes: PlannedFileChange[] = [await planBlock(ctx.root, 'CLAUDE.md', athenaInstructions({ heading: '##', rulesImport: '@.athena/rules.md' }))];\n changes.push(\n await planJsonChange(ctx.root, SETTINGS, (data) => {\n const hooks = (data.hooks && typeof data.hooks === 'object' && !Array.isArray(data.hooks) ? data.hooks : {}) as Record<string, HookEntry[]>;\n for (const event of CLAUDE_HOOK_EVENTS) {\n const list = (Array.isArray(hooks[event]) ? hooks[event] : []).filter((e) => !isAthenaEntry(e));\n list.push({\n ...(event === 'PreToolUse' ? { matcher: '*' } : {}),\n hooks: [{ type: 'command', command: hookCommand(), args: hookArgs('claude-code', event), async: true, timeout: 10 }],\n });\n hooks[event] = list;\n }\n data.hooks = hooks;\n }),\n );\n changes.push(await planJsonChange(ctx.root, MCP_FILE, mergeMcpServers));\n return changes;\n },\n async remove(root) {\n const touched: string[] = [];\n if (await removeBlockFrom(root, 'CLAUDE.md')) touched.push('CLAUDE.md');\n if (await removeJsonHooks(root, MCP_FILE, stripMcpServers, (d) => Object.keys(d).length === 0)) touched.push(MCP_FILE);\n const removed = await removeJsonHooks(\n root,\n SETTINGS,\n (data) => {\n const hooks = data.hooks as Record<string, HookEntry[]> | undefined;\n if (!hooks) return;\n for (const event of Object.keys(hooks)) {\n hooks[event] = (hooks[event] ?? []).filter((e) => !isAthenaEntry(e));\n if (!hooks[event]!.length) delete hooks[event];\n }\n pruneEmpty(data, 'hooks');\n },\n (data) => Object.keys(data).length === 0,\n );\n if (removed) touched.push(SETTINGS);\n return touched;\n },\n async check(root) {\n const checks = [await checkBlock(root, 'CLAUDE.md', 'Claude Code')];\n const text = await readTextIfExists(path.join(root, SETTINGS));\n if (text === null) checks.push({ ok: false, level: 'warn', message: `Claude Code: ${SETTINGS} not found — activity reporting is off` });\n else {\n const configured = CLAUDE_HOOK_EVENTS.filter((e) => new RegExp(`\"${e}\"`).test(text) && text.includes('--athena-hook'));\n checks.push(\n configured.length === CLAUDE_HOOK_EVENTS.length\n ? { ok: true, level: 'ok', message: `Claude Code: activity hooks installed (${configured.length} events)` }\n : { ok: false, level: 'warn', message: `Claude Code: only ${configured.length}/${CLAUDE_HOOK_EVENTS.length} activity hooks installed — re-run \\`athena agents add claude-code\\`` },\n );\n }\n return checks;\n },\n};\n","/**\n * The canonical registry of Athena knowledge documents. Everything that needs to\n * know \"which docs exist\" (renderers, agents, impact analysis, future web API\n * allowlist) derives from this list.\n */\nexport const KNOWLEDGE_DOCS = [\n { id: 'project', file: 'project.md', title: 'Project', purpose: 'What this project is, its technologies, structure, entry points, commands and development workflow.' },\n { id: 'architecture', file: 'architecture.md', title: 'Architecture', purpose: 'System and module architecture, service relationships, data flow and external services.' },\n { id: 'database', file: 'database.md', title: 'Database', purpose: 'Database technologies, schemas, entities, relationships, indexes and migrations.' },\n { id: 'api', file: 'api.md', title: 'API', purpose: 'API style, endpoints, specifications, and authentication/error-handling expectations.' },\n { id: 'auth', file: 'auth.md', title: 'Authentication & Authorization', purpose: 'Authentication mechanisms, sessions/tokens, roles and permissions, and security assumptions.' },\n { id: 'security', file: 'security.md', title: 'Security', purpose: 'Attack surface, security controls, secret handling, tooling, and known/potential issues.' },\n { id: 'testing', file: 'testing.md', title: 'Testing', purpose: 'Test frameworks, commands, layout, coverage configuration and detectable gaps.' },\n { id: 'debugging', file: 'debugging.md', title: 'Debugging', purpose: 'Known bugs, common errors, debugging commands, logs and troubleshooting procedures.' },\n { id: 'performance', file: 'performance.md', title: 'Performance', purpose: 'Performance-sensitive areas, caching, queues, background jobs and performance rules.' },\n { id: 'code-review', file: 'code-review.md', title: 'Code Review', purpose: 'Project-specific review checklist covering architecture, security, testing and performance.' },\n { id: 'deployment', file: 'deployment.md', title: 'Deployment', purpose: 'Deployment architecture, environments, containers, CI/CD, hosting and environment variables.' },\n { id: 'rules', file: 'rules.md', title: 'Project Rules', purpose: 'Developer-defined rules that AI agents must follow. Owned by the developer.' },\n] as const;\n\nexport type DocId = (typeof KNOWLEDGE_DOCS)[number]['id'];\nexport type GeneratedDocId = Exclude<DocId, 'rules'>;\n\nexport const DOC_FILES: ReadonlySet<string> = new Set(KNOWLEDGE_DOCS.map((d) => d.file));\n\nexport function docById(id: DocId) {\n return KNOWLEDGE_DOCS.find((d) => d.id === id)!;\n}\n\n/**\n * Task-type → documents to load. Agents use this instead of reading everything\n * for every task. `rules.md` is always relevant.\n */\nexport const RELEVANCE_MAP: Array<{ task: string; docs: DocId[] }> = [\n { task: 'Database / schema / migrations / queries', docs: ['database', 'architecture', 'api', 'security', 'testing', 'rules'] },\n { task: 'API endpoints / controllers / request handling', docs: ['api', 'auth', 'security', 'architecture', 'testing', 'rules'] },\n { task: 'Authentication / authorization / sessions / permissions', docs: ['auth', 'security', 'api', 'database', 'testing', 'rules'] },\n { task: 'Frontend UI / styling / components', docs: ['project', 'architecture', 'rules'] },\n { task: 'New feature spanning multiple layers', docs: ['project', 'architecture', 'database', 'api', 'auth', 'security', 'testing', 'rules'] },\n { task: 'Bug fix / debugging', docs: ['debugging', 'architecture', 'testing', 'rules'] },\n { task: 'Performance work / caching / background jobs', docs: ['performance', 'architecture', 'database', 'rules'] },\n { task: 'Tests', docs: ['testing', 'project', 'rules'] },\n { task: 'Build / CI / Docker / deployment / infrastructure', docs: ['deployment', 'project', 'security', 'rules'] },\n { task: 'Dependency changes', docs: ['project', 'security', 'rules'] },\n { task: 'Code review', docs: ['code-review', 'rules', 'security', 'testing'] },\n { task: 'Small, local change (typo, rename, copy)', docs: ['rules'] },\n];\n","import { KNOWLEDGE_DOCS, RELEVANCE_MAP } from '../../core/knowledge/documents.js';\n\n/** Single source of truth for the instruction text shared by all agent adapters. */\n\nexport function workflowSteps(): string {\n return [\n '1. Read `.athena/rules.md` and follow every enabled rule (lines marked `[disabled]` do not apply).',\n '2. Classify the task and read only the relevant Athena documents (see the relevance map below).',\n '3. Identify the affected modules and architecture boundaries.',\n '4. Check security implications (`.athena/security.md`, `.athena/auth.md`) when touching input handling, auth, data access or secrets.',\n '5. Check database and API implications when the change touches schema, queries or endpoints.',\n '6. For non-trivial work, state a short implementation plan before editing.',\n '7. Implement only the required changes.',\n '8. Run the relevant validation (tests, lint, type checks — commands are listed in `.athena/project.md` and `.athena/testing.md`).',\n '9. If you changed project structure, dependencies, routes, schema or infrastructure, run `athena sync --dry-run` to see which knowledge is affected, and tell the developer to review it with `athena sync` (apply it yourself only if permitted).',\n ].join('\\n');\n}\n\nexport function relevanceTable(): string {\n const file = (id: string) => `\\`${KNOWLEDGE_DOCS.find((d) => d.id === id)!.file}\\``;\n return ['| Task type | Read from `.athena/` |', '| --- | --- |', ...RELEVANCE_MAP.map((r) => `| ${r.task} | ${r.docs.map(file).join(', ')} |`)].join('\\n');\n}\n\nexport function trustNote(): string {\n return 'Athena knowledge labels every statement as `FACT`, `DETECTED`, `INFERRED` or `UNKNOWN`. Treat `INFERRED` and `UNKNOWN` as unverified — confirm in code before relying on them. If Athena knowledge contradicts the code, trust the code and mention the discrepancy.';\n}\n\nexport function skipNote(): string {\n return 'For small, local changes (typos, copy, a rename inside one file) reading `rules.md` is enough — do not load every document.';\n}\n\n/** Full instruction body used by adapters. */\nexport function athenaInstructions(opts: { heading?: string; rulesImport?: string } = {}): string {\n return [\n `${opts.heading ?? '##'} Athena Project Intelligence`,\n '',\n 'This project maintains structured project knowledge in `.athena/` (generated by Athena, curated by the developers).',\n '',\n opts.rulesImport ? `Project rules (always apply): ${opts.rulesImport}\\n` : '',\n 'Before making significant changes:',\n '',\n workflowSteps(),\n '',\n `${opts.heading ?? '##'}# Relevance map`,\n '',\n relevanceTable(),\n '',\n skipNote(),\n '',\n trustNote(),\n ]\n .filter((l, i, a) => !(l === '' && a[i - 1] === ''))\n .join('\\n');\n}\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { exists, readTextIfExists } from '../../core/util/fs.js';\nimport { INTEGRATION_END, INTEGRATION_START, removeIntegrationBlock, upsertIntegrationBlock } from '../../core/knowledge/managed-blocks.js';\nimport { ATHENA_MARK } from './hooks.js';\nimport type { IntegrationCheck, PlannedFileChange } from '../../core/agents/adapter.js';\n\nexport const OWNED_HEADER = '<!-- Generated by Athena. This file is owned by Athena and may be rewritten by `athena init`/`athena agents`. -->';\n\nexport async function planBlock(root: string, rel: string, body: string): Promise<PlannedFileChange> {\n const existing = await readTextIfExists(path.join(root, rel));\n const content = upsertIntegrationBlock(existing, body);\n return { path: rel, ownership: 'block', action: existing === null ? 'create' : existing === content ? 'unchanged' : 'update', content };\n}\n\nexport async function planOwned(root: string, rel: string, content: string): Promise<PlannedFileChange> {\n const existing = await readTextIfExists(path.join(root, rel));\n if (existing !== null && !existing.includes('Generated by Athena')) {\n // Never overwrite a user file that happens to live at an Athena path.\n return { path: rel, ownership: 'owned', action: 'unchanged', content: existing };\n }\n return { path: rel, ownership: 'owned', action: existing === null ? 'create' : existing === content ? 'unchanged' : 'update', content };\n}\n\nexport async function removeBlockFrom(root: string, rel: string): Promise<boolean> {\n const file = path.join(root, rel);\n const existing = await readTextIfExists(file);\n if (existing === null || !existing.includes(INTEGRATION_START)) return false;\n const next = removeIntegrationBlock(existing);\n if (next.trim() === '') await fs.rm(file);\n else await fs.writeFile(file, next, 'utf8');\n return true;\n}\n\nexport async function removeOwned(root: string, rel: string): Promise<boolean> {\n const file = path.join(root, rel);\n const existing = await readTextIfExists(file);\n if (existing === null || !existing.includes('Generated by Athena')) return false;\n await fs.rm(file);\n return true;\n}\n\nexport async function checkBlock(root: string, rel: string, label: string): Promise<IntegrationCheck> {\n const text = await readTextIfExists(path.join(root, rel));\n if (text === null) return { ok: false, level: 'warn', message: `${label}: ${rel} not found (run \\`athena init\\` or \\`athena analyze\\`)` };\n const s = text.indexOf(INTEGRATION_START);\n const e = text.indexOf(INTEGRATION_END);\n if (s === -1 && e === -1) return { ok: false, level: 'warn', message: `${label}: ${rel} has no Athena block` };\n if (s === -1 || e < s) return { ok: false, level: 'error', message: `${label}: ${rel} has a malformed Athena block (unmatched markers)` };\n return { ok: true, level: 'ok', message: `${label}: ${rel}` };\n}\n\nexport async function anyExists(root: string, rels: string[]): Promise<string[]> {\n const found: string[] = [];\n for (const r of rels) if (await exists(path.join(root, r))) found.push(r);\n return found;\n}\n\n/**\n * Evidence that the developer uses an agent, excluding anything Athena itself created.\n * - `files`: a file counts if it exists and has content outside Athena's block/marker.\n * - `dirs`: a directory counts if it contains any entry other than Athena-owned paths.\n */\nexport async function userEvidence(root: string, spec: { files?: string[]; dirs?: string[]; athenaOwned?: string[]; athenaOwnedJson?: string[] }): Promise<string[]> {\n const found: string[] = [];\n const owned = new Set(spec.athenaOwned ?? []);\n // A JSON config that contains nothing but Athena's own entries is not evidence\n // that the developer uses the agent — Athena created it.\n for (const rel of spec.athenaOwnedJson ?? []) {\n if (await jsonOnlyAthena(path.join(root, rel))) owned.add(rel);\n }\n for (const rel of spec.files ?? []) {\n const text = await readTextIfExists(path.join(root, rel)).catch(() => null);\n if (text === null) continue;\n if (text.includes(OWNED_HEADER)) continue; // entirely Athena-owned\n if (removeIntegrationBlock(text).trim()) found.push(rel); // content besides Athena's block\n }\n for (const rel of spec.dirs ?? []) {\n if (await hasNonAthenaEntries(path.join(root, rel), root, owned)) found.push(rel);\n }\n return found;\n}\n\nasync function hasNonAthenaEntries(dir: string, root: string, owned: Set<string>): Promise<boolean> {\n let entries;\n try {\n entries = await fs.readdir(dir, { withFileTypes: true });\n } catch {\n return false;\n }\n for (const e of entries) {\n const abs = path.join(dir, e.name);\n const rel = path.relative(root, abs).split(path.sep).join('/');\n if (owned.has(rel)) continue;\n if (e.isDirectory()) {\n if (await hasNonAthenaEntries(abs, root, owned)) return true;\n } else return true;\n }\n return false;\n}\n\n/** True when a JSON config has no content beyond Athena's marked hook entries. */\nexport async function jsonOnlyAthena(file: string): Promise<boolean> {\n const text = await readTextIfExists(file).catch(() => null);\n if (text === null) return false;\n let data: unknown;\n try {\n data = JSON.parse(text);\n } catch {\n return false;\n }\n // Athena's MCP registration is keyed by name rather than carrying the hook marker.\n const record = data as Record<string, unknown>;\n const servers = record?.mcpServers;\n let hadAthenaMcp = false;\n if (servers && typeof servers === 'object') {\n hadAthenaMcp = 'athena' in (servers as Record<string, unknown>);\n delete (servers as Record<string, unknown>).athena;\n if (Object.keys(servers as Record<string, unknown>).length === 0) delete record.mcpServers;\n }\n if (!text.includes(ATHENA_MARK) && !hadAthenaMcp) return false;\n const strip = (value: unknown): unknown => {\n if (Array.isArray(value)) {\n const kept = value.filter((v) => !JSON.stringify(v ?? '').includes(ATHENA_MARK)).map(strip);\n return kept.length ? kept : undefined;\n }\n if (value && typeof value === 'object') {\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(value as Record<string, unknown>)) {\n if (JSON.stringify(v ?? '').includes(ATHENA_MARK)) {\n const cleaned = strip(v);\n if (cleaned !== undefined) out[k] = cleaned;\n continue;\n }\n if (k === 'version') continue; // written by Athena for Cursor's hooks.json\n out[k] = v;\n }\n return Object.keys(out).length ? out : undefined;\n }\n return value;\n };\n return strip(data) === undefined;\n}\n","import { sha256 } from '../util/fs.js';\n\n/**\n * Generated content lives inside managed blocks:\n *\n * <!-- athena:generated:start id=overview hash=abc123def456 -->\n * ...\n * <!-- athena:generated:end id=overview -->\n *\n * Content outside blocks belongs to the developer and is never modified. The hash\n * records what Athena last wrote, so manual edits inside a block are detected and\n * preserved unless the caller forces regeneration.\n */\n\nexport interface Section {\n id: string;\n content: string;\n}\n\nexport interface ParsedBlock {\n id: string;\n hash: string;\n content: string;\n start: number;\n end: number;\n}\n\nconst START_RE = /<!-- athena:generated:start id=([a-z0-9-]+) hash=([a-f0-9]*) -->\\n?/g;\n\nexport function blockHash(content: string): string {\n return sha256(content.trim()).slice(0, 12);\n}\n\nexport function renderBlock(section: Section): string {\n const body = section.content.trim();\n return `<!-- athena:generated:start id=${section.id} hash=${blockHash(body)} -->\\n${body}\\n<!-- athena:generated:end id=${section.id} -->`;\n}\n\nexport function parseBlocks(text: string): ParsedBlock[] {\n const blocks: ParsedBlock[] = [];\n START_RE.lastIndex = 0;\n for (let m = START_RE.exec(text); m; m = START_RE.exec(text)) {\n const id = m[1]!;\n const endMarker = `<!-- athena:generated:end id=${id} -->`;\n const endIdx = text.indexOf(endMarker, m.index + m[0].length);\n if (endIdx === -1) continue; // malformed: treat as developer content\n blocks.push({ id, hash: m[2]!, content: text.slice(m.index + m[0].length, endIdx).trim(), start: m.index, end: endIdx + endMarker.length });\n START_RE.lastIndex = endIdx + endMarker.length;\n }\n return blocks;\n}\n\nexport function isBlockModified(block: ParsedBlock): boolean {\n return blockHash(block.content) !== block.hash;\n}\n\nexport interface MergeResult {\n text: string;\n changed: boolean;\n /** Blocks left untouched because the developer edited them. */\n preservedModified: string[];\n updated: string[];\n added: string[];\n}\n\nexport interface MergeOptions {\n force?: boolean;\n /** Block ids Athena previously wrote; if one is missing now, the developer removed it — don't re-add. */\n previouslyKnown?: string[];\n /** Marker before which newly introduced sections are inserted. */\n insertBefore?: string;\n}\n\nexport function mergeDocument(existing: string, sections: Section[], opts: MergeOptions = {}): MergeResult {\n const blocks = parseBlocks(existing);\n const byId = new Map(blocks.map((b) => [b.id, b]));\n const result: MergeResult = { text: existing, changed: false, preservedModified: [], updated: [], added: [] };\n const replacements: Array<{ start: number; end: number; text: string }> = [];\n\n for (const s of sections) {\n const b = byId.get(s.id);\n if (!b) continue;\n if (isBlockModified(b) && !opts.force) {\n result.preservedModified.push(s.id);\n continue;\n }\n if (b.content === s.content.trim() && !isBlockModified(b)) continue;\n replacements.push({ start: b.start, end: b.end, text: renderBlock(s) });\n result.updated.push(s.id);\n }\n\n let text = existing;\n for (const r of replacements.sort((a, b) => b.start - a.start)) text = text.slice(0, r.start) + r.text + text.slice(r.end);\n\n const known = new Set(opts.previouslyKnown ?? []);\n const toAdd = sections.filter((s) => !byId.has(s.id) && !known.has(s.id));\n if (toAdd.length) {\n const insert = toAdd.map((s) => renderBlock(s)).join('\\n\\n');\n const marker = opts.insertBefore ? text.indexOf(opts.insertBefore) : -1;\n text = marker >= 0 ? `${text.slice(0, marker)}${insert}\\n\\n${text.slice(marker)}` : `${text.replace(/\\s*$/, '')}\\n\\n${insert}\\n`;\n result.added.push(...toAdd.map((s) => s.id));\n }\n\n result.text = text;\n result.changed = text !== existing;\n return result;\n}\n\n/**\n * Markers for Athena-managed regions inside files owned by other tools\n * (e.g. agent instruction files). Separate from generated blocks: these are always\n * fully owned by Athena.\n */\nexport const INTEGRATION_START = '<!-- athena:start -->';\nexport const INTEGRATION_END = '<!-- athena:end -->';\n\nexport function upsertIntegrationBlock(existing: string | null, body: string): string {\n const block = `${INTEGRATION_START}\\n${body.trim()}\\n${INTEGRATION_END}`;\n if (!existing) return `${block}\\n`;\n const s = existing.indexOf(INTEGRATION_START);\n const e = existing.indexOf(INTEGRATION_END);\n if (s !== -1 && e > s) return existing.slice(0, s) + block + existing.slice(e + INTEGRATION_END.length);\n return `${existing.replace(/\\s*$/, '')}\\n\\n${block}\\n`;\n}\n\nexport function removeIntegrationBlock(existing: string): string {\n const s = existing.indexOf(INTEGRATION_START);\n const e = existing.indexOf(INTEGRATION_END);\n if (s === -1 || e < s) return existing;\n const before = existing.slice(0, s).replace(/\\s*$/, '');\n const after = existing.slice(e + INTEGRATION_END.length).replace(/^\\s*/, '');\n const joined = [before, after.replace(/\\s*$/, '')].filter(Boolean).join('\\n\\n');\n return joined ? `${joined}\\n` : '';\n}\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { readTextIfExists } from '../../core/util/fs.js';\nimport type { PlannedFileChange } from '../../core/agents/adapter.js';\n\n/**\n * Athena-owned entries inside agent-owned JSON config files.\n *\n * Athena only ever adds, updates or removes entries carrying ATHENA_MARK; every\n * other hook in the file belongs to the developer and is preserved byte-for-byte\n * wherever JSON round-tripping allows.\n */\nexport const ATHENA_MARK = '--athena-hook';\n\n/** The command agents run. Overridable for tests or unusual installs. */\nexport function hookCommand(): string {\n return process.env.ATHENA_HOOK_COMMAND?.trim() || 'athena';\n}\n\nexport function hookArgs(agent: string, hook: string): string[] {\n return ['event', ATHENA_MARK, '--agent', agent, '--hook', hook];\n}\n\nexport async function readJsonFile(file: string): Promise<{ data: Record<string, unknown>; existed: boolean; malformed: boolean }> {\n const text = await readTextIfExists(file);\n if (text === null) return { data: {}, existed: false, malformed: false };\n try {\n const parsed = JSON.parse(text) as unknown;\n if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) return { data: parsed as Record<string, unknown>, existed: true, malformed: false };\n return { data: {}, existed: true, malformed: true };\n } catch {\n return { data: {}, existed: true, malformed: true };\n }\n}\n\nexport function isAthenaEntry(entry: unknown): boolean {\n return JSON.stringify(entry ?? '').includes(ATHENA_MARK);\n}\n\nexport async function planJsonChange(root: string, rel: string, mutate: (data: Record<string, unknown>) => void): Promise<PlannedFileChange> {\n const file = path.join(root, rel);\n const { data, existed, malformed } = await readJsonFile(file);\n if (malformed) throw new Error(`${rel} is not valid JSON — fix it before configuring hooks`);\n const before = JSON.stringify(data);\n mutate(data);\n const content = `${JSON.stringify(data, null, 2)}\\n`;\n return { path: rel, ownership: 'block', action: !existed ? 'create' : JSON.stringify(data) === before ? 'unchanged' : 'update', content };\n}\n\n/** Remove Athena entries from a JSON hooks file; deletes the file if nothing else remains. */\nexport async function removeJsonHooks(root: string, rel: string, strip: (data: Record<string, unknown>) => void, isEmpty: (data: Record<string, unknown>) => boolean): Promise<boolean> {\n const file = path.join(root, rel);\n const { data, existed, malformed } = await readJsonFile(file);\n if (!existed || malformed) return false;\n const before = JSON.stringify(data);\n strip(data);\n if (JSON.stringify(data) === before) return false;\n if (isEmpty(data)) await fs.rm(file, { force: true });\n else await fs.writeFile(file, `${JSON.stringify(data, null, 2)}\\n`, 'utf8');\n return true;\n}\n\n/** Drop empty containers left behind after removing Athena entries. */\nexport function pruneEmpty(record: Record<string, unknown>, key: string): void {\n const value = record[key];\n if (value && typeof value === 'object' && !Array.isArray(value) && Object.keys(value).length === 0) delete record[key];\n if (Array.isArray(value) && value.length === 0) delete record[key];\n}\n\n/**\n * A tiny script that forwards the hook payload on stdin to `athena event`.\n * Used by agents that execute a script path rather than a command line.\n */\nexport function hookScript(agent: string, platform: NodeJS.Platform = process.platform): { file: string; content: string; mode: number } {\n const command = hookCommand();\n if (platform === 'win32') {\n return {\n file: 'athena-hook.cmd',\n content: ['@echo off', `${command} event ${ATHENA_MARK} --agent ${agent} --hook %1`, 'exit /b 0', ''].join('\\r\\n'),\n mode: 0o644,\n };\n }\n return {\n file: 'athena-hook.sh',\n content: ['#!/bin/sh', '# Generated by Athena: forwards agent hook payloads to `athena event`.', `exec ${command} event ${ATHENA_MARK} --agent ${agent} --hook \"$1\"`, ''].join('\\n'),\n mode: 0o755,\n };\n}\n\n/** Shared shape for MCP server registration (Claude Code's .mcp.json and Cursor's .cursor/mcp.json). */\nexport function athenaMcpEntry(): Record<string, unknown> {\n return { command: hookCommand(), args: ['mcp'] };\n}\n\nexport function mergeMcpServers(data: Record<string, unknown>): void {\n const servers = (data.mcpServers && typeof data.mcpServers === 'object' && !Array.isArray(data.mcpServers) ? data.mcpServers : {}) as Record<string, unknown>;\n servers.athena = athenaMcpEntry();\n data.mcpServers = servers;\n}\n\nexport function stripMcpServers(data: Record<string, unknown>): void {\n const servers = data.mcpServers as Record<string, unknown> | undefined;\n if (!servers) return;\n delete servers.athena;\n pruneEmpty(data, 'mcpServers');\n}\n","import crypto from 'node:crypto';\n\n/**\n * Normalization of agent hook payloads into Athena activity events.\n *\n * Everything here is *observed*: it comes from a hook the agent itself fired.\n * Athena never infers what an agent is \"thinking\" — only which tool ran, on what,\n * and when. Unknown hooks are recorded generically rather than guessed at.\n */\n\nexport type AgentEventKind = 'session-start' | 'session-end' | 'prompt' | 'read' | 'edit' | 'command' | 'search' | 'tool' | 'stop' | 'subagent' | 'other';\n\n/** Activity states Athena will display for an agent event. */\nexport type AgentActivityState = 'ANALYZING' | 'PLANNING' | 'CODING' | 'TESTING' | 'REVIEWING' | 'SUCCESS' | 'IDLE';\n\nexport interface AgentEvent {\n id: string;\n ts: string;\n agent: string;\n /** Agent-provided session/conversation id, when available. */\n session: string | null;\n hook: string;\n kind: AgentEventKind;\n state: AgentActivityState;\n message: string;\n /** Project-relative paths the agent touched, when the hook reports them. */\n files: string[];\n /** Shell command, truncated and never parsed for meaning. */\n command: string | null;\n tool: string | null;\n}\n\nconst TEST_COMMAND = /\\b(test|vitest|jest|pytest|go test|cargo test|mocha|rspec|phpunit|gradle test|mvn test|tox|playwright|cypress)\\b/i;\nconst REVIEW_COMMAND = /\\b(lint|eslint|ruff|clippy|tsc|typecheck|type-check|mypy|flake8|rubocop|golangci-lint|audit)\\b/i;\n\nconst READ_TOOLS = new Set(['read', 'glob', 'grep', 'notebookread', 'webfetch', 'websearch', 'ls', 'searchreplace']);\nconst EDIT_TOOLS = new Set(['edit', 'write', 'multiedit', 'notebookedit', 'applypatch', 'create_diff', 'str_replace']);\n\nfunction truncate(s: string, n = 160): string {\n const one = s.replace(/\\s+/g, ' ').trim();\n return one.length > n ? `${one.slice(0, n - 1)}…` : one;\n}\n\nfunction asString(v: unknown): string | null {\n return typeof v === 'string' && v.trim() ? v : null;\n}\n\nfunction filesFrom(input: Record<string, unknown> | null, payload: Record<string, unknown>): string[] {\n const out: string[] = [];\n for (const source of [input, payload]) {\n if (!source) continue;\n for (const key of ['file_path', 'filePath', 'path', 'notebook_path', 'target_file']) {\n const v = asString(source[key]);\n if (v) out.push(v);\n }\n const edits = source.edits;\n if (Array.isArray(edits)) {\n for (const e of edits) {\n const v = e && typeof e === 'object' ? asString((e as Record<string, unknown>).file_path) : null;\n if (v) out.push(v);\n }\n }\n }\n return [...new Set(out)];\n}\n\ninterface Classified {\n kind: AgentEventKind;\n state: AgentActivityState;\n message: string;\n}\n\nfunction classifyTool(tool: string, command: string | null, files: string[]): Classified {\n const t = tool.toLowerCase().replace(/^mcp__/, '');\n const where = files.length ? ` ${files.slice(0, 2).join(', ')}${files.length > 2 ? ` +${files.length - 2}` : ''}` : '';\n if (EDIT_TOOLS.has(t)) return { kind: 'edit', state: 'CODING', message: `Editing${where || ' files'}` };\n if (READ_TOOLS.has(t)) return { kind: t === 'grep' || t === 'glob' ? 'search' : 'read', state: 'ANALYZING', message: `Reading${where || ` (${tool})`}` };\n if (t === 'bash' || t === 'shell' || t.includes('terminal')) {\n if (command && TEST_COMMAND.test(command)) return { kind: 'command', state: 'TESTING', message: `Running tests: ${command}` };\n if (command && REVIEW_COMMAND.test(command)) return { kind: 'command', state: 'REVIEWING', message: `Running checks: ${command}` };\n return { kind: 'command', state: 'CODING', message: command ? `Running: ${command}` : 'Running a shell command' };\n }\n if (t === 'task' || t === 'agent') return { kind: 'subagent', state: 'PLANNING', message: 'Delegating to a subagent' };\n if (t === 'todowrite' || t === 'exitplanmode' || t === 'plan') return { kind: 'tool', state: 'PLANNING', message: 'Updating its plan' };\n return { kind: 'tool', state: 'CODING', message: `Using ${tool}` };\n}\n\n/**\n * Map a hook payload to an Athena event. Returns null for hooks that carry no\n * useful signal (so Athena stays quiet instead of inventing activity).\n */\nexport function normalizeHookEvent(agent: string, hookName: string, payload: Record<string, unknown>): AgentEvent | null {\n const hook = hookName || asString(payload.hook_event_name) || 'unknown';\n const h = hook.toLowerCase();\n const session = asString(payload.session_id) ?? asString(payload.conversation_id) ?? null;\n const toolInput = payload.tool_input && typeof payload.tool_input === 'object' ? (payload.tool_input as Record<string, unknown>) : null;\n const tool = asString(payload.tool_name) ?? asString(payload.tool) ?? null;\n const rawCommand = asString(toolInput?.command) ?? asString(payload.command);\n const command = rawCommand ? truncate(rawCommand) : null;\n const files = filesFrom(toolInput, payload);\n\n let c: Classified | null = null;\n if (h === 'sessionstart' || h === 'workspaceopen') c = { kind: 'session-start', state: 'IDLE', message: 'Session started' };\n else if (h === 'sessionend') c = { kind: 'session-end', state: 'IDLE', message: 'Session ended' };\n else if (h === 'userpromptsubmit' || h === 'beforesubmitprompt') c = { kind: 'prompt', state: 'PLANNING', message: 'Received a new task from the developer' };\n else if (h === 'stop' || h === 'afteragentresponse') c = { kind: 'stop', state: 'SUCCESS', message: 'Finished responding' };\n else if (h === 'subagentstart') c = { kind: 'subagent', state: 'PLANNING', message: 'Subagent started' };\n else if (h === 'subagentstop') c = { kind: 'subagent', state: 'CODING', message: 'Subagent finished' };\n else if (h === 'beforeshellexecution') c = classifyTool('bash', command, files);\n else if (h === 'aftershellexecution') return null; // the \"before\" event already reported it\n else if (h === 'beforereadfile' || h === 'beforetabfileread') c = classifyTool('read', null, files);\n else if (h === 'afterfileedit' || h === 'aftertabfileedit') c = classifyTool('edit', null, files);\n else if (h === 'pretooluse' || h === 'permissionrequest') c = tool ? classifyTool(tool, command, files) : null;\n else if (h === 'posttooluse' || h === 'posttoolusefailure') return null; // avoid duplicating PreToolUse\n else if (h === 'pretoolusefailure') return null;\n else c = { kind: 'other', state: 'CODING', message: `Hook: ${hook}` };\n\n if (!c) return null;\n return {\n id: crypto.randomUUID(),\n ts: new Date().toISOString(),\n agent,\n session,\n hook,\n kind: c.kind,\n state: c.state,\n message: c.message,\n files: files.slice(0, 10),\n command,\n tool,\n };\n}\n\n/** Hook events Athena installs, per agent. */\nexport const CLAUDE_HOOK_EVENTS = ['SessionStart', 'UserPromptSubmit', 'PreToolUse', 'Stop', 'SessionEnd'] as const;\nexport const CURSOR_HOOK_EVENTS = ['sessionStart', 'beforeSubmitPrompt', 'beforeShellExecution', 'afterFileEdit', 'stop', 'sessionEnd'] as const;\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport type { AgentAdapter, PlannedFileChange } from '../../core/agents/adapter.js';\nimport { readTextIfExists } from '../../core/util/fs.js';\nimport { athenaInstructions } from '../common/instructions.js';\nimport { OWNED_HEADER, planOwned, removeOwned, userEvidence } from '../common/files.js';\nimport { CURSOR_HOOK_EVENTS } from '../common/hook-events.js';\nimport { isAthenaEntry, hookScript, mergeMcpServers, planJsonChange, pruneEmpty, removeJsonHooks, stripMcpServers } from '../common/hooks.js';\n\nconst RULE_FILE = '.cursor/rules/athena.mdc';\nconst HOOKS_FILE = '.cursor/hooks.json';\nconst HOOK_DIR = '.cursor/hooks';\nconst MCP_FILE = '.cursor/mcp.json';\n\n/**\n * Cursor:\n * - rules: .cursor/rules/athena.mdc with frontmatter (alwaysApply)\n * - activity: .cursor/hooks.json ({ version: 1, hooks: { <event>: [{ command }] } })\n * per https://cursor.com/docs/agent/hooks (checked 2026-09). Cursor runs a script\n * path, so Athena writes a small forwarding script for the current platform.\n */\nexport const cursorAdapter: AgentAdapter = {\n id: 'cursor',\n displayName: 'Cursor',\n capabilities: { instructionsFile: true, scopedRules: true, hooks: true, mcp: true },\n supportNote: 'Uses an Athena-owned project rule at .cursor/rules/athena.mdc, hooks in .cursor/hooks.json that report activity, and an MCP server entry in .cursor/mcp.json.',\n async detectPresence(root) {\n const evidence = await userEvidence(root, { files: ['.cursorrules'], dirs: ['.cursor'], athenaOwned: [RULE_FILE, `${HOOK_DIR}/athena-hook.sh`, `${HOOK_DIR}/athena-hook.cmd`], athenaOwnedJson: [HOOKS_FILE, MCP_FILE] });\n return { detectedInProject: evidence.length > 0, evidence };\n },\n async plan(ctx) {\n const content = ['---', 'description: Athena project intelligence — how to use .athena/ knowledge and project rules', 'globs:', 'alwaysApply: true', '---', OWNED_HEADER, '', athenaInstructions({ heading: '#' }), ''].join('\\n');\n const changes: PlannedFileChange[] = [await planOwned(ctx.root, RULE_FILE, content)];\n\n const script = hookScript('cursor');\n const scriptRel = `${HOOK_DIR}/${script.file}`;\n changes.push(await planOwned(ctx.root, scriptRel, script.content));\n changes.push(\n await planJsonChange(ctx.root, HOOKS_FILE, (data) => {\n data.version = typeof data.version === 'number' ? data.version : 1;\n const hooks = (data.hooks && typeof data.hooks === 'object' && !Array.isArray(data.hooks) ? data.hooks : {}) as Record<string, Array<Record<string, unknown>>>;\n for (const event of CURSOR_HOOK_EVENTS) {\n const list = (Array.isArray(hooks[event]) ? hooks[event] : []).filter((e) => !isAthenaEntry(e));\n list.push({ command: `./${scriptRel} ${event} --athena-hook`, timeout: 10 });\n hooks[event] = list;\n }\n data.hooks = hooks;\n }),\n );\n changes.push(await planJsonChange(ctx.root, MCP_FILE, mergeMcpServers));\n return changes;\n },\n async remove(root) {\n const touched: string[] = [];\n if (await removeOwned(root, RULE_FILE)) touched.push(RULE_FILE);\n if (await removeJsonHooks(root, MCP_FILE, stripMcpServers, (d) => Object.keys(d).length === 0)) touched.push(MCP_FILE);\n for (const f of ['athena-hook.sh', 'athena-hook.cmd']) {\n if (await removeOwned(root, `${HOOK_DIR}/${f}`)) touched.push(`${HOOK_DIR}/${f}`);\n }\n const removed = await removeJsonHooks(\n root,\n HOOKS_FILE,\n (data) => {\n const hooks = data.hooks as Record<string, Array<Record<string, unknown>>> | undefined;\n if (!hooks) return;\n for (const event of Object.keys(hooks)) {\n hooks[event] = (hooks[event] ?? []).filter((e) => !isAthenaEntry(e));\n if (!hooks[event]!.length) delete hooks[event];\n }\n pruneEmpty(data, 'hooks');\n if (Object.keys(data).length === 1 && 'version' in data) delete data.version;\n },\n (data) => Object.keys(data).length === 0,\n );\n if (removed) touched.push(HOOKS_FILE);\n await fs.rm(path.join(root, HOOK_DIR), { recursive: true, force: true }).catch(() => {});\n return touched;\n },\n async check(root) {\n const text = await readTextIfExists(path.join(root, RULE_FILE));\n const checks = [];\n if (text === null) checks.push({ ok: false, level: 'warn' as const, message: `Cursor: ${RULE_FILE} not found` });\n else if (!/^---[\\s\\S]*?alwaysApply:\\s*true[\\s\\S]*?---/.test(text)) checks.push({ ok: false, level: 'warn' as const, message: `Cursor: ${RULE_FILE} frontmatter was modified (alwaysApply is not true)` });\n else checks.push({ ok: true, level: 'ok' as const, message: `Cursor: ${RULE_FILE}` });\n\n const hooks = await readTextIfExists(path.join(root, HOOKS_FILE));\n if (hooks === null) checks.push({ ok: false, level: 'warn' as const, message: `Cursor: ${HOOKS_FILE} not found — activity reporting is off` });\n else if (!hooks.includes('--athena-hook')) checks.push({ ok: false, level: 'warn' as const, message: `Cursor: no Athena hooks in ${HOOKS_FILE}` });\n else checks.push({ ok: true, level: 'ok' as const, message: `Cursor: activity hooks installed (${CURSOR_HOOK_EVENTS.length} events)` });\n return checks;\n },\n};\n","import path from 'node:path';\nimport type { AgentAdapter } from '../../core/agents/adapter.js';\nimport { readTextIfExists } from '../../core/util/fs.js';\nimport { athenaInstructions } from '../common/instructions.js';\nimport { OWNED_HEADER, planOwned, removeOwned, userEvidence } from '../common/files.js';\n\nconst RULE_FILE = '.agents/rules/athena.md';\n/** Antigravity documents a 12,000 character limit per rule file. */\nexport const ANTIGRAVITY_RULE_LIMIT = 12_000;\n\n/**\n * Google Antigravity reads workspace rules from `.agents/rules/` (legacy: `.agent/rules/`),\n * one Markdown file per rule, max 12,000 characters.\n * Source: https://antigravity.google/docs/rules-workflows/ (checked 2026-09).\n * Activation mode (Always On / Model Decision / Glob / Manual) is configured in\n * Antigravity; its frontmatter format is not documented, so Athena does not write one.\n */\nexport const antigravityAdapter: AgentAdapter = {\n id: 'antigravity',\n displayName: 'Antigravity',\n capabilities: { instructionsFile: true, scopedRules: true, hooks: false, mcp: true },\n supportNote: 'Uses an Athena-owned workspace rule at .agents/rules/athena.md. Set its activation to \"Always On\" in Antigravity if it is not applied automatically.',\n async detectPresence(root) {\n const evidence = await userEvidence(root, { files: ['GEMINI.md'], dirs: ['.agents', '.agent'], athenaOwned: [RULE_FILE] });\n return { detectedInProject: evidence.length > 0, evidence };\n },\n async plan(ctx) {\n const content = [OWNED_HEADER, '', athenaInstructions({ heading: '#' }), ''].join('\\n');\n if (content.length > ANTIGRAVITY_RULE_LIMIT) throw new Error(`Antigravity rule exceeds ${ANTIGRAVITY_RULE_LIMIT} characters`);\n return [await planOwned(ctx.root, RULE_FILE, content)];\n },\n async remove(root) {\n return (await removeOwned(root, RULE_FILE)) ? [RULE_FILE] : [];\n },\n async check(root) {\n const text = await readTextIfExists(path.join(root, RULE_FILE));\n if (text === null) return [{ ok: false, level: 'warn', message: `Antigravity: ${RULE_FILE} not found` }];\n if (text.length > ANTIGRAVITY_RULE_LIMIT) return [{ ok: false, level: 'error', message: `Antigravity: ${RULE_FILE} exceeds the 12,000 character rule limit` }];\n return [\n { ok: true, level: 'ok', message: `Antigravity: ${RULE_FILE}` },\n { ok: true, level: 'warn', message: 'Antigravity: activation mode cannot be verified from files — confirm the rule is \"Always On\" in Antigravity' },\n ];\n },\n};\n","import type { AgentAdapter } from '../../core/agents/adapter.js';\nimport { athenaInstructions } from '../common/instructions.js';\nimport { checkBlock, planBlock, removeBlockFrom, userEvidence } from '../common/files.js';\n\n/**\n * AGENTS.md is an open, cross-tool instruction file convention read by many\n * coding agents. Athena manages a marked block so agents without a dedicated\n * adapter still discover the knowledge layer.\n */\nexport const agentsMdAdapter: AgentAdapter = {\n id: 'agents-md',\n displayName: 'AGENTS.md (cross-agent)',\n capabilities: { instructionsFile: true, scopedRules: false, hooks: false, mcp: false },\n supportNote: 'Manages a marked block in AGENTS.md for agents that read the AGENTS.md convention.',\n async detectPresence(root) {\n const evidence = await userEvidence(root, { files: ['AGENTS.md'] });\n return { detectedInProject: evidence.length > 0, evidence };\n },\n async plan(ctx) {\n return [await planBlock(ctx.root, 'AGENTS.md', athenaInstructions({ heading: '##' }))];\n },\n async remove(root) {\n return (await removeBlockFrom(root, 'AGENTS.md')) ? ['AGENTS.md'] : [];\n },\n async check(root) {\n return [await checkBlock(root, 'AGENTS.md', 'AGENTS.md')];\n },\n};\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport crypto from 'node:crypto';\nimport { analyzeProject, type AnalysisResult } from '../core/analyzer/analyze.js';\nimport { ATHENA_DIR } from '../core/config.js';\nimport { ensureRules, writeKnowledge, type DocWriteReport } from '../core/knowledge/generate.js';\nimport { athenaDir, backupCorruptedState, buildFileIndex, readState, writeState, type AthenaState } from '../core/state/state.js';\nimport { exists, readTextIfExists, sha256, writeFileAtomic } from '../core/util/fs.js';\nimport type { FileEntry } from '../core/fs/walker.js';\nimport type { AgentAdapter, PlannedFileChange } from '../core/agents/adapter.js';\nimport { ADAPTERS, applyChanges } from '../agents/registry.js';\nimport { ATHENA_VERSION } from './version.js';\n\nexport interface PipelineOptions {\n root: string;\n mode: 'init' | 'analyze';\n force?: boolean;\n dryRun?: boolean;\n /** Explicit adapters; undefined = previously configured (analyze) or auto-detected (init). */\n agents?: AgentAdapter[];\n signal?: AbortSignal;\n onStage?: (stage: string) => void;\n}\n\nexport interface PipelineResult {\n analysis: AnalysisResult;\n docs: DocWriteReport[];\n agentChanges: Array<{ adapter: AgentAdapter; changes: PlannedFileChange[] }>;\n state: AthenaState | null;\n notes: string[];\n}\n\nconst ATHENA_GITIGNORE = [\n '# Local analysis cache — safe to delete, regenerated by `athena analyze`.',\n '# Commit the *.md knowledge files so your team and Git history share them.',\n 'state.json',\n 'model.json',\n 'graph.json',\n 'security-scan.json',\n 'ai-suggestions.md',\n '.backup/',\n '.server.json',\n '.sync-ignore.json',\n '.agent-events.jsonl',\n '',\n].join('\\n');\n\n/** Entries every .athena/.gitignore should carry; older projects are topped up in place. */\nconst GITIGNORE_ENTRIES = ['state.json', 'model.json', 'graph.json', 'security-scan.json', 'ai-suggestions.md', '.backup/', '.server.json', '.sync-ignore.json', '.agent-events.jsonl'];\n\nasync function ensureGitignoreEntries(file: string): Promise<void> {\n const existing = await readTextIfExists(file);\n if (existing === null) {\n await writeFileAtomic(file, ATHENA_GITIGNORE);\n return;\n }\n const lines = existing.split(/\\r?\\n/);\n const missing = GITIGNORE_ENTRIES.filter((e) => !lines.includes(e));\n if (!missing.length) return;\n await writeFileAtomic(file, `${existing.replace(/\\s*$/, '')}\\n${missing.join('\\n')}\\n`);\n}\n\n/** Include files Athena itself just wrote (agent integrations) so they don't show up as external changes. */\nexport async function indexWithIntegrations(root: string, files: FileEntry[], written: string[]): Promise<AthenaState['fileIndex']> {\n const index = buildFileIndex(files);\n for (const rel of written) {\n try {\n const abs = path.join(root, rel);\n const [st, buf] = await Promise.all([fs.stat(abs), fs.readFile(abs)]);\n index[rel] = { h: sha256(buf).slice(0, 16), s: st.size, m: Math.floor(st.mtimeMs) };\n } catch {\n /* removed or unreadable — leave as analyzed */\n }\n }\n return index;\n}\n\n/** Build the next state.json from an analysis and the documents written for it. */\nexport function composeState(input: { prevState: AthenaState | null; analysis: AnalysisResult; docs: DocWriteReport[]; agents: AthenaState['agents']; fileIndex: AthenaState['fileIndex'] }): AthenaState {\n const { prevState, analysis, docs } = input;\n const now = new Date().toISOString();\n const documents: AthenaState['documents'] = {};\n for (const d of docs) {\n const before = prevState?.documents[d.id];\n documents[d.id] = {\n file: d.file,\n blocks: d.blocks,\n lastGeneratedAt: now,\n lastChangedAt: d.status === 'unchanged' && before ? before.lastChangedAt : now,\n contentHash: d.contentHash,\n preservedModified: d.preservedModified,\n };\n }\n return {\n schemaVersion: 1,\n athenaVersion: ATHENA_VERSION,\n projectName: analysis.model.name,\n createdAt: prevState?.createdAt ?? now,\n analyzedAt: now,\n analysisDurationMs: analysis.durationMs,\n git: { isRepo: analysis.model.git.isRepo, head: analysis.model.git.head, branch: analysis.model.git.branch },\n fileIndex: input.fileIndex,\n documents,\n detectors: analysis.detectorVersions,\n agents: input.agents,\n warnings: analysis.model.warnings,\n };\n}\n\n/** Default adapter selection for init: agents detected in the project, plus the cross-agent AGENTS.md. */\nexport async function autoSelectAdapters(root: string): Promise<AgentAdapter[]> {\n const selected: AgentAdapter[] = [];\n for (const a of ADAPTERS) {\n if (a.id === 'agents-md' || (await a.detectPresence(root)).detectedInProject) selected.push(a);\n }\n return selected;\n}\n\nexport async function runPipeline(opts: PipelineOptions): Promise<PipelineResult> {\n const root = opts.root;\n const finalDir = athenaDir(root);\n const notes: string[] = [];\n\n const prev = await readState(finalDir);\n if (prev.kind === 'corrupted' && !opts.dryRun) {\n const backup = await backupCorruptedState(finalDir);\n notes.push(`state.json was corrupted (${prev.reason}); ${backup ? `moved to ${path.relative(root, backup)}` : 'it will be replaced'} and rebuilt.`);\n }\n const prevState = prev.kind === 'ok' ? prev.state : null;\n\n opts.onStage?.('analyze');\n const analysis = await analyzeProject(root, { signal: opts.signal, onStage: (s) => opts.onStage?.(s), reuse: prevState?.fileIndex });\n opts.signal?.throwIfAborted();\n\n const adapters = opts.agents ?? (prevState ? ADAPTERS.filter((a) => prevState.agents[a.id]?.configured) : await autoSelectAdapters(root));\n\n if (opts.dryRun) {\n const agentChanges = [];\n for (const adapter of adapters) agentChanges.push({ adapter, changes: await adapter.plan({ root, projectName: analysis.model.name }) });\n return { analysis, docs: [], agentChanges, state: null, notes };\n }\n\n // A fresh init builds into a temp directory and swaps it in, so an interrupted\n // run never leaves a half-written .athena/.\n const fresh = !(await exists(finalDir));\n const workDir = fresh ? path.join(root, `${ATHENA_DIR}.tmp-${crypto.randomBytes(4).toString('hex')}`) : finalDir;\n\n let docs: DocWriteReport[];\n try {\n opts.onStage?.('write');\n await fs.mkdir(workDir, { recursive: true });\n const previousBlocks = prevState ? Object.fromEntries(Object.entries(prevState.documents).map(([k, v]) => [k, v.blocks])) : undefined;\n docs = await writeKnowledge(workDir, analysis.model, { force: opts.force, previousBlocks });\n docs.push(await ensureRules(workDir, analysis.model));\n await writeFileAtomic(path.join(workDir, 'model.json'), `${JSON.stringify(analysis.model, null, 2)}\\n`);\n await ensureGitignoreEntries(path.join(workDir, '.gitignore'));\n opts.signal?.throwIfAborted();\n if (fresh) await fs.rename(workDir, finalDir);\n } catch (err) {\n if (fresh) await fs.rm(workDir, { recursive: true, force: true }).catch(() => {});\n throw err;\n }\n\n opts.onStage?.('agents');\n const agentChanges: PipelineResult['agentChanges'] = [];\n const agentsState: AthenaState['agents'] = { ...(prevState?.agents ?? {}) };\n for (const adapter of adapters) {\n try {\n const planned = await adapter.plan({ root, projectName: analysis.model.name });\n await applyChanges(root, planned);\n agentChanges.push({ adapter, changes: planned });\n agentsState[adapter.id] = { configured: true, files: planned.map((p) => p.path), configuredAt: new Date().toISOString() };\n } catch (err) {\n notes.push(`${adapter.displayName} integration not configured: ${(err as Error).message}`);\n }\n }\n\n const state = composeState({\n prevState,\n analysis,\n docs,\n agents: agentsState,\n fileIndex: await indexWithIntegrations(root, analysis.files, agentChanges.flatMap((a) => a.changes.map((c) => c.path))),\n });\n await writeState(finalDir, state);\n return { analysis, docs, agentChanges, state, notes };\n}\n","import path from 'node:path';\nimport { promises as fs } from 'node:fs';\nimport { loadConfig, type AthenaConfig } from '../config.js';\nimport { walkProject, type FileEntry } from '../fs/walker.js';\nimport { emptyModel, ProjectModel } from '../model/project-model.js';\nimport { createContext, type Detector } from './context.js';\nimport { structureDetector } from './detectors/structure.js';\nimport { manifestsDetector } from './detectors/manifests.js';\nimport { dependenciesDetector } from './detectors/dependencies.js';\nimport { envDetector } from './detectors/env.js';\nimport { infraDetector } from './detectors/infra.js';\nimport { testsDetector } from './detectors/tests.js';\nimport { databaseDetector } from './detectors/database.js';\nimport { routesDetector } from './detectors/routes.js';\nimport { authDetector } from './detectors/auth.js';\nimport { entryPointsDetector } from './detectors/entrypoints.js';\nimport { secretsDetector } from './detectors/secrets.js';\nimport { gitInfo } from '../git/git.js';\nimport { redact } from '../security/secrets.js';\n\n/** Ordered: later detectors may read earlier detectors' output. */\nexport const DETECTORS: Detector[] = [\n structureDetector,\n manifestsDetector,\n dependenciesDetector,\n envDetector,\n infraDetector,\n testsDetector,\n databaseDetector,\n routesDetector,\n authDetector,\n entryPointsDetector,\n secretsDetector,\n];\n\nexport type AnalysisStage = 'scan' | 'detect' | 'git' | 'finalize';\n\nexport interface AnalyzeOptions {\n signal?: AbortSignal;\n config?: AthenaConfig;\n onStage?: (stage: AnalysisStage, detail?: string) => void;\n onDetector?: (id: string, ms: number) => void;\n /** Previous file index: unchanged files (same size + mtime) are not re-hashed. */\n reuse?: Record<string, { h: string; s: number; m: number; b?: 1 }>;\n}\n\nexport interface AnalysisResult {\n model: ProjectModel;\n files: FileEntry[];\n config: AthenaConfig;\n detectorVersions: Record<string, number>;\n durationMs: number;\n}\n\nexport async function analyzeProject(rootInput: string, opts: AnalyzeOptions = {}): Promise<AnalysisResult> {\n const started = Date.now();\n const root = await fs.realpath(path.resolve(rootInput));\n const loaded = opts.config ? { config: opts.config } : await loadConfig(root);\n const config = loaded.config;\n const model = emptyModel(path.basename(root), root);\n if ('warning' in loaded && loaded.warning) model.warnings.push(loaded.warning);\n\n opts.onStage?.('scan');\n const walk = await walkProject(root, { config, signal: opts.signal, reuse: opts.reuse });\n model.stats = {\n filesScanned: walk.files.length,\n skippedBinary: walk.skippedBinary,\n skippedLarge: walk.skippedLarge,\n skippedUnreadable: walk.skippedUnreadable,\n };\n model.warnings.push(...walk.warnings);\n\n opts.onStage?.('detect');\n const ctx = createContext(root, config, walk.files, model, opts.signal);\n for (const d of DETECTORS) {\n opts.signal?.throwIfAborted();\n const t = Date.now();\n try {\n await d.run(ctx);\n } catch (err) {\n if (opts.signal?.aborted) throw err;\n model.warnings.push(`Detector \"${d.id}\" failed: ${(err as Error).message}`);\n }\n opts.onDetector?.(d.id, Date.now() - t);\n }\n\n opts.onStage?.('git');\n model.git = await gitInfo(root);\n\n opts.onStage?.('finalize');\n const redacted = redactDeep(model) as ProjectModel;\n // Validate our own output — a failure here is a bug, surfaced as a warning rather than a crash.\n const check = ProjectModel.safeParse(redacted);\n if (!check.success) redacted.warnings.push(`Internal model validation issue: ${check.error.issues[0]?.path.join('.')} ${check.error.issues[0]?.message}`);\n\n return {\n model: redacted,\n files: walk.files,\n config,\n detectorVersions: Object.fromEntries(DETECTORS.map((d) => [d.id, d.version])),\n durationMs: Date.now() - started,\n };\n}\n\n/** Apply secret redaction to every string in the model (defense in depth). */\nexport function redactDeep<T>(value: T): T {\n if (typeof value === 'string') return redact(value) as T;\n if (Array.isArray(value)) return value.map((v) => redactDeep(v)) as T;\n if (value && typeof value === 'object') {\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(value)) out[k] = redactDeep(v);\n return out as T;\n }\n return value;\n}\n","import { promises as fs } from 'node:fs';\nimport type { Dirent } from 'node:fs';\nimport path from 'node:path';\nimport crypto from 'node:crypto';\nimport type { AthenaConfig } from '../config.js';\nimport { IgnoreMatcher } from './ignore.js';\nimport { toPosix } from '../util/paths.js';\n\nexport interface FileEntry {\n /** Repo-relative POSIX path. */\n path: string;\n size: number;\n mtimeMs: number;\n /** sha256 of content; for oversized files, a metadata hash prefixed with \"meta:\". */\n hash: string;\n binary: boolean;\n large: boolean;\n}\n\nexport interface WalkResult {\n files: FileEntry[];\n skippedBinary: number;\n skippedLarge: number;\n skippedUnreadable: number;\n truncated: boolean;\n warnings: string[];\n}\n\nexport interface WalkOptions {\n config: AthenaConfig;\n signal?: AbortSignal;\n onProgress?: (scanned: number) => void;\n /**\n * Previous index (path → truncated hash/size/mtime). When size and mtime match, the\n * previous hash (and binary flag) is reused instead of re-reading the file.\n */\n reuse?: Record<string, { h: string; s: number; m: number; b?: 1 }>;\n /** Share a matcher (e.g. with a watcher). Nested .gitignore files found during the walk are registered on it. */\n matcher?: IgnoreMatcher;\n}\n\nconst SNIFF_BYTES = 8000;\n\nexport async function walkProject(root: string, opts: WalkOptions): Promise<WalkResult> {\n const rootReal = await fs.realpath(root);\n const matcher = opts.matcher ?? (await IgnoreMatcher.load(rootReal, opts.config));\n const result: WalkResult = { files: [], skippedBinary: 0, skippedLarge: 0, skippedUnreadable: 0, truncated: false, warnings: [] };\n const visitedDirs = new Set<string>([rootReal]);\n const pending: string[] = [];\n const isIgnored = (rel: string, isDir: boolean): boolean => matcher.ignores(rel, isDir);\n\n // Iterative DFS so huge trees don't blow the stack.\n const stack: string[] = [rootReal];\n while (stack.length) {\n opts.signal?.throwIfAborted();\n const dir = stack.pop()!;\n let entries: Dirent[];\n try {\n entries = await fs.readdir(dir, { withFileTypes: true });\n } catch (err) {\n result.skippedUnreadable++;\n result.warnings.push(`Cannot read directory ${toPosix(path.relative(rootReal, dir)) || '.'}: ${(err as NodeJS.ErrnoException).code ?? 'error'}`);\n continue;\n }\n entries.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));\n const dirRel = toPosix(path.relative(rootReal, dir));\n if (dirRel && entries.some((e) => e.name === '.gitignore' && e.isFile())) {\n const gi = await fs.readFile(path.join(dir, '.gitignore'), 'utf8').catch(() => null);\n if (gi !== null) matcher.setGitignore(dirRel, gi);\n }\n for (const ent of entries) {\n const abs = path.join(dir, ent.name);\n const rel = toPosix(path.relative(rootReal, abs));\n let isDir = ent.isDirectory();\n let isFile = ent.isFile();\n\n if (ent.isSymbolicLink()) {\n // Follow symlinks only if the target stays inside the project root.\n try {\n const target = await fs.realpath(abs);\n const relTarget = path.relative(rootReal, target);\n if (relTarget.startsWith('..') || path.isAbsolute(relTarget)) continue;\n const st = await fs.stat(target);\n isDir = st.isDirectory();\n isFile = st.isFile();\n if (isDir) {\n if (visitedDirs.has(target)) continue; // loop protection\n }\n } catch {\n continue; // broken link\n }\n }\n\n if (isDir) {\n if (isIgnored(rel, true)) continue;\n const real = await fs.realpath(abs).catch(() => abs);\n if (visitedDirs.has(real)) continue;\n visitedDirs.add(real);\n stack.push(abs);\n } else if (isFile) {\n if (isIgnored(rel, false)) continue;\n if (result.files.length + pending.length >= opts.config.maxFiles) {\n result.truncated = true;\n break;\n }\n pending.push(rel);\n }\n }\n if (result.truncated) break;\n if (pending.length >= 256) await flush();\n }\n await flush();\n\n if (result.truncated) {\n result.warnings.push(`File limit reached (${opts.config.maxFiles}); analysis is partial. Raise maxFiles in .athena/config.json or add ignores.`);\n }\n result.files.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));\n return result;\n\n async function flush(): Promise<void> {\n const batch = pending.splice(0, pending.length);\n await mapLimit(batch, 32, async (rel) => {\n opts.signal?.throwIfAborted();\n const entry = await indexFile(rootReal, rel, opts.config.maxFileBytes, opts.reuse?.[rel]);\n if (!entry) {\n result.skippedUnreadable++;\n return;\n }\n if (entry.binary) result.skippedBinary++;\n if (entry.large) result.skippedLarge++;\n result.files.push(entry);\n });\n opts.onProgress?.(result.files.length);\n }\n}\n\nasync function indexFile(root: string, rel: string, maxBytes: number, prev?: { h: string; s: number; m: number; b?: 1 }): Promise<FileEntry | null> {\n const abs = path.join(root, rel);\n try {\n const st = await fs.stat(abs);\n if (prev && prev.s === st.size && prev.m === Math.floor(st.mtimeMs)) {\n return { path: rel, size: st.size, mtimeMs: prev.m, hash: prev.h, binary: prev.b === 1, large: prev.h.startsWith('meta:') };\n }\n if (st.size > maxBytes) {\n return { path: rel, size: st.size, mtimeMs: Math.floor(st.mtimeMs), hash: `meta:${st.size}:${Math.floor(st.mtimeMs)}`, binary: false, large: true };\n }\n const buf = await fs.readFile(abs);\n const sniff = buf.subarray(0, SNIFF_BYTES);\n const binary = sniff.includes(0);\n return {\n path: rel,\n size: st.size,\n mtimeMs: Math.floor(st.mtimeMs),\n hash: crypto.createHash('sha256').update(buf).digest('hex'),\n binary,\n large: false,\n };\n } catch {\n return null;\n }\n}\n\nexport async function mapLimit<T, R>(items: T[], limit: number, fn: (item: T) => Promise<R>): Promise<R[]> {\n const out: R[] = new Array(items.length);\n let i = 0;\n const workers = Array.from({ length: Math.min(limit, items.length) }, async () => {\n while (i < items.length) {\n const idx = i++;\n out[idx] = await fn(items[idx]!);\n }\n });\n await Promise.all(workers);\n return out;\n}\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport ignoreFactory, { type Ignore } from 'ignore';\nimport { DEFAULT_IGNORES, type AthenaConfig } from '../config.js';\n\n/**\n * Gitignore-compatible matcher shared by the walker and the watcher:\n * default ignores, `.git/info/exclude`, nested `.gitignore` files (scoped to\n * their directory), and `.athena/config.json` ignore/include patterns.\n *\n * Matching is synchronous so it can be used from file-watcher callbacks;\n * nested `.gitignore` files are registered as they are discovered.\n */\nexport class IgnoreMatcher {\n private readonly base: Ignore;\n private readonly include: Ignore | null;\n /** Directory (repo-relative POSIX, \"\" for root) → rules from its .gitignore. */\n private readonly scoped = new Map<string, Ignore>();\n\n constructor(config: AthenaConfig) {\n this.base = ignoreFactory().add(DEFAULT_IGNORES.map((d) => `${d}/`)).add(config.ignore);\n this.include = config.include.length ? ignoreFactory().add(config.include) : null;\n }\n\n static async load(root: string, config: AthenaConfig): Promise<IgnoreMatcher> {\n const m = new IgnoreMatcher(config);\n const exclude = await fs.readFile(path.join(root, '.git', 'info', 'exclude'), 'utf8').catch(() => null);\n if (exclude) m.setGitignore('', exclude);\n const rootGi = await fs.readFile(path.join(root, '.gitignore'), 'utf8').catch(() => null);\n if (rootGi) m.setGitignore('', rootGi, true);\n return m;\n }\n\n /** Register (or replace) the rules of `<dir>/.gitignore`. `append` merges with existing rules for that dir. */\n setGitignore(dir: string, content: string, append = false): void {\n const existing = append ? this.scoped.get(dir) : undefined;\n this.scoped.set(dir, (existing ?? ignoreFactory()).add(content));\n }\n\n removeGitignore(dir: string): void {\n this.scoped.delete(dir);\n }\n\n /** Is the repo-relative POSIX path ignored? `isDir` enables directory-only patterns (\"build/\"). */\n ignores(rel: string, isDir = false): boolean {\n if (!rel || rel === '.') return false;\n const test = isDir ? `${rel}/` : rel;\n if (this.include?.ignores(test)) return false;\n if (this.base.ignores(test)) return true;\n for (const [dir, ig] of this.scoped) {\n if (dir === '') {\n if (ig.ignores(test)) return true;\n } else if (rel.startsWith(`${dir}/`)) {\n const sub = rel.slice(dir.length + 1);\n if (ig.ignores(isDir ? `${sub}/` : sub)) return true;\n }\n }\n return false;\n }\n}\n","import { z } from 'zod';\nimport { Provenance } from './fact.js';\n\nconst Named = z.object({ name: z.string(), provenance: Provenance });\n\nexport const Language = z.object({\n name: z.string(),\n files: z.number().int(),\n bytes: z.number().int(),\n});\n\nexport const Framework = Named.extend({\n category: z.enum(['frontend', 'backend', 'fullstack', 'mobile', 'desktop', 'orm', 'testing', 'other']),\n version: z.string().optional(),\n /** Workspace package root (repo-relative) this belongs to; \".\" for root. */\n root: z.string(),\n});\n\nexport const Manifest = z.object({\n path: z.string(),\n ecosystem: z.string(),\n name: z.string().optional(),\n version: z.string().optional(),\n dependencies: z.array(z.string()),\n devDependencies: z.array(z.string()),\n});\n\nexport const WorkspacePackage = z.object({\n name: z.string(),\n path: z.string(),\n kind: z.enum(['app', 'package', 'root', 'unknown']),\n ecosystem: z.string(),\n /** Names of other workspace packages this one depends on. */\n internalDependencies: z.array(z.string()),\n});\n\nexport const Command = z.object({\n name: z.string(),\n command: z.string(),\n source: z.string(),\n purpose: z.enum(['dev', 'build', 'test', 'lint', 'format', 'start', 'migrate', 'deploy', 'other']),\n});\n\nexport const Route = z.object({\n method: z.string(),\n path: z.string(),\n framework: z.string(),\n file: z.string(),\n line: z.number().int().optional(),\n provenance: Provenance,\n});\n\nexport const DbEntity = z.object({\n name: z.string(),\n kind: z.enum(['table', 'model', 'collection']),\n fields: z.array(z.object({ name: z.string(), type: z.string().optional(), attributes: z.array(z.string()) })),\n indexes: z.array(z.string()),\n relations: z.array(z.string()),\n file: z.string(),\n provenance: Provenance,\n});\n\nexport const Database = Named.extend({ kind: z.enum(['engine', 'orm', 'driver', 'service']) });\n\nexport const EnvVar = z.object({\n name: z.string(),\n /** Where the name was seen. Values are NEVER recorded. */\n references: z.array(z.string()),\n secretLike: z.boolean(),\n});\n\nexport const SecretFinding = z.object({\n type: z.string(),\n file: z.string(),\n line: z.number().int(),\n /** Short sha256 prefix of the matched value — allows dedup without storing the secret. */\n fingerprint: z.string(),\n});\n\nexport const CiJob = z.object({ system: z.string(), file: z.string(), name: z.string(), commands: z.array(z.string()) });\n\nexport const ContainerService = z.object({\n name: z.string(),\n image: z.string().optional(),\n ports: z.array(z.string()),\n dependsOn: z.array(z.string()),\n file: z.string(),\n});\n\nexport const TestInfo = z.object({\n frameworks: z.array(Named),\n testFileCount: z.number().int(),\n testDirs: z.array(z.string()),\n coverageConfigs: z.array(z.string()),\n /** Workspace packages that contain source files but zero detected test files (structural, not coverage). */\n packagesWithoutTests: z.array(z.string()),\n});\n\nexport const GitInfo = z.object({\n available: z.boolean(),\n isRepo: z.boolean(),\n branch: z.string().optional(),\n head: z.string().optional(),\n lastCommitDate: z.string().optional(),\n contributorCount: z.number().int().optional(),\n hotspots: z.array(z.object({ path: z.string(), commits: z.number().int() })),\n});\n\nexport const ProjectModel = z.object({\n schemaVersion: z.literal(1),\n name: z.string(),\n description: z.string().optional(),\n root: z.string(),\n stats: z.object({\n filesScanned: z.number().int(),\n skippedBinary: z.number().int(),\n skippedLarge: z.number().int(),\n skippedUnreadable: z.number().int(),\n }),\n topLevelDirs: z.array(z.string()),\n languages: z.array(Language),\n manifests: z.array(Manifest),\n packageManagers: z.array(Named),\n buildSystems: z.array(Named),\n workspace: z.object({\n isMonorepo: z.boolean(),\n tool: z.string().optional(),\n packages: z.array(WorkspacePackage),\n }),\n frameworks: z.array(Framework),\n entryPoints: z.array(z.object({ path: z.string(), provenance: Provenance })),\n commands: z.array(Command),\n databases: z.array(Database),\n dbEntities: z.array(DbEntity),\n migrations: z.array(z.object({ path: z.string(), tool: z.string(), count: z.number().int() })),\n routes: z.array(Route),\n apiSpecs: z.array(z.object({ path: z.string(), kind: z.enum(['openapi', 'graphql', 'grpc']) })),\n auth: z.array(Named.extend({ kind: z.enum(['library', 'provider', 'hashing', 'middleware', 'token']) })),\n containers: z.object({ dockerfiles: z.array(z.object({ path: z.string(), baseImages: z.array(z.string()), exposedPorts: z.array(z.string()) })), services: z.array(ContainerService) }),\n infrastructure: z.array(Named.extend({ kind: z.string(), file: z.string() })),\n ci: z.array(CiJob),\n tests: TestInfo,\n env: z.object({ vars: z.array(EnvVar), envFilesPresent: z.array(z.string()) }),\n security: z.object({\n secrets: z.array(SecretFinding),\n tooling: z.array(Named),\n /** Libraries/middleware relevant to web security controls (helmet, cors, csrf...). */\n controls: z.array(Named),\n }),\n caching: z.array(Named),\n queues: z.array(Named),\n observability: z.array(Named),\n git: GitInfo,\n warnings: z.array(z.string()),\n});\n\nexport type ProjectModel = z.infer<typeof ProjectModel>;\nexport type Framework = z.infer<typeof Framework>;\nexport type Manifest = z.infer<typeof Manifest>;\nexport type WorkspacePackage = z.infer<typeof WorkspacePackage>;\nexport type Command = z.infer<typeof Command>;\nexport type Route = z.infer<typeof Route>;\nexport type DbEntity = z.infer<typeof DbEntity>;\nexport type EnvVar = z.infer<typeof EnvVar>;\nexport type SecretFinding = z.infer<typeof SecretFinding>;\nexport type CiJob = z.infer<typeof CiJob>;\nexport type ContainerService = z.infer<typeof ContainerService>;\nexport type GitInfo = z.infer<typeof GitInfo>;\nexport type NamedFact = z.infer<typeof Named>;\n\nexport function emptyModel(name: string, root: string): ProjectModel {\n return {\n schemaVersion: 1,\n name,\n root,\n stats: { filesScanned: 0, skippedBinary: 0, skippedLarge: 0, skippedUnreadable: 0 },\n topLevelDirs: [],\n languages: [],\n manifests: [],\n packageManagers: [],\n buildSystems: [],\n workspace: { isMonorepo: false, packages: [] },\n frameworks: [],\n entryPoints: [],\n commands: [],\n databases: [],\n dbEntities: [],\n migrations: [],\n routes: [],\n apiSpecs: [],\n auth: [],\n containers: { dockerfiles: [], services: [] },\n infrastructure: [],\n ci: [],\n tests: { frameworks: [], testFileCount: 0, testDirs: [], coverageConfigs: [], packagesWithoutTests: [] },\n env: { vars: [], envFilesPresent: [] },\n security: { secrets: [], tooling: [], controls: [] },\n caching: [],\n queues: [],\n observability: [],\n git: { available: false, isRepo: false, hotspots: [] },\n warnings: [],\n };\n}\n","import { z } from 'zod';\n\n/**\n * Epistemic status of a piece of knowledge. This is the core anti-hallucination\n * mechanism: nothing is ever promoted to a higher status than its evidence supports.\n *\n * - FACT developer-asserted, or unambiguous declaration (e.g. a manifest dependency)\n * - DETECTED found by a detector, with evidence\n * - INFERRED heuristic conclusion (AI output is always at most INFERRED)\n * - UNKNOWN Athena looked and could not determine it\n */\nexport const FactStatus = z.enum(['FACT', 'DETECTED', 'INFERRED', 'UNKNOWN']);\nexport type FactStatus = z.infer<typeof FactStatus>;\n\nexport const Confidence = z.enum(['high', 'medium', 'low']);\nexport type Confidence = z.infer<typeof Confidence>;\n\nexport const FactSource = z.enum(['code', 'config', 'filesystem', 'git', 'developer', 'ai']);\nexport type FactSource = z.infer<typeof FactSource>;\n\nexport const Evidence = z.object({\n /** Repo-relative POSIX path. */\n file: z.string(),\n line: z.number().int().positive().optional(),\n detail: z.string().optional(),\n});\nexport type Evidence = z.infer<typeof Evidence>;\n\nexport const Provenance = z.object({\n status: FactStatus,\n confidence: Confidence,\n source: FactSource,\n evidence: z.array(Evidence),\n});\nexport type Provenance = z.infer<typeof Provenance>;\n\nexport function detected(\n source: FactSource,\n evidence: Evidence[],\n confidence: Confidence = 'high',\n): Provenance {\n return { status: 'DETECTED', confidence, source, evidence };\n}\n\nexport function inferred(\n source: FactSource,\n evidence: Evidence[],\n confidence: Confidence = 'medium',\n): Provenance {\n return { status: 'INFERRED', confidence, source, evidence };\n}\n\nexport function fact(source: FactSource, evidence: Evidence[]): Provenance {\n return { status: 'FACT', confidence: 'high', source, evidence };\n}\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport type { FileEntry } from '../fs/walker.js';\nimport type { ProjectModel } from '../model/project-model.js';\nimport type { AthenaConfig } from '../config.js';\n\nexport interface AnalysisContext {\n root: string;\n config: AthenaConfig;\n files: FileEntry[];\n model: ProjectModel;\n signal?: AbortSignal;\n /** Read a text file (repo-relative POSIX). Returns null for binary/oversized/missing files. */\n read(rel: string): Promise<string | null>;\n has(rel: string): boolean;\n /** Files whose path matches the predicate/regex. */\n find(match: RegExp | ((f: FileEntry) => boolean)): FileEntry[];\n warn(message: string): void;\n}\n\nexport interface Detector {\n id: string;\n /** Bump when detector output semantics change (recorded in state.json). */\n version: number;\n run(ctx: AnalysisContext): Promise<void>;\n}\n\nexport function createContext(root: string, config: AthenaConfig, files: FileEntry[], model: ProjectModel, signal?: AbortSignal): AnalysisContext {\n const byPath = new Map(files.map((f) => [f.path, f]));\n const cache = new Map<string, string | null>();\n return {\n root,\n config,\n files,\n model,\n signal,\n has: (rel) => byPath.has(rel),\n async read(rel) {\n if (cache.has(rel)) return cache.get(rel)!;\n const entry = byPath.get(rel);\n if (!entry || entry.binary || entry.large) return null;\n signal?.throwIfAborted();\n let text: string | null = null;\n try {\n text = await fs.readFile(path.join(root, rel), 'utf8');\n } catch {\n text = null;\n }\n // Only cache small files to bound memory on huge repos.\n if (!text || text.length < 256_000) cache.set(rel, text);\n return text;\n },\n find(match) {\n if (match instanceof RegExp) return files.filter((f) => match.test(f.path));\n return files.filter(match);\n },\n warn(message) {\n model.warnings.push(message);\n },\n };\n}\n","import type { Detector } from '../context.js';\n\nconst EXT_LANG: Record<string, string> = {\n ts: 'TypeScript', tsx: 'TypeScript', mts: 'TypeScript', cts: 'TypeScript',\n js: 'JavaScript', jsx: 'JavaScript', mjs: 'JavaScript', cjs: 'JavaScript',\n py: 'Python', go: 'Go', rs: 'Rust', java: 'Java', kt: 'Kotlin', kts: 'Kotlin',\n scala: 'Scala', swift: 'Swift', m: 'Objective-C', mm: 'Objective-C',\n c: 'C', h: 'C/C++ header', cc: 'C++', cpp: 'C++', cxx: 'C++', hpp: 'C++',\n cs: 'C#', fs: 'F#', vb: 'Visual Basic', php: 'PHP', rb: 'Ruby', dart: 'Dart',\n ex: 'Elixir', exs: 'Elixir', erl: 'Erlang', clj: 'Clojure', hs: 'Haskell',\n lua: 'Lua', r: 'R', jl: 'Julia', zig: 'Zig', sol: 'Solidity',\n vue: 'Vue', svelte: 'Svelte', astro: 'Astro',\n html: 'HTML', css: 'CSS', scss: 'SCSS', sass: 'Sass', less: 'Less',\n sql: 'SQL', sh: 'Shell', bash: 'Shell', zsh: 'Shell', ps1: 'PowerShell',\n tf: 'Terraform', hcl: 'HCL', proto: 'Protocol Buffers', graphql: 'GraphQL', gql: 'GraphQL',\n prisma: 'Prisma',\n};\n\nexport const structureDetector: Detector = {\n id: 'structure',\n version: 1,\n async run(ctx) {\n const langs = new Map<string, { files: number; bytes: number }>();\n const top = new Set<string>();\n for (const f of ctx.files) {\n const slash = f.path.indexOf('/');\n if (slash > 0) top.add(f.path.slice(0, slash));\n if (f.binary) continue;\n const dot = f.path.lastIndexOf('.');\n if (dot === -1 || dot < f.path.lastIndexOf('/')) continue;\n const lang = EXT_LANG[f.path.slice(dot + 1).toLowerCase()];\n if (!lang) continue;\n const cur = langs.get(lang) ?? { files: 0, bytes: 0 };\n cur.files++;\n cur.bytes += f.size;\n langs.set(lang, cur);\n }\n ctx.model.languages = [...langs.entries()]\n .map(([name, v]) => ({ name, ...v }))\n .sort((a, b) => b.bytes - a.bytes || a.name.localeCompare(b.name));\n ctx.model.topLevelDirs = [...top].sort();\n },\n};\n","import { parse as parseToml } from 'smol-toml';\nimport { parse as parseYaml } from 'yaml';\nimport ignoreFactory from 'ignore';\nimport type { AnalysisContext, Detector } from '../context.js';\nimport type { Command, Manifest, WorkspacePackage } from '../../model/project-model.js';\nimport { detected, fact } from '../../model/fact.js';\nimport { baseName, dirOf } from '../../util/paths.js';\n\ntype Obj = Record<string, unknown>;\nconst isObj = (v: unknown): v is Obj => typeof v === 'object' && v !== null && !Array.isArray(v);\nconst keys = (v: unknown): string[] => (isObj(v) ? Object.keys(v) : []);\n\ninterface Parsed {\n manifest: Manifest;\n workspaceGlobs?: string[];\n workspaceTool?: string;\n commands?: Command[];\n}\n\nfunction commandPurpose(name: string, cmd: string): Command['purpose'] {\n const n = name.toLowerCase();\n if (/^(dev|develop|serve|watch)(:|$)/.test(n)) return 'dev';\n if (/^build(:|$)/.test(n)) return 'build';\n if (/^(test|e2e|spec|coverage)(:|$)/.test(n) || /\\b(jest|vitest|pytest|playwright|cypress)\\b/.test(cmd)) return 'test';\n if (/^lint(:|$)|typecheck|type-check/.test(n)) return 'lint';\n if (/^(format|fmt|prettier)(:|$)/.test(n)) return 'format';\n if (/^start(:|$)/.test(n)) return 'start';\n if (/migrat|db:/.test(n)) return 'migrate';\n if (/deploy|release|publish/.test(n)) return 'deploy';\n return 'other';\n}\n\nasync function parseNpm(ctx: AnalysisContext, p: string): Promise<Parsed | null> {\n const text = await ctx.read(p);\n if (!text) return null;\n let json: Obj;\n try {\n json = JSON.parse(text) as Obj;\n } catch {\n ctx.warn(`Could not parse ${p} (invalid JSON)`);\n return null;\n }\n const scripts = isObj(json.scripts) ? json.scripts : {};\n const commands: Command[] = Object.entries(scripts)\n .filter(([, v]) => typeof v === 'string')\n .map(([name, v]) => ({ name, command: v as string, source: p, purpose: commandPurpose(name, v as string) }));\n let workspaceGlobs: string[] | undefined;\n if (Array.isArray(json.workspaces)) workspaceGlobs = json.workspaces.filter((x): x is string => typeof x === 'string');\n else if (isObj(json.workspaces) && Array.isArray(json.workspaces.packages)) workspaceGlobs = (json.workspaces.packages as unknown[]).filter((x): x is string => typeof x === 'string');\n return {\n manifest: {\n path: p,\n ecosystem: 'npm',\n name: typeof json.name === 'string' ? json.name : undefined,\n version: typeof json.version === 'string' ? json.version : undefined,\n dependencies: [...keys(json.dependencies), ...keys(json.peerDependencies)],\n devDependencies: keys(json.devDependencies),\n },\n workspaceGlobs,\n workspaceTool: workspaceGlobs ? 'npm/yarn workspaces' : undefined,\n commands,\n };\n}\n\nfunction pyReqName(spec: string): string | null {\n const m = /^\\s*([A-Za-z0-9][A-Za-z0-9._-]*)/.exec(spec);\n return m ? m[1]!.toLowerCase().replace(/_/g, '-') : null;\n}\n\nasync function parsePyproject(ctx: AnalysisContext, p: string): Promise<Parsed | null> {\n const text = await ctx.read(p);\n if (!text) return null;\n let t: Obj;\n try {\n t = parseToml(text) as Obj;\n } catch {\n ctx.warn(`Could not parse ${p} (invalid TOML)`);\n return null;\n }\n const project = isObj(t.project) ? t.project : {};\n const tool = isObj(t.tool) ? t.tool : {};\n const poetry = isObj(tool.poetry) ? tool.poetry : {};\n const deps = new Set<string>();\n const dev = new Set<string>();\n for (const d of Array.isArray(project.dependencies) ? project.dependencies : []) {\n const n = typeof d === 'string' ? pyReqName(d) : null;\n if (n) deps.add(n);\n }\n if (isObj(project['optional-dependencies'])) {\n for (const group of Object.values(project['optional-dependencies'])) {\n for (const d of Array.isArray(group) ? group : []) {\n const n = typeof d === 'string' ? pyReqName(d) : null;\n if (n) dev.add(n);\n }\n }\n }\n if (isObj(t['dependency-groups'])) {\n for (const group of Object.values(t['dependency-groups'])) {\n for (const d of Array.isArray(group) ? group : []) {\n const n = typeof d === 'string' ? pyReqName(d) : null;\n if (n) dev.add(n);\n }\n }\n }\n for (const k of keys(poetry.dependencies)) if (k.toLowerCase() !== 'python') deps.add(k.toLowerCase());\n for (const k of keys(poetry['dev-dependencies'])) dev.add(k.toLowerCase());\n if (isObj(poetry.group)) for (const g of Object.values(poetry.group)) if (isObj(g)) for (const k of keys(g.dependencies)) dev.add(k.toLowerCase());\n const commands: Command[] = [];\n const scripts = isObj(project.scripts) ? project.scripts : isObj(poetry.scripts) ? poetry.scripts : {};\n for (const [name, v] of Object.entries(scripts)) if (typeof v === 'string') commands.push({ name, command: v, source: p, purpose: commandPurpose(name, v) });\n const uvWs = isObj(tool.uv) && isObj(tool.uv.workspace) && Array.isArray(tool.uv.workspace.members) ? (tool.uv.workspace.members as string[]) : undefined;\n return {\n manifest: {\n path: p,\n ecosystem: 'python',\n name: typeof project.name === 'string' ? project.name : typeof poetry.name === 'string' ? poetry.name : undefined,\n version: typeof project.version === 'string' ? project.version : undefined,\n dependencies: [...deps],\n devDependencies: [...dev],\n },\n workspaceGlobs: uvWs,\n workspaceTool: uvWs ? 'uv workspace' : undefined,\n commands,\n };\n}\n\nasync function parseRequirements(ctx: AnalysisContext, p: string): Promise<Parsed | null> {\n const text = await ctx.read(p);\n if (text === null) return null;\n const deps: string[] = [];\n for (const line of text.split(/\\r?\\n/)) {\n const l = line.trim();\n if (!l || l.startsWith('#') || l.startsWith('-')) continue;\n const n = pyReqName(l);\n if (n) deps.push(n);\n }\n const isDev = /dev|test|lint/i.test(baseName(p));\n return { manifest: { path: p, ecosystem: 'python', dependencies: isDev ? [] : deps, devDependencies: isDev ? deps : [] } };\n}\n\nasync function parsePipfile(ctx: AnalysisContext, p: string): Promise<Parsed | null> {\n const text = await ctx.read(p);\n if (!text) return null;\n try {\n const t = parseToml(text) as Obj;\n return { manifest: { path: p, ecosystem: 'python', dependencies: keys(t.packages).map((k) => k.toLowerCase()), devDependencies: keys(t['dev-packages']).map((k) => k.toLowerCase()) } };\n } catch {\n ctx.warn(`Could not parse ${p}`);\n return null;\n }\n}\n\nasync function parseGoMod(ctx: AnalysisContext, p: string): Promise<Parsed | null> {\n const text = await ctx.read(p);\n if (!text) return null;\n const mod = /^module\\s+(\\S+)/m.exec(text)?.[1];\n const deps = new Set<string>();\n const block = /require\\s*\\(([\\s\\S]*?)\\)/g;\n for (const m of text.matchAll(block)) for (const line of m[1]!.split('\\n')) {\n const dep = /^\\s*(\\S+)\\s+v/.exec(line)?.[1];\n if (dep) deps.add(dep);\n }\n for (const m of text.matchAll(/^require\\s+(\\S+)\\s+v/gm)) deps.add(m[1]!);\n return { manifest: { path: p, ecosystem: 'go', name: mod, dependencies: [...deps], devDependencies: [] } };\n}\n\nasync function parseGoWork(ctx: AnalysisContext, p: string): Promise<Parsed | null> {\n const text = await ctx.read(p);\n if (!text) return null;\n const members: string[] = [];\n for (const m of text.matchAll(/use\\s*\\(([\\s\\S]*?)\\)/g)) for (const l of m[1]!.split('\\n')) if (l.trim()) members.push(l.trim().replace(/^\\.\\//, ''));\n for (const m of text.matchAll(/^use\\s+(\\S+)/gm)) if (m[1] !== '(') members.push(m[1]!.replace(/^\\.\\//, ''));\n return { manifest: { path: p, ecosystem: 'go', dependencies: [], devDependencies: [] }, workspaceGlobs: members, workspaceTool: 'go workspace' };\n}\n\nasync function parseCargo(ctx: AnalysisContext, p: string): Promise<Parsed | null> {\n const text = await ctx.read(p);\n if (!text) return null;\n let t: Obj;\n try {\n t = parseToml(text) as Obj;\n } catch {\n ctx.warn(`Could not parse ${p} (invalid TOML)`);\n return null;\n }\n const pkg = isObj(t.package) ? t.package : {};\n const ws = isObj(t.workspace) && Array.isArray(t.workspace.members) ? (t.workspace.members as string[]) : undefined;\n return {\n manifest: {\n path: p,\n ecosystem: 'cargo',\n name: typeof pkg.name === 'string' ? pkg.name : undefined,\n version: typeof pkg.version === 'string' ? pkg.version : undefined,\n dependencies: keys(t.dependencies),\n devDependencies: keys(t['dev-dependencies']),\n },\n workspaceGlobs: ws,\n workspaceTool: ws ? 'cargo workspace' : undefined,\n };\n}\n\nasync function parsePom(ctx: AnalysisContext, p: string): Promise<Parsed | null> {\n const text = await ctx.read(p);\n if (!text) return null;\n const noParent = text.replace(/<parent>[\\s\\S]*?<\\/parent>/, '').replace(/<dependencies>[\\s\\S]*<\\/dependencies>/, '').replace(/<build>[\\s\\S]*<\\/build>/, '');\n const name = /<artifactId>([^<]+)<\\/artifactId>/.exec(noParent)?.[1];\n const deps: string[] = [];\n const dev: string[] = [];\n for (const m of text.matchAll(/<dependency>([\\s\\S]*?)<\\/dependency>/g)) {\n const a = /<artifactId>([^<]+)<\\/artifactId>/.exec(m[1]!)?.[1];\n if (!a) continue;\n if (/<scope>\\s*test\\s*<\\/scope>/.test(m[1]!)) dev.push(a);\n else deps.push(a);\n }\n const modules = [...text.matchAll(/<module>([^<]+)<\\/module>/g)].map((m) => m[1]!.trim());\n return {\n manifest: { path: p, ecosystem: 'maven', name, dependencies: deps, devDependencies: dev },\n workspaceGlobs: modules.length ? modules : undefined,\n workspaceTool: modules.length ? 'maven multi-module' : undefined,\n };\n}\n\nasync function parseGradle(ctx: AnalysisContext, p: string): Promise<Parsed | null> {\n const text = await ctx.read(p);\n if (!text) return null;\n const deps: string[] = [];\n const dev: string[] = [];\n for (const m of text.matchAll(/\\b(implementation|api|compileOnly|runtimeOnly|testImplementation|testRuntimeOnly|kapt|ksp|annotationProcessor)\\s*\\(?\\s*[\"']([^\"':]+):([^\"':]+)(?::[^\"']*)?[\"']/g)) {\n (m[1]!.startsWith('test') ? dev : deps).push(m[3]!);\n }\n return { manifest: { path: p, ecosystem: 'gradle', dependencies: deps, devDependencies: dev } };\n}\n\nasync function parseGradleSettings(ctx: AnalysisContext, p: string): Promise<Parsed | null> {\n const text = await ctx.read(p);\n if (!text) return null;\n const members: string[] = [];\n for (const m of text.matchAll(/include\\s*\\(?([^)\\n]+)\\)?/g)) {\n for (const s of m[1]!.matchAll(/[\"']:?([^\"']+)[\"']/g)) members.push(s[1]!.replace(/:/g, '/'));\n }\n const name = /rootProject\\.name\\s*=\\s*[\"']([^\"']+)[\"']/.exec(text)?.[1];\n return {\n manifest: { path: p, ecosystem: 'gradle', name, dependencies: [], devDependencies: [] },\n workspaceGlobs: members.length ? members : undefined,\n workspaceTool: members.length ? 'gradle multi-project' : undefined,\n };\n}\n\nasync function parseComposer(ctx: AnalysisContext, p: string): Promise<Parsed | null> {\n const text = await ctx.read(p);\n if (!text) return null;\n try {\n const j = JSON.parse(text) as Obj;\n const scripts = isObj(j.scripts) ? j.scripts : {};\n const commands = Object.entries(scripts).filter(([, v]) => typeof v === 'string').map(([name, v]) => ({ name, command: v as string, source: p, purpose: commandPurpose(name, v as string) }));\n return {\n manifest: { path: p, ecosystem: 'composer', name: typeof j.name === 'string' ? j.name : undefined, dependencies: keys(j.require).filter((k) => k !== 'php' && !k.startsWith('ext-')), devDependencies: keys(j['require-dev']) },\n commands,\n };\n } catch {\n ctx.warn(`Could not parse ${p} (invalid JSON)`);\n return null;\n }\n}\n\nasync function parseCsproj(ctx: AnalysisContext, p: string): Promise<Parsed | null> {\n const text = await ctx.read(p);\n if (!text) return null;\n const deps = [...text.matchAll(/<PackageReference\\s+Include=[\"']([^\"']+)[\"']/g)].map((m) => m[1]!);\n if (/Sdk=[\"']Microsoft\\.NET\\.Sdk\\.Web[\"']/.test(text)) deps.push('Microsoft.AspNetCore.App');\n const isTest = /xunit|nunit|mstest/i.test(deps.join(' '));\n return { manifest: { path: p, ecosystem: 'nuget', name: baseName(p).replace(/\\.(cs|fs|vb)proj$/, ''), dependencies: isTest ? [] : deps, devDependencies: isTest ? deps : [] } };\n}\n\nasync function parseGemfile(ctx: AnalysisContext, p: string): Promise<Parsed | null> {\n const text = await ctx.read(p);\n if (!text) return null;\n const deps: string[] = [];\n const dev: string[] = [];\n let inDevGroup = false;\n for (const line of text.split(/\\r?\\n/)) {\n if (/^\\s*group\\s+.*:(development|test)/.test(line)) inDevGroup = true;\n else if (/^\\s*end\\b/.test(line)) inDevGroup = false;\n const m = /^\\s*gem\\s+[\"']([^\"']+)[\"']/.exec(line);\n if (m) (inDevGroup ? dev : deps).push(m[1]!);\n }\n return { manifest: { path: p, ecosystem: 'rubygems', dependencies: deps, devDependencies: dev } };\n}\n\nasync function parsePubspec(ctx: AnalysisContext, p: string): Promise<Parsed | null> {\n const text = await ctx.read(p);\n if (!text) return null;\n try {\n const y = parseYaml(text) as Obj;\n return { manifest: { path: p, ecosystem: 'pub', name: typeof y.name === 'string' ? y.name : undefined, dependencies: keys(y.dependencies), devDependencies: keys(y.dev_dependencies) } };\n } catch {\n ctx.warn(`Could not parse ${p} (invalid YAML)`);\n return null;\n }\n}\n\nasync function parseMix(ctx: AnalysisContext, p: string): Promise<Parsed | null> {\n const text = await ctx.read(p);\n if (!text) return null;\n const deps = [...text.matchAll(/\\{\\s*:([a-z0-9_]+)\\s*,/g)].map((m) => m[1]!);\n const name = /app:\\s*:([a-z0-9_]+)/.exec(text)?.[1];\n return { manifest: { path: p, ecosystem: 'hex', name, dependencies: deps, devDependencies: [] } };\n}\n\nasync function parsePnpmWorkspace(ctx: AnalysisContext, p: string): Promise<string[] | undefined> {\n const text = await ctx.read(p);\n if (!text) return undefined;\n try {\n const y = parseYaml(text) as Obj;\n return Array.isArray(y.packages) ? y.packages.filter((x): x is string => typeof x === 'string') : undefined;\n } catch {\n return undefined;\n }\n}\n\nconst PARSERS: Array<[RegExp, (ctx: AnalysisContext, p: string) => Promise<Parsed | null>]> = [\n [/(^|\\/)package\\.json$/, parseNpm],\n [/(^|\\/)pyproject\\.toml$/, parsePyproject],\n [/(^|\\/)requirements[^/]*\\.txt$/, parseRequirements],\n [/(^|\\/)Pipfile$/, parsePipfile],\n [/(^|\\/)go\\.mod$/, parseGoMod],\n [/(^|\\/)go\\.work$/, parseGoWork],\n [/(^|\\/)Cargo\\.toml$/, parseCargo],\n [/(^|\\/)pom\\.xml$/, parsePom],\n [/(^|\\/)build\\.gradle(\\.kts)?$/, parseGradle],\n [/(^|\\/)settings\\.gradle(\\.kts)?$/, parseGradleSettings],\n [/(^|\\/)composer\\.json$/, parseComposer],\n [/\\.(cs|fs|vb)proj$/, parseCsproj],\n [/(^|\\/)Gemfile$/, parseGemfile],\n [/(^|\\/)pubspec\\.yaml$/, parsePubspec],\n [/(^|\\/)mix\\.exs$/, parseMix],\n];\n\nconst LOCKFILES: Array<[RegExp, string]> = [\n [/(^|\\/)package-lock\\.json$/, 'npm'],\n [/(^|\\/)npm-shrinkwrap\\.json$/, 'npm'],\n [/(^|\\/)yarn\\.lock$/, 'yarn'],\n [/(^|\\/)pnpm-lock\\.yaml$/, 'pnpm'],\n [/(^|\\/)bun\\.lockb?$/, 'bun'],\n [/(^|\\/)poetry\\.lock$/, 'poetry'],\n [/(^|\\/)uv\\.lock$/, 'uv'],\n [/(^|\\/)Pipfile\\.lock$/, 'pipenv'],\n [/(^|\\/)pdm\\.lock$/, 'pdm'],\n [/(^|\\/)go\\.sum$/, 'go modules'],\n [/(^|\\/)Cargo\\.lock$/, 'cargo'],\n [/(^|\\/)composer\\.lock$/, 'composer'],\n [/(^|\\/)Gemfile\\.lock$/, 'bundler'],\n [/(^|\\/)pubspec\\.lock$/, 'pub'],\n [/(^|\\/)mix\\.lock$/, 'mix'],\n [/(^|\\/)packages\\.lock\\.json$/, 'nuget'],\n];\n\nconst BUILD_SYSTEMS: Array<[RegExp, string]> = [\n [/(^|\\/)turbo\\.json$/, 'Turborepo'],\n [/(^|\\/)nx\\.json$/, 'Nx'],\n [/(^|\\/)lerna\\.json$/, 'Lerna'],\n [/(^|\\/)(vite|vitest)\\.config\\.(js|ts|mjs|cjs)$/, 'Vite'],\n [/(^|\\/)webpack\\.config\\.(js|ts|cjs|mjs)$/, 'webpack'],\n [/(^|\\/)rollup\\.config\\.(js|ts|mjs)$/, 'Rollup'],\n [/(^|\\/)tsup\\.config\\.(js|ts)$/, 'tsup'],\n [/(^|\\/)tsconfig\\.json$/, 'TypeScript compiler'],\n [/(^|\\/)(Makefile|makefile|GNUmakefile)$/, 'Make'],\n [/(^|\\/)justfile$/i, 'just'],\n [/(^|\\/)Taskfile\\.ya?ml$/, 'Task'],\n [/(^|\\/)CMakeLists\\.txt$/, 'CMake'],\n [/(^|\\/)BUILD(\\.bazel)?$|(^|\\/)WORKSPACE(\\.bazel)?$|(^|\\/)MODULE\\.bazel$/, 'Bazel'],\n [/(^|\\/)build\\.gradle(\\.kts)?$/, 'Gradle'],\n [/(^|\\/)pom\\.xml$/, 'Maven'],\n [/\\.sln$/, '.NET solution'],\n];\n\nexport const manifestsDetector: Detector = {\n id: 'manifests',\n version: 1,\n async run(ctx) {\n const { model } = ctx;\n const parsed: Parsed[] = [];\n for (const [re, parser] of PARSERS) {\n for (const f of ctx.find(re)) {\n ctx.signal?.throwIfAborted();\n const r = await parser(ctx, f.path);\n if (r) parsed.push(r);\n }\n }\n parsed.sort((a, b) => a.manifest.path.localeCompare(b.manifest.path));\n model.manifests = parsed.map((p) => p.manifest);\n model.commands.push(...parsed.flatMap((p) => p.commands ?? []));\n\n // Makefile / justfile targets\n for (const f of ctx.find(/(^|\\/)(Makefile|makefile|justfile)$/)) {\n if (f.path.split('/').length > 3) continue;\n const text = await ctx.read(f.path);\n if (!text) continue;\n const isJust = baseName(f.path) === 'justfile';\n for (const m of text.matchAll(/^([A-Za-z0-9][A-Za-z0-9_.-]*)\\s*:(?!=)/gm)) {\n const name = m[1]!;\n if (name === 'PHONY' || name.startsWith('.')) continue;\n model.commands.push({ name, command: isJust ? `just ${name}` : `make ${name}`, source: f.path, purpose: commandPurpose(name, '') });\n }\n }\n\n // Package managers\n const pm = new Map<string, string[]>();\n for (const [re, name] of LOCKFILES) for (const f of ctx.find(re)) pm.set(name, [...(pm.get(name) ?? []), f.path]);\n for (const m of parsed) {\n const eco = m.manifest.ecosystem;\n const implied = eco === 'python' && baseName(m.manifest.path).startsWith('requirements') ? 'pip' : eco === 'maven' ? 'maven' : eco === 'gradle' ? 'gradle' : eco === 'nuget' ? 'dotnet' : null;\n if (implied && !pm.has(implied)) pm.set(implied, [m.manifest.path]);\n }\n const rootPkg = parsed.find((p) => p.manifest.path === 'package.json');\n if (rootPkg) {\n const text = await ctx.read('package.json');\n const declared = text ? /\"packageManager\"\\s*:\\s*\"([a-z]+)@/.exec(text)?.[1] : undefined;\n if (declared && !pm.has(declared)) pm.set(declared, ['package.json']);\n }\n model.packageManagers = [...pm.entries()].sort(([a], [b]) => a.localeCompare(b)).map(([name, files]) => ({\n name,\n provenance: detected('filesystem', files.slice(0, 5).map((file) => ({ file }))),\n }));\n\n // Build systems\n const bs = new Map<string, string[]>();\n for (const [re, name] of BUILD_SYSTEMS) for (const f of ctx.find(re)) bs.set(name, [...(bs.get(name) ?? []), f.path]);\n model.buildSystems = [...bs.entries()].sort(([a], [b]) => a.localeCompare(b)).map(([name, files]) => ({\n name,\n provenance: detected('filesystem', files.slice(0, 5).map((file) => ({ file }))),\n }));\n\n // Workspace / monorepo\n const globs: string[] = [];\n let tool: string | undefined;\n for (const p of parsed) {\n if (p.workspaceGlobs?.length && dirOf(p.manifest.path) === '.') {\n globs.push(...p.workspaceGlobs);\n tool ??= p.workspaceTool;\n }\n }\n if (ctx.has('pnpm-workspace.yaml')) {\n const g = await parsePnpmWorkspace(ctx, 'pnpm-workspace.yaml');\n if (g?.length) {\n globs.push(...g);\n tool = 'pnpm workspaces';\n }\n }\n const markerTool = ctx.has('turbo.json') ? 'Turborepo' : ctx.has('nx.json') ? 'Nx' : ctx.has('lerna.json') ? 'Lerna' : undefined;\n if (markerTool) tool = tool ? `${tool} + ${markerTool}` : markerTool;\n\n const manifestDirs = new Map<string, Manifest[]>();\n for (const m of model.manifests) {\n const d = dirOf(m.path);\n manifestDirs.set(d, [...(manifestDirs.get(d) ?? []), m]);\n }\n const matcher = globs.length ? ignoreFactory().add(globs.map((g) => g.replace(/^\\.\\//, '').replace(/\\/$/, ''))) : null;\n const pkgDirs = [...manifestDirs.keys()].filter((d) => d !== '.' && (matcher ? matcher.ignores(d) : true));\n const isMonorepo = globs.length > 0 || !!markerTool || (pkgDirs.length >= 2 && !manifestDirs.has('.'));\n model.workspace.isMonorepo = isMonorepo;\n model.workspace.tool = tool;\n\n const packages: WorkspacePackage[] = [];\n const dirsForPackages = isMonorepo ? ['.', ...pkgDirs] : manifestDirs.has('.') ? ['.'] : pkgDirs;\n for (const d of dirsForPackages) {\n const ms = manifestDirs.get(d);\n if (!ms) continue;\n const primary = ms.find((m) => m.name) ?? ms[0]!;\n const seg = d.split('/')[0] ?? '';\n const kind: WorkspacePackage['kind'] = d === '.' ? 'root' : /^(apps|services|examples)$/.test(seg) ? 'app' : /^(packages|libs|crates|modules|shared|internal)$/.test(seg) ? 'package' : 'unknown';\n packages.push({ name: primary.name ?? (d === '.' ? model.name : baseName(d)), path: d, kind, ecosystem: primary.ecosystem, internalDependencies: [] });\n }\n const names = new Set(packages.map((p) => p.name));\n for (const pkg of packages) {\n const deps = (manifestDirs.get(pkg.path) ?? []).flatMap((m) => [...m.dependencies, ...m.devDependencies]);\n pkg.internalDependencies = [...new Set(deps.filter((d) => names.has(d) && d !== pkg.name))].sort();\n }\n model.workspace.packages = packages;\n\n const rootManifest = model.manifests.find((m) => dirOf(m.path) === '.' && m.name);\n if (rootManifest?.name) model.name = rootManifest.name;\n const pkgJson = rootPkg ? await ctx.read('package.json') : null;\n if (pkgJson) {\n try {\n const d = (JSON.parse(pkgJson) as Obj).description;\n if (typeof d === 'string' && d.trim()) model.description = d.trim();\n } catch {\n /* already warned */\n }\n }\n\n // Record root manifest names as FACT-level provenance on entry points where declared.\n if (pkgJson) {\n try {\n const j = JSON.parse(pkgJson) as Obj;\n for (const field of ['main', 'module']) {\n const v = j[field];\n if (typeof v === 'string') model.entryPoints.push({ path: v.replace(/^\\.\\//, ''), provenance: fact('config', [{ file: 'package.json', detail: `\"${field}\" field` }]) });\n }\n if (isObj(j.bin)) for (const v of Object.values(j.bin)) if (typeof v === 'string') model.entryPoints.push({ path: v.replace(/^\\.\\//, ''), provenance: fact('config', [{ file: 'package.json', detail: '\"bin\" field' }]) });\n } catch {\n /* ignore */\n }\n }\n },\n};\n","/**\n * Known dependency → capability catalog. Matching a dependency name here yields a\n * DETECTED fact (\"X is a declared dependency\"), never a claim about *how* it is used.\n */\n\nexport type CatalogKind =\n | { type: 'framework'; category: 'frontend' | 'backend' | 'fullstack' | 'mobile' | 'desktop' | 'orm' | 'other' }\n | { type: 'database'; kind: 'engine' | 'orm' | 'driver' }\n | { type: 'auth'; kind: 'library' | 'provider' | 'hashing' | 'token' }\n | { type: 'cache' }\n | { type: 'queue' }\n | { type: 'observability' }\n | { type: 'securityControl' }\n | { type: 'securityTooling' }\n | { type: 'testing' };\n\nexport interface CatalogEntry {\n name: string;\n kind: CatalogKind;\n /** Config/marker files that corroborate usage (raises confidence). */\n markers?: RegExp[];\n}\n\ntype Eco = 'npm' | 'python' | 'go' | 'cargo' | 'maven' | 'composer' | 'nuget' | 'gem' | 'pub' | 'hex';\n\nconst fw = (category: Extract<CatalogKind, { type: 'framework' }>['category']): CatalogKind => ({ type: 'framework', category });\nconst db = (kind: 'engine' | 'orm' | 'driver'): CatalogKind => ({ type: 'database', kind });\nconst auth = (kind: 'library' | 'provider' | 'hashing' | 'token'): CatalogKind => ({ type: 'auth', kind });\nconst CACHE: CatalogKind = { type: 'cache' };\nconst QUEUE: CatalogKind = { type: 'queue' };\nconst OBS: CatalogKind = { type: 'observability' };\nconst SEC: CatalogKind = { type: 'securityControl' };\nconst SECTOOL: CatalogKind = { type: 'securityTooling' };\nconst TEST: CatalogKind = { type: 'testing' };\n\nexport const CATALOG: Record<Eco, Record<string, CatalogEntry>> = {\n npm: {\n next: { name: 'Next.js', kind: fw('fullstack'), markers: [/(^|\\/)next\\.config\\.(js|mjs|cjs|ts)$/] },\n react: { name: 'React', kind: fw('frontend') },\n vue: { name: 'Vue', kind: fw('frontend') },\n nuxt: { name: 'Nuxt', kind: fw('fullstack'), markers: [/(^|\\/)nuxt\\.config\\.(js|ts|mjs)$/] },\n '@angular/core': { name: 'Angular', kind: fw('frontend'), markers: [/(^|\\/)angular\\.json$/] },\n svelte: { name: 'Svelte', kind: fw('frontend') },\n '@sveltejs/kit': { name: 'SvelteKit', kind: fw('fullstack'), markers: [/(^|\\/)svelte\\.config\\.(js|ts)$/] },\n 'solid-js': { name: 'SolidJS', kind: fw('frontend') },\n astro: { name: 'Astro', kind: fw('fullstack'), markers: [/(^|\\/)astro\\.config\\.(mjs|ts|js)$/] },\n '@remix-run/react': { name: 'Remix', kind: fw('fullstack') },\n '@tanstack/react-start': { name: 'TanStack Start', kind: fw('fullstack') },\n '@tanstack/solid-start': { name: 'TanStack Start', kind: fw('fullstack') },\n '@tanstack/react-router': { name: 'TanStack Router', kind: fw('frontend') },\n '@tanstack/react-query': { name: 'TanStack Query', kind: fw('frontend') },\n '@vercel/node': { name: 'Vercel Functions (Node)', kind: fw('backend') },\n 'react-router': { name: 'React Router', kind: fw('frontend') },\n vite: { name: 'Vite', kind: fw('other'), markers: [/(^|\\/)vite\\.config\\.(js|ts|mjs)$/] },\n 'react-native': { name: 'React Native', kind: fw('mobile') },\n expo: { name: 'Expo', kind: fw('mobile'), markers: [/(^|\\/)app\\.json$/] },\n electron: { name: 'Electron', kind: fw('desktop') },\n '@tauri-apps/api': { name: 'Tauri', kind: fw('desktop') },\n express: { name: 'Express', kind: fw('backend') },\n fastify: { name: 'Fastify', kind: fw('backend') },\n koa: { name: 'Koa', kind: fw('backend') },\n hono: { name: 'Hono', kind: fw('backend') },\n '@nestjs/core': { name: 'NestJS', kind: fw('backend'), markers: [/(^|\\/)nest-cli\\.json$/] },\n '@trpc/server': { name: 'tRPC', kind: fw('backend') },\n '@apollo/server': { name: 'Apollo Server', kind: fw('backend') },\n 'apollo-server': { name: 'Apollo Server', kind: fw('backend') },\n graphql: { name: 'GraphQL', kind: fw('other') },\n tailwindcss: { name: 'Tailwind CSS', kind: fw('frontend') },\n prisma: { name: 'Prisma', kind: db('orm'), markers: [/(^|\\/)schema\\.prisma$/] },\n '@prisma/client': { name: 'Prisma', kind: db('orm'), markers: [/(^|\\/)schema\\.prisma$/] },\n 'drizzle-orm': { name: 'Drizzle ORM', kind: db('orm'), markers: [/(^|\\/)drizzle\\.config\\.(ts|js)$/] },\n typeorm: { name: 'TypeORM', kind: db('orm') },\n sequelize: { name: 'Sequelize', kind: db('orm') },\n mongoose: { name: 'Mongoose', kind: db('orm') },\n knex: { name: 'Knex', kind: db('orm') },\n kysely: { name: 'Kysely', kind: db('orm') },\n '@mikro-orm/core': { name: 'MikroORM', kind: db('orm') },\n pg: { name: 'PostgreSQL (pg driver)', kind: db('driver') },\n postgres: { name: 'PostgreSQL (postgres.js driver)', kind: db('driver') },\n mysql: { name: 'MySQL driver', kind: db('driver') },\n mysql2: { name: 'MySQL driver', kind: db('driver') },\n 'better-sqlite3': { name: 'SQLite (better-sqlite3)', kind: db('driver') },\n sqlite3: { name: 'SQLite driver', kind: db('driver') },\n mongodb: { name: 'MongoDB driver', kind: db('driver') },\n '@supabase/supabase-js': { name: 'Supabase', kind: db('driver') },\n firebase: { name: 'Firebase', kind: db('driver') },\n 'firebase-admin': { name: 'Firebase Admin', kind: db('driver') },\n '@planetscale/database': { name: 'PlanetScale driver', kind: db('driver') },\n '@neondatabase/serverless': { name: 'Neon serverless driver', kind: db('driver') },\n 'next-auth': { name: 'NextAuth.js / Auth.js', kind: auth('library') },\n '@auth/core': { name: 'Auth.js', kind: auth('library') },\n 'better-auth': { name: 'Better Auth', kind: auth('library') },\n passport: { name: 'Passport', kind: auth('library') },\n lucia: { name: 'Lucia', kind: auth('library') },\n '@clerk/nextjs': { name: 'Clerk', kind: auth('provider') },\n '@clerk/clerk-react': { name: 'Clerk', kind: auth('provider') },\n '@auth0/nextjs-auth0': { name: 'Auth0', kind: auth('provider') },\n 'auth0': { name: 'Auth0', kind: auth('provider') },\n '@supabase/auth-helpers-nextjs': { name: 'Supabase Auth', kind: auth('provider') },\n '@supabase/ssr': { name: 'Supabase SSR Auth', kind: auth('provider') },\n 'firebase-auth': { name: 'Firebase Auth', kind: auth('provider') },\n jsonwebtoken: { name: 'jsonwebtoken (JWT)', kind: auth('token') },\n jose: { name: 'jose (JWT/JWE)', kind: auth('token') },\n 'express-session': { name: 'express-session', kind: auth('library') },\n 'iron-session': { name: 'iron-session', kind: auth('library') },\n bcrypt: { name: 'bcrypt', kind: auth('hashing') },\n bcryptjs: { name: 'bcryptjs', kind: auth('hashing') },\n argon2: { name: 'argon2', kind: auth('hashing') },\n '@node-rs/argon2': { name: 'argon2', kind: auth('hashing') },\n ioredis: { name: 'Redis (ioredis)', kind: CACHE },\n redis: { name: 'Redis client', kind: CACHE },\n '@upstash/redis': { name: 'Upstash Redis', kind: CACHE },\n 'lru-cache': { name: 'lru-cache', kind: CACHE },\n 'node-cache': { name: 'node-cache', kind: CACHE },\n bullmq: { name: 'BullMQ', kind: QUEUE },\n bull: { name: 'Bull', kind: QUEUE },\n 'bee-queue': { name: 'Bee-Queue', kind: QUEUE },\n amqplib: { name: 'RabbitMQ (amqplib)', kind: QUEUE },\n kafkajs: { name: 'Kafka (kafkajs)', kind: QUEUE },\n '@aws-sdk/client-sqs': { name: 'AWS SQS', kind: QUEUE },\n inngest: { name: 'Inngest', kind: QUEUE },\n '@trigger.dev/sdk': { name: 'Trigger.dev', kind: QUEUE },\n '@sentry/node': { name: 'Sentry', kind: OBS },\n '@sentry/nextjs': { name: 'Sentry', kind: OBS },\n '@sentry/react': { name: 'Sentry', kind: OBS },\n pino: { name: 'Pino logger', kind: OBS },\n winston: { name: 'Winston logger', kind: OBS },\n '@opentelemetry/api': { name: 'OpenTelemetry', kind: OBS },\n 'dd-trace': { name: 'Datadog APM', kind: OBS },\n helmet: { name: 'helmet', kind: SEC },\n cors: { name: 'cors', kind: SEC },\n '@fastify/cors': { name: '@fastify/cors', kind: SEC },\n '@fastify/helmet': { name: '@fastify/helmet', kind: SEC },\n csurf: { name: 'csurf (deprecated)', kind: SEC },\n 'csrf-csrf': { name: 'csrf-csrf', kind: SEC },\n 'express-rate-limit': { name: 'express-rate-limit', kind: SEC },\n '@fastify/rate-limit': { name: '@fastify/rate-limit', kind: SEC },\n zod: { name: 'zod (schema validation)', kind: SEC },\n joi: { name: 'joi (schema validation)', kind: SEC },\n yup: { name: 'yup (schema validation)', kind: SEC },\n 'class-validator': { name: 'class-validator', kind: SEC },\n dompurify: { name: 'DOMPurify', kind: SEC },\n 'isomorphic-dompurify': { name: 'DOMPurify', kind: SEC },\n eslint: { name: 'ESLint', kind: SECTOOL },\n 'eslint-plugin-security': { name: 'eslint-plugin-security', kind: SECTOOL },\n snyk: { name: 'Snyk', kind: SECTOOL },\n jest: { name: 'Jest', kind: TEST },\n vitest: { name: 'Vitest', kind: TEST },\n mocha: { name: 'Mocha', kind: TEST },\n ava: { name: 'AVA', kind: TEST },\n '@playwright/test': { name: 'Playwright', kind: TEST },\n cypress: { name: 'Cypress', kind: TEST },\n '@testing-library/react': { name: 'Testing Library', kind: TEST },\n supertest: { name: 'Supertest', kind: TEST },\n detox: { name: 'Detox', kind: TEST },\n },\n python: {\n django: { name: 'Django', kind: fw('fullstack'), markers: [/(^|\\/)manage\\.py$/] },\n djangorestframework: { name: 'Django REST Framework', kind: fw('backend') },\n fastapi: { name: 'FastAPI', kind: fw('backend') },\n flask: { name: 'Flask', kind: fw('backend') },\n starlette: { name: 'Starlette', kind: fw('backend') },\n litestar: { name: 'Litestar', kind: fw('backend') },\n tornado: { name: 'Tornado', kind: fw('backend') },\n aiohttp: { name: 'aiohttp', kind: fw('backend') },\n streamlit: { name: 'Streamlit', kind: fw('frontend') },\n pydantic: { name: 'Pydantic (validation)', kind: SEC },\n sqlalchemy: { name: 'SQLAlchemy', kind: db('orm') },\n sqlmodel: { name: 'SQLModel', kind: db('orm') },\n 'tortoise-orm': { name: 'Tortoise ORM', kind: db('orm') },\n peewee: { name: 'Peewee', kind: db('orm') },\n alembic: { name: 'Alembic migrations', kind: db('orm') },\n 'psycopg2': { name: 'PostgreSQL (psycopg2)', kind: db('driver') },\n 'psycopg2-binary': { name: 'PostgreSQL (psycopg2)', kind: db('driver') },\n psycopg: { name: 'PostgreSQL (psycopg 3)', kind: db('driver') },\n asyncpg: { name: 'PostgreSQL (asyncpg)', kind: db('driver') },\n pymysql: { name: 'MySQL (PyMySQL)', kind: db('driver') },\n mysqlclient: { name: 'MySQL (mysqlclient)', kind: db('driver') },\n pymongo: { name: 'MongoDB (pymongo)', kind: db('driver') },\n motor: { name: 'MongoDB (motor)', kind: db('driver') },\n 'django-allauth': { name: 'django-allauth', kind: auth('library') },\n 'djangorestframework-simplejwt': { name: 'Simple JWT (DRF)', kind: auth('token') },\n pyjwt: { name: 'PyJWT', kind: auth('token') },\n 'python-jose': { name: 'python-jose', kind: auth('token') },\n authlib: { name: 'Authlib', kind: auth('library') },\n 'flask-login': { name: 'Flask-Login', kind: auth('library') },\n 'fastapi-users': { name: 'FastAPI Users', kind: auth('library') },\n passlib: { name: 'passlib', kind: auth('hashing') },\n bcrypt: { name: 'bcrypt', kind: auth('hashing') },\n 'argon2-cffi': { name: 'argon2-cffi', kind: auth('hashing') },\n redis: { name: 'Redis client', kind: CACHE },\n 'django-redis': { name: 'django-redis', kind: CACHE },\n celery: { name: 'Celery', kind: QUEUE },\n rq: { name: 'RQ', kind: QUEUE },\n dramatiq: { name: 'Dramatiq', kind: QUEUE },\n 'sentry-sdk': { name: 'Sentry', kind: OBS },\n structlog: { name: 'structlog', kind: OBS },\n 'opentelemetry-api': { name: 'OpenTelemetry', kind: OBS },\n 'django-cors-headers': { name: 'django-cors-headers', kind: SEC },\n bandit: { name: 'Bandit', kind: SECTOOL },\n 'pip-audit': { name: 'pip-audit', kind: SECTOOL },\n safety: { name: 'Safety', kind: SECTOOL },\n ruff: { name: 'Ruff', kind: SECTOOL },\n pytest: { name: 'pytest', kind: TEST },\n 'pytest-django': { name: 'pytest-django', kind: TEST },\n hypothesis: { name: 'Hypothesis', kind: TEST },\n playwright: { name: 'Playwright', kind: TEST },\n },\n go: {\n 'github.com/gin-gonic/gin': { name: 'Gin', kind: fw('backend') },\n 'github.com/labstack/echo/v4': { name: 'Echo', kind: fw('backend') },\n 'github.com/gofiber/fiber/v2': { name: 'Fiber', kind: fw('backend') },\n 'github.com/gofiber/fiber/v3': { name: 'Fiber', kind: fw('backend') },\n 'github.com/go-chi/chi/v5': { name: 'chi', kind: fw('backend') },\n 'github.com/gorilla/mux': { name: 'gorilla/mux', kind: fw('backend') },\n 'google.golang.org/grpc': { name: 'gRPC', kind: fw('backend') },\n 'gorm.io/gorm': { name: 'GORM', kind: db('orm') },\n 'entgo.io/ent': { name: 'ent', kind: db('orm') },\n 'github.com/jmoiron/sqlx': { name: 'sqlx', kind: db('driver') },\n 'github.com/jackc/pgx/v5': { name: 'PostgreSQL (pgx)', kind: db('driver') },\n 'github.com/lib/pq': { name: 'PostgreSQL (lib/pq)', kind: db('driver') },\n 'github.com/go-sql-driver/mysql': { name: 'MySQL driver', kind: db('driver') },\n 'go.mongodb.org/mongo-driver': { name: 'MongoDB driver', kind: db('driver') },\n 'github.com/golang-migrate/migrate/v4': { name: 'golang-migrate', kind: db('orm') },\n 'github.com/golang-jwt/jwt/v5': { name: 'golang-jwt', kind: auth('token') },\n 'golang.org/x/crypto': { name: 'x/crypto (may include bcrypt/argon2)', kind: auth('hashing') },\n 'golang.org/x/oauth2': { name: 'x/oauth2', kind: auth('library') },\n 'github.com/redis/go-redis/v9': { name: 'Redis (go-redis)', kind: CACHE },\n 'github.com/hibiken/asynq': { name: 'Asynq', kind: QUEUE },\n 'github.com/segmentio/kafka-go': { name: 'Kafka (kafka-go)', kind: QUEUE },\n 'go.uber.org/zap': { name: 'zap logger', kind: OBS },\n 'github.com/rs/zerolog': { name: 'zerolog', kind: OBS },\n 'github.com/getsentry/sentry-go': { name: 'Sentry', kind: OBS },\n 'github.com/stretchr/testify': { name: 'testify', kind: TEST },\n },\n cargo: {\n axum: { name: 'Axum', kind: fw('backend') },\n 'actix-web': { name: 'Actix Web', kind: fw('backend') },\n rocket: { name: 'Rocket', kind: fw('backend') },\n warp: { name: 'warp', kind: fw('backend') },\n tonic: { name: 'tonic (gRPC)', kind: fw('backend') },\n leptos: { name: 'Leptos', kind: fw('fullstack') },\n tauri: { name: 'Tauri', kind: fw('desktop') },\n diesel: { name: 'Diesel', kind: db('orm') },\n sqlx: { name: 'SQLx', kind: db('driver') },\n 'sea-orm': { name: 'SeaORM', kind: db('orm') },\n 'tokio-postgres': { name: 'PostgreSQL (tokio-postgres)', kind: db('driver') },\n mongodb: { name: 'MongoDB driver', kind: db('driver') },\n jsonwebtoken: { name: 'jsonwebtoken', kind: auth('token') },\n argon2: { name: 'argon2', kind: auth('hashing') },\n bcrypt: { name: 'bcrypt', kind: auth('hashing') },\n oauth2: { name: 'oauth2', kind: auth('library') },\n redis: { name: 'Redis client', kind: CACHE },\n moka: { name: 'moka cache', kind: CACHE },\n lapin: { name: 'RabbitMQ (lapin)', kind: QUEUE },\n rdkafka: { name: 'Kafka (rdkafka)', kind: QUEUE },\n tracing: { name: 'tracing', kind: OBS },\n sentry: { name: 'Sentry', kind: OBS },\n 'tower-http': { name: 'tower-http (may include CORS)', kind: SEC },\n },\n maven: {\n 'spring-boot-starter-web': { name: 'Spring Boot (Web)', kind: fw('backend') },\n 'spring-boot-starter-webflux': { name: 'Spring WebFlux', kind: fw('backend') },\n 'spring-boot-starter': { name: 'Spring Boot', kind: fw('backend') },\n 'spring-boot-starter-data-jpa': { name: 'Spring Data JPA', kind: db('orm') },\n 'spring-boot-starter-data-mongodb': { name: 'Spring Data MongoDB', kind: db('orm') },\n 'hibernate-core': { name: 'Hibernate', kind: db('orm') },\n 'mybatis': { name: 'MyBatis', kind: db('orm') },\n postgresql: { name: 'PostgreSQL JDBC', kind: db('driver') },\n 'mysql-connector-j': { name: 'MySQL JDBC', kind: db('driver') },\n 'flyway-core': { name: 'Flyway', kind: db('orm') },\n 'liquibase-core': { name: 'Liquibase', kind: db('orm') },\n 'spring-boot-starter-security': { name: 'Spring Security', kind: auth('library') },\n 'spring-boot-starter-oauth2-resource-server': { name: 'Spring OAuth2 Resource Server', kind: auth('library') },\n 'spring-boot-starter-oauth2-client': { name: 'Spring OAuth2 Client', kind: auth('library') },\n 'jjwt-api': { name: 'JJWT', kind: auth('token') },\n 'spring-boot-starter-data-redis': { name: 'Spring Data Redis', kind: CACHE },\n 'spring-boot-starter-cache': { name: 'Spring Cache', kind: CACHE },\n 'spring-kafka': { name: 'Spring Kafka', kind: QUEUE },\n 'spring-boot-starter-amqp': { name: 'Spring AMQP', kind: QUEUE },\n 'spring-boot-starter-actuator': { name: 'Spring Boot Actuator', kind: OBS },\n 'spring-boot-starter-validation': { name: 'Bean Validation', kind: SEC },\n 'spring-boot-starter-test': { name: 'Spring Boot Test', kind: TEST },\n 'junit-jupiter': { name: 'JUnit 5', kind: TEST },\n junit: { name: 'JUnit', kind: TEST },\n 'mockito-core': { name: 'Mockito', kind: TEST },\n testcontainers: { name: 'Testcontainers', kind: TEST },\n },\n composer: {\n 'laravel/framework': { name: 'Laravel', kind: fw('fullstack'), markers: [/(^|\\/)artisan$/] },\n 'symfony/framework-bundle': { name: 'Symfony', kind: fw('fullstack') },\n 'slim/slim': { name: 'Slim', kind: fw('backend') },\n 'doctrine/orm': { name: 'Doctrine ORM', kind: db('orm') },\n 'laravel/sanctum': { name: 'Laravel Sanctum', kind: auth('library') },\n 'laravel/passport': { name: 'Laravel Passport', kind: auth('library') },\n 'tymon/jwt-auth': { name: 'jwt-auth', kind: auth('token') },\n 'firebase/php-jwt': { name: 'php-jwt', kind: auth('token') },\n 'predis/predis': { name: 'Predis (Redis)', kind: CACHE },\n 'sentry/sentry-laravel': { name: 'Sentry', kind: OBS },\n 'phpunit/phpunit': { name: 'PHPUnit', kind: TEST },\n 'pestphp/pest': { name: 'Pest', kind: TEST },\n },\n nuget: {\n 'Microsoft.AspNetCore.App': { name: 'ASP.NET Core', kind: fw('backend') },\n 'Microsoft.EntityFrameworkCore': { name: 'Entity Framework Core', kind: db('orm') },\n 'Npgsql.EntityFrameworkCore.PostgreSQL': { name: 'PostgreSQL (Npgsql EF)', kind: db('driver') },\n 'Microsoft.EntityFrameworkCore.SqlServer': { name: 'SQL Server (EF)', kind: db('driver') },\n Dapper: { name: 'Dapper', kind: db('orm') },\n 'Microsoft.AspNetCore.Identity.EntityFrameworkCore': { name: 'ASP.NET Core Identity', kind: auth('library') },\n 'Microsoft.AspNetCore.Authentication.JwtBearer': { name: 'JWT Bearer auth', kind: auth('token') },\n 'StackExchange.Redis': { name: 'StackExchange.Redis', kind: CACHE },\n 'MassTransit': { name: 'MassTransit', kind: QUEUE },\n Serilog: { name: 'Serilog', kind: OBS },\n xunit: { name: 'xUnit', kind: TEST },\n NUnit: { name: 'NUnit', kind: TEST },\n MSTest: { name: 'MSTest', kind: TEST },\n },\n gem: {\n rails: { name: 'Ruby on Rails', kind: fw('fullstack'), markers: [/(^|\\/)config\\/routes\\.rb$/] },\n sinatra: { name: 'Sinatra', kind: fw('backend') },\n 'activerecord': { name: 'ActiveRecord', kind: db('orm') },\n pg: { name: 'PostgreSQL (pg gem)', kind: db('driver') },\n mysql2: { name: 'MySQL (mysql2 gem)', kind: db('driver') },\n devise: { name: 'Devise', kind: auth('library') },\n omniauth: { name: 'OmniAuth', kind: auth('library') },\n pundit: { name: 'Pundit (authorization)', kind: auth('library') },\n cancancan: { name: 'CanCanCan (authorization)', kind: auth('library') },\n jwt: { name: 'ruby-jwt', kind: auth('token') },\n bcrypt: { name: 'bcrypt', kind: auth('hashing') },\n redis: { name: 'Redis client', kind: CACHE },\n sidekiq: { name: 'Sidekiq', kind: QUEUE },\n 'sentry-ruby': { name: 'Sentry', kind: OBS },\n brakeman: { name: 'Brakeman', kind: SECTOOL },\n 'bundler-audit': { name: 'bundler-audit', kind: SECTOOL },\n rspec: { name: 'RSpec', kind: TEST },\n 'rspec-rails': { name: 'RSpec Rails', kind: TEST },\n minitest: { name: 'Minitest', kind: TEST },\n },\n pub: {\n flutter: { name: 'Flutter', kind: fw('mobile') },\n firebase_core: { name: 'Firebase', kind: db('driver') },\n cloud_firestore: { name: 'Cloud Firestore', kind: db('driver') },\n sqflite: { name: 'SQLite (sqflite)', kind: db('driver') },\n drift: { name: 'Drift', kind: db('orm') },\n firebase_auth: { name: 'Firebase Auth', kind: auth('provider') },\n supabase_flutter: { name: 'Supabase', kind: db('driver') },\n flutter_test: { name: 'flutter_test', kind: TEST },\n integration_test: { name: 'integration_test', kind: TEST },\n sentry_flutter: { name: 'Sentry', kind: OBS },\n },\n hex: {\n phoenix: { name: 'Phoenix', kind: fw('fullstack') },\n ecto_sql: { name: 'Ecto', kind: db('orm') },\n postgrex: { name: 'PostgreSQL (Postgrex)', kind: db('driver') },\n guardian: { name: 'Guardian', kind: auth('token') },\n bcrypt_elixir: { name: 'bcrypt_elixir', kind: auth('hashing') },\n oban: { name: 'Oban', kind: QUEUE },\n },\n};\n\nexport function ecosystemKey(ecosystem: string): Eco | null {\n const map: Record<string, Eco> = {\n npm: 'npm', python: 'python', go: 'go', cargo: 'cargo', maven: 'maven', gradle: 'maven',\n composer: 'composer', nuget: 'nuget', rubygems: 'gem', pub: 'pub', hex: 'hex',\n };\n return map[ecosystem] ?? null;\n}\n\n/** Normalize dependency names per ecosystem (python is case/underscore insensitive). */\nexport function normalizeDep(ecosystem: string, dep: string): string {\n if (ecosystem === 'python') return dep.toLowerCase().replace(/_/g, '-');\n return dep;\n}\n","import type { Detector } from '../context.js';\nimport { CATALOG, ecosystemKey, normalizeDep, type CatalogEntry } from '../catalog.js';\nimport type { Evidence, Provenance } from '../../model/fact.js';\nimport type { NamedFact } from '../../model/project-model.js';\nimport { dirOf } from '../../util/paths.js';\n\n/**\n * Maps declared dependencies to capabilities via the catalog. Output is always\n * \"X is a declared dependency\" — usage details remain UNKNOWN unless other\n * detectors find direct evidence.\n */\nexport const dependenciesDetector: Detector = {\n id: 'dependencies',\n version: 1,\n async run(ctx) {\n const { model } = ctx;\n const buckets = {\n database: new Map<string, NamedFact & { kind: 'engine' | 'orm' | 'driver' | 'service' }>(),\n auth: new Map<string, NamedFact & { kind: 'library' | 'provider' | 'hashing' | 'middleware' | 'token' }>(),\n cache: new Map<string, NamedFact>(),\n queue: new Map<string, NamedFact>(),\n observability: new Map<string, NamedFact>(),\n securityControl: new Map<string, NamedFact>(),\n securityTooling: new Map<string, NamedFact>(),\n testing: new Map<string, NamedFact>(),\n };\n const frameworks = new Map<string, (typeof model.frameworks)[number]>();\n\n const addEvidence = (prov: Provenance, ev: Evidence) => {\n if (!prov.evidence.some((e) => e.file === ev.file && e.detail === ev.detail)) prov.evidence.push(ev);\n };\n\n for (const manifest of model.manifests) {\n const eco = ecosystemKey(manifest.ecosystem);\n if (!eco) continue;\n const table = CATALOG[eco];\n const lookup = new Map(Object.entries(table).map(([k, v]) => [normalizeDep(manifest.ecosystem, k), v]));\n const root = dirOf(manifest.path);\n const all: Array<[string, boolean]> = [\n ...manifest.dependencies.map((d): [string, boolean] => [d, false]),\n ...manifest.devDependencies.map((d): [string, boolean] => [d, true]),\n ];\n for (const [dep, isDev] of all) {\n const entry: CatalogEntry | undefined = lookup.get(normalizeDep(manifest.ecosystem, dep));\n if (!entry) continue;\n const ev: Evidence = { file: manifest.path, detail: `${isDev ? 'dev ' : ''}dependency \"${dep}\"` };\n const marker = entry.markers?.flatMap((re) => ctx.find(re).map((f) => f.path)).find((p) => dirOf(p) === root || p.startsWith(root === '.' ? '' : `${root}/`));\n const kind = entry.kind;\n const confidence = marker || !isDev || kind.type === 'testing' || kind.type === 'securityTooling' ? 'high' : 'medium';\n const mkProv = (): Provenance => ({ status: 'DETECTED', confidence, source: 'config', evidence: [] });\n\n if (kind.type === 'framework') {\n const key = `${entry.name}@${root}`;\n const cur = frameworks.get(key) ?? { name: entry.name, category: kind.category, root, provenance: mkProv() };\n addEvidence(cur.provenance, ev);\n if (marker) addEvidence(cur.provenance, { file: marker, detail: 'framework config file' });\n if (confidence === 'high') cur.provenance.confidence = 'high';\n frameworks.set(key, cur);\n continue;\n }\n const bucket = buckets[kind.type] as Map<string, NamedFact & { kind?: string }>;\n const cur = bucket.get(entry.name) ?? { name: entry.name, provenance: mkProv(), ...('kind' in kind ? { kind: kind.kind } : {}) };\n addEvidence(cur.provenance, ev);\n if (marker) addEvidence(cur.provenance, { file: marker, detail: 'config file' });\n if (confidence === 'high') cur.provenance.confidence = 'high';\n bucket.set(entry.name, cur);\n }\n }\n\n const sorted = <T extends { name: string }>(m: Map<string, T>) => [...m.values()].sort((a, b) => a.name.localeCompare(b.name));\n model.frameworks = [...frameworks.values()].sort((a, b) => a.root.localeCompare(b.root) || a.name.localeCompare(b.name));\n model.databases.push(...sorted(buckets.database));\n model.auth.push(...sorted(buckets.auth));\n model.caching.push(...sorted(buckets.cache));\n model.queues.push(...sorted(buckets.queue));\n model.observability.push(...sorted(buckets.observability));\n model.security.controls.push(...sorted(buckets.securityControl));\n model.security.tooling.push(...sorted(buckets.securityTooling));\n model.tests.frameworks.push(...sorted(buckets.testing));\n },\n};\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport type { Detector } from '../context.js';\nimport { isSecretLikeName } from '../../security/secrets.js';\n\nconst TEMPLATE_ENV = /(^|\\/)\\.env\\.(example|sample|template|dist|defaults)$|(^|\\/)(example|sample)\\.env$/;\nconst REAL_ENV_NAMES = ['.env', '.env.local', '.env.development', '.env.production', '.env.test', '.env.development.local', '.env.production.local'];\n\nconst CODE_REFS: Array<[RegExp, RegExp]> = [\n [/\\.(m|c)?(t|j)sx?$/, /\\b(?:process\\.env|import\\.meta\\.env)\\.([A-Z][A-Z0-9_]{1,})|process\\.env\\[\\s*[\"']([A-Z][A-Z0-9_]+)[\"']\\s*\\]/g],\n [/\\.py$/, /os\\.(?:environ(?:\\.get)?\\s*[[(]\\s*|getenv\\s*\\(\\s*)[\"']([A-Z][A-Z0-9_]+)[\"']/g],\n [/\\.go$/, /os\\.(?:Getenv|LookupEnv)\\(\\s*\"([A-Z][A-Z0-9_]+)\"/g],\n [/\\.rs$/, /env::var\\(\\s*\"([A-Z][A-Z0-9_]+)\"/g],\n [/\\.rb$/, /ENV\\[\\s*[\"']([A-Z][A-Z0-9_]+)[\"']\\s*\\]|ENV\\.fetch\\(\\s*[\"']([A-Z][A-Z0-9_]+)[\"']/g],\n [/\\.php$/, /(?:getenv|env)\\(\\s*[\"']([A-Z][A-Z0-9_]+)[\"']/g],\n [/\\.(java|kt)$/, /System\\.getenv\\(\\s*\"([A-Z][A-Z0-9_]+)\"/g],\n [/\\.cs$/, /GetEnvironmentVariable\\(\\s*\"([A-Z][A-Z0-9_]+)\"/g],\n [/\\.dart$/, /fromEnvironment\\(\\s*'([A-Z][A-Z0-9_]+)'/g],\n];\n\n/**\n * Collects environment variable NAMES only. Values are never read into the model:\n * template files are parsed for keys; real .env files are only noted as present.\n */\nexport const envDetector: Detector = {\n id: 'env',\n version: 1,\n async run(ctx) {\n const vars = new Map<string, Set<string>>();\n const add = (name: string, ref: string) => {\n if (!vars.has(name)) vars.set(name, new Set());\n vars.get(name)!.add(ref);\n };\n\n for (const f of ctx.find(TEMPLATE_ENV)) {\n const text = await ctx.read(f.path);\n if (!text) continue;\n for (const m of text.matchAll(/^\\s*(?:export\\s+)?([A-Za-z_][A-Za-z0-9_]*)\\s*=/gm)) add(m[1]!, f.path);\n }\n\n let scanned = 0;\n for (const [fileRe, refRe] of CODE_REFS) {\n for (const f of ctx.find(fileRe)) {\n if (f.large || f.binary || /(^|\\/)(test|tests|__tests__|spec)\\//.test(f.path)) continue;\n if (++scanned > 20_000) break;\n const text = await ctx.read(f.path);\n if (!text) continue;\n refRe.lastIndex = 0;\n for (const m of text.matchAll(refRe)) {\n const name = m[1] ?? m[2];\n if (name && name !== 'NODE_ENV') add(name, f.path);\n }\n }\n }\n\n // Real env files are frequently gitignored and therefore not walked; check for presence directly.\n const present = new Set<string>();\n for (const f of ctx.find(/(^|\\/)\\.env(\\.[a-z.]+)?$/)) if (!TEMPLATE_ENV.test(f.path)) present.add(f.path);\n for (const name of REAL_ENV_NAMES) {\n try {\n const st = await fs.stat(path.join(ctx.root, name));\n if (st.isFile()) present.add(name);\n } catch {\n /* absent */\n }\n }\n\n ctx.model.env.vars = [...vars.entries()]\n .map(([name, refs]) => ({ name, references: [...refs].sort().slice(0, 10), secretLike: isSecretLikeName(name) }))\n .sort((a, b) => a.name.localeCompare(b.name));\n ctx.model.env.envFilesPresent = [...present].sort();\n },\n};\n","import { sha256 } from '../util/fs.js';\n\nexport interface SecretPattern {\n id: string;\n description: string;\n regex: RegExp;\n /** Capture group holding the secret value (0 = whole match). */\n group?: number;\n /** Minimum Shannon entropy (bits/char) for the captured value. */\n minEntropy?: number;\n}\n\nexport interface SecretMatch {\n type: string;\n line: number;\n /** Start/end offsets of the secret value within the scanned text. */\n start: number;\n end: number;\n fingerprint: string;\n}\n\n/**\n * Conservative, well-known credential formats. Generic patterns require entropy\n * so ordinary identifiers (\"password = form.password\") are not flagged.\n */\nexport const SECRET_PATTERNS: SecretPattern[] = [\n { id: 'private-key', description: 'Private key block', regex: /-----BEGIN (?:RSA |EC |DSA |OPENSSH |PGP |ENCRYPTED )?PRIVATE KEY(?: BLOCK)?-----[\\s\\S]*?-----END (?:RSA |EC |DSA |OPENSSH |PGP |ENCRYPTED )?PRIVATE KEY(?: BLOCK)?-----/g },\n { id: 'aws-access-key-id', description: 'AWS access key ID', regex: /\\b((?:AKIA|ASIA|ABIA|ACCA)[0-9A-Z]{16})\\b/g, group: 1 },\n { id: 'aws-secret-access-key', description: 'AWS secret access key', regex: /aws_?secret_?access_?key[\"']?\\s*[:=]\\s*[\"']?([A-Za-z0-9/+=]{40})\\b/gi, group: 1 },\n { id: 'gcp-service-account', description: 'GCP service account private key', regex: /\"private_key\"\\s*:\\s*\"(-----BEGIN PRIVATE KEY-----[^\"]+)\"/g, group: 1 },\n { id: 'azure-storage-key', description: 'Azure storage connection string', regex: /AccountKey=([A-Za-z0-9+/=]{60,})/g, group: 1 },\n { id: 'github-token', description: 'GitHub token', regex: /\\b((?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{36,}|github_pat_[A-Za-z0-9_]{60,})\\b/g, group: 1 },\n { id: 'gitlab-token', description: 'GitLab token', regex: /\\b(glpat-[A-Za-z0-9_-]{20,})\\b/g, group: 1 },\n { id: 'slack-token', description: 'Slack token', regex: /\\b(xox[abprs]-[A-Za-z0-9-]{10,})\\b/g, group: 1 },\n { id: 'slack-webhook', description: 'Slack webhook URL', regex: /(https:\\/\\/hooks\\.slack\\.com\\/services\\/[A-Za-z0-9/_-]{20,})/g, group: 1 },\n { id: 'stripe-key', description: 'Stripe secret key', regex: /\\b((?:sk|rk)_(?:live|test)_[A-Za-z0-9]{20,})\\b/g, group: 1 },\n { id: 'anthropic-key', description: 'Anthropic API key', regex: /\\b(sk-ant-[A-Za-z0-9_-]{20,})\\b/g, group: 1 },\n { id: 'openai-key', description: 'OpenAI API key', regex: /\\b(sk-(?:proj-|svcacct-)?[A-Za-z0-9_-]{32,})\\b/g, group: 1 },\n { id: 'google-api-key', description: 'Google API key', regex: /\\b(AIza[0-9A-Za-z_-]{35})\\b/g, group: 1 },\n { id: 'sendgrid-key', description: 'SendGrid API key', regex: /\\b(SG\\.[A-Za-z0-9_-]{22}\\.[A-Za-z0-9_-]{43})\\b/g, group: 1 },\n { id: 'npm-token', description: 'npm token', regex: /\\b(npm_[A-Za-z0-9]{36})\\b/g, group: 1 },\n { id: 'jwt', description: 'JSON Web Token', regex: /\\b(eyJ[A-Za-z0-9_-]{10,}\\.eyJ[A-Za-z0-9_-]{10,}\\.[A-Za-z0-9_-]{10,})\\b/g, group: 1 },\n {\n id: 'connection-string-credentials',\n description: 'Connection string with embedded password',\n regex: /\\b(?:postgres(?:ql)?|mysql|mariadb|mongodb(?:\\+srv)?|redis|rediss|amqps?|mssql|sqlserver):\\/\\/[^\\s:@/\"'`]+:([^\\s@/\"'`]{3,})@/gi,\n group: 1,\n },\n {\n id: 'generic-secret-assignment',\n description: 'Hardcoded secret-like assignment',\n regex: /\\b[A-Za-z0-9_.-]*(?:password|passwd|pwd|secret|token|api[_-]?key|apikey|access[_-]?key|auth[_-]?key|client[_-]?secret|private[_-]?key)[A-Za-z0-9_.-]*[\"']?\\s*[:=]\\s*[\"'`]([^\"'`\\s]{12,})[\"'`]/gi,\n group: 1,\n minEntropy: 3.5,\n },\n {\n id: 'env-secret-assignment',\n description: 'Secret-like environment value',\n regex: /^\\s*(?:export\\s+)?[A-Z0-9_]*(?:PASSWORD|SECRET|TOKEN|API_KEY|APIKEY|ACCESS_KEY|PRIVATE_KEY|CLIENT_SECRET)[A-Z0-9_]*\\s*=\\s*[\"']?([^\\s\"'#$]{8,})[\"']?\\s*$/gm,\n group: 1,\n minEntropy: 3.0,\n },\n];\n\nconst PLACEHOLDER_VALUE = /^(?:<.*>|\\$\\{.*\\}|\\{\\{.*\\}\\}|x{4,}|\\*{4,}|changeme|change[-_]?me|your[-_].*|example.*|placeholder.*|dummy.*|test.*|fake.*|replace[-_]?me|todo|null|none|undefined|password|secret|redacted)$/i;\n\nexport function shannonEntropy(s: string): number {\n if (!s) return 0;\n const counts = new Map<string, number>();\n for (const ch of s) counts.set(ch, (counts.get(ch) ?? 0) + 1);\n let h = 0;\n for (const c of counts.values()) {\n const p = c / s.length;\n h -= p * Math.log2(p);\n }\n return h;\n}\n\nexport function scanText(text: string): SecretMatch[] {\n const matches: SecretMatch[] = [];\n const taken: Array<[number, number]> = [];\n const lineStarts = computeLineStarts(text);\n\n for (const pattern of SECRET_PATTERNS) {\n pattern.regex.lastIndex = 0;\n for (const m of text.matchAll(pattern.regex)) {\n const group = pattern.group ?? 0;\n const value = m[group];\n if (!value || m.index === undefined) continue;\n if (PLACEHOLDER_VALUE.test(value)) continue;\n if (pattern.minEntropy !== undefined && shannonEntropy(value) < pattern.minEntropy) continue;\n const offsetInMatch = group === 0 ? 0 : m[0].indexOf(value);\n const start = m.index + Math.max(offsetInMatch, 0);\n const end = start + value.length;\n if (taken.some(([s, e]) => start < e && end > s)) continue;\n taken.push([start, end]);\n matches.push({\n type: pattern.id,\n line: lineAt(lineStarts, start),\n start,\n end,\n fingerprint: sha256(value).slice(0, 12),\n });\n }\n }\n return matches.sort((a, b) => a.start - b.start);\n}\n\n/** Replace any detected secret values in `text` with a placeholder. */\nexport function redact(text: string, placeholder = '<redacted>'): string {\n const matches = scanText(text);\n if (!matches.length) return text;\n let out = '';\n let cursor = 0;\n for (const m of matches) {\n out += text.slice(cursor, m.start) + placeholder;\n cursor = m.end;\n }\n return out + text.slice(cursor);\n}\n\nfunction computeLineStarts(text: string): number[] {\n const starts = [0];\n for (let i = 0; i < text.length; i++) if (text.charCodeAt(i) === 10) starts.push(i + 1);\n return starts;\n}\n\nfunction lineAt(starts: number[], offset: number): number {\n let lo = 0;\n let hi = starts.length - 1;\n while (lo < hi) {\n const mid = (lo + hi + 1) >> 1;\n if (starts[mid]! <= offset) lo = mid;\n else hi = mid - 1;\n }\n return lo + 1;\n}\n\n/** Heuristic: does an env var *name* look like it holds a secret? */\nexport function isSecretLikeName(name: string): boolean {\n return /(PASSWORD|PASSWD|SECRET|TOKEN|API_?KEY|ACCESS_?KEY|PRIVATE_?KEY|CREDENTIAL|DATABASE_URL|DB_URL|CONNECTION_STRING|DSN|WEBHOOK)/i.test(name);\n}\n","import { parseAllDocuments, parse as parseYaml } from 'yaml';\nimport type { AnalysisContext, Detector } from '../context.js';\nimport type { CiJob, ContainerService } from '../../model/project-model.js';\nimport { detected } from '../../model/fact.js';\nimport { redact } from '../../security/secrets.js';\n\ntype Obj = Record<string, unknown>;\nconst isObj = (v: unknown): v is Obj => typeof v === 'object' && v !== null && !Array.isArray(v);\n\nconst IMAGE_CAPS: Array<[RegExp, string, 'database' | 'cache' | 'queue']> = [\n [/^(?:.*\\/)?(postgres|postgis\\/postgis|pgvector\\/pgvector|timescale\\/timescaledb)(:|$)/, 'PostgreSQL', 'database'],\n [/^(?:.*\\/)?(mysql|mariadb)(:|$)/, 'MySQL/MariaDB', 'database'],\n [/^(?:.*\\/)?mongo(:|$)/, 'MongoDB', 'database'],\n [/^(?:.*\\/)?(mcr\\.microsoft\\.com\\/mssql\\/server|mssql)/, 'SQL Server', 'database'],\n [/^(?:.*\\/)?(elasticsearch|opensearch)/, 'Elasticsearch/OpenSearch', 'database'],\n [/^(?:.*\\/)?clickhouse/, 'ClickHouse', 'database'],\n [/^(?:.*\\/)?(redis|valkey|redis\\/redis-stack)(:|$)/, 'Redis', 'cache'],\n [/^(?:.*\\/)?memcached(:|$)/, 'Memcached', 'cache'],\n [/^(?:.*\\/)?rabbitmq(:|$)/, 'RabbitMQ', 'queue'],\n [/^(?:.*\\/)?(confluentinc\\/cp-kafka|bitnami\\/kafka|apache\\/kafka)/, 'Kafka', 'queue'],\n [/^(?:.*\\/)?nats(:|$)/, 'NATS', 'queue'],\n];\n\nconst HOSTING: Array<[RegExp, string, string]> = [\n [/(^|\\/)vercel\\.json$/, 'Vercel', 'hosting'],\n [/(^|\\/)netlify\\.toml$/, 'Netlify', 'hosting'],\n [/(^|\\/)fly\\.toml$/, 'Fly.io', 'hosting'],\n [/(^|\\/)render\\.ya?ml$/, 'Render', 'hosting'],\n [/(^|\\/)railway\\.(json|toml)$/, 'Railway', 'hosting'],\n [/(^|\\/)Procfile$/, 'Procfile (Heroku-style)', 'hosting'],\n [/(^|\\/)app\\.ya?ml$/, 'Google App Engine (app.yaml)', 'hosting'],\n [/(^|\\/)firebase\\.json$/, 'Firebase Hosting/config', 'hosting'],\n [/(^|\\/)wrangler\\.(toml|jsonc?)$/, 'Cloudflare Workers', 'hosting'],\n [/(^|\\/)serverless\\.ya?ml$/, 'Serverless Framework', 'hosting'],\n [/(^|\\/)template\\.ya?ml$|(^|\\/)samconfig\\.toml$/, 'AWS SAM (possible)', 'hosting'],\n [/(^|\\/)cdk\\.json$/, 'AWS CDK', 'iac'],\n [/(^|\\/)Pulumi\\.ya?ml$/, 'Pulumi', 'iac'],\n [/(^|\\/)Chart\\.yaml$/, 'Helm chart', 'kubernetes'],\n [/(^|\\/)kustomization\\.ya?ml$/, 'Kustomize', 'kubernetes'],\n [/(^|\\/)skaffold\\.ya?ml$/, 'Skaffold', 'kubernetes'],\n [/(^|\\/)nginx[^/]*\\.conf$|(^|\\/)nginx\\/.*\\.conf$/, 'nginx config', 'reverse-proxy'],\n [/(^|\\/)Caddyfile$/, 'Caddy', 'reverse-proxy'],\n [/(^|\\/)traefik\\.ya?ml$/, 'Traefik', 'reverse-proxy'],\n];\n\nfunction strList(v: unknown): string[] {\n if (Array.isArray(v)) return v.map((x) => (typeof x === 'string' || typeof x === 'number' ? String(x) : isObj(x) && x.target ? `${x.published ?? ''}:${x.target}` : '')).filter(Boolean);\n if (isObj(v)) return Object.keys(v);\n return [];\n}\n\nfunction trimCmd(s: string): string {\n const one = s.split('\\n').map((l) => l.trim()).filter(Boolean).join(' && ');\n return redact(one.length > 160 ? `${one.slice(0, 157)}...` : one);\n}\n\nasync function composeServices(ctx: AnalysisContext): Promise<ContainerService[]> {\n const out: ContainerService[] = [];\n for (const f of ctx.find(/(^|\\/)(docker-)?compose(\\.[\\w-]+)?\\.ya?ml$/)) {\n const text = await ctx.read(f.path);\n if (!text) continue;\n let y: unknown;\n try {\n y = parseYaml(text);\n } catch {\n ctx.warn(`Could not parse ${f.path} (invalid YAML)`);\n continue;\n }\n if (!isObj(y) || !isObj(y.services)) continue;\n for (const [name, svc] of Object.entries(y.services)) {\n if (!isObj(svc)) continue;\n out.push({\n name,\n image: typeof svc.image === 'string' ? svc.image : isObj(svc.build) || typeof svc.build === 'string' ? '(built locally)' : undefined,\n ports: strList(svc.ports),\n dependsOn: strList(svc.depends_on),\n file: f.path,\n });\n }\n }\n return out;\n}\n\nasync function ciJobs(ctx: AnalysisContext): Promise<CiJob[]> {\n const jobs: CiJob[] = [];\n const loadYaml = async (p: string): Promise<Obj | null> => {\n const text = await ctx.read(p);\n if (!text) return null;\n try {\n const y = parseYaml(text);\n return isObj(y) ? y : null;\n } catch {\n ctx.warn(`Could not parse ${p} (invalid YAML)`);\n return null;\n }\n };\n\n for (const f of ctx.find(/^\\.github\\/workflows\\/[^/]+\\.ya?ml$/)) {\n const y = await loadYaml(f.path);\n if (!y || !isObj(y.jobs)) continue;\n for (const [id, job] of Object.entries(y.jobs)) {\n if (!isObj(job)) continue;\n const steps = Array.isArray(job.steps) ? job.steps : [];\n const commands = steps.flatMap((s) => (isObj(s) && typeof s.run === 'string' ? [trimCmd(s.run)] : isObj(s) && typeof s.uses === 'string' ? [`uses: ${s.uses}`] : []));\n jobs.push({ system: 'GitHub Actions', file: f.path, name: typeof job.name === 'string' ? job.name : id, commands: commands.slice(0, 12) });\n }\n }\n if (ctx.has('.gitlab-ci.yml')) {\n const y = await loadYaml('.gitlab-ci.yml');\n if (y) for (const [id, job] of Object.entries(y)) {\n if (id.startsWith('.') || !isObj(job) || !('script' in job)) continue;\n const script = Array.isArray(job.script) ? job.script.map(String) : [String(job.script)];\n jobs.push({ system: 'GitLab CI', file: '.gitlab-ci.yml', name: id, commands: script.map(trimCmd).slice(0, 12) });\n }\n }\n if (ctx.has('.circleci/config.yml')) {\n const y = await loadYaml('.circleci/config.yml');\n if (y && isObj(y.jobs)) for (const [id, job] of Object.entries(y.jobs)) {\n const steps = isObj(job) && Array.isArray(job.steps) ? job.steps : [];\n const commands = steps.flatMap((s) => (isObj(s) && isObj(s.run) && typeof s.run.command === 'string' ? [trimCmd(s.run.command)] : isObj(s) && typeof s.run === 'string' ? [trimCmd(s.run)] : []));\n jobs.push({ system: 'CircleCI', file: '.circleci/config.yml', name: id, commands: commands.slice(0, 12) });\n }\n }\n for (const f of ctx.find(/(^|\\/)azure-pipelines\\.ya?ml$/)) jobs.push({ system: 'Azure Pipelines', file: f.path, name: 'pipeline', commands: [] });\n for (const f of ctx.find(/(^|\\/)bitbucket-pipelines\\.yml$/)) jobs.push({ system: 'Bitbucket Pipelines', file: f.path, name: 'pipeline', commands: [] });\n for (const f of ctx.find(/(^|\\/)Jenkinsfile$/)) {\n const text = (await ctx.read(f.path)) ?? '';\n const stages = [...text.matchAll(/stage\\s*\\(\\s*['\"]([^'\"]+)['\"]/g)].map((m) => m[1]!);\n if (stages.length) for (const s of stages) jobs.push({ system: 'Jenkins', file: f.path, name: s, commands: [] });\n else jobs.push({ system: 'Jenkins', file: f.path, name: 'pipeline', commands: [] });\n }\n return jobs;\n}\n\nexport const infraDetector: Detector = {\n id: 'infra',\n version: 1,\n async run(ctx) {\n const { model } = ctx;\n\n for (const f of ctx.find(/(^|\\/)(Dockerfile|Containerfile)(\\.[\\w.-]+)?$|\\.dockerfile$/i)) {\n const text = await ctx.read(f.path);\n if (!text) continue;\n const baseImages = [...text.matchAll(/^\\s*FROM\\s+(?:--platform=\\S+\\s+)?(\\S+)/gim)].map((m) => m[1]!);\n const exposedPorts = [...text.matchAll(/^\\s*EXPOSE\\s+(.+)$/gim)].flatMap((m) => m[1]!.trim().split(/\\s+/));\n model.containers.dockerfiles.push({ path: f.path, baseImages: [...new Set(baseImages)], exposedPorts: [...new Set(exposedPorts)] });\n }\n\n model.containers.services = await composeServices(ctx);\n for (const svc of model.containers.services) {\n if (!svc.image) continue;\n for (const [re, name, cap] of IMAGE_CAPS) {\n if (!re.test(svc.image)) continue;\n const prov = detected('config', [{ file: svc.file, detail: `compose service \"${svc.name}\" image ${svc.image}` }]);\n if (cap === 'database') model.databases.push({ name, kind: 'service', provenance: prov });\n else if (cap === 'cache') model.caching.push({ name: `${name} (container)`, provenance: prov });\n else model.queues.push({ name: `${name} (container)`, provenance: prov });\n }\n }\n\n for (const [re, name, kind] of HOSTING) {\n for (const f of ctx.find(re)) model.infrastructure.push({ name, kind, file: f.path, provenance: detected('filesystem', [{ file: f.path }], name.includes('possible') ? 'low' : 'high') });\n }\n\n const tfProviders = new Map<string, string>();\n for (const f of ctx.find(/\\.tf$/)) {\n const text = await ctx.read(f.path);\n if (!text) continue;\n for (const m of text.matchAll(/(?:provider|required_providers)\\s*\"?([a-z0-9_-]+)\"?\\s*\\{|source\\s*=\\s*\"(?:[\\w.-]+\\/)?([\\w-]+)\\/([\\w-]+)\"/g)) {\n const p = m[1] ?? m[3];\n if (p && p !== 'required_providers' && !tfProviders.has(p)) tfProviders.set(p, f.path);\n }\n }\n for (const [p, file] of tfProviders) model.infrastructure.push({ name: `Terraform provider: ${p}`, kind: 'iac', file, provenance: detected('config', [{ file }]) });\n\n const k8sKinds = new Map<string, string>();\n for (const f of ctx.find(/\\.ya?ml$/)) {\n if (f.large || /(^|\\/)(\\.github|\\.gitlab|\\.circleci)\\//.test(f.path) || /compose/.test(f.path)) continue;\n const text = await ctx.read(f.path);\n if (!text || !/^apiVersion:/m.test(text) || !/^kind:/m.test(text)) continue;\n try {\n for (const doc of parseAllDocuments(text)) {\n const j = doc.toJSON() as unknown;\n if (isObj(j) && typeof j.kind === 'string' && typeof j.apiVersion === 'string' && !k8sKinds.has(j.kind)) k8sKinds.set(j.kind, f.path);\n }\n } catch {\n /* templated YAML (Helm) is expected to fail */\n }\n }\n for (const [kind, file] of k8sKinds) model.infrastructure.push({ name: `Kubernetes ${kind}`, kind: 'kubernetes', file, provenance: detected('config', [{ file }]) });\n\n model.ci = await ciJobs(ctx);\n\n for (const f of ctx.find(/(^|\\/)(\\.github\\/dependabot\\.ya?ml|renovate\\.json5?|\\.renovaterc(\\.json)?|\\.snyk|\\.semgrep\\.ya?ml|\\.gitleaks\\.toml|\\.trivyignore|codeql[^/]*\\.ya?ml|\\.pre-commit-config\\.yaml|SECURITY\\.md)$/)) {\n const name = /dependabot/.test(f.path) ? 'Dependabot' : /renovate/.test(f.path) ? 'Renovate' : /snyk/.test(f.path) ? 'Snyk' : /semgrep/.test(f.path) ? 'Semgrep' : /gitleaks/.test(f.path) ? 'Gitleaks' : /trivy/.test(f.path) ? 'Trivy' : /codeql/.test(f.path) ? 'CodeQL' : /pre-commit/.test(f.path) ? 'pre-commit hooks' : 'Security policy (SECURITY.md)';\n model.security.tooling.push({ name, provenance: detected('filesystem', [{ file: f.path }]) });\n }\n for (const job of model.ci) {\n for (const c of job.commands) {\n const m = /(codeql|trivy|snyk|semgrep|gitleaks|npm audit|pip-audit|govulncheck|cargo audit|bandit|brakeman|zap)/i.exec(c);\n if (m) model.security.tooling.push({ name: `${m[1]} (in CI)`, provenance: detected('config', [{ file: job.file, detail: `job \"${job.name}\"` }]) });\n }\n }\n },\n};\n","import type { Detector } from '../context.js';\nimport { detected } from '../../model/fact.js';\n\nexport const TEST_FILE_RE = /(^|\\/)(__tests__|tests?|spec|specs|e2e|integration_tests|androidTest|test_driver)\\/|\\.(test|spec|e2e)\\.[cm]?[jt]sx?$|(^|\\/)test_[^/]+\\.py$|_test\\.(py|go|exs)$|_spec\\.rb$|Tests?\\.(java|kt|cs)$|_test\\.dart$/;\nconst SOURCE_RE = /\\.(m|c)?(t|j)sx?$|\\.(py|go|rs|java|kt|cs|php|rb|dart|ex|swift|vue|svelte)$/;\n\nconst RUNNER_CONFIGS: Array<[RegExp, string]> = [\n [/(^|\\/)jest\\.config\\.(js|ts|cjs|mjs|json)$/, 'Jest'],\n [/(^|\\/)vitest\\.config\\.(js|ts|mjs|cjs)$/, 'Vitest'],\n [/(^|\\/)playwright\\.config\\.(js|ts)$/, 'Playwright'],\n [/(^|\\/)cypress\\.config\\.(js|ts)$|(^|\\/)cypress\\.json$/, 'Cypress'],\n [/(^|\\/)(pytest\\.ini|conftest\\.py)$/, 'pytest'],\n [/(^|\\/)\\.mocharc\\.(js|json|ya?ml|cjs)$/, 'Mocha'],\n [/(^|\\/)karma\\.conf\\.(js|ts)$/, 'Karma'],\n [/(^|\\/)phpunit\\.xml(\\.dist)?$/, 'PHPUnit'],\n [/(^|\\/)\\.rspec$/, 'RSpec'],\n];\n\nconst COVERAGE: RegExp = /(^|\\/)(\\.nycrc(\\.json)?|\\.coveragerc|codecov\\.ya?ml|\\.codecov\\.ya?ml|jacoco[^/]*\\.xml|\\.c8rc(\\.json)?|coverage\\.xml|sonar-project\\.properties)$/;\n\nexport const testsDetector: Detector = {\n id: 'tests',\n version: 1,\n async run(ctx) {\n const { model } = ctx;\n const testFiles = ctx.find((f) => !f.binary && SOURCE_RE.test(f.path) && TEST_FILE_RE.test(f.path));\n model.tests.testFileCount = testFiles.length;\n\n const dirs = new Map<string, number>();\n for (const f of testFiles) {\n const m = /^(.*?(?:__tests__|tests?|spec|specs|e2e))\\//.exec(f.path);\n if (m) dirs.set(m[1]!, (dirs.get(m[1]!) ?? 0) + 1);\n }\n model.tests.testDirs = [...dirs.entries()].sort((a, b) => b[1] - a[1]).slice(0, 15).map(([d]) => d);\n\n const known = new Set(model.tests.frameworks.map((f) => f.name));\n for (const [re, name] of RUNNER_CONFIGS) {\n const files = ctx.find(re);\n if (!files.length) continue;\n const existing = model.tests.frameworks.find((f) => f.name === name);\n if (existing) existing.provenance.evidence.push(...files.slice(0, 3).map((f) => ({ file: f.path, detail: 'runner config' })));\n else if (!known.has(name)) model.tests.frameworks.push({ name, provenance: detected('config', files.slice(0, 3).map((f) => ({ file: f.path, detail: 'runner config' }))) });\n }\n if (ctx.find(/_test\\.go$/).length && !known.has('go test')) model.tests.frameworks.push({ name: 'go test', provenance: detected('filesystem', ctx.find(/_test\\.go$/).slice(0, 3).map((f) => ({ file: f.path }))) });\n if (model.manifests.some((m) => m.ecosystem === 'cargo') && ctx.find(/\\.rs$/).length) {\n const withTests: string[] = [];\n for (const f of ctx.find(/\\.rs$/).slice(0, 2000)) {\n const t = await ctx.read(f.path);\n if (t && /#\\[(tokio::)?test\\]/.test(t)) withTests.push(f.path);\n if (withTests.length >= 3) break;\n }\n if (withTests.length) model.tests.frameworks.push({ name: 'cargo test', provenance: detected('code', withTests.map((file) => ({ file, detail: '#[test] attribute' }))) });\n }\n model.tests.frameworks.sort((a, b) => a.name.localeCompare(b.name));\n\n model.tests.coverageConfigs = ctx.find(COVERAGE).map((f) => f.path);\n for (const f of ctx.find(/(^|\\/)(jest|vitest)\\.config\\.(js|ts|mjs|cjs)$/)) {\n const t = await ctx.read(f.path);\n if (t && /coverage/.test(t)) model.tests.coverageConfigs.push(f.path);\n }\n\n // Structural gap: workspace packages with source files but no test files.\n if (model.workspace.isMonorepo) {\n for (const pkg of model.workspace.packages) {\n if (pkg.path === '.') continue;\n const prefix = `${pkg.path}/`;\n const src = ctx.files.some((f) => f.path.startsWith(prefix) && SOURCE_RE.test(f.path) && !TEST_FILE_RE.test(f.path));\n const tests = testFiles.some((f) => f.path.startsWith(prefix));\n if (src && !tests) model.tests.packagesWithoutTests.push(pkg.path);\n }\n }\n },\n};\n","import type { AnalysisContext, Detector } from '../context.js';\nimport type { DbEntity } from '../../model/project-model.js';\nimport { detected } from '../../model/fact.js';\nimport { dirOf } from '../../util/paths.js';\n\nasync function prisma(ctx: AnalysisContext): Promise<DbEntity[]> {\n const out: DbEntity[] = [];\n for (const f of ctx.find(/\\.prisma$/)) {\n const text = await ctx.read(f.path);\n if (!text) continue;\n const provider = /datasource\\s+\\w+\\s*\\{[^}]*provider\\s*=\\s*\"([^\"]+)\"/.exec(text)?.[1];\n if (provider) ctx.model.databases.push({ name: `${provider} (Prisma datasource)`, kind: 'engine', provenance: detected('config', [{ file: f.path, detail: 'datasource provider' }]) });\n for (const m of text.matchAll(/^(model|view)\\s+(\\w+)\\s*\\{([\\s\\S]*?)^\\}/gm)) {\n const body = m[3]!;\n const fields: DbEntity['fields'] = [];\n const indexes: string[] = [];\n const relations: string[] = [];\n for (const raw of body.split('\\n')) {\n const line = raw.replace(/\\/\\/.*$/, '').trim();\n if (!line) continue;\n if (line.startsWith('@@')) {\n indexes.push(line);\n continue;\n }\n const fm = /^(\\w+)\\s+([\\w[\\]?.()\"]+)\\s*(.*)$/.exec(line);\n if (!fm) continue;\n const attributes = [...fm[3]!.matchAll(/@[\\w.]+(\\([^)]*\\))?/g)].map((a) => a[0]);\n fields.push({ name: fm[1]!, type: fm[2]!, attributes });\n const rel = attributes.find((a) => a.startsWith('@relation'));\n if (rel) relations.push(`${fm[1]} → ${fm[2]!.replace(/[[\\]?]/g, '')}`);\n }\n const lineNo = text.slice(0, m.index).split('\\n').length;\n out.push({ name: m[2]!, kind: 'model', fields, indexes, relations, file: f.path, provenance: detected('code', [{ file: f.path, line: lineNo }]) });\n }\n }\n return out;\n}\n\nfunction stripSqlComments(sql: string): string {\n return sql.replace(/--[^\\n]*/g, '').replace(/\\/\\*[\\s\\S]*?\\*\\//g, '');\n}\n\nasync function sqlFiles(ctx: AnalysisContext): Promise<DbEntity[]> {\n const tables = new Map<string, DbEntity>();\n const files = ctx.find((f) => /\\.sql$/i.test(f.path) && !f.large).slice(0, 2000);\n for (const f of files) {\n const raw = await ctx.read(f.path);\n if (!raw) continue;\n const text = stripSqlComments(raw);\n for (const m of text.matchAll(/CREATE\\s+(?:UNLOGGED\\s+|TEMP(?:ORARY)?\\s+)?TABLE\\s+(?:IF\\s+NOT\\s+EXISTS\\s+)?([`\"[\\]\\w.]+)\\s*\\(([\\s\\S]*?)\\)\\s*;/gi)) {\n const name = m[1]!.replace(/[`\"[\\]]/g, '');\n const fields: DbEntity['fields'] = [];\n const relations: string[] = [];\n for (const col of splitTopLevel(m[2]!)) {\n const c = col.trim();\n const fk = /FOREIGN\\s+KEY\\s*\\(([^)]+)\\)\\s*REFERENCES\\s+([`\"\\w.]+)/i.exec(c);\n if (fk) {\n relations.push(`${fk[1]!.trim()} → ${fk[2]!.replace(/[`\"]/g, '')}`);\n continue;\n }\n if (/^(CONSTRAINT|PRIMARY\\s+KEY|UNIQUE|CHECK|INDEX|KEY)\\b/i.test(c)) continue;\n const cm = /^([`\"\\w]+)\\s+([\\w]+(?:\\s*\\([^)]*\\))?)(.*)$/s.exec(c);\n if (!cm) continue;\n const attrs: string[] = [];\n if (/PRIMARY\\s+KEY/i.test(cm[3]!)) attrs.push('PRIMARY KEY');\n if (/NOT\\s+NULL/i.test(cm[3]!)) attrs.push('NOT NULL');\n if (/\\bUNIQUE\\b/i.test(cm[3]!)) attrs.push('UNIQUE');\n const ref = /REFERENCES\\s+([`\"\\w.]+)/i.exec(cm[3]!);\n if (ref) relations.push(`${cm[1]!.replace(/[`\"]/g, '')} → ${ref[1]!.replace(/[`\"]/g, '')}`);\n fields.push({ name: cm[1]!.replace(/[`\"]/g, ''), type: cm[2]!, attributes: attrs });\n }\n const line = raw.slice(0, raw.indexOf(m[0].slice(0, 20))).split('\\n').length;\n // Later migrations may redefine a table; keep the latest definition by path order.\n tables.set(name.toLowerCase(), { name, kind: 'table', fields, indexes: tables.get(name.toLowerCase())?.indexes ?? [], relations, file: f.path, provenance: detected('code', [{ file: f.path, line: line > 0 ? line : undefined }]) });\n }\n for (const m of text.matchAll(/CREATE\\s+(UNIQUE\\s+)?INDEX\\s+(?:CONCURRENTLY\\s+)?(?:IF\\s+NOT\\s+EXISTS\\s+)?([`\"\\w.]+)\\s+ON\\s+([`\"\\w.]+)\\s*(?:USING\\s+\\w+\\s*)?\\(([^)]*)\\)/gi)) {\n const t = tables.get(m[3]!.replace(/[`\"]/g, '').toLowerCase());\n if (t) t.indexes.push(`${m[1] ? 'UNIQUE ' : ''}${m[2]!.replace(/[`\"]/g, '')} (${m[4]!.trim()})`);\n }\n }\n return [...tables.values()];\n}\n\nfunction splitTopLevel(s: string): string[] {\n const parts: string[] = [];\n let depth = 0;\n let cur = '';\n for (const ch of s) {\n if (ch === '(') depth++;\n if (ch === ')') depth--;\n if (ch === ',' && depth === 0) {\n parts.push(cur);\n cur = '';\n } else cur += ch;\n }\n if (cur.trim()) parts.push(cur);\n return parts;\n}\n\nasync function djangoModels(ctx: AnalysisContext): Promise<DbEntity[]> {\n const out: DbEntity[] = [];\n for (const f of ctx.find(/(^|\\/)models(\\.py|\\/[^/]+\\.py)$/)) {\n const text = await ctx.read(f.path);\n if (!text || !/from django\\.db import models|models\\.Model/.test(text)) continue;\n const classRe = /^class\\s+(\\w+)\\(([^)]*models\\.Model[^)]*)\\):\\s*\\n((?:[ \\t]+.*\\n|\\s*\\n)*)/gm;\n for (const m of text.matchAll(classRe)) {\n const fields: DbEntity['fields'] = [];\n const relations: string[] = [];\n for (const fm of m[3]!.matchAll(/^\\s+(\\w+)\\s*=\\s*models\\.(\\w+)\\(([^)\\n]*)/gm)) {\n fields.push({ name: fm[1]!, type: fm[2]!, attributes: [] });\n if (/ForeignKey|OneToOneField|ManyToManyField/.test(fm[2]!)) relations.push(`${fm[1]} → ${fm[3]!.split(',')[0]!.trim().replace(/[\"']/g, '')}`);\n }\n out.push({ name: m[1]!, kind: 'model', fields, indexes: [], relations, file: f.path, provenance: detected('code', [{ file: f.path, line: text.slice(0, m.index).split('\\n').length }], 'medium') });\n }\n }\n return out;\n}\n\nasync function sqlalchemyModels(ctx: AnalysisContext): Promise<DbEntity[]> {\n const out: DbEntity[] = [];\n if (!ctx.model.databases.some((d) => /SQLAlchemy|SQLModel/.test(d.name))) return out;\n for (const f of ctx.find(/\\.py$/).slice(0, 5000)) {\n const text = await ctx.read(f.path);\n if (!text || !/__tablename__|table=True/.test(text)) continue;\n for (const m of text.matchAll(/^class\\s+(\\w+)\\(([^)]*)\\):\\s*\\n((?:[ \\t]+.*\\n|\\s*\\n)*)/gm)) {\n const body = m[3]!;\n const tn = /__tablename__\\s*=\\s*[\"'](\\w+)[\"']/.exec(body)?.[1];\n if (!tn && !/table\\s*=\\s*True/.test(m[2]!)) continue;\n const fields = [...body.matchAll(/^\\s+(\\w+)\\s*(?::\\s*[^=\\n]+)?=\\s*(?:Column|mapped_column|Field)\\(/gm)].map((fm) => ({ name: fm[1]!, attributes: [] as string[] }));\n out.push({ name: tn ?? m[1]!, kind: 'table', fields, indexes: [], relations: [], file: f.path, provenance: detected('code', [{ file: f.path, line: text.slice(0, m.index).split('\\n').length }], 'medium') });\n }\n }\n return out;\n}\n\nasync function mongooseModels(ctx: AnalysisContext): Promise<DbEntity[]> {\n if (!ctx.model.databases.some((d) => d.name === 'Mongoose')) return [];\n const out: DbEntity[] = [];\n for (const f of ctx.find(/\\.(m|c)?(t|j)s$/).slice(0, 5000)) {\n const text = await ctx.read(f.path);\n if (!text || !text.includes('model(')) continue;\n for (const m of text.matchAll(/mongoose\\.model\\s*(?:<[^>]*>)?\\(\\s*[\"'](\\w+)[\"']|\\bmodel\\s*(?:<[^>]*>)?\\(\\s*[\"'](\\w+)[\"']\\s*,/g)) {\n out.push({ name: (m[1] ?? m[2])!, kind: 'collection', fields: [], indexes: [], relations: [], file: f.path, provenance: detected('code', [{ file: f.path, line: text.slice(0, m.index).split('\\n').length }], 'medium') });\n }\n }\n return out;\n}\n\nconst MIGRATION_DIRS: Array<[RegExp, string]> = [\n [/(^|\\/)prisma\\/migrations\\/[^/]+\\/migration\\.sql$/, 'Prisma Migrate'],\n [/(^|\\/)drizzle\\/[^/]*\\.sql$/, 'Drizzle Kit'],\n [/(^|\\/)alembic\\/versions\\/[^/]+\\.py$|(^|\\/)migrations\\/versions\\/[^/]+\\.py$/, 'Alembic'],\n [/(^|\\/)migrations\\/\\d{4}_[^/]+\\.py$/, 'Django migrations'],\n [/(^|\\/)db\\/migrate\\/[^/]+\\.rb$/, 'Rails migrations'],\n [/(^|\\/)db\\/migration\\/V\\d+[^/]*\\.sql$|(^|\\/)resources\\/db\\/migration\\/[^/]+\\.sql$/, 'Flyway'],\n [/(^|\\/)(db\\/)?changelog\\/[^/]+\\.(xml|ya?ml|sql)$/, 'Liquibase'],\n [/(^|\\/)database\\/migrations\\/[^/]+\\.php$/, 'Laravel migrations'],\n [/(^|\\/)Migrations\\/\\d+_[^/]+\\.cs$/, 'EF Core migrations'],\n [/(^|\\/)migrations\\/[^/]+\\.(up|down)\\.sql$|(^|\\/)migrations\\/\\d+[^/]*\\.sql$/, 'SQL migrations'],\n [/(^|\\/)priv\\/repo\\/migrations\\/[^/]+\\.exs$/, 'Ecto migrations'],\n [/(^|\\/)supabase\\/migrations\\/[^/]+\\.sql$/, 'Supabase migrations'],\n];\n\nexport const databaseDetector: Detector = {\n id: 'database',\n version: 1,\n async run(ctx) {\n const { model } = ctx;\n const entities = [...(await prisma(ctx)), ...(await sqlFiles(ctx)), ...(await djangoModels(ctx)), ...(await sqlalchemyModels(ctx)), ...(await mongooseModels(ctx))];\n model.dbEntities = entities.sort((a, b) => a.name.localeCompare(b.name));\n\n const seen = new Set<string>();\n for (const [re, tool] of MIGRATION_DIRS) {\n const files = ctx.find(re).filter((f) => !seen.has(f.path));\n if (!files.length) continue;\n files.forEach((f) => seen.add(f.path));\n const byDir = new Map<string, number>();\n for (const f of files) {\n const d = tool === 'Prisma Migrate' ? dirOf(dirOf(f.path)) : dirOf(f.path);\n byDir.set(d, (byDir.get(d) ?? 0) + 1);\n }\n for (const [dir, count] of byDir) model.migrations.push({ path: dir, tool, count });\n }\n\n // Dedupe databases by name, merging evidence.\n const merged = new Map<string, (typeof model.databases)[number]>();\n for (const d of model.databases) {\n const cur = merged.get(d.name);\n if (cur) cur.provenance.evidence.push(...d.provenance.evidence);\n else merged.set(d.name, d);\n }\n model.databases = [...merged.values()];\n },\n};\n","import { parse as babelParse } from '@babel/parser';\nimport type { AnalysisContext, Detector } from '../context.js';\nimport type { Route } from '../../model/project-model.js';\nimport { detected } from '../../model/fact.js';\n\nconst HTTP = ['get', 'post', 'put', 'patch', 'delete', 'options', 'head', 'all'];\nconst MAX_ROUTES = 5000;\n\ntype Node = { type: string; [k: string]: unknown };\nconst isNode = (v: unknown): v is Node => typeof v === 'object' && v !== null && typeof (v as Node).type === 'string';\n\nfunction walk(node: unknown, visit: (n: Node, parent: Node | null) => void, parent: Node | null = null): void {\n if (Array.isArray(node)) {\n for (const c of node) walk(c, visit, parent);\n return;\n }\n if (!isNode(node)) return;\n visit(node, parent);\n for (const key of Object.keys(node)) {\n if (key === 'loc' || key === 'start' || key === 'end' || key === 'extra' || key === 'comments' || key === 'leadingComments' || key === 'trailingComments') continue;\n const v = node[key];\n if (typeof v === 'object' && v !== null) walk(v, visit, node);\n }\n}\n\nfunction strValue(n: unknown): string | null {\n if (!isNode(n)) return null;\n if (n.type === 'StringLiteral') return n.value as string;\n if (n.type === 'TemplateLiteral' && Array.isArray(n.quasis) && n.quasis.length === 1) return ((n.quasis[0] as Node).value as { cooked: string }).cooked;\n return null;\n}\n\nconst lineOf = (n: Node): number | undefined => (n.loc as { start?: { line: number } } | undefined)?.start?.line;\n\nfunction jsRoutes(file: string, text: string, framework: string): Route[] {\n let ast: unknown;\n try {\n ast = babelParse(text, { sourceType: 'unambiguous', errorRecovery: true, plugins: ['typescript', 'jsx', 'decorators'] as never });\n } catch {\n return [];\n }\n const routes: Route[] = [];\n const prov = (line?: number) => detected('code', [{ file, line }], 'high');\n\n walk(ast, (n) => {\n // app.get('/path', ...) / router.post(...) / fastify.get(...) / hono.get(...)\n if (n.type === 'CallExpression' && isNode(n.callee) && n.callee.type === 'MemberExpression' && isNode(n.callee.property) && n.callee.property.type === 'Identifier') {\n const method = (n.callee.property.name as string).toLowerCase();\n const args = n.arguments as unknown[];\n if (HTTP.includes(method) && args.length >= 2) {\n const p = strValue(args[0]);\n if (p !== null && (p.startsWith('/') || p === '*')) routes.push({ method: method.toUpperCase(), path: p, framework, file, line: lineOf(n), provenance: prov(lineOf(n)) });\n }\n // fastify.route({ method: 'GET', url: '/x' })\n if (method === 'route' && isNode(args[0]) && args[0].type === 'ObjectExpression') {\n let m: string | null = null;\n let u: string | null = null;\n for (const prop of args[0].properties as Node[]) {\n const k = isNode(prop.key) ? ((prop.key.name as string) ?? (prop.key.value as string)) : null;\n if (k === 'method') m = strValue(prop.value);\n if (k === 'url' || k === 'path') u = strValue(prop.value);\n }\n if (m && u) routes.push({ method: m.toUpperCase(), path: u, framework, file, line: lineOf(n), provenance: prov(lineOf(n)) });\n }\n }\n // NestJS: @Controller('prefix') class { @Get('x') method() {} }\n if ((n.type === 'ClassDeclaration' || n.type === 'ClassExpression') && Array.isArray(n.decorators)) {\n let prefix: string | null = null;\n for (const d of n.decorators as Node[]) {\n const expr = d.expression as Node;\n if (expr?.type === 'CallExpression' && isNode(expr.callee) && expr.callee.name === 'Controller') {\n const a = (expr.arguments as unknown[])[0];\n prefix = strValue(a) ?? (isNode(a) && a.type === 'ObjectExpression' ? null : '');\n }\n }\n if (prefix === null) return;\n const body = (n.body as Node).body as Node[];\n for (const member of body) {\n for (const d of (member.decorators as Node[] | undefined) ?? []) {\n const expr = d.expression as Node;\n if (expr?.type !== 'CallExpression' || !isNode(expr.callee)) continue;\n const name = expr.callee.name as string;\n if (!['Get', 'Post', 'Put', 'Patch', 'Delete', 'Options', 'Head', 'All'].includes(name)) continue;\n const sub = strValue((expr.arguments as unknown[])[0]) ?? '';\n const full = `/${[prefix, sub].filter(Boolean).join('/')}`.replace(/\\/+/g, '/');\n routes.push({ method: name.toUpperCase(), path: full, framework: 'NestJS', file, line: lineOf(d), provenance: prov(lineOf(d)) });\n }\n }\n }\n });\n return routes;\n}\n\nfunction regexRoutes(file: string, text: string, framework: string, re: RegExp, pick: (m: RegExpMatchArray) => { method: string; path: string } | null): Route[] {\n const out: Route[] = [];\n for (const m of text.matchAll(re)) {\n const r = pick(m);\n if (!r) continue;\n const line = text.slice(0, m.index).split('\\n').length;\n out.push({ ...r, framework, file, line, provenance: detected('code', [{ file, line }], 'medium') });\n }\n return out;\n}\n\nasync function nextRoutes(ctx: AnalysisContext): Promise<Route[]> {\n const out: Route[] = [];\n for (const f of ctx.find(/(^|\\/)(src\\/)?app\\/(.+\\/)?route\\.(t|j)sx?$/)) {\n const text = await ctx.read(f.path);\n if (!text) continue;\n const seg = /(?:^|\\/)(?:src\\/)?app\\/(.*)route\\.(?:t|j)sx?$/.exec(f.path)?.[1] ?? '';\n const urlPath = `/${seg.replace(/\\/$/, '')}`.split('/').filter((s) => !/^\\(.*\\)$/.test(s) && !s.startsWith('@')).join('/') || '/';\n for (const m of text.matchAll(/export\\s+(?:async\\s+)?(?:function|const)\\s+(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)\\b/g)) {\n const line = text.slice(0, m.index).split('\\n').length;\n out.push({ method: m[1]!, path: urlPath, framework: 'Next.js (app router)', file: f.path, line, provenance: detected('code', [{ file: f.path, line }]) });\n }\n }\n for (const f of ctx.find(/(^|\\/)(src\\/)?pages\\/api\\/.+\\.(t|j)sx?$/)) {\n const seg = /(?:^|\\/)(?:src\\/)?pages(\\/api\\/.+)\\.(?:t|j)sx?$/.exec(f.path)?.[1] ?? '';\n out.push({ method: 'ANY', path: seg.replace(/\\/index$/, ''), framework: 'Next.js (pages API)', file: f.path, provenance: detected('filesystem', [{ file: f.path }]) });\n }\n return out;\n}\n\nexport const routesDetector: Detector = {\n id: 'routes',\n version: 1,\n async run(ctx) {\n const { model } = ctx;\n const routes: Route[] = [];\n const fw = new Set(model.frameworks.map((f) => f.name));\n const push = (rs: Route[]) => {\n for (const r of rs) if (routes.length < MAX_ROUTES) routes.push(r);\n };\n\n if (fw.has('Next.js')) push(await nextRoutes(ctx));\n if (!fw.has('Next.js') && (ctx.has('vercel.json') || fw.has('Vercel Functions (Node)'))) {\n // Vercel maps files in the root api/ directory to /api/<path> serverless functions.\n for (const f of ctx.find(/^api\\/.+\\.(m|c)?(t|j)s$/)) {\n if (/(^|\\/)_|\\.(test|spec|d)\\./.test(f.path)) continue;\n const urlPath = `/${f.path.replace(/\\.(m|c)?(t|j)s$/, '').replace(/\\/index$/, '')}`;\n routes.push({ method: 'ANY', path: urlPath, framework: 'Vercel Functions', file: f.path, provenance: detected('filesystem', [{ file: f.path, detail: 'Vercel api/ directory convention' }], 'medium') });\n }\n }\n\n const jsFrameworks = ['Express', 'Fastify', 'Koa', 'Hono', 'NestJS'].filter((n) => fw.has(n));\n if (jsFrameworks.length) {\n for (const f of ctx.find(/\\.(m|c)?(t|j)sx?$/)) {\n if (f.large || /\\.(test|spec|d)\\.[cm]?[jt]sx?$/.test(f.path)) continue;\n const text = await ctx.read(f.path);\n if (!text || !/\\b(express|fastify|hono|koa|@nestjs\\/common|Router)\\b/.test(text)) continue;\n const guess = /@nestjs\\/common/.test(text) ? 'NestJS' : /\\bfastify\\b/i.test(text) ? 'Fastify' : /\\bhono\\b/.test(text) ? 'Hono' : /\\bkoa\\b/.test(text) ? 'Koa' : 'Express';\n push(jsRoutes(f.path, text, guess));\n }\n }\n\n const pyFw = ['FastAPI', 'Flask', 'Starlette', 'Litestar'].some((n) => fw.has(n));\n if (pyFw) {\n for (const f of ctx.find(/\\.py$/)) {\n const text = await ctx.read(f.path);\n if (!text || !/@\\w+\\.(get|post|put|patch|delete|route|api_route)\\(/.test(text)) continue;\n push(regexRoutes(f.path, text, fw.has('FastAPI') ? 'FastAPI' : 'Flask', /@(\\w+)\\.(get|post|put|patch|delete|options|head|route|api_route)\\(\\s*[\"']([^\"']*)[\"']([^\\n]*)/g, (m) => {\n const verb = m[2]!;\n if (verb === 'route' || verb === 'api_route') {\n const methods = /methods\\s*=\\s*\\[([^\\]]+)\\]/.exec(m[4]!)?.[1]?.replace(/[\"'\\s]/g, '').toUpperCase();\n return { method: methods || 'GET', path: m[3]! };\n }\n return { method: verb.toUpperCase(), path: m[3]! };\n }));\n }\n }\n if (fw.has('Django')) {\n for (const f of ctx.find(/(^|\\/)urls\\.py$/)) {\n const text = await ctx.read(f.path);\n if (text) push(regexRoutes(f.path, text, 'Django', /\\b(re_)?path\\(\\s*r?[\"']([^\"']*)[\"']\\s*,\\s*([\\w.]+)/g, (m) => ({ method: 'ANY', path: `/${m[2]!}` })));\n }\n }\n\n const java = ctx.find(/\\.(java|kt)$/);\n for (const f of java) {\n const text = await ctx.read(f.path);\n if (!text || !/@(Get|Post|Put|Patch|Delete|Request)Mapping/.test(text)) continue;\n const prefix = /@RequestMapping\\(\\s*(?:value\\s*=\\s*|path\\s*=\\s*)?[\"']([^\"']*)[\"']\\s*\\)\\s*(?:@\\w+(?:\\([^)]*\\))?\\s*)*(?:public\\s+)?(?:abstract\\s+)?(?:class|interface)/.exec(text)?.[1] ?? '';\n push(regexRoutes(f.path, text, 'Spring', /@(Get|Post|Put|Patch|Delete)Mapping(?:\\(\\s*(?:value\\s*=\\s*|path\\s*=\\s*)?\\{?\\s*[\"']([^\"']*)[\"'])?/g, (m) => ({ method: m[1]!.toUpperCase(), path: `${prefix}${m[2] ?? ''}` || '/' })));\n }\n\n for (const f of ctx.find(/\\.go$/)) {\n if (f.path.endsWith('_test.go')) continue;\n const text = await ctx.read(f.path);\n if (!text) continue;\n push(regexRoutes(f.path, text, 'Go', /\\.(GET|POST|PUT|PATCH|DELETE|Get|Post|Put|Patch|Delete|HandleFunc|Handle)\\(\\s*\"([^\"]+)\"/g, (m) => {\n const verb = m[1]!;\n if (verb.startsWith('Handle')) {\n const sp = /^(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)\\s+(\\/.*)$/.exec(m[2]!);\n if (sp) return { method: sp[1]!, path: sp[2]! };\n return m[2]!.startsWith('/') ? { method: 'ANY', path: m[2]! } : null;\n }\n return m[2]!.startsWith('/') ? { method: verb.toUpperCase(), path: m[2]! } : null;\n }));\n }\n\n for (const f of ctx.find(/\\.rs$/)) {\n const text = await ctx.read(f.path);\n if (!text) continue;\n push(regexRoutes(f.path, text, 'Axum', /\\.route\\(\\s*\"([^\"]+)\"\\s*,\\s*(get|post|put|patch|delete)/g, (m) => ({ method: m[2]!.toUpperCase(), path: m[1]! })));\n push(regexRoutes(f.path, text, 'Actix/Rocket', /#\\[(get|post|put|patch|delete)\\(\\s*\"([^\"]+)\"/g, (m) => ({ method: m[1]!.toUpperCase(), path: m[2]! })));\n }\n\n if (ctx.has('config/routes.rb')) {\n const text = await ctx.read('config/routes.rb');\n if (text) {\n push(regexRoutes('config/routes.rb', text, 'Rails', /^\\s*(get|post|put|patch|delete)\\s+[\"']([^\"']+)[\"']/gm, (m) => ({ method: m[1]!.toUpperCase(), path: m[2]!.startsWith('/') ? m[2]! : `/${m[2]}` })));\n push(regexRoutes('config/routes.rb', text, 'Rails', /^\\s*resources?\\s+:(\\w+)/gm, (m) => ({ method: 'RESOURCE', path: `/${m[1]}` })));\n }\n }\n for (const f of ctx.find(/(^|\\/)routes\\/[^/]+\\.php$/)) {\n const text = await ctx.read(f.path);\n if (text) push(regexRoutes(f.path, text, 'Laravel', /Route::(get|post|put|patch|delete|any|resource|apiResource)\\(\\s*[\"']([^\"']+)[\"']/g, (m) => ({ method: m[1]!.toUpperCase(), path: m[2]!.startsWith('/') ? m[2]! : `/${m[2]}` })));\n }\n for (const f of ctx.find(/\\.cs$/)) {\n const text = await ctx.read(f.path);\n if (!text) continue;\n push(regexRoutes(f.path, text, 'ASP.NET Core', /\\.Map(Get|Post|Put|Patch|Delete)\\(\\s*\"([^\"]+)\"/g, (m) => ({ method: m[1]!.toUpperCase(), path: m[2]! })));\n if (/\\[Http(Get|Post|Put|Patch|Delete)/.test(text)) {\n const prefix = /\\[Route\\(\\s*\"([^\"]+)\"\\s*\\)\\]\\s*(?:\\[[^\\]]+\\]\\s*)*public\\s+(?:sealed\\s+|partial\\s+)*class/.exec(text)?.[1] ?? '';\n push(regexRoutes(f.path, text, 'ASP.NET Core', /\\[Http(Get|Post|Put|Patch|Delete)(?:\\(\\s*\"([^\"]*)\"\\s*\\))?\\]/g, (m) => ({ method: m[1]!.toUpperCase(), path: `/${[prefix, m[2] ?? ''].filter(Boolean).join('/')}` })));\n }\n }\n\n model.routes = routes.sort((a, b) => a.path.localeCompare(b.path) || a.method.localeCompare(b.method));\n if (routes.length >= MAX_ROUTES) ctx.warn(`Route listing truncated at ${MAX_ROUTES} entries.`);\n\n for (const f of ctx.find(/(^|\\/)(openapi|swagger)[^/]*\\.(json|ya?ml)$/i)) model.apiSpecs.push({ path: f.path, kind: 'openapi' });\n for (const f of ctx.find(/\\.(graphql|gql)$/)) model.apiSpecs.push({ path: f.path, kind: 'graphql' });\n for (const f of ctx.find(/\\.proto$/)) model.apiSpecs.push({ path: f.path, kind: 'grpc' });\n },\n};\n","import type { Detector } from '../context.js';\nimport { detected, inferred } from '../../model/fact.js';\n\n/**\n * Auth libraries come from the dependency catalog. This detector adds structural\n * hints: auth-related files, middleware, and role/permission definitions.\n * Everything here is INFERRED unless the code pattern is unambiguous.\n */\nexport const authDetector: Detector = {\n id: 'auth',\n version: 1,\n async run(ctx) {\n const { model } = ctx;\n const authFiles = ctx.find((f) => !f.binary && /\\.(m|c)?(t|j)sx?$|\\.(py|go|rs|java|kt|cs|php|rb|ex)$/.test(f.path) && /(^|\\/)[^/]*(auth|session|login|oauth|jwt|guard|permission|rbac|acl|polic(y|ies))[^/]*$/i.test(f.path) && !/\\.(test|spec)\\./.test(f.path));\n if (authFiles.length) {\n model.auth.push({\n name: `Auth-related source files (${authFiles.length})`,\n kind: 'middleware',\n provenance: inferred('filesystem', authFiles.slice(0, 8).map((f) => ({ file: f.path, detail: 'file name suggests auth concern' })), 'low'),\n });\n }\n\n for (const f of ctx.find(/(^|\\/)(src\\/)?middleware\\.(t|j)s$/)) {\n const text = await ctx.read(f.path);\n if (text && /(auth|session|token|redirect\\(.*login)/i.test(text)) {\n model.auth.push({ name: 'Next.js middleware referencing auth/session', kind: 'middleware', provenance: detected('code', [{ file: f.path }], 'medium') });\n }\n }\n\n // Role / permission definitions\n const roleEvidence: Array<{ file: string; line: number; detail: string }> = [];\n for (const f of ctx.find(/\\.(prisma|ts|tsx|py|java|kt|cs|go|rb|php)$/)) {\n if (f.large || roleEvidence.length >= 10) continue;\n const text = await ctx.read(f.path);\n if (!text || !/role|permission/i.test(text)) continue;\n for (const m of text.matchAll(/\\b(?:enum|class|type|interface)\\s+(\\w*(?:Role|Permission)s?)\\b/g)) {\n roleEvidence.push({ file: f.path, line: text.slice(0, m.index).split('\\n').length, detail: `definition \"${m[1]}\"` });\n if (roleEvidence.length >= 10) break;\n }\n }\n for (const e of model.dbEntities) {\n if (/^(roles?|permissions?|user_roles?|role_permissions?)$/i.test(e.name)) roleEvidence.push({ file: e.file, line: e.provenance.evidence[0]?.line ?? 1, detail: `database entity \"${e.name}\"` });\n }\n if (roleEvidence.length) {\n model.auth.push({ name: 'Role/permission definitions', kind: 'middleware', provenance: detected('code', roleEvidence, 'medium') });\n }\n },\n};\n","import type { Detector } from '../context.js';\nimport { inferred } from '../../model/fact.js';\n\nconst CONVENTIONAL = /(^|\\/)(src\\/)?(main|index|server|app|cli)\\.(m|c)?(t|j)sx?$|(^|\\/)(main|app|wsgi|asgi|manage|__main__)\\.py$|(^|\\/)(cmd\\/[^/]+\\/)?main\\.go$|(^|\\/)src\\/(main|lib)\\.rs$|(^|\\/)Program\\.cs$|(^|\\/)[A-Za-z]+Application\\.(java|kt)$|(^|\\/)lib\\/main\\.dart$|(^|\\/)public\\/index\\.php$|(^|\\/)config\\.ru$/;\n\nexport const entryPointsDetector: Detector = {\n id: 'entrypoints',\n version: 1,\n async run(ctx) {\n const known = new Set(ctx.model.entryPoints.map((e) => e.path));\n const candidates = ctx.find((f) => CONVENTIONAL.test(f.path) && f.path.split('/').length <= 5 && !/(^|\\/)(test|tests|__tests__|examples?|fixtures?)\\//.test(f.path));\n for (const f of candidates.slice(0, 30)) {\n if (known.has(f.path)) continue;\n ctx.model.entryPoints.push({ path: f.path, provenance: inferred('filesystem', [{ file: f.path, detail: 'conventional entry-point file name' }], 'medium') });\n }\n },\n};\n","import type { Detector } from '../context.js';\nimport { scanText } from '../../security/secrets.js';\n\nconst SKIP = /(^|\\/)(package-lock\\.json|yarn\\.lock|pnpm-lock\\.yaml|bun\\.lock|poetry\\.lock|uv\\.lock|Cargo\\.lock|go\\.sum|composer\\.lock|Gemfile\\.lock|pubspec\\.lock)$|\\.(min\\.js|map|svg|snap)$/;\nconst MAX_FINDINGS = 500;\n\n/**\n * Scans indexed text files for likely credentials. Only type, location and a short\n * fingerprint are recorded — never the value.\n */\nexport const secretsDetector: Detector = {\n id: 'secrets',\n version: 1,\n async run(ctx) {\n const findings = ctx.model.security.secrets;\n for (const f of ctx.files) {\n if (f.binary || f.large || SKIP.test(f.path)) continue;\n if (findings.length >= MAX_FINDINGS) {\n ctx.warn(`Secret scan stopped after ${MAX_FINDINGS} findings.`);\n break;\n }\n ctx.signal?.throwIfAborted();\n const text = await ctx.read(f.path);\n if (!text) continue;\n for (const m of scanText(text)) findings.push({ type: m.type, file: f.path, line: m.line, fingerprint: m.fingerprint });\n }\n },\n};\n","import { execFile } from 'node:child_process';\nimport type { GitInfo } from '../model/project-model.js';\n\nexport interface GitResult {\n ok: boolean;\n stdout: string;\n}\n\n/** Run git with a fixed argv (never through a shell). */\nexport function git(cwd: string, args: string[], timeoutMs = 15_000): Promise<GitResult> {\n return new Promise((resolve) => {\n execFile('git', args, { cwd, timeout: timeoutMs, maxBuffer: 32 * 1024 * 1024, windowsHide: true, env: { ...process.env, GIT_TERMINAL_PROMPT: '0', LC_ALL: 'C' } }, (err, stdout) => {\n resolve({ ok: !err, stdout: typeof stdout === 'string' ? stdout : '' });\n });\n });\n}\n\nexport async function gitAvailable(): Promise<boolean> {\n return (await git(process.cwd(), ['--version'])).ok;\n}\n\nexport async function isGitRepo(cwd: string): Promise<boolean> {\n const r = await git(cwd, ['rev-parse', '--is-inside-work-tree']);\n return r.ok && r.stdout.trim() === 'true';\n}\n\nexport async function gitInfo(cwd: string): Promise<GitInfo> {\n const info: GitInfo = { available: await gitAvailable(), isRepo: false, hotspots: [] };\n if (!info.available) return info;\n info.isRepo = await isGitRepo(cwd);\n if (!info.isRepo) return info;\n const [branch, head, date, authors, log] = await Promise.all([\n git(cwd, ['rev-parse', '--abbrev-ref', 'HEAD']),\n git(cwd, ['rev-parse', 'HEAD']),\n git(cwd, ['log', '-1', '--format=%cI']),\n git(cwd, ['shortlog', '-sn', '--no-merges', 'HEAD']),\n git(cwd, ['log', '--since=180.days', '--name-only', '--format=', '--no-merges', '--relative', '-n', '2000', '--', '.']),\n ]);\n if (branch.ok) info.branch = branch.stdout.trim();\n if (head.ok) info.head = head.stdout.trim();\n if (date.ok && date.stdout.trim()) info.lastCommitDate = date.stdout.trim();\n // Count only — contributor names are personal data and not needed.\n if (authors.ok) info.contributorCount = authors.stdout.split('\\n').filter((l) => l.trim()).length;\n if (log.ok) {\n const counts = new Map<string, number>();\n for (const line of log.stdout.split('\\n')) {\n const p = line.trim();\n if (!p) continue;\n const dir = p.includes('/') ? p.split('/').slice(0, 2).join('/') : '.';\n counts.set(dir, (counts.get(dir) ?? 0) + 1);\n }\n info.hotspots = [...counts.entries()].sort((a, b) => b[1] - a[1]).slice(0, 10).map(([path, commits]) => ({ path, commits }));\n }\n return info;\n}\n\nexport interface ChangedFile {\n path: string;\n status: 'added' | 'modified' | 'deleted' | 'renamed' | 'untracked' | 'other';\n from?: string;\n}\n\n/** Working-tree changes (staged, unstaged, untracked) relative to HEAD. */\nexport async function workingChanges(cwd: string): Promise<ChangedFile[] | null> {\n const r = await git(cwd, ['status', '--porcelain=v1', '-z', '--untracked-files=all', '--', '.']);\n if (!r.ok) return null;\n const prefix = await repoPrefix(cwd);\n const out: ChangedFile[] = [];\n const parts = r.stdout.split('\\0');\n for (let i = 0; i < parts.length; i++) {\n const entry = parts[i]!;\n if (entry.length < 4) continue;\n const code = entry.slice(0, 2);\n const p = entry.slice(3);\n if (code.includes('R')) {\n out.push({ path: p, status: 'renamed', from: parts[++i] });\n } else if (code === '??') out.push({ path: p, status: 'untracked' });\n else if (code.includes('D')) out.push({ path: p, status: 'deleted' });\n else if (code.includes('A')) out.push({ path: p, status: 'added' });\n else if (code.includes('M')) out.push({ path: p, status: 'modified' });\n else out.push({ path: p, status: 'other' });\n }\n return stripPrefix(out, prefix);\n}\n\n/** Path of `cwd` relative to the repository root (\"\" at the root). Git reports paths repo-relative. */\nexport async function repoPrefix(cwd: string): Promise<string> {\n const r = await git(cwd, ['rev-parse', '--show-prefix']);\n return r.ok ? r.stdout.trim() : '';\n}\n\nfunction stripPrefix(files: ChangedFile[], prefix: string): ChangedFile[] {\n if (!prefix) return files;\n return files\n .filter((f) => f.path.startsWith(prefix))\n .map((f) => ({ ...f, path: f.path.slice(prefix.length), from: f.from?.startsWith(prefix) ? f.from.slice(prefix.length) : f.from }));\n}\n\n/** Files changed in commits between `fromRef` and HEAD. */\nexport async function changesSince(cwd: string, fromRef: string): Promise<ChangedFile[] | null> {\n // Accept commit SHAs and ordinary ref expressions (HEAD~1, origin/main, v1.2.3),\n // but never anything that could be read as an option or shell metacharacter.\n if (!isSafeRef(fromRef)) return null;\n const r = await git(cwd, ['diff', '--name-status', '-M', '-z', `${fromRef}..HEAD`, '--', '.']);\n if (!r.ok) return null;\n const prefix = await repoPrefix(cwd);\n const out: ChangedFile[] = [];\n const parts = r.stdout.split('\\0').filter(Boolean);\n for (let i = 0; i < parts.length; i++) {\n const code = parts[i]!;\n if (code.startsWith('R')) {\n const from = parts[++i];\n out.push({ path: parts[++i]!, status: 'renamed', from });\n } else {\n const p = parts[++i]!;\n out.push({ path: p, status: code === 'A' ? 'added' : code === 'D' ? 'deleted' : code === 'M' ? 'modified' : 'other' });\n }\n }\n return stripPrefix(out, prefix);\n}\n\n/** Conservative allowlist for user-supplied git refs. */\nexport function isSafeRef(ref: string): boolean {\n return /^[A-Za-z0-9][\\w./@^~-]{0,119}$/.test(ref);\n}\n\nexport interface CommitSummary {\n sha: string;\n subject: string;\n}\n\nexport interface HeadMovement {\n /** Commits reachable from `to` but not `from` (newest first), when `from` is an ancestor. */\n commits: CommitSummary[];\n /** True when `from` is not an ancestor of `to` (branch switch, rebase, reset). */\n diverged: boolean;\n truncated: boolean;\n}\n\nexport async function headMovement(cwd: string, from: string, to: string, limit = 20): Promise<HeadMovement | null> {\n if (!/^[0-9a-f]{7,64}$/i.test(from) || !/^[0-9a-f]{7,64}$/i.test(to)) return null;\n if (from === to) return { commits: [], diverged: false, truncated: false };\n const exists = await git(cwd, ['cat-file', '-e', `${from}^{commit}`]);\n if (!exists.ok) return { commits: [], diverged: true, truncated: false };\n const ancestor = await git(cwd, ['merge-base', '--is-ancestor', from, to]);\n const log = await git(cwd, ['log', `-n${limit + 1}`, '--format=%H%x1f%s', `${from}..${to}`]);\n if (!log.ok) return null;\n const commits = log.stdout\n .split('\\n')\n .filter(Boolean)\n .map((l) => {\n const [sha, subject] = l.split('\\x1f');\n return { sha: sha!, subject: subject ?? '' };\n });\n return { commits: commits.slice(0, limit), diverged: !ancestor.ok, truncated: commits.length > limit };\n}\n","import path from 'node:path';\nimport type { ProjectModel } from '../model/project-model.js';\nimport { redact } from '../security/secrets.js';\nimport { readTextIfExists, sha256, writeFileAtomic } from '../util/fs.js';\nimport { KNOWLEDGE_DOCS, type GeneratedDocId } from './documents.js';\nimport { LEGEND } from './md.js';\nimport { mergeDocument, renderBlock, type Section } from './managed-blocks.js';\nimport { renderProject } from './renderers/project.js';\nimport { renderArchitecture } from './renderers/architecture.js';\nimport { renderApi, renderAuth, renderDatabase } from './renderers/data.js';\nimport { renderSecurity } from './renderers/security.js';\nimport { renderCodeReview, renderDebugging, renderPerformance, renderTesting } from './renderers/quality.js';\nimport { renderDeployment } from './renderers/deployment.js';\nimport { seedRules } from './rules-seed.js';\nimport { loadScanFromDir, type SecurityScan } from '../model/security-scan.js';\n\nexport interface KnowledgeExtras {\n /** Latest dependency/secret scan, when one has been run. */\n securityScan?: SecurityScan | null;\n}\n\nexport const RENDERERS: Record<GeneratedDocId, (m: ProjectModel, extras: KnowledgeExtras) => Section[]> = {\n project: renderProject,\n architecture: renderArchitecture,\n database: renderDatabase,\n api: renderApi,\n auth: renderAuth,\n security: renderSecurity,\n testing: renderTesting,\n debugging: renderDebugging,\n performance: renderPerformance,\n 'code-review': renderCodeReview,\n deployment: renderDeployment,\n};\n\nexport const DEVELOPER_NOTES_HEADING = '## Developer Notes';\n\nexport type DocWriteStatus = 'created' | 'updated' | 'unchanged';\n\nexport interface DocWriteReport {\n id: string;\n file: string;\n status: DocWriteStatus;\n blocks: string[];\n /** Blocks not regenerated because the developer edited them. */\n preservedModified: string[];\n contentHash: string;\n}\n\nexport interface WriteKnowledgeOptions {\n force?: boolean;\n /** Block ids per doc id from the previous state (to respect deliberately deleted blocks). */\n previousBlocks?: Record<string, string[]>;\n /** Restrict regeneration to these docs (used by incremental sync later). */\n only?: GeneratedDocId[];\n}\n\nexport function renderSections(id: GeneratedDocId, model: ProjectModel, extras: KnowledgeExtras = {}): Section[] {\n const doc = KNOWLEDGE_DOCS.find((d) => d.id === id)!;\n const about: Section = {\n id: 'about',\n content: [\n `> **Purpose:** ${doc.purpose}`,\n '>',\n '> Generated by Athena from repository analysis. Content between `athena:generated` markers is refreshed by `athena analyze`; if you edit inside a marker, Athena keeps your edit and stops refreshing that section (use `--force` to regenerate). Everything outside the markers is yours.',\n '>',\n `> ${LEGEND}`,\n ].join('\\n'),\n };\n // Redact generated content only — developer-authored text is never rewritten.\n return [about, ...RENDERERS[id](model, extras)].map((s) => ({ id: s.id, content: redact(s.content) }));\n}\n\nexport function composeNewDocument(id: GeneratedDocId, sections: Section[]): string {\n const doc = KNOWLEDGE_DOCS.find((d) => d.id === id)!;\n return [\n `# ${doc.title}`,\n '',\n sections.map((s) => renderBlock(s)).join('\\n\\n'),\n '',\n DEVELOPER_NOTES_HEADING,\n '',\n '<!-- Knowledge Athena cannot detect: decisions, conventions, known issues, gotchas. Athena never modifies this section. -->',\n '',\n ].join('\\n');\n}\n\nexport interface DocPlan {\n id: GeneratedDocId;\n file: string;\n status: DocWriteStatus;\n /** Current file content (null if missing). */\n before: string | null;\n /** Content after regeneration. Equal to `before` when unchanged. */\n after: string;\n blocks: string[];\n /** Generated sections whose content would change or be added. */\n changedBlocks: string[];\n preservedModified: string[];\n}\n\n/** Compute regenerated documents without writing anything. */\nexport async function planKnowledge(athenaDir: string, model: ProjectModel, opts: WriteKnowledgeOptions = {}): Promise<DocPlan[]> {\n const plans: DocPlan[] = [];\n // Security scan results live beside the knowledge files and are rendered into security.md.\n const extras: KnowledgeExtras = { securityScan: await loadScanFromDir(athenaDir) };\n const ids = (Object.keys(RENDERERS) as GeneratedDocId[]).filter((id) => !opts.only || opts.only.includes(id));\n for (const id of ids) {\n const doc = KNOWLEDGE_DOCS.find((d) => d.id === id)!;\n const sections = renderSections(id, model, extras);\n const before = await readTextIfExists(path.join(athenaDir, doc.file));\n if (before === null) {\n plans.push({ id, file: doc.file, status: 'created', before, after: composeNewDocument(id, sections), blocks: sections.map((s) => s.id), changedBlocks: sections.map((s) => s.id), preservedModified: [] });\n continue;\n }\n const merged = mergeDocument(before, sections, { force: opts.force, previouslyKnown: opts.previousBlocks?.[id], insertBefore: DEVELOPER_NOTES_HEADING });\n plans.push({\n id,\n file: doc.file,\n status: merged.changed ? 'updated' : 'unchanged',\n before,\n after: merged.text,\n blocks: sections.map((s) => s.id),\n changedBlocks: [...merged.updated, ...merged.added],\n preservedModified: merged.preservedModified,\n });\n }\n return plans;\n}\n\nexport async function writePlannedKnowledge(athenaDir: string, plans: DocPlan[]): Promise<DocWriteReport[]> {\n const reports: DocWriteReport[] = [];\n for (const p of plans) {\n if (p.status !== 'unchanged') await writeFileAtomic(path.join(athenaDir, p.file), p.after);\n reports.push({ id: p.id, file: p.file, status: p.status, blocks: p.blocks, preservedModified: p.preservedModified, contentHash: sha256(p.after).slice(0, 16) });\n }\n return reports;\n}\n\nexport async function writeKnowledge(athenaDir: string, model: ProjectModel, opts: WriteKnowledgeOptions = {}): Promise<DocWriteReport[]> {\n return writePlannedKnowledge(athenaDir, await planKnowledge(athenaDir, model, opts));\n}\n\n/** Create rules.md only if it does not exist. Never regenerated. */\nexport async function ensureRules(athenaDir: string, model: ProjectModel): Promise<DocWriteReport> {\n const file = path.join(athenaDir, 'rules.md');\n const existing = await readTextIfExists(file);\n if (existing !== null) return { id: 'rules', file: 'rules.md', status: 'unchanged', blocks: [], preservedModified: [], contentHash: sha256(existing).slice(0, 16) };\n const text = seedRules(model);\n await writeFileAtomic(file, text);\n return { id: 'rules', file: 'rules.md', status: 'created', blocks: [], preservedModified: [], contentHash: sha256(text).slice(0, 16) };\n}\n","import type { Evidence, Provenance } from '../model/fact.js';\n\n/** Escape text for use inside a Markdown table cell or inline context. */\nexport function esc(s: string): string {\n return s.replace(/\\\\/g, '\\\\\\\\').replace(/\\|/g, '\\\\|').replace(/[<>]/g, (c) => (c === '<' ? '<' : '>')).replace(/\\r?\\n/g, ' ');\n}\n\nexport function code(s: string): string {\n const clean = s.replace(/\\r?\\n/g, ' ');\n const ticks = clean.includes('`') ? '``' : '`';\n return `${ticks}${ticks.length === 2 ? ' ' : ''}${clean}${ticks.length === 2 ? ' ' : ''}${ticks}`;\n}\n\nexport function evidenceRef(e: Evidence): string {\n return code(`${e.file}${e.line ? `:${e.line}` : ''}`);\n}\n\nexport function evidenceList(evidence: Evidence[], max = 3): string {\n if (!evidence.length) return '—';\n const shown = evidence.slice(0, max).map(evidenceRef).join(', ');\n return evidence.length > max ? `${shown} +${evidence.length - max} more` : shown;\n}\n\n/** Compact provenance label, e.g. \"DETECTED · high\". */\nexport function status(p: Provenance): string {\n return p.status === 'UNKNOWN' ? 'UNKNOWN' : `${p.status} · ${p.confidence}`;\n}\n\nexport function table(headers: string[], rows: string[][]): string {\n if (!rows.length) return '';\n const head = `| ${headers.join(' | ')} |`;\n const sep = `| ${headers.map(() => '---').join(' | ')} |`;\n return [head, sep, ...rows.map((r) => `| ${r.join(' | ')} |`)].join('\\n');\n}\n\nexport function unknown(what: string, hint?: string): string {\n return `**${what}:** UNKNOWN${hint ? ` — ${hint}` : ''}`;\n}\n\nexport function notDetected(what: string): string {\n return `_No ${what} detected._ Status: **UNKNOWN** (absence of detection is not proof of absence).`;\n}\n\nexport function bullets(items: string[]): string {\n return items.map((i) => `- ${i}`).join('\\n');\n}\n\nexport function truncatedNote(shown: number, total: number, what: string): string {\n return total > shown ? `\\n\\n_Showing ${shown} of ${total} ${what}. The full list is in \\`.athena/model.json\\`._` : '';\n}\n\n/** Sanitize a label for use inside a Mermaid node. */\nexport function mermaidLabel(s: string): string {\n return s.replace(/[\"`<>{}[\\]()|#;]/g, ' ').replace(/\\s+/g, ' ').trim().slice(0, 60) || 'node';\n}\n\nexport function mermaidId(s: string): string {\n return `n_${s.replace(/[^A-Za-z0-9]/g, '_')}`.slice(0, 64);\n}\n\nexport const LEGEND = [\n '**Status legend** — `FACT`: declared or developer-asserted · `DETECTED`: found by analysis, with evidence · `INFERRED`: heuristic, verify before relying on it · `UNKNOWN`: could not be determined.',\n].join('\\n');\n","import type { ProjectModel } from '../../model/project-model.js';\nimport type { Section } from '../managed-blocks.js';\nimport { bullets, code, esc, evidenceList, notDetected, status, table, truncatedNote, unknown } from '../md.js';\n\nexport function renderProject(m: ProjectModel): Section[] {\n const sections: Section[] = [];\n\n const purpose = m.description\n ? `${esc(m.description)}\\n\\n_Source: package manifest description (FACT)._`\n : `${unknown('Project purpose', 'no description found in manifests. Describe the project in Developer Notes below.')}`;\n sections.push({ id: 'overview', content: `## Overview\\n\\n**Name:** ${esc(m.name)}\\n\\n${purpose}` });\n\n // Rounded shares keep this section stable: adding one file should not churn the document.\n const totalBytes = m.languages.reduce((n, l) => n + l.bytes, 0) || 1;\n const share = (bytes: number) => {\n const pct = (bytes / totalBytes) * 100;\n return pct < 5 ? '<5%' : `~${Math.round(pct / 5) * 5}%`;\n };\n const langRows = m.languages.slice(0, 12).map((l) => [esc(l.name), share(l.bytes)]);\n sections.push({\n id: 'technologies',\n content: [\n '## Technologies',\n '',\n '### Languages',\n '',\n langRows.length ? table(['Language', 'Share of source'], langRows) : notDetected('source languages'),\n '',\n '### Frameworks & Libraries',\n '',\n m.frameworks.length\n ? table(['Name', 'Category', 'Location', 'Status', 'Evidence'], m.frameworks.map((f) => [esc(f.name), f.category, code(f.root), status(f.provenance), evidenceList(f.provenance.evidence, 2)]))\n : notDetected('known frameworks'),\n '',\n '### Package Managers & Build Tools',\n '',\n m.packageManagers.length || m.buildSystems.length\n ? bullets([...m.packageManagers.map((p) => `Package manager: **${esc(p.name)}** — ${status(p.provenance)} (${evidenceList(p.provenance.evidence, 2)})`), ...m.buildSystems.map((b) => `Build tool: **${esc(b.name)}** — ${status(b.provenance)} (${evidenceList(b.provenance.evidence, 2)})`)])\n : notDetected('package managers or build tools'),\n ].join('\\n'),\n });\n\n const ws = m.workspace;\n const structure: string[] = ['## Structure', ''];\n structure.push(`**Top-level directories:** ${m.topLevelDirs.length ? m.topLevelDirs.map(code).join(', ') : '_none_'}`);\n if (ws.isMonorepo) {\n structure.push('', `**Monorepo:** yes${ws.tool ? ` (${esc(ws.tool)})` : ''} — DETECTED`, '');\n structure.push(table(['Package', 'Path', 'Kind', 'Ecosystem', 'Internal deps'], ws.packages.map((p) => [esc(p.name), code(p.path), p.kind, p.ecosystem, p.internalDependencies.map(esc).join(', ') || '—'])));\n } else {\n structure.push('', '**Monorepo:** no workspace configuration detected.');\n }\n sections.push({ id: 'structure', content: structure.join('\\n') });\n\n sections.push({\n id: 'entry-points',\n content: ['## Entry Points', '', m.entryPoints.length ? table(['Path', 'Status', 'Evidence'], m.entryPoints.map((e) => [code(e.path), status(e.provenance), esc(e.provenance.evidence[0]?.detail ?? evidenceList(e.provenance.evidence))])) : notDetected('entry points')].join('\\n'),\n });\n\n const cmds = m.commands.slice(0, 40);\n sections.push({\n id: 'commands',\n content: ['## Commands', '', cmds.length ? table(['Name', 'Command', 'Purpose', 'Defined in'], cmds.map((c) => [code(c.name), code(c.command.length > 100 ? `${c.command.slice(0, 97)}...` : c.command), c.purpose, code(c.source)])) + truncatedNote(cmds.length, m.commands.length, 'commands') : notDetected('scripted commands (package scripts, Makefile, justfile)')].join('\\n'),\n });\n\n const env: string[] = ['## Environment Requirements', ''];\n const runtimes = m.manifests.map((x) => x.ecosystem).filter((v, i, a) => a.indexOf(v) === i);\n env.push(`**Ecosystems:** ${runtimes.length ? runtimes.join(', ') : 'UNKNOWN'}`);\n env.push('', `**Environment variables referenced:** ${m.env.vars.length} (names only — see \\`deployment.md\\`)`);\n if (m.env.envFilesPresent.length) env.push('', `**Local env files present (contents never read):** ${m.env.envFilesPresent.map(code).join(', ')}`);\n env.push('', unknown('Required runtime versions', 'not inferred; check manifests/tool-version files'));\n sections.push({ id: 'environment', content: env.join('\\n') });\n\n const devCmds = m.commands.filter((c) => ['dev', 'build', 'test', 'lint', 'start'].includes(c.purpose)).slice(0, 8);\n sections.push({\n id: 'workflow',\n content: ['## Development Workflow', '', devCmds.length ? `Detected workflow commands:\\n\\n${bullets(devCmds.map((c) => `${c.purpose}: ${code(c.command)} (${code(c.source)})`))}` : unknown('Development workflow', 'no dev/build/test commands detected'), '', '_Branching strategy, review process and release process are not detectable from code — document them in Developer Notes._'].join('\\n'),\n });\n\n if (m.warnings.length) {\n sections.push({ id: 'analysis-warnings', content: ['## Analysis Warnings', '', bullets(m.warnings.slice(0, 20).map(esc))].join('\\n') });\n } else {\n sections.push({ id: 'analysis-warnings', content: '## Analysis Warnings\\n\\nNone.' });\n }\n return sections;\n}\n\nexport function formatBytes(n: number): string {\n if (n < 1024) return `${n} B`;\n if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`;\n return `${(n / (1024 * 1024)).toFixed(1)} MB`;\n}\n","import type { ProjectModel } from '../../model/project-model.js';\nimport type { Section } from '../managed-blocks.js';\nimport { bullets, code, esc, evidenceList, mermaidId, mermaidLabel, notDetected, status, table, unknown } from '../md.js';\n\nexport function renderArchitecture(m: ProjectModel): Section[] {\n const s: Section[] = [];\n const fe = m.frameworks.filter((f) => ['frontend', 'fullstack', 'mobile', 'desktop'].includes(f.category));\n const be = m.frameworks.filter((f) => ['backend', 'fullstack'].includes(f.category));\n\n const summary: string[] = ['## System Overview', ''];\n const layers: string[] = [];\n if (fe.length) layers.push(`Client/UI layer: ${[...new Set(fe.map((f) => f.name))].map(esc).join(', ')} — DETECTED`);\n if (be.length) layers.push(`Server/API layer: ${[...new Set(be.map((f) => f.name))].map(esc).join(', ')} — DETECTED`);\n if (m.databases.length) layers.push(`Data layer: ${m.databases.map((d) => esc(d.name)).join(', ')} — DETECTED`);\n if (m.caching.length) layers.push(`Caching: ${m.caching.map((d) => esc(d.name)).join(', ')} — DETECTED`);\n if (m.queues.length) layers.push(`Async/queues: ${m.queues.map((d) => esc(d.name)).join(', ')} — DETECTED`);\n summary.push(layers.length ? bullets(layers) : unknown('Architecture layers', 'no known frameworks or data stores detected'));\n summary.push('', '_Layer membership is based on declared dependencies. How components interact at runtime is not verified by static analysis._');\n s.push({ id: 'overview', content: summary.join('\\n') });\n\n const ws = m.workspace;\n if (ws.isMonorepo && ws.packages.length > 1) {\n const edges = ws.packages.flatMap((p) => p.internalDependencies.map((d) => [p.name, d] as const));\n const lines = ['```mermaid', 'graph LR'];\n for (const p of ws.packages) if (p.path !== '.') lines.push(` ${mermaidId(p.name)}[\"${mermaidLabel(`${p.name} (${p.kind})`)}\"]`);\n for (const [from, to] of edges) lines.push(` ${mermaidId(from)} --> ${mermaidId(to)}`);\n lines.push('```');\n s.push({\n id: 'modules',\n content: ['## Workspace Modules & Dependencies', '', `Edges are declared internal dependencies between workspace packages (DETECTED from manifests).`, '', lines.join('\\n'), '', edges.length ? '' : '_No internal dependencies declared between packages._'].join('\\n').trim(),\n });\n } else {\n const dirs = m.topLevelDirs.filter((d) => !d.startsWith('.'));\n s.push({ id: 'modules', content: ['## Modules', '', dirs.length ? `Top-level directories: ${dirs.map(code).join(', ')}` : '_Flat project structure._', '', unknown('Module boundaries and responsibilities', 'describe them in Developer Notes')].join('\\n') });\n }\n\n if (m.containers.services.length) {\n const lines = ['```mermaid', 'graph TD'];\n for (const svc of m.containers.services) lines.push(` ${mermaidId(svc.name)}[\"${mermaidLabel(`${svc.name}${svc.image ? ` · ${svc.image}` : ''}`)}\"]`);\n for (const svc of m.containers.services) for (const dep of svc.dependsOn) lines.push(` ${mermaidId(svc.name)} --> ${mermaidId(dep)}`);\n lines.push('```');\n s.push({\n id: 'services',\n content: ['## Service Topology (containers)', '', 'From compose files. Arrows are `depends_on` relationships (DETECTED).', '', lines.join('\\n'), '', table(['Service', 'Image', 'Ports', 'Depends on', 'File'], m.containers.services.map((c) => [esc(c.name), esc(c.image ?? '—'), c.ports.map(esc).join(', ') || '—', c.dependsOn.map(esc).join(', ') || '—', code(c.file)]))].join('\\n'),\n });\n } else {\n s.push({ id: 'services', content: '## Service Topology\\n\\n_No container orchestration (compose) detected._ Runtime service topology: **UNKNOWN**.' });\n }\n\n const flow: string[] = ['## Data Flow', ''];\n if (fe.length && be.length && m.databases.length) {\n flow.push('```mermaid', 'graph LR', ' client[\"Client / UI\"] --> api[\"API / Server\"]', ' api --> data[\"Data store\"]', '```', '', '_INFERRED from the presence of UI, server and data-layer dependencies. Actual request paths are not verified._');\n } else if (be.length && m.databases.length) {\n flow.push('```mermaid', 'graph LR', ' caller[\"Caller\"] --> api[\"API / Server\"]', ' api --> data[\"Data store\"]', '```', '', '_INFERRED from server and data-layer dependencies._');\n } else {\n flow.push(unknown('Data flow', 'insufficient evidence to infer a request/data path'));\n }\n s.push({ id: 'data-flow', content: flow.join('\\n') });\n\n const external = [...m.auth.filter((a) => a.kind === 'provider'), ...m.observability, ...m.infrastructure.filter((i) => i.kind === 'hosting')];\n s.push({\n id: 'external-services',\n content: ['## External Services', '', external.length ? table(['Service', 'Status', 'Evidence'], external.map((e) => [esc(e.name), status(e.provenance), evidenceList(e.provenance.evidence, 2)])) : notDetected('external service integrations'), '', '_Only services identifiable from dependencies/config are listed. Third-party APIs called over plain HTTP are not detected in this version._'].join('\\n'),\n });\n\n s.push({ id: 'decisions', content: '## Architectural Decisions\\n\\n_Athena does not infer architectural decisions. Record them in Developer Notes (or link ADRs) so agents can respect them._' });\n return s;\n}\n","import type { ProjectModel } from '../../model/project-model.js';\nimport type { Section } from '../managed-blocks.js';\nimport { bullets, code, esc, evidenceList, notDetected, status, table, truncatedNote, unknown } from '../md.js';\n\nconst MAX_ENTITIES = 60;\nconst MAX_ROUTES = 200;\n\nexport function renderDatabase(m: ProjectModel): Section[] {\n const s: Section[] = [];\n s.push({\n id: 'technology',\n content: ['## Database Technology', '', m.databases.length ? table(['Technology', 'Kind', 'Status', 'Evidence'], m.databases.map((d) => [esc(d.name), d.kind, status(d.provenance), evidenceList(d.provenance.evidence, 2)])) : notDetected('database engines, ORMs or drivers')].join('\\n'),\n });\n\n const ents = m.dbEntities.slice(0, MAX_ENTITIES);\n const entityDocs = ents.map((e) => {\n const fields = e.fields.slice(0, 40).map((f) => `${code(f.name)}${f.type ? ` ${esc(f.type)}` : ''}${f.attributes.length ? ` — ${f.attributes.map(esc).join(' ')}` : ''}`);\n const parts = [`### ${esc(e.name)} (${e.kind})`, '', `Defined in ${evidenceList(e.provenance.evidence, 1)} · ${status(e.provenance)}`];\n if (fields.length) parts.push('', bullets(fields));\n if (e.relations.length) parts.push('', `**Relations:** ${e.relations.map(esc).join('; ')}`);\n if (e.indexes.length) parts.push('', `**Indexes/constraints:** ${e.indexes.map((i) => code(i)).join(', ')}`);\n return parts.join('\\n');\n });\n s.push({\n id: 'schema',\n content: ['## Schema & Entities', '', entityDocs.length ? entityDocs.join('\\n\\n') + truncatedNote(ents.length, m.dbEntities.length, 'entities') : notDetected('schema definitions (Prisma, SQL DDL, Django/SQLAlchemy models, Mongoose models)')].join('\\n'),\n });\n\n s.push({\n id: 'migrations',\n content: ['## Migrations', '', m.migrations.length ? table(['Location', 'Tool', 'Files'], m.migrations.map((x) => [code(x.path), esc(x.tool), String(x.count)])) : notDetected('migration directories'), '', m.commands.filter((c) => c.purpose === 'migrate').length ? `Migration commands: ${m.commands.filter((c) => c.purpose === 'migrate').map((c) => code(c.command)).join(', ')}` : ''].join('\\n').trim(),\n });\n\n const tenantCols = m.dbEntities.filter((e) => e.fields.some((f) => /^(tenant|organization|org|workspace|account)_?id$/i.test(f.name)));\n const iso: string[] = ['## Data Ownership & Tenant Isolation', ''];\n if (tenantCols.length) {\n iso.push(`Entities with tenant/organization-style key columns (DETECTED column names): ${tenantCols.map((e) => code(e.name)).join(', ')}`, '', unknown('Whether tenant isolation is enforced for all queries', 'column presence does not prove enforcement'));\n } else {\n iso.push(unknown('Tenancy model', 'no tenant/organization key columns detected'));\n }\n s.push({ id: 'ownership', content: iso.join('\\n') });\n s.push({ id: 'constraints', content: '## Important Constraints\\n\\n_Business-level data constraints are not inferred. Record them in Developer Notes or `rules.md`._' });\n return s;\n}\n\nexport function renderApi(m: ProjectModel): Section[] {\n const s: Section[] = [];\n const be = m.frameworks.filter((f) => ['backend', 'fullstack'].includes(f.category));\n const styles: string[] = [];\n if (m.routes.length) styles.push(`HTTP routes (${m.routes.length} detected)`);\n if (m.apiSpecs.some((x) => x.kind === 'graphql') || m.frameworks.some((f) => /GraphQL|Apollo/.test(f.name))) styles.push('GraphQL');\n if (m.apiSpecs.some((x) => x.kind === 'grpc') || m.frameworks.some((f) => /gRPC|tonic/.test(f.name))) styles.push('gRPC / Protocol Buffers');\n if (m.frameworks.some((f) => f.name === 'tRPC')) styles.push('tRPC');\n s.push({\n id: 'architecture',\n content: ['## API Architecture', '', be.length ? `**Server frameworks:** ${[...new Set(be.map((f) => f.name))].map(esc).join(', ')} (DETECTED)` : unknown('Server framework', 'no known backend framework detected'), '', styles.length ? `**API styles:** ${styles.join(', ')}` : unknown('API style')].join('\\n'),\n });\n\n const routes = m.routes.slice(0, MAX_ROUTES);\n s.push({\n id: 'endpoints',\n content: [\n '## Endpoints',\n '',\n routes.length\n ? `Paths are as written in code. Router prefixes applied elsewhere (mounting, include_router, blueprints) may not be reflected.\\n\\n${table(['Method', 'Path', 'Framework', 'Location', 'Status'], routes.map((r) => [r.method, code(r.path), esc(r.framework), code(`${r.file}${r.line ? `:${r.line}` : ''}`), status(r.provenance)]))}${truncatedNote(routes.length, m.routes.length, 'routes')}`\n : notDetected('HTTP routes'),\n ].join('\\n'),\n });\n\n s.push({\n id: 'specs',\n content: ['## API Specifications', '', m.apiSpecs.length ? bullets(m.apiSpecs.slice(0, 30).map((x) => `${x.kind}: ${code(x.path)}`)) : notDetected('OpenAPI, GraphQL or protobuf specifications')].join('\\n'),\n });\n\n s.push({\n id: 'auth-requirements',\n content: ['## Authentication & Authorization Requirements', '', unknown('Per-endpoint auth requirements', 'static route detection does not determine which middleware/guards apply to each route'), '', 'See `auth.md` for detected auth mechanisms.'].join('\\n'),\n });\n s.push({\n id: 'errors',\n content: ['## Request/Response & Error Handling', '', unknown('Request/response schemas', 'not extracted in this version'), '', unknown('Error response format', 'document the convention in Developer Notes or rules.md')].join('\\n'),\n });\n return s;\n}\n\nexport function renderAuth(m: ProjectModel): Section[] {\n const s: Section[] = [];\n const by = (k: string) => m.auth.filter((a) => a.kind === k);\n const row = (a: (typeof m.auth)[number]) => [esc(a.name), status(a.provenance), evidenceList(a.provenance.evidence, 3)];\n\n s.push({\n id: 'mechanism',\n content: [\n '## Authentication Mechanism',\n '',\n [...by('library'), ...by('provider')].length ? table(['Library / Provider', 'Status', 'Evidence'], [...by('library'), ...by('provider')].map(row)) : notDetected('authentication libraries or identity providers'),\n '',\n '_A declared auth dependency shows the capability is available, not that every route is protected._',\n ].join('\\n'),\n });\n s.push({\n id: 'tokens-sessions',\n content: ['## Sessions & Tokens', '', by('token').length ? table(['Library', 'Status', 'Evidence'], by('token').map(row)) : notDetected('token (JWT/JWE) libraries'), '', unknown('Session storage, token lifetime and refresh-token strategy', 'not determinable from dependencies alone')].join('\\n'),\n });\n const rbac = m.auth.filter((a) => a.kind === 'middleware');\n s.push({\n id: 'authorization',\n content: ['## Authorization, Roles & Permissions', '', rbac.length ? table(['Signal', 'Status', 'Evidence'], rbac.map(row)) : notDetected('role/permission definitions or auth middleware'), '', unknown('Authorization model (RBAC/ABAC/ownership checks)', 'confirm and document in Developer Notes')].join('\\n'),\n });\n s.push({\n id: 'passwords-mfa',\n content: ['## Password Handling, OAuth & MFA', '', by('hashing').length ? `**Password hashing libraries:** ${by('hashing').map((h) => `${esc(h.name)} (${evidenceList(h.provenance.evidence, 1)})`).join(', ')} — DETECTED` : unknown('Password hashing', 'no known hashing library detected (may be delegated to a provider)'), '', unknown('OAuth providers & MFA', 'not detected in this version')].join('\\n'),\n });\n s.push({\n id: 'assumptions',\n content: ['## Security Assumptions', '', '_No auth security assumptions are inferred automatically._ Document assumptions (e.g. \"all /admin routes require the admin role\") in Developer Notes so agents can check changes against them.', '', '> Athena never stores passwords, API keys, tokens or private keys in this file.'].join('\\n'),\n });\n return s;\n}\n","import type { ProjectModel } from '../../model/project-model.js';\nimport type { SecurityScan } from '../../model/security-scan.js';\nimport type { KnowledgeExtras } from '../generate.js';\nimport type { Section } from '../managed-blocks.js';\nimport { bullets, code, esc, evidenceList, notDetected, table, unknown } from '../md.js';\n\nexport function renderSecurity(m: ProjectModel, extras: KnowledgeExtras = {}): Section[] {\n const s: Section[] = [];\n\n s.push({\n id: 'classification',\n content: [\n '## How to Read This Document',\n '',\n bullets([\n '**Detected** — observed directly in code/config by Athena, with evidence.',\n '**Verified** — reported by a dedicated security tool (dependency audits below), or confirmed by a human.',\n '**Potential** — pattern that may indicate a problem; requires human review.',\n '**Unknown** — not determinable by static analysis.',\n ]),\n '',\n '_This document improves security awareness. It is not a security audit and does not certify the absence of vulnerabilities._',\n ].join('\\n'),\n });\n\n const surface: string[] = [];\n if (m.routes.length) surface.push(`**Detected:** ${m.routes.length} HTTP route definitions (see \\`api.md\\`).`);\n if (m.apiSpecs.length) surface.push(`**Detected:** ${m.apiSpecs.length} API specification files.`);\n const exposed = m.containers.services.filter((c) => c.ports.length);\n if (exposed.length) surface.push(`**Detected:** compose services publishing ports: ${exposed.map((c) => `${esc(c.name)} (${c.ports.map(esc).join(', ')})`).join('; ')}.`);\n const exposedDocker = m.containers.dockerfiles.filter((d) => d.exposedPorts.length);\n if (exposedDocker.length) surface.push(`**Detected:** Dockerfile EXPOSE: ${exposedDocker.map((d) => `${code(d.path)} → ${d.exposedPorts.map(esc).join(', ')}`).join('; ')}.`);\n if (m.frameworks.some((f) => ['frontend', 'fullstack', 'mobile'].includes(f.category))) surface.push('**Detected:** client-side code exists — anything bundled into the client is public.');\n if (m.queues.length) surface.push(`**Detected:** message/queue consumers may process untrusted payloads (${m.queues.map((q) => esc(q.name)).join(', ')}).`);\n s.push({ id: 'attack-surface', content: ['## Attack Surface', '', surface.length ? bullets(surface) : unknown('Attack surface', 'no routes, exposed ports or client code detected')].join('\\n') });\n\n s.push({\n id: 'controls',\n content: ['## Security Controls (declared)', '', m.security.controls.length ? table(['Control', 'Evidence'], m.security.controls.map((c) => [esc(c.name), evidenceList(c.provenance.evidence, 2)])) : notDetected('security middleware or validation libraries'), '', '_Detected as dependencies. Whether they are applied to every relevant code path is **Unknown**._'].join('\\n'),\n });\n\n const secretRows = m.security.secrets.slice(0, 100).map((f) => [esc(f.type), code(`${f.file}:${f.line}`), code(f.fingerprint)]);\n const secretBody: string[] = ['## Secret Management', ''];\n if (m.security.secrets.length) {\n secretBody.push(`**Potential:** ${m.security.secrets.length} possible hardcoded secret(s). Values are never recorded; the fingerprint is a truncated SHA-256 for tracking. Review each and rotate any real credential.`, '', table(['Type', 'Location', 'Fingerprint'], secretRows));\n } else {\n secretBody.push('No likely secrets matched Athena\\'s patterns in scanned files. This is **not** proof that no secrets exist (gitignored and oversized files are not scanned).');\n }\n if (m.env.envFilesPresent.length) secretBody.push('', `Local env files present: ${m.env.envFilesPresent.map(code).join(', ')}. Athena does not read their contents. Ensure they are gitignored.`);\n const secretVars = m.env.vars.filter((v) => v.secretLike);\n if (secretVars.length) secretBody.push('', `Secret-like environment variable names (values configured externally): ${secretVars.slice(0, 30).map((v) => code(v.name)).join(', ')}`);\n s.push({ id: 'secrets', content: secretBody.join('\\n') });\n\n const risks: string[] = [];\n const hasBackend = m.frameworks.some((f) => ['backend', 'fullstack'].includes(f.category));\n const names = new Set([...m.security.controls.map((c) => c.name)]);\n if (hasBackend && m.routes.length && !m.auth.some((a) => a.kind !== 'hashing')) risks.push('**Potential:** routes detected but no authentication library/provider detected. Auth may be custom, external (gateway) or absent — verify.');\n if (hasBackend && ![...names].some((n) => /zod|joi|yup|validator|pydantic|validation/i.test(n))) risks.push('**Unknown:** input validation approach — no schema-validation library detected.');\n if (m.frameworks.some((f) => ['Express', 'Fastify', 'Koa', 'Hono'].includes(f.name)) && ![...names].some((n) => /helmet/i.test(n))) risks.push('**Potential:** no security-headers middleware (e.g. helmet) detected for the Node HTTP server.');\n if (hasBackend && ![...names].some((n) => /cors/i.test(n))) risks.push('**Unknown:** CORS policy — no CORS library detected (may be configured in framework/gateway).');\n if (m.frameworks.some((f) => ['Express', 'Fastify', 'Koa'].includes(f.name)) && ![...names].some((n) => /rate-limit/i.test(n))) risks.push('**Unknown:** rate limiting — no rate-limit middleware detected.');\n if (m.databases.some((d) => d.kind === 'driver') && !m.databases.some((d) => d.kind === 'orm')) risks.push('**Potential:** raw database driver without an ORM detected — review queries for injection (use parameterized queries).');\n if (m.auth.some((a) => /csurf/.test(a.name)) || names.has('csurf (deprecated)')) risks.push('**Detected:** `csurf` is deprecated; consider a maintained CSRF library.');\n risks.push('**Unknown:** CSRF protection for cookie-based sessions, SSRF protections for server-side fetches, and output encoding — not analyzed in this version.');\n s.push({ id: 'risks', content: ['## Risk Areas', '', bullets(risks)].join('\\n') });\n\n s.push({\n id: 'tooling',\n content: ['## Security Tooling', '', m.security.tooling.length ? table(['Tool', 'Evidence'], dedupe(m.security.tooling).map((t) => [esc(t.name), evidenceList(t.provenance.evidence, 2)])) : notDetected('security tooling (dependency scanning, SAST, secret scanning)')].join('\\n'),\n });\n\n s.push({ id: 'dependencies', content: renderDependencyRisks(m, extras.securityScan ?? null) });\n\n s.push({ id: 'known-issues', content: '## Known Unresolved Security Issues\\n\\n_None recorded by Athena._ Track confirmed issues in Developer Notes (without exploit details or secrets).' });\n return s;\n}\n\nfunction renderDependencyRisks(m: ProjectModel, scan: SecurityScan | null): string {\n const head = ['## Dependency Risks', ''];\n const manifests = `Manifests in scope: ${m.manifests.length ? m.manifests.map((x) => code(x.path)).slice(0, 15).join(', ') : '_none_'}`;\n if (!scan) {\n return [...head, 'No dependency audit has been run. Run `athena security` to audit dependencies with the tools installed for this project.', '', manifests].join('\\n');\n }\n const lines = [...head, `Last scan: ${scan.scannedAt} (${(scan.durationMs / 1000).toFixed(1)}s). Findings come from the tools below, not from Athena.`, ''];\n const ran = scan.tools.filter((t) => t.status === 'ok');\n const missing = scan.tools.filter((t) => t.status !== 'ok');\n const findings = ran.flatMap((t) => t.findings.map((f) => ({ ...f, tool: t.tool })));\n\n if (findings.length) {\n const rows = findings\n .slice(0, 60)\n .map((f) => [esc(f.package), f.severity.toUpperCase(), esc(f.title.slice(0, 90)), esc(f.id ?? '—'), esc(f.tool), f.fixAvailable ? 'yes' : 'unknown']);\n lines.push(`**Detected by tooling:** ${findings.length} vulnerable dependenc${findings.length === 1 ? 'y' : 'ies'}.`, '', table(['Package', 'Severity', 'Advisory', 'ID', 'Tool', 'Fix available'], rows));\n if (findings.length > 60) lines.push('', `_Showing 60 of ${findings.length}. See \\`.athena/security-scan.json\\`._`);\n } else if (ran.length) {\n lines.push(`**Detected:** no known vulnerable dependencies reported by ${ran.map((t) => esc(t.tool)).join(', ')} at the time of the scan.`);\n }\n if (missing.length) {\n lines.push('', '**Unknown** — these ecosystems were not audited:', '', bullets(missing.map((t) => `${esc(t.tool)} (${esc(t.ecosystem)}): ${esc(t.message ?? t.status)}`)));\n }\n lines.push('', manifests, '', '_Athena does not maintain its own vulnerability database, and a clean audit is not proof that dependencies are safe._');\n return lines.join('\\n');\n}\n\nfunction dedupe<T extends { name: string }>(items: T[]): T[] {\n const seen = new Set<string>();\n return items.filter((i) => (seen.has(i.name) ? false : (seen.add(i.name), true)));\n}\n","import type { ProjectModel } from '../../model/project-model.js';\nimport type { Section } from '../managed-blocks.js';\nimport { bullets, code, esc, evidenceList, notDetected, table, unknown } from '../md.js';\n\nexport function renderTesting(m: ProjectModel): Section[] {\n const t = m.tests;\n const s: Section[] = [];\n s.push({\n id: 'frameworks',\n content: ['## Test Frameworks', '', t.frameworks.length ? table(['Framework', 'Evidence'], t.frameworks.map((f) => [esc(f.name), evidenceList(f.provenance.evidence, 3)])) : notDetected('test frameworks')].join('\\n'),\n });\n const kinds: string[] = [];\n const names = t.frameworks.map((f) => f.name);\n if (names.some((n) => /Playwright|Cypress|Detox|integration_test/.test(n))) kinds.push('End-to-end / UI tests: framework DETECTED');\n if (names.some((n) => /Supertest|Testcontainers|pytest-django|Spring Boot Test/.test(n))) kinds.push('Integration tests: supporting library DETECTED');\n if (names.some((n) => /Jest|Vitest|Mocha|pytest|go test|cargo test|JUnit|RSpec|PHPUnit|xUnit|NUnit|flutter_test|Minitest|Pest|testify/.test(n))) kinds.push('Unit tests: runner DETECTED');\n s.push({\n id: 'layout',\n content: [\n '## Test Layout',\n '',\n `**Test files detected:** ${t.testFileCount}`,\n '',\n t.testDirs.length ? `**Test directories:** ${t.testDirs.map(code).join(', ')}` : '_No dedicated test directories detected._',\n '',\n kinds.length ? bullets(kinds) : unknown('Unit/integration/E2E split'),\n ].join('\\n'),\n });\n const cmds = m.commands.filter((c) => c.purpose === 'test');\n s.push({ id: 'commands', content: ['## Test Commands', '', cmds.length ? table(['Name', 'Command', 'Defined in'], cmds.slice(0, 20).map((c) => [code(c.name), code(c.command), code(c.source)])) : notDetected('test commands')].join('\\n') });\n s.push({\n id: 'coverage',\n content: ['## Coverage', '', t.coverageConfigs.length ? `Coverage configuration found in: ${[...new Set(t.coverageConfigs)].map(code).join(', ')}` : notDetected('coverage configuration'), '', unknown('Actual coverage percentage', 'Athena does not run tests or read coverage reports in this version')].join('\\n'),\n });\n const gaps: string[] = [];\n if (t.testFileCount === 0 && m.stats.filesScanned > 0) gaps.push('**Detected:** no test files found in the project.');\n if (t.packagesWithoutTests.length) gaps.push(`**Detected:** workspace packages with source files but no test files: ${t.packagesWithoutTests.map(code).join(', ')}`);\n if (m.routes.length && !names.some((n) => /Supertest|Playwright|Cypress|pytest|Spring Boot Test|Testcontainers/.test(n))) gaps.push('**Potential:** HTTP routes exist but no API/integration testing library was detected.');\n s.push({ id: 'gaps', content: ['## Missing Coverage (structural)', '', gaps.length ? bullets(gaps) : '_No structural gaps detected._ This does not measure test quality or coverage.'].join('\\n') });\n s.push({ id: 'critical-areas', content: '## Critical Test Areas\\n\\n_Not inferred. List business-critical flows (payments, auth, data deletion, migrations) in Developer Notes so agents prioritize tests for them._' });\n return s;\n}\n\nexport function renderDebugging(m: ProjectModel): Section[] {\n const s: Section[] = [];\n s.push({ id: 'known-bugs', content: '## Known Bugs\\n\\n_None recorded._ Add known bugs and their status in Developer Notes.' });\n const cmds = m.commands.filter((c) => ['dev', 'start', 'test', 'lint'].includes(c.purpose)).slice(0, 15);\n s.push({ id: 'commands', content: ['## Debugging & Diagnostic Commands', '', cmds.length ? table(['Purpose', 'Command', 'Defined in'], cmds.map((c) => [c.purpose, code(c.command), code(c.source)])) : notDetected('runnable dev/test commands')].join('\\n') });\n s.push({\n id: 'logging',\n content: ['## Logging & Observability', '', m.observability.length ? table(['Tool', 'Evidence'], m.observability.map((o) => [esc(o.name), evidenceList(o.provenance.evidence, 2)])) : notDetected('logging/monitoring libraries'), '', unknown('Log locations and formats', 'document where logs are written and how to access them')].join('\\n'),\n });\n const hot = m.git.hotspots;\n s.push({\n id: 'hotspots',\n content: ['## Change Hotspots', '', hot.length ? `Directories with the most file changes in the last 180 days (git history), most-changed first. **INFERRED** as areas more likely to contain regressions. Exact counts are omitted to keep this document stable; see \\`model.json\\`.\\n\\n${hot.slice(0, 8).map((h, i) => `${i + 1}. ${code(h.path)}`).join('\\n')}` : '_Not available (no git history)._'].join('\\n'),\n });\n s.push({ id: 'common-errors', content: '## Common Errors & Workarounds\\n\\n_None recorded._ When an agent or developer resolves a recurring error, record the symptom, cause and fix in Developer Notes.' });\n return s;\n}\n\nexport function renderPerformance(m: ProjectModel): Section[] {\n const s: Section[] = [];\n s.push({ id: 'caching', content: ['## Caching', '', m.caching.length ? table(['Technology', 'Evidence'], m.caching.map((c) => [esc(c.name), evidenceList(c.provenance.evidence, 2)])) : notDetected('caching libraries or cache services'), '', unknown('Cache strategy and invalidation rules')].join('\\n') });\n s.push({ id: 'queues', content: ['## Background Jobs & Queues', '', m.queues.length ? table(['Technology', 'Evidence'], m.queues.map((c) => [esc(c.name), evidenceList(c.provenance.evidence, 2)])) : notDetected('queue or background-job systems')].join('\\n') });\n const idx = m.dbEntities.filter((e) => e.indexes.length).length;\n s.push({\n id: 'database',\n content: ['## Database Performance', '', m.dbEntities.length ? `${m.dbEntities.length} entities detected; ${idx} with explicit indexes/constraints (see \\`database.md\\`).` : notDetected('database entities'), '', unknown('Query patterns, N+1 risks and slow queries', 'requires runtime data or deeper analysis')].join('\\n'),\n });\n const fe = m.frameworks.filter((f) => ['frontend', 'fullstack'].includes(f.category));\n s.push({ id: 'frontend', content: ['## Frontend Performance', '', fe.length ? `Frontend frameworks: ${[...new Set(fe.map((f) => f.name))].map(esc).join(', ')}.` : '_No frontend framework detected._', '', unknown('Bundle size, rendering strategy and Core Web Vitals')].join('\\n') });\n s.push({ id: 'bottlenecks', content: '## Known Bottlenecks\\n\\n_None recorded._ Athena does not invent benchmarks. Record measured bottlenecks (with how they were measured) in Developer Notes.' });\n return s;\n}\n\nexport function renderCodeReview(m: ProjectModel): Section[] {\n const s: Section[] = [];\n const general = [\n 'Change is limited to the stated task; no unrelated files modified.',\n 'Follows every enabled rule in `rules.md`.',\n 'No secrets, credentials or tokens added to code, config, logs or tests.',\n 'New dependencies are justified and actively maintained.',\n 'Breaking changes (API, schema, config) are called out explicitly.',\n 'Athena knowledge synchronized (`athena sync`) if structure, routes, schema or infrastructure changed.',\n ];\n s.push({ id: 'general', content: ['## General Checklist', '', bullets(general.map((g) => `[ ] ${g}`))].join('\\n') });\n\n const arch: string[] = [];\n if (m.workspace.isMonorepo) arch.push('Cross-package imports go through declared workspace dependencies (no deep relative imports into other packages).');\n if (m.frameworks.some((f) => ['backend', 'fullstack'].includes(f.category))) arch.push('Business logic is not added directly to route handlers/controllers when a service layer exists.');\n arch.push('New modules follow the existing directory conventions (see `project.md` → Structure).');\n s.push({ id: 'architecture', content: ['## Architecture', '', bullets(arch.map((a) => `[ ] ${a}`))].join('\\n') });\n\n const sec: string[] = [];\n if (m.routes.length) sec.push('New/changed endpoints enforce authentication and authorization as required.', 'Request input is validated before use.');\n if (m.databases.length) sec.push('Database access uses parameterized queries / ORM APIs — no string-built SQL with user input.');\n if (m.frameworks.some((f) => ['frontend', 'fullstack', 'mobile'].includes(f.category))) sec.push('No server-only secrets or privileged keys exposed to client bundles.', 'User-provided content is not rendered as raw HTML without sanitization.');\n sec.push('Errors do not leak stack traces, secrets or internal identifiers to clients.');\n s.push({ id: 'security', content: ['## Security', '', bullets(sec.map((x) => `[ ] ${x}`))].join('\\n') });\n\n const testing = [m.tests.frameworks.length ? `New logic has tests using the project's framework(s): ${m.tests.frameworks.map((f) => esc(f.name)).join(', ')}.` : 'Consider adding tests — no test framework was detected.'];\n const testCmd = m.commands.find((c) => c.purpose === 'test');\n if (testCmd) testing.push(`Tests pass: ${code(testCmd.command)}`);\n const lintCmd = m.commands.find((c) => c.purpose === 'lint');\n if (lintCmd) testing.push(`Lint/type checks pass: ${code(lintCmd.command)}`);\n s.push({ id: 'testing', content: ['## Testing Expectations', '', bullets(testing.map((x) => `[ ] ${x}`))].join('\\n') });\n\n const perf: string[] = [];\n if (m.databases.length) perf.push('New queries on large tables use indexes; no N+1 query patterns introduced.');\n if (m.caching.length) perf.push('Cache invalidation is handled for changed data.');\n if (m.queues.length) perf.push('Long-running work is offloaded to background jobs where appropriate.');\n perf.push('No unbounded loops/fetches over user-controlled sizes.');\n s.push({ id: 'performance', content: ['## Performance', '', bullets(perf.map((x) => `[ ] ${x}`))].join('\\n') });\n s.push({ id: 'common-mistakes', content: '## Common Mistakes in This Project\\n\\n_None recorded._ Add recurring review findings in Developer Notes.' });\n return s;\n}\n","import type { ProjectModel } from '../../model/project-model.js';\nimport type { Section } from '../managed-blocks.js';\nimport { bullets, code, esc, evidenceList, notDetected, table, truncatedNote, unknown } from '../md.js';\n\nexport function renderDeployment(m: ProjectModel): Section[] {\n const s: Section[] = [];\n const hosting = m.infrastructure.filter((i) => i.kind === 'hosting');\n const iac = m.infrastructure.filter((i) => i.kind === 'iac');\n const k8s = m.infrastructure.filter((i) => i.kind === 'kubernetes');\n const proxy = m.infrastructure.filter((i) => i.kind === 'reverse-proxy');\n\n s.push({\n id: 'architecture',\n content: [\n '## Deployment Architecture',\n '',\n hosting.length ? `**Hosting/platform configuration:**\\n\\n${table(['Platform', 'File'], hosting.map((h) => [esc(h.name), code(h.file)]))}` : unknown('Hosting platform', 'no platform configuration files detected'),\n '',\n iac.length ? `**Infrastructure as code:** ${iac.map((i) => `${esc(i.name)} (${code(i.file)})`).join(', ')}` : '_No infrastructure-as-code detected._',\n '',\n k8s.length ? `**Kubernetes resources:** ${k8s.map((i) => `${esc(i.name)} (${code(i.file)})`).join(', ')}` : '',\n proxy.length ? `**Reverse proxy:** ${proxy.map((i) => `${esc(i.name)} (${code(i.file)})`).join(', ')}` : '',\n ].filter((l, i, a) => l !== '' || a[i - 1] !== '').join('\\n').trim(),\n });\n\n const df = m.containers.dockerfiles;\n s.push({\n id: 'containers',\n content: ['## Containers', '', df.length ? table(['Dockerfile', 'Base images', 'Exposed ports'], df.map((d) => [code(d.path), d.baseImages.map(esc).join(', ') || '—', d.exposedPorts.map(esc).join(', ') || '—'])) : notDetected('Dockerfiles'), '', m.containers.services.length ? `Compose services: ${m.containers.services.map((c) => code(c.name)).join(', ')} (see \\`architecture.md\\`).` : ''].join('\\n').trim(),\n });\n\n const jobs = m.ci.slice(0, 30);\n s.push({\n id: 'ci-cd',\n content: [\n '## CI/CD',\n '',\n jobs.length\n ? table(['System', 'Job', 'Key steps', 'File'], jobs.map((j) => [esc(j.system), esc(j.name), j.commands.slice(0, 4).map((c) => code(c)).join('<br>') || '—', code(j.file)])) + truncatedNote(jobs.length, m.ci.length, 'CI jobs')\n : notDetected('CI/CD pipelines'),\n ].join('\\n'),\n });\n\n s.push({ id: 'environments', content: ['## Environments', '', unknown('Environment list (dev/staging/production), domains and promotion flow', 'not determinable from code — document them in Developer Notes')].join('\\n') });\n\n const vars = m.env.vars.slice(0, 80);\n s.push({\n id: 'env-vars',\n content: [\n '## Environment Variables',\n '',\n 'Names only. **Values are never read or stored by Athena** — all values are `<configured externally>`.',\n '',\n vars.length ? table(['Variable', 'Value', 'Referenced in'], vars.map((v) => [code(v.name), v.secretLike ? '`<secret>`' : '`<configured externally>`', v.references.slice(0, 2).map(code).join(', ') + (v.references.length > 2 ? ` +${v.references.length - 2}` : '')])) + truncatedNote(vars.length, m.env.vars.length, 'variables') : notDetected('environment variable references'),\n ].join('\\n'),\n });\n\n const deployCmds = m.commands.filter((c) => ['build', 'deploy', 'migrate', 'start'].includes(c.purpose)).slice(0, 15);\n s.push({\n id: 'commands',\n content: ['## Build, Release & Migration Commands', '', deployCmds.length ? table(['Purpose', 'Command', 'Defined in'], deployCmds.map((c) => [c.purpose, code(c.command), code(c.source)])) : notDetected('build/deploy commands'), '', m.migrations.length ? `Migrations: ${m.migrations.map((x) => `${esc(x.tool)} in ${code(x.path)}`).join(', ')}. ${unknown('When migrations run during deploy')}` : ''].join('\\n').trim(),\n });\n s.push({ id: 'notes', content: ['## Deployment Safety', '', bullets(['Never commit secrets; configure them in the hosting platform or a secret manager.', 'Document rollback procedures in Developer Notes.']), '', `_Evidence for this document comes from ${m.infrastructure.length + m.ci.length + df.length} infrastructure/CI files (${evidenceList(m.infrastructure.flatMap((i) => i.provenance.evidence), 3)})._`].join('\\n') });\n return s;\n}\n","import type { ProjectModel } from '../model/project-model.js';\n\n/**\n * Initial rules.md. Universal, low-risk rules are enabled. Stack-specific rules are\n * seeded as `[disabled]` suggestions: Athena must not silently turn its own\n * guesses into project policy — the developer opts in.\n */\nexport function seedRules(m: ProjectModel): string {\n const hasBackend = m.frameworks.some((f) => ['backend', 'fullstack'].includes(f.category));\n const hasFrontend = m.frameworks.some((f) => ['frontend', 'fullstack', 'mobile'].includes(f.category));\n const hasDb = m.databases.length > 0;\n const hasMigrations = m.migrations.length > 0;\n const hasTests = m.tests.frameworks.length > 0;\n const tenant = m.dbEntities.some((e) => e.fields.some((f) => /^(tenant|organization|org|workspace|account)_?id$/i.test(f.name)));\n\n const out: string[] = [\n '# Athena Project Rules',\n '',\n '<!--',\n 'This file is owned by you. Athena creates it once and never regenerates it.',\n 'AI agents configured by Athena are instructed to follow every enabled rule.',\n '',\n 'Format: one rule per top-level bullet under a \"## Section\" heading.',\n 'Disable a rule without deleting it by writing \"- [disabled] ...\".',\n 'Rules marked [disabled] below are SUGGESTIONS based on the detected stack — enable the ones that apply.',\n '-->',\n '',\n '## AI Agent Rules',\n '',\n '- Read the relevant Athena knowledge (see the relevance map in your agent instructions) before making significant changes.',\n '- Do not modify files unrelated to the task.',\n '- Do not introduce new dependencies without stating the justification.',\n '- Explain breaking changes (API, schema, configuration) before implementing them.',\n '- Never add secrets, credentials or tokens to code, config, tests or logs.',\n '- Treat statements marked INFERRED or UNKNOWN in Athena knowledge as unverified.',\n '',\n '## Security',\n '',\n '- Validate all external input at trust boundaries.',\n ];\n if (hasFrontend) out.push('- Never expose server-side secrets to frontend code or client bundles.');\n if (hasDb) out.push('- Use parameterized queries or ORM query APIs; never build SQL from user input.');\n\n out.push('', '## Architecture', '');\n out.push(hasBackend ? '- [disabled] Keep business logic out of route handlers/controllers; use the service layer.' : '- [disabled] Keep modules focused; do not create circular dependencies.');\n if (m.workspace.isMonorepo) out.push('- [disabled] Packages may only import other workspace packages through declared dependencies.');\n\n if (hasDb) {\n out.push('', '## Database', '');\n if (hasMigrations) out.push('- [disabled] All schema changes must go through migrations; never modify production schema manually.');\n else out.push('- [disabled] Schema changes must be reviewed before applying them to shared environments.');\n if (tenant) out.push('- [disabled] Every tenant-owned table must include the tenant key, and every query must filter by it.');\n }\n if (m.routes.length || hasBackend) {\n out.push('', '## API', '');\n out.push('- [disabled] Return consistent error responses across endpoints.');\n out.push('- [disabled] New endpoints must declare their authentication and authorization requirements.');\n }\n out.push('', '## Testing', '');\n out.push(hasTests ? '- [disabled] New business logic requires tests.' : '- [disabled] Add a test framework before adding complex business logic.');\n out.push('');\n return out.join('\\n');\n}\n","import { z } from 'zod';\nimport path from 'node:path';\nimport { athenaDir } from '../state/state.js';\nimport { readTextIfExists, writeFileAtomic } from '../util/fs.js';\n\n/**\n * Results of a dependency/secret security scan. Kept beside the knowledge files\n * (gitignored) because findings are time-sensitive and machine-specific: they\n * depend on which audit tools are installed and when they last ran.\n */\nexport const SCAN_FILE = 'security-scan.json';\n\nexport const Severity = z.enum(['critical', 'high', 'moderate', 'low', 'unknown']);\nexport type Severity = z.infer<typeof Severity>;\nexport const SEVERITY_ORDER: Severity[] = ['critical', 'high', 'moderate', 'low', 'unknown'];\n\nexport const Vulnerability = z.object({\n package: z.string(),\n severity: Severity,\n title: z.string(),\n id: z.string().optional(),\n url: z.string().optional(),\n vulnerableRange: z.string().optional(),\n fixAvailable: z.boolean().optional(),\n});\nexport type Vulnerability = z.infer<typeof Vulnerability>;\n\nexport const ToolResult = z.object({\n tool: z.string(),\n ecosystem: z.string(),\n /** ok: ran and produced results · unavailable: not installed · failed/timeout: ran but no usable output */\n status: z.enum(['ok', 'unavailable', 'failed', 'timeout']),\n message: z.string().optional(),\n durationMs: z.number(),\n findings: z.array(Vulnerability),\n});\nexport type ToolResult = z.infer<typeof ToolResult>;\n\nexport const SecurityScan = z.object({\n schemaVersion: z.literal(1),\n scannedAt: z.string(),\n durationMs: z.number(),\n tools: z.array(ToolResult),\n counts: z.record(Severity, z.number()),\n secrets: z.object({ count: z.number(), files: z.array(z.string()) }),\n});\nexport type SecurityScan = z.infer<typeof SecurityScan>;\n\nexport const loadScan = (root: string) => loadScanFromDir(athenaDir(root));\n\nexport async function saveScan(root: string, scan: SecurityScan): Promise<void> {\n await writeFileAtomic(path.join(athenaDir(root), SCAN_FILE), `${JSON.stringify(scan, null, 2)}\\n`);\n}\n\nexport async function loadScanFromDir(dir: string): Promise<SecurityScan | null> {\n const raw = await readTextIfExists(path.join(dir, SCAN_FILE));\n if (!raw) return null;\n try {\n const parsed = SecurityScan.safeParse(JSON.parse(raw));\n return parsed.success ? parsed.data : null;\n } catch {\n return null;\n }\n}\n\nexport function totalFindings(scan: SecurityScan): number {\n return scan.tools.reduce((n, t) => n + t.findings.length, 0);\n}\n\n/** True when the scan contains a finding at or above `level`. */\nexport function meetsThreshold(scan: SecurityScan, level: Severity): boolean {\n const max = SEVERITY_ORDER.indexOf(level);\n return scan.tools.some((t) => t.findings.some((f) => SEVERITY_ORDER.indexOf(f.severity) <= max && f.severity !== 'unknown'));\n}\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { AthenaError, EXIT } from '../services/errors.js';\nimport { findProjectRoot } from '../services/project.js';\n\nexport { findProjectRoot };\n\nexport interface GlobalOptions {\n cwd?: string;\n json?: boolean;\n quiet?: boolean;\n verbose?: boolean;\n color?: boolean;\n}\n\nexport async function resolveCwd(opts: GlobalOptions): Promise<string> {\n const dir = path.resolve(opts.cwd ?? process.cwd());\n try {\n const st = await fs.stat(dir);\n if (!st.isDirectory()) throw new AthenaError(`Not a directory: ${dir}`);\n return await fs.realpath(dir);\n } catch (err) {\n if (err instanceof AthenaError) throw err;\n throw new AthenaError(`Directory not accessible: ${dir}`, 'Check the path and your permissions.');\n }\n}\n\nexport async function requireProjectRoot(opts: GlobalOptions): Promise<string> {\n const cwd = await resolveCwd(opts);\n const root = await findProjectRoot(cwd);\n if (!root) throw new AthenaError('Athena is not initialized in this project.', 'Run `athena init` in the project root.', EXIT.NOT_INITIALIZED);\n return root;\n}\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { ATHENA_DIR } from '../core/config.js';\n\n/** Walk up from `start` to find the nearest directory containing `.athena/`. */\nexport async function findProjectRoot(start: string): Promise<string | null> {\n let dir = start;\n for (;;) {\n try {\n const st = await fs.stat(path.join(dir, ATHENA_DIR));\n if (st.isDirectory()) return dir;\n } catch {\n /* keep walking */\n }\n const parent = path.dirname(dir);\n if (parent === dir) return null;\n dir = parent;\n }\n}\n","import { requireProjectRoot, type GlobalOptions } from '../context.js';\nimport { parseAgentsOption, printSummary, runWithProgress, summarize } from './init.js';\nimport * as ui from '../ui/term.js';\n\nexport interface AnalyzeOptions extends GlobalOptions {\n force?: boolean;\n agents?: string;\n signal?: AbortSignal;\n}\n\nexport async function analyzeCommand(opts: AnalyzeOptions): Promise<void> {\n const root = await requireProjectRoot(opts);\n const agents = parseAgentsOption(opts.agents, false);\n const result = await runWithProgress(root, { mode: 'analyze', force: opts.force, agents, signal: opts.signal });\n if (ui.isJson()) ui.json(summarize(result, root, false));\n else printSummary(result, false, 'analyze');\n}\n","import path from 'node:path';\nimport { loadConfig } from '../core/config.js';\nimport { walkProject } from '../core/fs/walker.js';\nimport { impactOf } from '../core/impact/impact.js';\nimport { KNOWLEDGE_DOCS } from '../core/knowledge/documents.js';\nimport { isBlockModified, parseBlocks } from '../core/knowledge/managed-blocks.js';\nimport { athenaDir, buildFileIndex, diffFileIndex, readState } from '../core/state/state.js';\nimport { readTextIfExists } from '../core/util/fs.js';\nimport { workingChanges } from '../core/git/git.js';\nimport { AthenaError } from './errors.js';\n\nexport interface DocStatus {\n file: string;\n title: string;\n present: boolean;\n editedBlocks: string[];\n lastChangedAt?: string;\n}\n\nexport interface StatusReport {\n project: string;\n root: string;\n health: 'healthy' | 'needs-update' | 'degraded';\n analyzedAt: string;\n documents: DocStatus[];\n changes: { added: string[]; modified: string[]; deleted: string[] };\n git: { isRepo: boolean; branch?: string; headChanged: boolean; uncommitted: number | null };\n affectedDocuments: Array<{ file: string; reasons: string[] }>;\n sync: 'up-to-date' | 'needs-update';\n}\n\nexport async function buildStatus(root: string, signal?: AbortSignal): Promise<StatusReport> {\n const dir = athenaDir(root);\n const st = await readState(dir);\n if (st.kind === 'missing') throw new AthenaError('.athena/state.json is missing.', 'Run `athena analyze` to rebuild it.');\n if (st.kind === 'corrupted') throw new AthenaError(`.athena/state.json is corrupted (${st.reason}).`, 'Run `athena analyze` — the corrupted file will be backed up and rebuilt.');\n const state = st.state;\n\n const documents: DocStatus[] = [];\n for (const d of KNOWLEDGE_DOCS) {\n const text = await readTextIfExists(path.join(dir, d.file));\n documents.push({\n file: d.file,\n title: d.title,\n present: text !== null,\n editedBlocks: text ? parseBlocks(text).filter(isBlockModified).map((b) => b.id) : [],\n lastChangedAt: state.documents[d.id]?.lastChangedAt,\n });\n }\n\n const { config } = await loadConfig(root);\n const walk = await walkProject(root, { config, signal, reuse: state.fileIndex });\n const raw = diffFileIndex(state.fileIndex, buildFileIndex(walk.files));\n // Files Athena manages for agent integrations are not developer changes.\n const managed = new Set(Object.values(state.agents).flatMap((a) => a.files));\n const keep = (p: string) => !managed.has(p);\n const changes = { added: raw.added.filter(keep), modified: raw.modified.filter(keep), deleted: raw.deleted.filter(keep) };\n\n const git = { isRepo: state.git.isRepo, branch: state.git.branch, headChanged: false, uncommitted: null as number | null };\n if (state.git.isRepo) {\n const wc = await workingChanges(root);\n git.uncommitted = wc ? wc.filter((f) => !f.path.startsWith('.athena/')).length : null;\n }\n\n const impact = impactOf([...changes.added, ...changes.modified, ...changes.deleted], { structural: [...changes.added, ...changes.deleted] });\n const affectedDocuments = impact.docs.map((id) => ({ file: KNOWLEDGE_DOCS.find((d) => d.id === id)!.file, reasons: impact.reasons[id] ?? [] }));\n const totalChanges = changes.added.length + changes.modified.length + changes.deleted.length;\n const missing = documents.some((d) => !d.present);\n return {\n project: state.projectName,\n root,\n health: missing ? 'degraded' : totalChanges ? 'needs-update' : 'healthy',\n analyzedAt: state.analyzedAt,\n documents,\n changes,\n git,\n affectedDocuments,\n sync: totalChanges ? 'needs-update' : 'up-to-date',\n };\n}\n\n","import type { DocId } from '../knowledge/documents.js';\n\n/**\n * Path-based impact rules: which knowledge documents a changed file may affect.\n * Used by `athena status` and combined with the model-level diff in sync planning.\n */\nconst RULES: Array<{ match: RegExp; docs: DocId[]; reason: string }> = [\n { match: /(^|\\/)(package\\.json|pyproject\\.toml|requirements[^/]*\\.txt|Pipfile|go\\.mod|Cargo\\.toml|pom\\.xml|build\\.gradle(\\.kts)?|composer\\.json|Gemfile|pubspec\\.yaml|mix\\.exs|[^/]+\\.csproj)$/, docs: ['project', 'architecture', 'security', 'testing'], reason: 'dependency manifest' },\n { match: /(^|\\/)(package-lock\\.json|yarn\\.lock|pnpm-lock\\.yaml|bun\\.lockb?|poetry\\.lock|uv\\.lock|Cargo\\.lock|go\\.sum|composer\\.lock|Gemfile\\.lock)$/, docs: ['project', 'security'], reason: 'lockfile' },\n { match: /(^|\\/)(pnpm-workspace\\.yaml|turbo\\.json|nx\\.json|lerna\\.json|go\\.work|settings\\.gradle(\\.kts)?)$/, docs: ['project', 'architecture'], reason: 'workspace configuration' },\n { match: /\\.prisma$|\\.sql$|(^|\\/)(migrations?|migrate|alembic|changelog)\\/|(^|\\/)models(\\.py|\\/)|(^|\\/)(schema|entities|entity)\\b/i, docs: ['database', 'performance', 'code-review'], reason: 'schema / migration' },\n { match: /(^|\\/)(routes?|controllers?|handlers?|api|endpoints?|views|resolvers?)\\/|(^|\\/)(urls\\.py|routes\\.rb)$|(^|\\/)app\\/(.+\\/)?route\\.(t|j)sx?$|\\.(graphql|gql|proto)$|(openapi|swagger)[^/]*\\.(json|ya?ml)$/i, docs: ['api', 'security', 'testing'], reason: 'API surface' },\n { match: /(auth|session|login|oauth|jwt|guard|permission|rbac|acl|polic(y|ies)|middleware)/i, docs: ['auth', 'security'], reason: 'auth-related' },\n { match: /(^|\\/)(Dockerfile|Containerfile)[^/]*$|(^|\\/)(docker-)?compose[^/]*\\.ya?ml$/i, docs: ['deployment', 'architecture', 'security'], reason: 'container configuration' },\n { match: /^\\.github\\/workflows\\/|(^|\\/)(\\.gitlab-ci\\.yml|Jenkinsfile|azure-pipelines\\.ya?ml|bitbucket-pipelines\\.yml)$|^\\.circleci\\//, docs: ['deployment', 'testing'], reason: 'CI/CD' },\n { match: /\\.tf$|(^|\\/)(vercel\\.json|netlify\\.toml|fly\\.toml|render\\.ya?ml|railway\\.(json|toml)|Procfile|wrangler\\.(toml|jsonc?)|serverless\\.ya?ml|Chart\\.yaml|kustomization\\.ya?ml)$|(^|\\/)(k8s|kubernetes|helm|deploy|infra)\\//, docs: ['deployment', 'architecture'], reason: 'infrastructure' },\n { match: /(^|\\/)\\.env\\.(example|sample|template)$/, docs: ['deployment', 'project'], reason: 'environment template' },\n { match: /(^|\\/)(__tests__|tests?|spec|e2e)\\/|\\.(test|spec)\\.[cm]?[jt]sx?$|(^|\\/)test_[^/]+\\.py$|_test\\.(go|py)$|(^|\\/)(jest|vitest|playwright|cypress)\\.config\\./, docs: ['testing'], reason: 'tests' },\n { match: /(cache|redis|queue|worker|jobs?)\\b/i, docs: ['performance'], reason: 'caching / background work' },\n { match: /(^|\\/)(Makefile|justfile|Taskfile\\.ya?ml)$/, docs: ['project', 'debugging'], reason: 'task runner' },\n];\n\nexport interface ImpactResult {\n docs: DocId[];\n reasons: Record<string, string[]>;\n}\n\nexport function impactOf(paths: string[], opts: { structural?: string[] } = {}): ImpactResult {\n const docs = new Set<DocId>();\n const reasons: Record<string, string[]> = {};\n const note = (doc: DocId, why: string) => {\n docs.add(doc);\n reasons[doc] ??= [];\n if (!reasons[doc]!.includes(why)) reasons[doc]!.push(why);\n };\n for (const p of paths) {\n if (p.startsWith('.athena/')) continue;\n for (const r of RULES) if (r.match.test(p)) for (const d of r.docs) note(d, r.reason);\n }\n // Added/deleted files change project structure even when no rule matches.\n if (opts.structural?.some((p) => !p.startsWith('.athena/'))) note('project', 'files added or removed');\n const order = ['project', 'architecture', 'database', 'api', 'auth', 'security', 'testing', 'debugging', 'performance', 'code-review', 'deployment', 'rules'];\n return { docs: [...docs].sort((a, b) => order.indexOf(a) - order.indexOf(b)), reasons };\n}\n","import { buildStatus } from '../../services/status.js';\nimport { requireProjectRoot, type GlobalOptions } from '../context.js';\nimport * as ui from '../ui/term.js';\n\nexport async function statusCommand(opts: GlobalOptions & { signal?: AbortSignal }): Promise<void> {\n const root = await requireProjectRoot(opts);\n const report = await buildStatus(root, opts.signal);\n if (ui.isJson()) {\n ui.json(report);\n return;\n }\n const healthLabel = report.health === 'healthy' ? ui.c.green('Healthy') : report.health === 'needs-update' ? ui.c.yellow('Needs update') : ui.c.red('Degraded (missing knowledge files)');\n ui.heading('Athena Status');\n ui.line();\n ui.line(`Project: ${ui.c.bold(report.project)}`);\n ui.line(`Athena: ${healthLabel}`);\n ui.line(`Analyzed: ${ui.relativeTime(report.analyzedAt)}${report.git.branch ? ui.dim(` · branch ${report.git.branch}`) : ''}`);\n ui.line();\n ui.heading('Knowledge');\n for (const d of report.documents) {\n if (!d.present) ui.fail(`${d.title} ${ui.dim(`— ${d.file} missing`)}`);\n else if (d.editedBlocks.length) ui.ok(`${d.title} ${ui.dim(`— developer-edited sections: ${d.editedBlocks.join(', ')}`)}`);\n else ui.ok(d.title);\n }\n ui.line();\n const total = report.changes.added.length + report.changes.modified.length + report.changes.deleted.length;\n ui.heading('Changes since last analysis');\n if (!total) ui.line(ui.dim('No file changes detected.'));\n else {\n ui.line(`${total} file${total === 1 ? '' : 's'} changed ${ui.dim(`(${report.changes.modified.length} modified, ${report.changes.added.length} added, ${report.changes.deleted.length} deleted)`)}`);\n const sample = [...report.changes.modified, ...report.changes.added, ...report.changes.deleted].slice(0, 8);\n for (const p of sample) ui.line(` ${ui.dim(p)}`);\n if (total > sample.length) ui.line(ui.dim(` +${total - sample.length} more`));\n }\n if (report.git.uncommitted !== null) ui.line(ui.dim(`Git: ${report.git.uncommitted} uncommitted change(s) in the working tree`));\n if (report.affectedDocuments.length) {\n ui.line();\n ui.heading('Potentially affected');\n for (const a of report.affectedDocuments) ui.bullet(`${a.file} ${ui.dim(`(${a.reasons.join(', ')})`)}`);\n }\n ui.line();\n ui.line(`Synchronization: ${report.sync === 'up-to-date' ? ui.c.green('Up to date') : `${ui.c.yellow('Needs update')} ${ui.dim('— run `athena sync` to review')}`}`);\n}\n","import { constants, promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { gitAvailable, isGitRepo } from '../core/git/git.js';\nimport { KNOWLEDGE_DOCS } from '../core/knowledge/documents.js';\nimport { parseBlocks } from '../core/knowledge/managed-blocks.js';\nimport { listRules, parseRules } from '../core/knowledge/rules.js';\nimport { athenaDir, readState } from '../core/state/state.js';\nimport { loadConfig } from '../core/config.js';\nimport { readTextIfExists } from '../core/util/fs.js';\nimport { findProjectRoot } from './project.js';\nimport { relativeTime } from './time.js';\nimport { ADAPTERS } from '../agents/registry.js';\nimport { ATHENA_VERSION } from './version.js';\nimport { findRunningInstance } from './instance.js';\nimport { whichExecutable } from './which.js';\nimport { hookCommand } from '../agents/common/hooks.js';\nimport { readRecentEvents } from './agent-activity.js';\n\nexport interface Check {\n area: string;\n level: 'ok' | 'warn' | 'error' | 'info';\n message: string;\n hint?: string;\n}\n\nexport async function runDoctor(cwd: string): Promise<{ checks: Check[]; root: string | null }> {\n const checks: Check[] = [];\n const add = (c: Check) => checks.push(c);\n\n const [major, minor] = process.versions.node.split('.').map(Number) as [number, number];\n const nodeOk = major > 22 || (major === 22 && minor >= 12);\n add({ area: 'CLI', level: nodeOk ? 'ok' : 'error', message: `Athena ${ATHENA_VERSION} on Node.js ${process.versions.node} (${process.platform}/${process.arch})`, hint: nodeOk ? undefined : 'Athena requires Node.js >= 22.12' });\n\n const root = await findProjectRoot(cwd);\n const projectRoot = root ?? cwd;\n\n if (await gitAvailable()) {\n add({ area: 'Git', level: (await isGitRepo(projectRoot)) ? 'ok' : 'warn', message: (await isGitRepo(projectRoot)) ? 'Git repository detected' : 'Not a Git repository', hint: (await isGitRepo(projectRoot)) ? undefined : 'Change detection and knowledge history work best in a Git repository.' });\n } else {\n add({ area: 'Git', level: 'warn', message: 'git executable not found', hint: 'Install Git to enable change detection and knowledge history.' });\n }\n\n if (!root) {\n add({ area: 'Project', level: 'error', message: 'Athena is not initialized here', hint: 'Run `athena init` in the project root.' });\n return { checks, root };\n }\n add({ area: 'Project', level: 'ok', message: root });\n\n const dir = athenaDir(root);\n try {\n await fs.access(dir, constants.R_OK | constants.W_OK);\n add({ area: 'Knowledge directory', level: 'ok', message: '.athena/ is readable and writable' });\n } catch {\n add({ area: 'Knowledge directory', level: 'error', message: '.athena/ is not writable', hint: 'Check file permissions.' });\n }\n\n const cfg = await loadConfig(root);\n if (cfg.warning) add({ area: 'Configuration', level: 'warn', message: cfg.warning });\n\n const st = await readState(dir);\n if (st.kind === 'ok') add({ area: 'State', level: 'ok', message: `state.json valid (analyzed ${relativeTime(st.state.analyzedAt)})` });\n else if (st.kind === 'missing') add({ area: 'State', level: 'error', message: 'state.json missing', hint: 'Run `athena analyze`.' });\n else add({ area: 'State', level: 'error', message: `state.json corrupted: ${st.reason}`, hint: 'Run `athena analyze` (the file is backed up and rebuilt).' });\n\n const missing: string[] = [];\n const malformed: string[] = [];\n for (const d of KNOWLEDGE_DOCS) {\n const text = await readTextIfExists(path.join(dir, d.file));\n if (text === null) missing.push(d.file);\n else if (d.id !== 'rules' && (text.match(/athena:generated:start/g)?.length ?? 0) !== parseBlocks(text).length) malformed.push(d.file);\n }\n add({ area: 'Knowledge files', level: missing.length ? 'error' : 'ok', message: missing.length ? `Missing: ${missing.join(', ')}` : `${KNOWLEDGE_DOCS.length} knowledge files present`, hint: missing.length ? 'Run `athena analyze` to regenerate missing files.' : undefined });\n if (malformed.length) add({ area: 'Knowledge files', level: 'warn', message: `Unmatched generated-section markers in: ${malformed.join(', ')}`, hint: 'Those sections are treated as developer content and will not be refreshed.' });\n\n const rulesText = await readTextIfExists(path.join(dir, 'rules.md'));\n if (rulesText !== null) {\n const rules = listRules(parseRules(rulesText));\n const enabled = rules.filter((r) => r.enabled).length;\n add({ area: 'Rules', level: rules.length ? 'ok' : 'warn', message: `${enabled} enabled, ${rules.length - enabled} disabled`, hint: rules.length ? undefined : 'rules.md has no rules. Add some with `athena rules add`.' });\n }\n\n const stateAgents = st.kind === 'ok' ? st.state.agents : {};\n for (const a of ADAPTERS) {\n const configured = stateAgents[a.id]?.configured;\n if (!configured) {\n add({ area: a.displayName, level: 'info', message: 'Integration not configured', hint: `Enable with \\`athena agents add ${a.id}\\`.` });\n continue;\n }\n for (const c of await a.check(root)) add({ area: a.displayName, level: c.level, message: c.message.replace(/^[^:]+:\\s*/, '') });\n }\n\n // Hooks invoke the `athena` executable, so it must be resolvable from the agent's environment.\n const hooksConfigured = ADAPTERS.some((a) => a.capabilities.hooks && stateAgents[a.id]?.configured);\n if (hooksConfigured) {\n const cmd = hookCommand();\n const resolved = await whichExecutable(cmd);\n add(\n resolved\n ? { area: 'Agent hooks', level: 'ok', message: `\\`${cmd}\\` resolves to ${resolved}` }\n : { area: 'Agent hooks', level: 'warn', message: `\\`${cmd}\\` is not on PATH — agent hooks cannot report activity`, hint: 'Install globally (`npm i -g project-athena`) or set ATHENA_HOOK_COMMAND to an absolute path and re-run `athena agents add`.' },\n );\n const events = await readRecentEvents(root, 1);\n add({ area: 'Agent hooks', level: 'info', message: events.length ? `Last agent event: ${relativeTime(events[0]!.ts)}` : 'No agent activity recorded yet (hooks fire when an agent runs)' });\n }\n\n const running = await findRunningInstance(root);\n add(\n running\n ? { area: 'Local server', level: 'ok', message: `Running on ${running.host}:${running.port} (pid ${running.pid})`, hint: 'Run `athena open` to get the access link.' }\n : { area: 'Local server', level: 'info', message: 'Not running', hint: 'Start the web UI with `athena open`.' },\n );\n if (running && !['127.0.0.1', '::1', 'localhost'].includes(running.host)) {\n add({ area: 'Local server', level: 'warn', message: `Bound to ${running.host} — reachable beyond this machine` });\n }\n return { checks, root };\n}\n\n","/**\n * Round-trip parser for `.athena/rules.md`.\n *\n * The file is plain Markdown and the single source of truth. A rule is a top-level\n * bullet (\"- ...\") under a \"## Section\" heading. A disabled rule is written as\n * \"- [disabled] ...\". Every other line (prose, nested bullets, code, comments) is\n * preserved exactly.\n */\n\nexport interface RuleLine {\n kind: 'rule';\n section: string;\n text: string;\n enabled: boolean;\n bullet: '-' | '*' | '+';\n}\nexport interface OtherLine {\n kind: 'other';\n raw: string;\n}\nexport type Line = RuleLine | OtherLine;\n\nexport interface RulesDocument {\n lines: Line[];\n eol: '\\n' | '\\r\\n';\n}\n\nexport interface Rule {\n /** 1-based position among rules in file order — stable for a given file version. */\n index: number;\n section: string;\n text: string;\n enabled: boolean;\n}\n\nconst RULE_RE = /^([-*+])\\s+(?:\\[(disabled)\\]\\s+)?(.+?)\\s*$/;\nconst SECTION_RE = /^##\\s+(.+?)\\s*#*\\s*$/;\nconst DISABLED_PREFIX = '[disabled]';\n\nexport function parseRules(text: string): RulesDocument {\n const eol = text.includes('\\r\\n') ? '\\r\\n' : '\\n';\n const lines: Line[] = [];\n let section = 'General';\n let inFence = false;\n const raw = text.split(/\\r?\\n/);\n if (raw.length && raw[raw.length - 1] === '') raw.pop();\n for (const l of raw) {\n if (/^\\s*(```|~~~)/.test(l)) inFence = !inFence;\n const sm = !inFence ? SECTION_RE.exec(l) : null;\n if (sm) section = sm[1]!;\n const rm = !inFence ? RULE_RE.exec(l) : null;\n if (rm && !/^\\[[ xX]\\]/.test(rm[3]!)) {\n lines.push({ kind: 'rule', section, text: rm[3]!, enabled: rm[2] !== 'disabled', bullet: rm[1] as RuleLine['bullet'] });\n } else {\n lines.push({ kind: 'other', raw: l });\n }\n }\n return { lines, eol };\n}\n\nexport function serializeRules(doc: RulesDocument): string {\n return (\n doc.lines\n .map((l) => (l.kind === 'other' ? l.raw : `${l.bullet} ${l.enabled ? '' : `${DISABLED_PREFIX} `}${l.text}`))\n .join(doc.eol) + doc.eol\n );\n}\n\nexport function listRules(doc: RulesDocument): Rule[] {\n const out: Rule[] = [];\n for (const l of doc.lines) if (l.kind === 'rule') out.push({ index: out.length + 1, section: l.section, text: l.text, enabled: l.enabled });\n return out;\n}\n\nfunction ruleAt(doc: RulesDocument, index: number): RuleLine {\n let n = 0;\n for (const l of doc.lines) if (l.kind === 'rule' && ++n === index) return l;\n throw new RangeError(`No rule #${index} (there are ${n} rules)`);\n}\n\nexport function validateRuleText(text: string): string {\n const t = text.replace(/[\\r\\n]+/g, ' ').trim();\n if (!t) throw new Error('Rule text cannot be empty');\n if (t.length > 1000) throw new Error('Rule text is too long (max 1000 characters)');\n return t;\n}\n\nexport function addRule(doc: RulesDocument, section: string, text: string): RulesDocument {\n const clean = validateRuleText(text);\n const sec = section.replace(/[\\r\\n#]+/g, ' ').trim() || 'General';\n const lines = [...doc.lines];\n let lastRuleIdx = -1;\n let headingIdx = -1;\n lines.forEach((l, i) => {\n if (l.kind === 'other' && SECTION_RE.exec(l.raw)?.[1]?.toLowerCase() === sec.toLowerCase()) headingIdx = i;\n if (l.kind === 'rule' && l.section.toLowerCase() === sec.toLowerCase()) lastRuleIdx = i;\n });\n const existingSection = headingIdx >= 0 ? (SECTION_RE.exec((lines[headingIdx] as OtherLine).raw)?.[1] ?? sec) : sec;\n const rule: RuleLine = { kind: 'rule', section: existingSection, text: clean, enabled: true, bullet: '-' };\n if (lastRuleIdx >= 0) lines.splice(lastRuleIdx + 1, 0, rule);\n else if (headingIdx >= 0) {\n let at = headingIdx + 1;\n while (at < lines.length && lines[at]!.kind === 'other' && (lines[at] as OtherLine).raw.trim() === '') at++;\n lines.splice(at, 0, rule);\n } else {\n while (lines.length && lines[lines.length - 1]!.kind === 'other' && (lines[lines.length - 1] as OtherLine).raw.trim() === '') lines.pop();\n lines.push({ kind: 'other', raw: '' }, { kind: 'other', raw: `## ${sec}` }, { kind: 'other', raw: '' }, rule);\n }\n return { ...doc, lines };\n}\n\nexport function updateRule(doc: RulesDocument, index: number, patch: { text?: string; enabled?: boolean }): RulesDocument {\n const target = ruleAt(doc, index);\n return {\n ...doc,\n lines: doc.lines.map((l) => (l === target ? { ...target, ...(patch.text !== undefined ? { text: validateRuleText(patch.text) } : {}), ...(patch.enabled !== undefined ? { enabled: patch.enabled } : {}) } : l)),\n };\n}\n\nexport function removeRule(doc: RulesDocument, index: number): RulesDocument {\n const target = ruleAt(doc, index);\n return { ...doc, lines: doc.lines.filter((l) => l !== target) };\n}\n","export function relativeTime(iso: string, now = Date.now()): string {\n const ms = now - Date.parse(iso);\n if (Number.isNaN(ms)) return 'unknown';\n const s = Math.round(ms / 1000);\n if (s < 60) return `${s}s ago`;\n const m = Math.round(s / 60);\n if (m < 60) return `${m} min ago`;\n const h = Math.round(m / 60);\n if (h < 48) return `${h} h ago`;\n return `${Math.round(h / 24)} days ago`;\n}\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { athenaDir } from '../core/state/state.js';\nimport { readTextIfExists } from '../core/util/fs.js';\n\nexport const INSTANCE_FILE = '.server.json';\n\nexport interface InstanceInfo {\n pid: number;\n host: string;\n port: number;\n instanceId: string;\n token: string;\n startedAt: string;\n}\n\n/** Find an already-running Athena server for this project, verified by instance id. */\nexport async function findRunningInstance(root: string): Promise<InstanceInfo | null> {\n const file = path.join(athenaDir(root), INSTANCE_FILE);\n const raw = await readTextIfExists(file);\n if (!raw) return null;\n let info: InstanceInfo;\n try {\n info = JSON.parse(raw) as InstanceInfo;\n } catch {\n return null;\n }\n if (typeof info.pid !== 'number' || typeof info.port !== 'number' || typeof info.token !== 'string') return null;\n try {\n process.kill(info.pid, 0);\n } catch {\n await fs.rm(file, { force: true }).catch(() => {});\n return null;\n }\n try {\n const host = info.host.includes(':') ? `[${info.host}]` : info.host;\n const res = await fetch(`http://${host}:${info.port}/api/health`, { signal: AbortSignal.timeout(1500) });\n const body = (await res.json()) as { instanceId?: string };\n return body.instanceId === info.instanceId ? info : null;\n } catch {\n return null;\n }\n}\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\n\n/** Resolve an executable on PATH without running a shell. Returns null when not found. */\nexport async function whichExecutable(command: string): Promise<string | null> {\n if (command.includes('/') || command.includes('\\\\')) {\n return (await fs.access(command).then(() => true).catch(() => false)) ? command : null;\n }\n const dirs = (process.env.PATH ?? '').split(path.delimiter).filter(Boolean);\n const exts = process.platform === 'win32' ? (process.env.PATHEXT ?? '.EXE;.CMD;.BAT').split(';') : [''];\n for (const dir of dirs) {\n for (const ext of exts) {\n const candidate = path.join(dir, command + ext.toLowerCase());\n try {\n const st = await fs.stat(candidate);\n if (st.isFile()) return candidate;\n } catch {\n /* keep looking */\n }\n }\n }\n return null;\n}\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { athenaDir } from '../core/state/state.js';\nimport { redact } from '../core/security/secrets.js';\nimport { toPosix } from '../core/util/paths.js';\nimport type { AgentEvent } from '../agents/common/hook-events.js';\n\n/**\n * Agent activity log. Hooks append one JSON object per line; the local server\n * tails the file. No network, no token, and it keeps working when the UI is closed.\n */\nexport const ACTIVITY_FILE = '.agent-events.jsonl';\nconst MAX_LINES = 2000;\nconst MAX_BYTES = 512 * 1024;\n\nexport function activityFile(root: string): string {\n return path.join(athenaDir(root), ACTIVITY_FILE);\n}\n\n/** Make paths project-relative and strip anything secret-looking before it is stored. */\nexport function sanitizeEvent(root: string, event: AgentEvent): AgentEvent {\n const rel = (p: string) => {\n const abs = path.isAbsolute(p) ? p : path.resolve(root, p);\n const r = toPosix(path.relative(root, abs));\n return !r || r.startsWith('..') ? toPosix(p) : r;\n };\n // Hook payloads carry absolute paths; keep the log project-relative and portable.\n const stripRoot = (text: string) => text.split(`${root}${path.sep}`).join('').split(toPosix(root) + '/').join('');\n return {\n ...event,\n message: redact(stripRoot(event.message)),\n command: event.command ? redact(stripRoot(event.command)) : null,\n files: event.files.map(rel),\n };\n}\n\nexport async function appendEvent(root: string, event: AgentEvent): Promise<void> {\n const file = activityFile(root);\n await fs.mkdir(path.dirname(file), { recursive: true });\n await fs.appendFile(file, `${JSON.stringify(sanitizeEvent(root, event))}\\n`);\n await rotateIfNeeded(file);\n}\n\nasync function rotateIfNeeded(file: string): Promise<void> {\n try {\n const st = await fs.stat(file);\n if (st.size < MAX_BYTES) return;\n const lines = (await fs.readFile(file, 'utf8')).split('\\n').filter(Boolean);\n await fs.writeFile(file, `${lines.slice(-MAX_LINES / 2).join('\\n')}\\n`);\n } catch {\n /* rotation is best-effort */\n }\n}\n\nexport function parseEventLines(text: string): AgentEvent[] {\n const out: AgentEvent[] = [];\n for (const line of text.split('\\n')) {\n if (!line.trim()) continue;\n try {\n const e = JSON.parse(line) as AgentEvent;\n if (e && typeof e.id === 'string' && typeof e.ts === 'string' && typeof e.agent === 'string') out.push(e);\n } catch {\n /* skip malformed lines (partial write) */\n }\n }\n return out;\n}\n\nexport async function readRecentEvents(root: string, limit = 200): Promise<AgentEvent[]> {\n try {\n const text = await fs.readFile(activityFile(root), 'utf8');\n return parseEventLines(text).slice(-limit);\n } catch {\n return [];\n }\n}\n\nexport interface AgentSession {\n agent: string;\n session: string | null;\n lastEventAt: string;\n lastMessage: string;\n events: number;\n}\n\n/** Sessions seen in the log, most recent first. Presence here means \"hooks fired\", nothing more. */\nexport function summarizeSessions(events: AgentEvent[]): AgentSession[] {\n const byKey = new Map<string, AgentSession>();\n for (const e of events) {\n const key = `${e.agent}:${e.session ?? '-'}`;\n const cur = byKey.get(key);\n byKey.set(key, { agent: e.agent, session: e.session, lastEventAt: e.ts, lastMessage: e.message, events: (cur?.events ?? 0) + 1 });\n }\n return [...byKey.values()].sort((a, b) => b.lastEventAt.localeCompare(a.lastEventAt));\n}\n","import { runDoctor } from '../../services/doctor.js';\nimport { resolveCwd, type GlobalOptions } from '../context.js';\nimport * as ui from '../ui/term.js';\n\nexport async function doctorCommand(opts: GlobalOptions): Promise<number> {\n const cwd = await resolveCwd(opts);\n const { checks } = await runDoctor(cwd);\n const errors = checks.filter((c) => c.level === 'error').length;\n if (ui.isJson()) {\n ui.json({ ok: errors === 0, checks });\n return errors ? 1 : 0;\n }\n ui.heading('Athena Doctor');\n ui.line();\n for (const c of checks) {\n const icon = c.level === 'ok' ? ui.c.green(ui.sym.ok) : c.level === 'warn' ? ui.c.yellow(ui.sym.warn) : c.level === 'error' ? ui.c.red(ui.sym.err) : ui.c.dim(ui.sym.ring);\n ui.line(`${icon} ${ui.c.bold(c.area)} ${ui.dim('—')} ${c.message}`);\n if (c.hint) ui.line(` ${ui.dim(c.hint)}`);\n }\n ui.line();\n const warns = checks.filter((c) => c.level === 'warn').length;\n if (errors) ui.line(ui.c.red(`${errors} problem${errors === 1 ? '' : 's'} found.`));\n else ui.line(ui.c.green(`Athena is ready.${warns ? ui.dim(` (${warns} warning${warns === 1 ? '' : 's'})`) : ''}`));\n return errors ? 1 : 0;\n}\n","import path from 'node:path';\nimport { addRule, listRules, parseRules, removeRule, serializeRules, updateRule, type Rule, type RulesDocument } from '../core/knowledge/rules.js';\nimport { scanText } from '../core/security/secrets.js';\nimport { athenaDir } from '../core/state/state.js';\nimport { readTextIfExists, writeFileAtomic } from '../core/util/fs.js';\nimport { AthenaError, conflict, notFound } from './errors.js';\nimport { contentHash } from './knowledge.js';\n\nexport interface RulesView {\n hash: string;\n rules: Rule[];\n sections: string[];\n}\n\nasync function load(root: string): Promise<{ file: string; text: string; doc: RulesDocument }> {\n const file = path.join(athenaDir(root), 'rules.md');\n const text = await readTextIfExists(file);\n if (text === null) throw notFound('.athena/rules.md not found. Run `athena analyze` to recreate it.');\n return { file, text, doc: parseRules(text) };\n}\n\nfunction view(text: string, doc: RulesDocument): RulesView {\n const rules = listRules(doc);\n const sections = [...new Set([...doc.lines.flatMap((l) => (l.kind === 'other' ? (/^##\\s+(.+?)\\s*#*\\s*$/.exec(l.raw)?.[1] ?? []) : [])), ...rules.map((r) => r.section)])];\n return { hash: contentHash(text), rules, sections };\n}\n\nexport async function getRules(root: string): Promise<RulesView> {\n const { text, doc } = await load(root);\n return view(text, doc);\n}\n\n/**\n * Apply a rule mutation. Rules are addressed by index, so every mutation requires\n * the hash of the file the client last saw; a mismatch means indexes may have shifted.\n */\nexport async function mutateRules(root: string, baseHash: string | undefined, fn: (doc: RulesDocument) => RulesDocument): Promise<RulesView> {\n const { file, text, doc } = await load(root);\n if (baseHash !== undefined && baseHash !== contentHash(text)) {\n throw conflict('rules.md changed since it was loaded.', 'Reload the rules and try again.', { currentHash: contentHash(text) });\n }\n let next: RulesDocument;\n try {\n next = fn(doc);\n } catch (err) {\n throw new AthenaError((err as Error).message);\n }\n const out = serializeRules(next);\n const secrets = scanText(out).filter((s) => !scanText(text).some((o) => o.fingerprint === s.fingerprint));\n if (secrets.length) throw new AthenaError('Refusing to save a rule that appears to contain a secret.', 'Rules must never contain credentials.', 1, 'unprocessable');\n await writeFileAtomic(file, out);\n return view(out, next);\n}\n\nexport const rulesAdd = (root: string, baseHash: string | undefined, section: string, text: string) => mutateRules(root, baseHash, (d) => addRule(d, section, text));\nexport const rulesUpdate = (root: string, baseHash: string | undefined, index: number, patch: { text?: string; enabled?: boolean }) => mutateRules(root, baseHash, (d) => updateRule(d, index, patch));\nexport const rulesRemove = (root: string, baseHash: string | undefined, index: number) => mutateRules(root, baseHash, (d) => removeRule(d, index));\n","import path from 'node:path';\nimport { KNOWLEDGE_DOCS, type DocId } from '../core/knowledge/documents.js';\nimport { isBlockModified, parseBlocks } from '../core/knowledge/managed-blocks.js';\nimport { git } from '../core/git/git.js';\nimport { scanText } from '../core/security/secrets.js';\nimport { athenaDir, readState } from '../core/state/state.js';\nimport { readTextIfExists, sha256, writeFileAtomic } from '../core/util/fs.js';\nimport { AthenaError, conflict, notFound } from './errors.js';\n\nexport const MAX_DOC_BYTES = 1_000_000;\n\nexport type Segment =\n | { kind: 'generated'; id: string; modified: boolean; content: string }\n | { kind: 'developer'; content: string };\n\nexport interface DocMeta {\n id: DocId;\n file: string;\n title: string;\n purpose: string;\n present: boolean;\n bytes: number;\n /** Content hash used for optimistic concurrency on save. */\n hash: string | null;\n lastGeneratedAt: string | null;\n lastChangedAt: string | null;\n generatedSections: number;\n editedSections: string[];\n}\n\nexport interface DocContent extends DocMeta {\n content: string;\n segments: Segment[];\n}\n\n/** Resolve a document id strictly against the fixed allowlist. Never builds paths from user input. */\nexport function resolveDoc(id: string) {\n const doc = KNOWLEDGE_DOCS.find((d) => d.id === id);\n if (!doc) throw notFound(`Unknown knowledge document: ${id.slice(0, 64)}`);\n return doc;\n}\n\nexport function contentHash(text: string): string {\n return sha256(text).slice(0, 16);\n}\n\nexport function segmentDocument(text: string): Segment[] {\n const segments: Segment[] = [];\n let cursor = 0;\n for (const b of parseBlocks(text)) {\n const before = text.slice(cursor, b.start);\n if (before.trim()) segments.push({ kind: 'developer', content: before });\n segments.push({ kind: 'generated', id: b.id, modified: isBlockModified(b), content: b.content });\n cursor = b.end;\n }\n const rest = text.slice(cursor);\n if (rest.trim()) segments.push({ kind: 'developer', content: rest });\n return segments;\n}\n\nasync function meta(root: string, id: DocId, text: string | null): Promise<DocMeta> {\n const doc = resolveDoc(id);\n const st = await readState(athenaDir(root));\n const ds = st.kind === 'ok' ? st.state.documents[id] : undefined;\n const blocks = text ? parseBlocks(text) : [];\n return {\n id,\n file: doc.file,\n title: doc.title,\n purpose: doc.purpose,\n present: text !== null,\n bytes: text ? Buffer.byteLength(text) : 0,\n hash: text === null ? null : contentHash(text),\n lastGeneratedAt: ds?.lastGeneratedAt ?? (st.kind === 'ok' && id === 'rules' ? st.state.createdAt : null),\n lastChangedAt: ds?.lastChangedAt ?? null,\n generatedSections: blocks.length,\n editedSections: blocks.filter(isBlockModified).map((b) => b.id),\n };\n}\n\nexport async function listDocs(root: string): Promise<DocMeta[]> {\n const out: DocMeta[] = [];\n for (const d of KNOWLEDGE_DOCS) out.push(await meta(root, d.id, await readTextIfExists(path.join(athenaDir(root), d.file))));\n return out;\n}\n\nexport async function readDoc(root: string, id: string): Promise<DocContent> {\n const doc = resolveDoc(id);\n const text = await readTextIfExists(path.join(athenaDir(root), doc.file));\n if (text === null) throw notFound(`${doc.file} does not exist. Run \\`athena analyze\\` to regenerate it.`);\n return { ...(await meta(root, doc.id, text)), content: text, segments: segmentDocument(text) };\n}\n\n/**\n * Save a knowledge document. Refuses when:\n * - the file changed on disk since the client loaded it (409, optimistic concurrency)\n * - the content contains likely secrets (422) — knowledge files must never hold secrets\n */\nexport async function saveDoc(root: string, id: string, content: string, baseHash: string | null): Promise<DocContent> {\n const doc = resolveDoc(id);\n if (typeof content !== 'string') throw new AthenaError('content must be a string');\n if (Buffer.byteLength(content) > MAX_DOC_BYTES) throw new AthenaError(`Document exceeds ${MAX_DOC_BYTES} bytes`, undefined, 1, 'unprocessable');\n const file = path.join(athenaDir(root), doc.file);\n const current = await readTextIfExists(file);\n const currentHash = current === null ? null : contentHash(current);\n if (currentHash !== baseHash) {\n throw conflict(`${doc.file} was changed on disk since you opened it.`, 'Reload to see the latest version, then re-apply your edits.', { currentHash });\n }\n const secrets = scanText(content);\n if (secrets.length) {\n throw new AthenaError(\n `Refusing to save: ${secrets.length} likely secret(s) found (${[...new Set(secrets.map((s) => s.type))].join(', ')}).`,\n 'Knowledge files must never contain secrets. Replace values with placeholders such as <configured externally>.',\n 1,\n 'unprocessable',\n { secrets: secrets.map((s) => ({ type: s.type, line: s.line })) },\n );\n }\n const normalized = content.replace(/\\r\\n/g, '\\n');\n await writeFileAtomic(file, normalized.endsWith('\\n') ? normalized : `${normalized}\\n`);\n return readDoc(root, doc.id);\n}\n\nexport interface SearchHit {\n id: DocId;\n file: string;\n title: string;\n line: number;\n text: string;\n}\n\nexport async function searchDocs(root: string, query: string, limit = 50): Promise<SearchHit[]> {\n const q = query.trim().toLowerCase();\n if (q.length < 2) return [];\n const hits: SearchHit[] = [];\n for (const d of KNOWLEDGE_DOCS) {\n const text = await readTextIfExists(path.join(athenaDir(root), d.file));\n if (!text) continue;\n const lines = text.split('\\n');\n for (let i = 0; i < lines.length && hits.length < limit; i++) {\n const line = lines[i]!;\n if (line.startsWith('<!-- athena:')) continue;\n if (line.toLowerCase().includes(q)) hits.push({ id: d.id, file: d.file, title: d.title, line: i + 1, text: line.trim().slice(0, 240) });\n }\n if (d.title.toLowerCase().includes(q) && !hits.some((h) => h.id === d.id)) hits.unshift({ id: d.id, file: d.file, title: d.title, line: 1, text: d.purpose });\n }\n return hits.slice(0, limit);\n}\n\nexport interface HistoryEntry {\n sha: string;\n date: string;\n subject: string;\n}\n\nexport interface DocHistory {\n available: boolean;\n reason?: string;\n entries: HistoryEntry[];\n}\n\n/** Knowledge history comes from Git — Athena does not maintain its own version store. */\nexport async function docHistory(root: string, id: string, limit = 50): Promise<DocHistory> {\n const doc = resolveDoc(id);\n const rel = `.athena/${doc.file}`;\n const r = await git(root, ['log', `-n${limit}`, '--follow', '--format=%H%x1f%cI%x1f%s', '--', rel]);\n if (!r.ok) return { available: false, reason: 'Git history is not available (not a Git repository, or git is not installed).', entries: [] };\n const entries = r.stdout\n .split('\\n')\n .filter(Boolean)\n .map((l) => {\n const [sha, date, subject] = l.split('\\x1f');\n return { sha: sha!, date: date!, subject: subject ?? '' };\n });\n if (!entries.length) return { available: true, reason: `${rel} has not been committed yet.`, entries };\n return { available: true, entries };\n}\n\nexport async function docAtRevision(root: string, id: string, sha: string): Promise<string> {\n const doc = resolveDoc(id);\n if (!/^[0-9a-f]{7,64}$/i.test(sha)) throw new AthenaError('Invalid revision');\n const prefix = (await git(root, ['rev-parse', '--show-prefix'])).stdout.trim();\n const r = await git(root, ['show', `${sha}:${prefix}.athena/${doc.file}`]);\n if (!r.ok) throw notFound(`${doc.file} does not exist at revision ${sha.slice(0, 12)}`);\n return r.stdout;\n}\n","import { addRule, removeRule, updateRule, type RulesDocument } from '../../core/knowledge/rules.js';\nimport { getRules, mutateRules } from '../../services/rules.js';\nimport { requireProjectRoot, type GlobalOptions } from '../context.js';\nimport { AthenaError } from '../../services/errors.js';\nimport * as ui from '../ui/term.js';\n\nfunction parseIndex(raw: string): number {\n const n = Number(raw);\n if (!Number.isInteger(n) || n < 1) throw new AthenaError(`Invalid rule number: ${raw}`, 'Use `athena rules list` to see rule numbers.');\n return n;\n}\n\nasync function mutate(opts: GlobalOptions, fn: (doc: RulesDocument) => RulesDocument, message: string): Promise<void> {\n const root = await requireProjectRoot(opts);\n const view = await mutateRules(root, undefined, fn);\n if (ui.isJson()) ui.json({ ok: true, rules: view.rules });\n else ui.ok(message);\n}\n\nexport async function rulesListCommand(opts: GlobalOptions): Promise<void> {\n const root = await requireProjectRoot(opts);\n const { rules } = await getRules(root);\n if (ui.isJson()) {\n ui.json(rules);\n return;\n }\n if (!rules.length) {\n ui.line(ui.dim('No rules defined. Add one with `athena rules add \"<rule>\" --section <name>`.'));\n return;\n }\n let section = '';\n for (const r of rules) {\n if (r.section !== section) {\n section = r.section;\n ui.line();\n ui.heading(section);\n }\n const num = ui.dim(`${String(r.index).padStart(3)}.`);\n ui.line(r.enabled ? `${num} ${r.text}` : `${num} ${ui.dim(`[disabled] ${r.text}`)}`);\n }\n ui.line();\n ui.line(ui.dim(`${rules.filter((r) => r.enabled).length} enabled · ${rules.filter((r) => !r.enabled).length} disabled · source: .athena/rules.md`));\n}\n\nexport const rulesAddCommand = (text: string, opts: GlobalOptions & { section?: string }) => mutate(opts, (d) => addRule(d, opts.section ?? 'General', text), `Rule added to \"${opts.section ?? 'General'}\".`);\nexport const rulesEnableCommand = (n: string, opts: GlobalOptions) => mutate(opts, (d) => updateRule(d, parseIndex(n), { enabled: true }), `Rule ${n} enabled.`);\nexport const rulesDisableCommand = (n: string, opts: GlobalOptions) => mutate(opts, (d) => updateRule(d, parseIndex(n), { enabled: false }), `Rule ${n} disabled.`);\nexport const rulesEditCommand = (n: string, text: string, opts: GlobalOptions) => mutate(opts, (d) => updateRule(d, parseIndex(n), { text }), `Rule ${n} updated.`);\nexport const rulesRemoveCommand = (n: string, opts: GlobalOptions) => mutate(opts, (d) => removeRule(d, parseIndex(n)), `Rule ${n} removed.`);\n","import { promises as fs } from 'node:fs';\nimport { createInterface } from 'node:readline/promises';\nimport { athenaDir } from '../../core/state/state.js';\nimport { ADAPTERS } from '../../agents/registry.js';\nimport { requireProjectRoot, type GlobalOptions } from '../context.js';\nimport { AthenaError } from '../../services/errors.js';\nimport * as ui from '../ui/term.js';\n\nexport async function confirm(question: string): Promise<boolean> {\n if (!process.stdin.isTTY) return false;\n const rl = createInterface({ input: process.stdin, output: process.stdout });\n try {\n const answer = await rl.question(`${question} ${ui.dim('[y/N]')} `);\n return /^y(es)?$/i.test(answer.trim());\n } finally {\n rl.close();\n }\n}\n\nexport async function cleanCommand(opts: GlobalOptions & { yes?: boolean; keepAgents?: boolean }): Promise<void> {\n const root = await requireProjectRoot(opts);\n if (!opts.yes) {\n if (!process.stdin.isTTY) throw new AthenaError('Refusing to delete .athena/ without confirmation.', 'Re-run with --yes in non-interactive environments.');\n ui.line(`This removes ${ui.c.bold('.athena/')} (including rules.md and your Developer Notes)${opts.keepAgents ? '' : ' and Athena blocks/files in agent configurations'}.`);\n ui.line(ui.dim('If .athena/ is committed to Git you can restore it from history.'));\n if (!(await confirm('Continue?'))) {\n ui.line('Cancelled.');\n return;\n }\n }\n const touched: string[] = [];\n if (!opts.keepAgents) for (const a of ADAPTERS) touched.push(...(await a.remove(root)));\n await fs.rm(athenaDir(root), { recursive: true, force: true });\n if (ui.isJson()) ui.json({ ok: true, removed: ['.athena/', ...touched] });\n else {\n ui.ok('Removed .athena/');\n for (const t of touched) ui.ok(`Removed Athena integration from ${t}`);\n }\n}\n","import { execFile } from 'node:child_process';\nimport { browserUrl, findRunningInstance, startServer } from '../../server/instance.js';\nimport { requireProjectRoot, type GlobalOptions } from '../context.js';\nimport { AthenaError } from '../../services/errors.js';\nimport * as ui from '../ui/term.js';\n\nexport interface OpenOptions extends GlobalOptions {\n port?: string;\n host?: string;\n open?: boolean;\n allowRemote?: boolean;\n watch?: boolean;\n signal: AbortSignal;\n}\n\n/** Open a URL in the default browser using fixed argv (no shell parsing). */\nexport function openBrowser(url: string): void {\n const [cmd, args] =\n process.platform === 'darwin' ? ['open', [url]] : process.platform === 'win32' ? ['rundll32', ['url.dll,FileProtocolHandler', url]] : ['xdg-open', [url]];\n const child = execFile(cmd, args as string[], { windowsHide: true }, () => {});\n child.on('error', () => {});\n child.unref();\n}\n\nexport async function openCommand(opts: OpenOptions): Promise<void> {\n const root = await requireProjectRoot(opts);\n const shouldOpen = opts.open !== false;\n\n const existing = await findRunningInstance(root);\n if (existing) {\n const url = browserUrl(existing);\n if (ui.isJson()) ui.json({ running: true, reused: true, url, port: existing.port, pid: existing.pid });\n else {\n ui.ok(`Athena is already running for this project ${ui.dim(`(pid ${existing.pid})`)}`);\n ui.line();\n ui.line(`Local: ${ui.c.cyan(url)}`);\n }\n if (shouldOpen) openBrowser(url);\n return;\n }\n\n let port: number | undefined;\n if (opts.port !== undefined) {\n port = Number(opts.port);\n if (!Number.isInteger(port) || port < 1 || port > 65535) throw new AthenaError(`Invalid port: ${opts.port}`);\n }\n const host = opts.host ?? '127.0.0.1';\n\n let running;\n try {\n running = await startServer({ root, host, port, allowRemote: opts.allowRemote, watch: opts.watch !== false });\n } catch (err) {\n const e = err as NodeJS.ErrnoException;\n if (e.code === 'EADDRINUSE') throw new AthenaError(`Port ${port} is already in use.`, 'Omit --port to pick a free port automatically.');\n throw new AthenaError(e.message);\n }\n\n if (ui.isJson()) ui.json({ running: true, reused: false, url: running.url, port: running.info.port, pid: process.pid });\n else {\n ui.banner();\n ui.line(ui.c.bold(ui.c.green('Athena is running')));\n ui.line();\n ui.line(`Local: ${ui.c.cyan(running.url)}`);\n if (opts.allowRemote) ui.warn(ui.c.yellow(`Bound to ${host} — reachable from other machines. The access token in the URL is required for every API call.`));\n ui.line();\n ui.line(ui.dim(opts.watch === false ? 'File watching is off.' : 'Watching for changes — knowledge updates are proposed in the UI, never applied without your review.'));\n ui.line(ui.dim('The link contains a private access token. Press Ctrl+C to stop.'));\n }\n if (shouldOpen) openBrowser(running.url);\n ui.setInterruptMessage('Stopping Athena server...');\n\n await new Promise<void>((resolve) => {\n if (opts.signal.aborted) resolve();\n opts.signal.addEventListener('abort', () => resolve(), { once: true });\n });\n await running.close();\n if (!ui.isJson()) ui.line(ui.dim('Athena server stopped.'));\n}\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { athenaDir } from '../core/state/state.js';\nimport { readTextIfExists } from '../core/util/fs.js';\nimport { createServer, type AthenaServer } from './app.js';\nimport { DEFAULT_PORT, findAvailablePort } from './port.js';\nimport { generateToken, isLoopbackHost } from './security.js';\nimport { INSTANCE_FILE, type InstanceInfo } from '../services/instance.js';\n\nexport { findRunningInstance, INSTANCE_FILE, type InstanceInfo } from '../services/instance.js';\n\n\nexport interface StartOptions {\n root: string;\n host?: string;\n port?: number;\n allowRemote?: boolean;\n webDir?: string;\n watch?: boolean;\n}\n\nexport interface RunningServer {\n server: AthenaServer;\n info: InstanceInfo;\n url: string;\n close(): Promise<void>;\n}\n\n/** Location of built UI assets: dist/web next to the bundled CLI. */\nexport function defaultWebDir(): string {\n const here = path.dirname(fileURLToPath(import.meta.url));\n // Bundled: dist/cli.js → dist/web. Source (tests/dev): src/server → dist/web.\n return path.basename(here) === 'dist' ? path.join(here, 'web') : path.resolve(here, '../../dist/web');\n}\n\nexport function browserUrl(info: Pick<InstanceInfo, 'host' | 'port' | 'token'>): string {\n const host = info.host.includes(':') ? `[${info.host}]` : info.host;\n // The token travels in the URL fragment, which browsers never send to servers or put in Referer headers.\n return `http://${host}:${info.port}/#token=${info.token}`;\n}\n\nexport async function startServer(opts: StartOptions): Promise<RunningServer> {\n const host = opts.host ?? '127.0.0.1';\n if (!isLoopbackHost(host) && !opts.allowRemote) {\n throw new Error(`Refusing to bind to non-loopback address ${host} without --allow-remote.`);\n }\n const port = opts.port ?? (await findAvailablePort(host, DEFAULT_PORT));\n const token = generateToken();\n const server = await createServer({ root: opts.root, token, host, port, webDir: opts.webDir ?? defaultWebDir(), allowRemote: opts.allowRemote, watch: opts.watch ?? true });\n await server.app.listen({ host, port });\n const info: InstanceInfo = { pid: process.pid, host, port, instanceId: server.instanceId, token, startedAt: new Date().toISOString() };\n const file = path.join(athenaDir(opts.root), INSTANCE_FILE);\n await fs.writeFile(file, `${JSON.stringify(info, null, 2)}\\n`, { mode: 0o600 });\n await ensureGitignored(opts.root, INSTANCE_FILE);\n return {\n server,\n info,\n url: browserUrl(info),\n async close() {\n const current = await readTextIfExists(file);\n if (current && current.includes(server.instanceId)) await fs.rm(file, { force: true });\n await server.close();\n },\n };\n}\n\nasync function ensureGitignored(root: string, entry: string): Promise<void> {\n const file = path.join(athenaDir(root), '.gitignore');\n const text = (await readTextIfExists(file)) ?? '';\n if (text.split(/\\r?\\n/).includes(entry)) return;\n await fs.writeFile(file, `${text}${text.endsWith('\\n') || !text ? '' : '\\n'}${entry}\\n`);\n}\n","import { promises as fs, watch, type FSWatcher } from 'node:fs';\nimport crypto from 'node:crypto';\nimport path from 'node:path';\nimport Fastify, { type FastifyInstance, type FastifyReply } from 'fastify';\nimport { KNOWLEDGE_DOCS, RELEVANCE_MAP } from '../core/knowledge/documents.js';\nimport { athenaDir } from '../core/state/state.js';\nimport { AthenaError, type ErrorKind } from '../services/errors.js';\nimport { contentHash, docAtRevision, docHistory, listDocs, readDoc, saveDoc, searchDocs } from '../services/knowledge.js';\nimport { getRules, rulesAdd, rulesRemove, rulesUpdate } from '../services/rules.js';\nimport { buildStatus, type StatusReport } from '../services/status.js';\nimport { runDoctor } from '../services/doctor.js';\nimport { configureAgents, listAgents, removeAgents } from '../services/agents.js';\nimport { getOverview } from '../services/overview.js';\nimport { runPipeline } from '../services/pipeline.js';\nimport { applySync, ignorePlan, planSync, type SyncPlan } from '../services/sync.js';\nimport { loadScan, runSecurityScan, saveScan, type SecurityScan } from '../services/security.js';\nimport { reviewChanges } from '../services/review.js';\nimport { getRelevantContext, graphSummary, refreshGraph } from '../services/context.js';\nimport { aiStatus } from '../services/ai.js';\nimport { ProjectModel } from '../core/model/project-model.js';\nimport { watchProject, type ProjectWatcher } from '../services/watch.js';\nimport { ACTIVITY_FILE, activityFile, parseEventLines, readRecentEvents, summarizeSessions } from '../services/agent-activity.js';\nimport type { AgentEvent } from '../agents/common/hook-events.js';\nimport { ATHENA_VERSION } from '../services/version.js';\nimport { EventBus } from './events.js';\nimport { allowedHostsFor, allowedOriginsFor, makeGuard, SECURITY_HEADERS } from './security.js';\nimport { buildAssetMap, MISSING_UI_HTML } from './static.js';\n\nexport interface ServerOptions {\n root: string;\n token: string;\n host: string;\n port: number;\n webDir: string;\n /** Explicit opt-in to non-loopback binding; disables the Host allowlist. */\n allowRemote?: boolean;\n logger?: boolean;\n /** Watch the project and propose knowledge updates as files change. */\n watch?: boolean;\n /** Watcher debounce (ms); mainly for tests. */\n watchDebounceMs?: number;\n}\n\nexport interface AthenaServer {\n app: FastifyInstance;\n events: EventBus;\n instanceId: string;\n close(): Promise<void>;\n}\n\nconst STATUS: Record<ErrorKind, number> = {\n invalid: 400,\n 'not-found': 404,\n conflict: 409,\n 'not-initialized': 409,\n busy: 423,\n unprocessable: 422,\n forbidden: 403,\n internal: 500,\n};\n\nexport async function createServer(opts: ServerOptions): Promise<AthenaServer> {\n const root = opts.root;\n const events = new EventBus();\n const instanceId = crypto.randomUUID();\n const app = Fastify({\n logger: opts.logger ?? false,\n bodyLimit: 2 * 1024 * 1024,\n trustProxy: false,\n // Strict validation: no type coercion, reject (don't silently strip) unknown fields.\n ajv: { customOptions: { coerceTypes: false, removeAdditional: false, allErrors: false } },\n });\n const assets = await buildAssetMap(opts.webDir);\n const recentWrites = new Map<string, string>(); // file → hash written by this server\n let analysisRunning = false;\n let currentPlan: SyncPlan | null = null;\n let lastCheckedAt: string | null = null;\n let watcher: ProjectWatcher | null = null;\n let syncBusy = false;\n let activityOffset = 0;\n /** Agent activity is only shown while it is fresh; after this it reverts to idle. */\n const AGENT_IDLE_MS = 5 * 60 * 1000;\n let statusCache: { at: number; report: StatusReport } | null = null;\n\n app.addHook('onRequest', makeGuard({\n token: opts.token,\n allowedHosts: opts.allowRemote ? new Set() : allowedHostsFor(opts.host, opts.port),\n allowedOrigins: opts.allowRemote ? new Set() : allowedOriginsFor(opts.host, opts.port),\n }));\n app.addHook('onSend', async (req, reply, payload) => {\n for (const [k, v] of Object.entries(SECURITY_HEADERS)) reply.header(k, v);\n if (req.url.startsWith('/api/')) reply.header('Cache-Control', 'no-store');\n return payload;\n });\n\n app.setErrorHandler((err, _req, reply) => {\n if (err instanceof AthenaError) {\n return reply.code(STATUS[err.kind]).send({ error: err.message, hint: err.hint, kind: err.kind, details: err.details });\n }\n const e = err as { statusCode?: number; message?: string };\n if (e.statusCode && e.statusCode < 500) return reply.code(e.statusCode).send({ error: e.message });\n app.log.error(err);\n return reply.code(500).send({ error: 'Internal error' });\n });\n\n const invalidateStatus = () => (statusCache = null);\n const getStatus = async (): Promise<StatusReport> => {\n if (statusCache && Date.now() - statusCache.at < 3000) return statusCache.report;\n const report = await buildStatus(root);\n statusCache = { at: Date.now(), report };\n return report;\n };\n\n // ---- health & session -------------------------------------------------\n app.get('/api/health', async () => ({ ok: true, instanceId, version: ATHENA_VERSION }));\n app.get('/api/session', async () => ({ ok: true, instanceId, version: ATHENA_VERSION, root, docs: KNOWLEDGE_DOCS, relevanceMap: RELEVANCE_MAP }));\n\n // ---- overview / status / doctor ------------------------------------------\n app.get('/api/overview', async () => getOverview(root));\n app.get('/api/status', async () => getStatus());\n app.get('/api/doctor', async () => runDoctor(root));\n\n // ---- knowledge documents --------------------------------------------------\n app.get('/api/docs', async () => {\n const [docs, status] = await Promise.all([listDocs(root), getStatus().catch(() => null)]);\n const affected = new Map(status?.affectedDocuments.map((a) => [a.file, a.reasons]) ?? []);\n return docs.map((d) => ({ ...d, sync: syncState(d.id, d.present, affected.get(d.file)), affectedBy: affected.get(d.file) ?? [] }));\n });\n\n const withSync = async <T extends { id: string; file: string }>(doc: T) => {\n const status = await getStatus().catch(() => null);\n const reasons = status?.affectedDocuments.find((a) => a.file === doc.file)?.reasons;\n return { ...doc, sync: syncState(doc.id, true, reasons), affectedBy: reasons ?? [] };\n };\n\n app.get<{ Params: { id: string } }>('/api/docs/:id', async (req) => withSync(await readDoc(root, req.params.id)));\n\n app.put<{ Params: { id: string }; Body: { content: string; baseHash: string | null } }>(\n '/api/docs/:id',\n { schema: { body: { type: 'object', required: ['content', 'baseHash'], additionalProperties: false, properties: { content: { type: 'string' }, baseHash: { type: ['string', 'null'] } } } } },\n async (req) => {\n const doc = await saveDoc(root, req.params.id, req.body.content, req.body.baseHash);\n recentWrites.set(doc.file, doc.hash!);\n invalidateStatus();\n events.emit({ source: 'web-ui', type: 'knowledge.saved', level: 'success', message: `Saved ${doc.file}`, data: { file: doc.file } });\n replanSoon();\n return withSync(doc);\n },\n );\n\n app.get<{ Params: { id: string } }>('/api/docs/:id/history', async (req) => docHistory(root, req.params.id));\n app.get<{ Params: { id: string; sha: string } }>('/api/docs/:id/history/:sha', async (req) => ({ content: await docAtRevision(root, req.params.id, req.params.sha) }));\n\n app.get<{ Querystring: { q?: string } }>('/api/search', async (req) => searchDocs(root, String(req.query.q ?? '').slice(0, 200)));\n\n // ---- rules -------------------------------------------------------------------\n const ruleAfter = (message: string) => {\n events.emit({ source: 'web-ui', type: 'rules.changed', level: 'success', message });\n };\n app.get('/api/rules', async () => getRules(root));\n app.post<{ Body: { section: string; text: string; baseHash?: string } }>(\n '/api/rules',\n { schema: { body: { type: 'object', required: ['section', 'text'], additionalProperties: false, properties: { section: { type: 'string', maxLength: 200 }, text: { type: 'string', maxLength: 1000 }, baseHash: { type: 'string' } } } } },\n async (req) => {\n const v = await rulesAdd(root, req.body.baseHash, req.body.section, req.body.text);\n recentWrites.set('rules.md', v.hash);\n ruleAfter(`Added rule to \"${req.body.section}\"`);\n return v;\n },\n );\n app.patch<{ Params: { index: string }; Body: { text?: string; enabled?: boolean; baseHash: string } }>(\n '/api/rules/:index',\n { schema: { body: { type: 'object', required: ['baseHash'], additionalProperties: false, properties: { text: { type: 'string', maxLength: 1000 }, enabled: { type: 'boolean' }, baseHash: { type: 'string' } } } } },\n async (req) => {\n const index = parseIndex(req.params.index);\n const v = await rulesUpdate(root, req.body.baseHash, index, { text: req.body.text, enabled: req.body.enabled });\n recentWrites.set('rules.md', v.hash);\n ruleAfter(req.body.enabled === undefined ? `Edited rule #${index}` : `${req.body.enabled ? 'Enabled' : 'Disabled'} rule #${index}`);\n return v;\n },\n );\n app.delete<{ Params: { index: string }; Querystring: { baseHash?: string } }>('/api/rules/:index', async (req) => {\n const index = parseIndex(req.params.index);\n if (!req.query.baseHash) throw new AthenaError('baseHash is required');\n const v = await rulesRemove(root, req.query.baseHash, index);\n recentWrites.set('rules.md', v.hash);\n ruleAfter(`Deleted rule #${index}`);\n return v;\n });\n\n // ---- agents ----------------------------------------------------------------------\n app.get('/api/agents', async () => listAgents(root));\n app.post<{ Body: { agents: string[] } }>(\n '/api/agents/configure',\n { schema: { body: { type: 'object', required: ['agents'], additionalProperties: false, properties: { agents: { type: 'array', maxItems: 10, items: { type: 'string', maxLength: 40 } } } } } },\n async (req) => {\n const r = await configureAgents(root, req.body.agents);\n events.emit({ source: 'web-ui', type: 'agents.configured', level: 'success', message: `Configured ${r.map((x) => x.id).join(', ')}`, data: { files: r.flatMap((x) => x.files.map((f) => f.path)) } });\n return listAgents(root);\n },\n );\n app.post<{ Body: { agents: string[] } }>(\n '/api/agents/remove',\n { schema: { body: { type: 'object', required: ['agents'], additionalProperties: false, properties: { agents: { type: 'array', maxItems: 10, items: { type: 'string', maxLength: 40 } } } } } },\n async (req) => {\n const removed = await removeAgents(root, req.body.agents);\n events.emit({ source: 'web-ui', type: 'agents.removed', level: 'info', message: `Removed ${req.body.agents.join(', ')} integration${removed.length ? ` (${removed.join(', ')})` : ''}` });\n return listAgents(root);\n },\n );\n\n // ---- analysis ------------------------------------------------------------------------\n app.post<{ Body: { force?: boolean } }>(\n '/api/analyze',\n { schema: { body: { type: 'object', additionalProperties: false, properties: { force: { type: 'boolean' } } } } },\n async (req, reply) => {\n if (analysisRunning) throw new AthenaError('An analysis is already running.', undefined, 1, 'busy');\n analysisRunning = true;\n const started = Date.now();\n events.setActivity({ state: 'ANALYZING', actor: 'athena', task: 'Analyzing project', reading: [] });\n events.emit({ source: 'athena', type: 'analysis.started', level: 'info', message: 'Analysis started (requested from web UI)' });\n void runPipeline({\n root,\n mode: 'analyze',\n force: req.body?.force,\n onStage: (stage) => {\n const labels: Record<string, string> = { scan: 'Scanning files', detect: 'Detecting technologies, schema and routes', git: 'Reading Git metadata', write: 'Writing knowledge', agents: 'Updating agent integrations' };\n if (labels[stage]) events.setActivity({ state: 'ANALYZING', actor: 'athena', task: labels[stage]!, reading: [] });\n },\n })\n .then((result) => {\n for (const d of result.docs) recentWrites.set(d.file, d.contentHash);\n const changed = result.docs.filter((d) => d.status !== 'unchanged').map((d) => d.file);\n const preserved = result.docs.filter((d) => d.preservedModified.length).map((d) => d.file);\n invalidateStatus();\n currentPlan = null;\n events.emit({\n source: 'athena',\n type: 'analysis.completed',\n level: 'success',\n message: `Analysis completed in ${((Date.now() - started) / 1000).toFixed(1)}s — ${changed.length ? `updated ${changed.join(', ')}` : 'knowledge already up to date'}`,\n data: { changed, preserved, filesScanned: result.analysis.model.stats.filesScanned, warnings: result.analysis.model.warnings.length },\n });\n events.setActivity({ state: 'SUCCESS', actor: 'athena', task: 'Analysis complete', reading: [] }, 4000);\n })\n .catch((err: Error) => {\n events.emit({ source: 'athena', type: 'analysis.failed', level: 'error', message: `Analysis failed: ${err.message}` });\n events.setActivity({ state: 'ERROR', actor: 'athena', task: 'Analysis failed', reading: [] }, 8000);\n })\n .finally(() => {\n analysisRunning = false;\n });\n return reply.code(202).send({ accepted: true });\n },\n );\n\n // ---- agent activity (from hooks) -----------------------------------------------------------\n const toAthenaEvent = (e: AgentEvent) => ({\n id: e.id,\n ts: e.ts,\n source: 'agent' as const,\n type: `agent.${e.kind}`,\n level: (e.kind === 'stop' ? 'success' : 'info') as 'success' | 'info',\n message: `${e.agent}: ${e.message}`,\n data: { agent: e.agent, session: e.session, hook: e.hook, files: e.files, command: e.command, tool: e.tool },\n });\n\n const applyAgentEvent = (e: AgentEvent, live: boolean) => {\n if (events.has(e.id)) return;\n if (live) events.emit(toAthenaEvent(e));\n else events.seed([{ ...toAthenaEvent(e) }]);\n if (!live) return;\n if (e.state === 'IDLE') {\n if (events.activity().actor === 'agent') events.setActivity({ state: 'IDLE', actor: 'none', task: null, reading: [] });\n return;\n }\n // Athena's own analysis takes precedence only while it is running.\n if (analysisRunning) return;\n events.setActivity({ state: e.state, actor: 'agent', task: `${e.agent}: ${e.message}`, reading: e.files.slice(0, 4) }, e.state === 'SUCCESS' ? 10_000 : AGENT_IDLE_MS);\n };\n\n const readNewAgentEvents = async () => {\n try {\n const file = activityFile(root);\n const st = await fs.stat(file).catch(() => null);\n if (!st) return;\n if (st.size < activityOffset) activityOffset = 0; // file rotated\n if (st.size === activityOffset) return;\n const handle = await fs.open(file, 'r');\n try {\n const length = st.size - activityOffset;\n const buf = Buffer.alloc(length);\n await handle.read(buf, 0, length, activityOffset);\n const text = buf.toString('utf8');\n const lastNewline = text.lastIndexOf('\\n');\n if (lastNewline === -1) return; // partial line; wait for the rest\n activityOffset += Buffer.byteLength(text.slice(0, lastNewline + 1));\n for (const e of parseEventLines(text.slice(0, lastNewline + 1))) applyAgentEvent(e, true);\n } finally {\n await handle.close();\n }\n } catch {\n /* activity log unreadable: ignore */\n }\n };\n\n // ---- synchronization ----------------------------------------------------------------------\n const setPlan = (plan: SyncPlan | null) => {\n lastCheckedAt = new Date().toISOString();\n currentPlan = plan && !plan.upToDate ? plan : null;\n };\n const checkNow = async (): Promise<SyncPlan | null> => {\n if (watcher) return watcher.planNow();\n const plan = await planSync(root);\n setPlan(plan);\n return plan;\n };\n const replanSoon = () => {\n if (currentPlan) void checkNow().catch(() => {});\n };\n\n app.get('/api/sync', async () => ({ watching: Boolean(watcher), lastCheckedAt, plan: currentPlan }));\n\n app.post('/api/sync/check', async () => {\n const plan = await checkNow();\n if (!watcher) setPlan(plan);\n return { watching: Boolean(watcher), lastCheckedAt, plan: currentPlan, upToDate: plan?.upToDate ?? true };\n });\n\n const planIdSchema = { schema: { body: { type: 'object', required: ['planId'], additionalProperties: false, properties: { planId: { type: 'string', pattern: '^[a-f0-9]{16}$' } } } } };\n\n app.post<{ Body: { planId: string } }>('/api/sync/apply', planIdSchema, async (req) => {\n if (!currentPlan || currentPlan.id !== req.body.planId) throw new AthenaError('This proposal is out of date.', 'Check for changes again and review the new proposal.', 1, 'conflict');\n if (syncBusy || analysisRunning) throw new AthenaError('Another update is in progress.', undefined, 1, 'busy');\n syncBusy = true;\n const plan = currentPlan;\n try {\n const result = await applySync(root, plan);\n for (const d of plan.documents) {\n const text = await fs.readFile(path.join(athenaDir(root), d.file), 'utf8').catch(() => null);\n if (text !== null) recentWrites.set(d.file, contentHash(text));\n }\n currentPlan = null;\n lastCheckedAt = new Date().toISOString();\n invalidateStatus();\n events.emit({ source: 'web-ui', type: 'sync.applied', level: 'success', message: `Knowledge updated: ${result.applied.join(', ')}`, data: { files: result.applied, preserved: result.preserved } });\n events.setActivity({ state: 'SUCCESS', actor: 'athena', task: 'Knowledge synchronized', reading: [] }, 4000);\n return result;\n } catch (err) {\n if (err instanceof AthenaError && err.kind === 'conflict') replanSoon();\n throw err;\n } finally {\n syncBusy = false;\n }\n });\n\n app.post<{ Body: { planId: string } }>('/api/sync/ignore', planIdSchema, async (req) => {\n if (!currentPlan || currentPlan.id !== req.body.planId) throw new AthenaError('This proposal is out of date.', undefined, 1, 'conflict');\n await ignorePlan(root, req.body.planId);\n currentPlan = { ...currentPlan, ignored: true };\n events.emit({ source: 'web-ui', type: 'sync.ignored', level: 'info', message: `Ignored proposed update to ${currentPlan.documents.map((d) => d.file).join(', ')}` });\n return { ok: true };\n });\n\n // ---- security & review ---------------------------------------------------------------------\n let scanRunning = false;\n const projectModel = async (): Promise<ProjectModel> => {\n const raw = await fs.readFile(path.join(athenaDir(root), 'model.json'), 'utf8').catch(() => null);\n if (raw) {\n const parsed = ProjectModel.safeParse(JSON.parse(raw));\n if (parsed.success) return parsed.data;\n }\n throw new AthenaError('model.json is missing.', 'Run `athena analyze` (or re-analyze from the overview) first.');\n };\n\n app.get('/api/security', async () => ({ scan: await loadScan(root), running: scanRunning }));\n\n app.post<{ Body: { skipAudit?: boolean } }>(\n '/api/security/scan',\n { schema: { body: { type: 'object', additionalProperties: false, properties: { skipAudit: { type: 'boolean' } } } } },\n async (req, reply) => {\n if (scanRunning) throw new AthenaError('A security scan is already running.', undefined, 1, 'busy');\n scanRunning = true;\n const model = await projectModel();\n events.emit({ source: 'web-ui', type: 'security.started', level: 'info', message: 'Security scan started' });\n events.setActivity({ state: 'REVIEWING', actor: 'athena', task: 'Scanning dependencies', reading: [] });\n void runSecurityScan(root, model, { skipAudit: req.body?.skipAudit, onTool: (tool) => events.setActivity({ state: 'REVIEWING', actor: 'athena', task: `Running ${tool}`, reading: [] }) })\n .then(async (scan: SecurityScan) => {\n await saveScan(root, scan);\n const findings = scan.tools.reduce((n, t) => n + t.findings.length, 0);\n events.emit({\n source: 'athena',\n type: 'security.completed',\n level: findings || scan.secrets.count ? 'warn' : 'success',\n message: `Security scan finished — ${findings} dependency finding(s), ${scan.secrets.count} potential secret(s)`,\n data: { findings, secrets: scan.secrets.count },\n });\n events.setActivity({ state: 'SUCCESS', actor: 'athena', task: 'Security scan complete', reading: [] }, 4000);\n replanSoon();\n })\n .catch((err: Error) => {\n events.emit({ source: 'athena', type: 'security.failed', level: 'error', message: `Security scan failed: ${err.message}` });\n events.setActivity({ state: 'ERROR', actor: 'athena', task: 'Security scan failed', reading: [] }, 8000);\n })\n .finally(() => {\n scanRunning = false;\n });\n return reply.code(202).send({ accepted: true });\n },\n );\n\n app.get<{ Querystring: { base?: string } }>('/api/review', async (req) => {\n const base = typeof req.query.base === 'string' && req.query.base ? req.query.base : undefined;\n return reviewChanges(root, { base, checkSync: async (r) => (await planSync(r)).upToDate });\n });\n\n // ---- context engine & graph -------------------------------------------------------------\n let graphBuilding = false;\n\n app.get<{ Querystring: { task?: string; maxChars?: string } }>('/api/context', async (req) => {\n const task = String(req.query.task ?? '').slice(0, 500);\n const maxChars = req.query.maxChars ? Number(req.query.maxChars) : undefined;\n return getRelevantContext(root, task, { maxChars: Number.isFinite(maxChars) ? maxChars : undefined });\n });\n\n app.get('/api/graph', async () => ({ ...(await graphSummary(root)), building: graphBuilding }));\n\n app.post('/api/graph/build', async () => {\n if (graphBuilding) throw new AthenaError('The graph is already being built.', undefined, 1, 'busy');\n graphBuilding = true;\n try {\n const graph = await refreshGraph(root);\n events.emit({ source: 'web-ui', type: 'graph.built', level: 'success', message: `Project graph built: ${graph.stats.nodes} nodes, ${graph.stats.edges} relationships` });\n return { built: true, builtAt: graph.builtAt, stats: graph.stats };\n } finally {\n graphBuilding = false;\n }\n });\n\n app.get('/api/ai', async () => aiStatus(root));\n\n // ---- events (streamed) ------------------------------------------------------------------\n app.get('/api/activity', async () => {\n const agents = await listAgents(root);\n const observing = agents.filter((a) => a.activityObservation === 'hooks');\n return {\n activity: events.activity(),\n events: events.recent(),\n sessions: summarizeSessions(await readRecentEvents(root, 500)),\n agentObservation: {\n available: observing.length > 0,\n agents: observing.map((a) => a.name),\n reason: observing.length\n ? 'Events below come from hooks the agent fired. Athena sees which tool ran and on which files — never the agent\\'s reasoning.'\n : 'No agent is reporting activity yet. Configure an agent with hooks (Claude Code or Cursor) to see its actions here.',\n },\n };\n });\n\n app.get('/api/events', (req, reply) => {\n reply.hijack();\n const res = reply.raw;\n res.writeHead(200, { ...SECURITY_HEADERS, 'Content-Type': 'text/event-stream; charset=utf-8', 'Cache-Control': 'no-store', Connection: 'keep-alive', 'X-Accel-Buffering': 'no' });\n const send = (event: string, data: unknown) => res.write(`event: ${event}\\ndata: ${JSON.stringify(data)}\\n\\n`);\n send('activity', events.activity());\n const unsubscribe = events.subscribe((e) => {\n if (e.type === '__activity') send('activity', (e as { activity: unknown }).activity);\n else send('event', e);\n });\n const heartbeat = setInterval(() => res.write(': ping\\n\\n'), 20_000);\n heartbeat.unref();\n req.raw.on('close', () => {\n clearInterval(heartbeat);\n unsubscribe();\n });\n });\n\n // ---- static UI ---------------------------------------------------------------------------\n const sendAsset = async (reply: FastifyReply, urlPath: string) => {\n if (!assets) return reply.code(503).type('text/html; charset=utf-8').send(MISSING_UI_HTML);\n const asset = assets.get(urlPath) ?? assets.get('/index.html')!;\n const body = await fs.readFile(asset.abs);\n reply.header('Cache-Control', asset.immutable ? 'public, max-age=31536000, immutable' : 'no-cache');\n return reply.type(asset.type).send(body);\n };\n app.route({\n method: 'GET',\n url: '/*',\n handler: async (req, reply) => {\n let urlPath: string;\n try {\n urlPath = decodeURIComponent(req.url.split('?')[0]!);\n } catch {\n return reply.code(400).send('Bad request');\n }\n if (urlPath.startsWith('/api/')) return reply.code(404).send({ error: 'Not found' });\n // Unknown extensions are SPA routes only when they look like app paths (no dot).\n if (assets && !assets.has(urlPath) && /\\.[a-z0-9]+$/i.test(urlPath)) return reply.code(404).send('Not found');\n return sendAsset(reply, urlPath === '/' ? '/index.html' : urlPath);\n },\n });\n\n // ---- knowledge directory watcher -------------------------------------------------------------\n let docsWatcher: FSWatcher | null = null;\n const pending = new Map<string, NodeJS.Timeout>();\n try {\n const dir = athenaDir(root);\n docsWatcher = watch(dir, { persistent: false }, (_type, filename) => {\n const name = filename?.toString();\n if (name === ACTIVITY_FILE) {\n void readNewAgentEvents();\n return;\n }\n if (!name || !KNOWLEDGE_DOCS.some((d) => d.file === name)) return;\n clearTimeout(pending.get(name));\n pending.set(\n name,\n setTimeout(async () => {\n pending.delete(name);\n const text = await fs.readFile(path.join(dir, name), 'utf8').catch(() => null);\n const hash = text === null ? null : contentHash(text);\n if (hash && recentWrites.get(name) === hash) return; // our own write\n invalidateStatus();\n events.emit({ source: 'filesystem', type: 'knowledge.external-change', level: 'info', message: text === null ? `${name} was deleted on disk` : `${name} changed on disk`, data: { file: name, hash } });\n }, 150),\n );\n });\n docsWatcher.on('error', () => {});\n } catch {\n docsWatcher = null;\n }\n\n // Seed the timeline with agent events recorded while the UI was closed.\n {\n const history = await readRecentEvents(root, 200);\n for (const e of history) applyAgentEvent(e, false);\n activityOffset = await fs.stat(activityFile(root)).then((st) => st.size).catch(() => 0);\n }\n\n if (opts.watch) {\n try {\n watcher = await watchProject(root, {\n debounceMs: opts.watchDebounceMs,\n onEvent: (e) => {\n switch (e.type) {\n case 'planning':\n if (!analysisRunning) events.setActivity({ state: 'ANALYZING', actor: 'athena', task: e.paths?.length ? `Checking ${e.paths.length} changed file${e.paths.length === 1 ? '' : 's'}` : 'Checking for changes', reading: [] });\n break;\n case 'plan': {\n const plan = e.plan!;\n const prevId = currentPlan?.id;\n setPlan(plan);\n if (!analysisRunning) events.setActivity({ state: 'IDLE', actor: 'none', task: null, reading: [] });\n if (!plan.upToDate && !plan.ignored && plan.id !== prevId) {\n events.emit({ source: 'athena', type: 'sync.proposed', level: 'warn', message: `Knowledge update proposed for ${plan.documents.map((d) => d.file).join(', ')}`, data: { planId: plan.id, files: plan.documents.map((d) => d.file) } });\n }\n if (plan.upToDate && prevId) events.emit({ source: 'athena', type: 'sync.up-to-date', level: 'info', message: 'Proposal no longer needed — knowledge is up to date' });\n break;\n }\n case 'refreshed':\n setPlan(null);\n invalidateStatus();\n if (!analysisRunning) events.setActivity({ state: 'IDLE', actor: 'none', task: null, reading: [] });\n events.emit({ source: 'athena', type: 'sync.up-to-date', level: 'info', message: 'Files changed — knowledge already up to date (index refreshed)' });\n break;\n case 'git-head':\n events.emit({ source: 'filesystem', type: 'git.head', level: 'info', message: `Git HEAD moved ${e.head?.from?.slice(0, 8) ?? '?'} → ${e.head?.to?.slice(0, 8) ?? '?'}` });\n break;\n case 'error':\n if (!analysisRunning) events.setActivity({ state: 'ERROR', actor: 'athena', task: 'Change check failed', reading: [] }, 6000);\n events.emit({ source: 'athena', type: 'sync.error', level: 'error', message: `Change check failed: ${e.error?.message ?? 'unknown error'}` });\n break;\n default:\n break;\n }\n },\n });\n void watcher.planNow();\n } catch (err) {\n events.emit({ source: 'athena', type: 'sync.error', level: 'error', message: `File watching unavailable: ${(err as Error).message}` });\n }\n }\n\n return {\n app,\n events,\n instanceId,\n async close() {\n await watcher?.close();\n watcher = null;\n docsWatcher?.close();\n for (const t of pending.values()) clearTimeout(t);\n events.close();\n await app.close();\n },\n };\n}\n\nfunction parseIndex(raw: string): number {\n const n = Number(raw);\n if (!Number.isInteger(n) || n < 1) throw new AthenaError(`Invalid rule index: ${raw.slice(0, 20)}`);\n return n;\n}\n\nfunction syncState(id: string, present: boolean, affectedReasons: string[] | undefined): 'missing' | 'developer-owned' | 'synchronized' | 'may-be-outdated' {\n if (!present) return 'missing';\n if (id === 'rules') return 'developer-owned';\n return affectedReasons?.length ? 'may-be-outdated' : 'synchronized';\n}\n","import { ADAPTERS, applyChanges, resolveAdapters } from '../agents/registry.js';\nimport type { IntegrationCheck } from '../core/agents/adapter.js';\nimport { athenaDir, readState, writeState } from '../core/state/state.js';\nimport { AthenaError } from './errors.js';\nimport { readRecentEvents, summarizeSessions } from './agent-activity.js';\n\nfunction resolve(names: string[]) {\n try {\n return names.length === 1 && names[0] === 'all' ? ADAPTERS : resolveAdapters(names);\n } catch (err) {\n throw new AthenaError((err as Error).message);\n }\n}\n\nexport interface AgentView {\n id: string;\n name: string;\n configured: boolean;\n configuredAt: string | null;\n files: string[];\n detectedInProject: boolean;\n evidence: string[];\n note: string;\n capabilities: { instructionsFile: boolean; scopedRules: boolean; hooks: boolean; mcp: boolean };\n checks: IntegrationCheck[];\n /** 'hooks': the agent reports activity to Athena. 'unsupported': no documented hook mechanism. */\n activityObservation: 'hooks' | 'not-configured' | 'unsupported';\n /** Last time Athena observed a hook event from this agent (null = never). */\n lastActivityAt: string | null;\n observedEvents: number;\n}\n\nexport async function listAgents(root: string): Promise<AgentView[]> {\n const st = await readState(athenaDir(root));\n const sessions = summarizeSessions(await readRecentEvents(root, 500));\n const out: AgentView[] = [];\n for (const a of ADAPTERS) {\n const presence = await a.detectPresence(root);\n const s = st.kind === 'ok' ? st.state.agents[a.id] : undefined;\n const checks = s?.configured ? await a.check(root) : [];\n const hooksInstalled = a.capabilities.hooks && checks.some((c) => c.ok && /hooks installed/i.test(c.message));\n const mine = sessions.filter((x) => x.agent === a.id);\n out.push({\n id: a.id,\n name: a.displayName,\n configured: Boolean(s?.configured),\n configuredAt: s?.configuredAt ?? null,\n files: s?.files ?? [],\n detectedInProject: presence.detectedInProject,\n evidence: presence.evidence,\n note: a.supportNote,\n capabilities: a.capabilities,\n checks,\n activityObservation: !a.capabilities.hooks ? 'unsupported' : hooksInstalled ? 'hooks' : 'not-configured',\n lastActivityAt: mine[0]?.lastEventAt ?? null,\n observedEvents: mine.reduce((n, x) => n + x.events, 0),\n });\n }\n return out;\n}\n\nexport async function configureAgents(root: string, names: string[]): Promise<Array<{ id: string; files: Array<{ path: string; action: string }> }>> {\n const st = await readState(athenaDir(root));\n if (st.kind !== 'ok') throw new AthenaError('state.json is missing or corrupted.', 'Run `athena analyze` first.');\n const adapters = resolve(names);\n const results = [];\n for (const a of adapters) {\n const planned = await a.plan({ root, projectName: st.state.projectName });\n await applyChanges(root, planned);\n st.state.agents[a.id] = { configured: true, files: planned.map((p) => p.path), configuredAt: new Date().toISOString() };\n results.push({ id: a.id, files: planned.map((p) => ({ path: p.path, action: p.action })) });\n }\n await writeState(athenaDir(root), st.state);\n return results;\n}\n\nexport async function removeAgents(root: string, names: string[]): Promise<string[]> {\n const st = await readState(athenaDir(root));\n const removed: string[] = [];\n for (const a of resolve(names)) {\n removed.push(...(await a.remove(root)));\n if (st.kind === 'ok') delete st.state.agents[a.id];\n }\n if (st.kind === 'ok') await writeState(athenaDir(root), st.state);\n return removed;\n}\n","import path from 'node:path';\nimport { ProjectModel } from '../core/model/project-model.js';\nimport { athenaDir, readState } from '../core/state/state.js';\nimport { readTextIfExists } from '../core/util/fs.js';\nimport { AthenaError } from './errors.js';\nimport { ATHENA_VERSION } from './version.js';\n\nexport interface Overview {\n athenaVersion: string;\n project: { name: string; description: string | null; root: string };\n analyzedAt: string;\n analysisDurationMs: number;\n git: { isRepo: boolean; branch: string | null; head: string | null };\n /** null when model.json is unavailable (e.g. fresh clone) — never guessed. */\n summary: null | {\n filesAnalyzed: number;\n languages: Array<{ name: string; files: number }>;\n frameworks: Array<{ name: string; category: string; root: string; status: string; confidence: string }>;\n monorepo: { isMonorepo: boolean; tool: string | null; packages: number };\n databases: string[];\n entities: number;\n migrations: number;\n routes: number;\n apiSpecs: number;\n auth: string[];\n testFrameworks: string[];\n testFiles: number;\n ci: string[];\n containers: number;\n hosting: string[];\n envVars: number;\n potentialSecrets: number;\n securityControls: number;\n warnings: string[];\n };\n}\n\nexport async function getOverview(root: string): Promise<Overview> {\n const st = await readState(athenaDir(root));\n if (st.kind === 'missing') throw new AthenaError('Athena is not initialized in this project.', 'Run `athena init`.', 3);\n if (st.kind === 'corrupted') throw new AthenaError(`.athena/state.json is corrupted (${st.reason}).`, 'Run `athena analyze` to rebuild it.');\n const state = st.state;\n\n let model: ProjectModel | null = null;\n const raw = await readTextIfExists(path.join(athenaDir(root), 'model.json'));\n if (raw) {\n try {\n const parsed = ProjectModel.safeParse(JSON.parse(raw));\n if (parsed.success) model = parsed.data;\n } catch {\n model = null;\n }\n }\n const uniq = (xs: string[]) => [...new Set(xs)];\n return {\n athenaVersion: ATHENA_VERSION,\n project: { name: state.projectName, description: model?.description ?? null, root },\n analyzedAt: state.analyzedAt,\n analysisDurationMs: state.analysisDurationMs,\n git: { isRepo: state.git.isRepo, branch: state.git.branch ?? null, head: state.git.head ?? null },\n summary: model && {\n filesAnalyzed: model.stats.filesScanned,\n languages: model.languages.slice(0, 6).map((l) => ({ name: l.name, files: l.files })),\n frameworks: model.frameworks.map((f) => ({ name: f.name, category: f.category, root: f.root, status: f.provenance.status, confidence: f.provenance.confidence })),\n monorepo: { isMonorepo: model.workspace.isMonorepo, tool: model.workspace.tool ?? null, packages: model.workspace.packages.length },\n databases: uniq(model.databases.map((d) => d.name)),\n entities: model.dbEntities.length,\n migrations: model.migrations.reduce((n, m) => n + m.count, 0),\n routes: model.routes.length,\n apiSpecs: model.apiSpecs.length,\n auth: uniq(model.auth.map((a) => a.name)),\n testFrameworks: uniq(model.tests.frameworks.map((t) => t.name)),\n testFiles: model.tests.testFileCount,\n ci: uniq(model.ci.map((c) => c.system)),\n containers: model.containers.dockerfiles.length + model.containers.services.length,\n hosting: uniq(model.infrastructure.filter((i) => i.kind === 'hosting').map((i) => i.name)),\n envVars: model.env.vars.length,\n potentialSecrets: model.security.secrets.length,\n securityControls: model.security.controls.length,\n warnings: model.warnings,\n },\n };\n}\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { createTwoFilesPatch } from 'diff';\nimport { analyzeProject, type AnalysisResult } from '../core/analyzer/analyze.js';\nimport { KNOWLEDGE_DOCS, type GeneratedDocId } from '../core/knowledge/documents.js';\nimport { ensureRules, planKnowledge, writePlannedKnowledge, type DocPlan } from '../core/knowledge/generate.js';\nimport { diffModels, type ModelChange } from '../core/impact/model-diff.js';\nimport { impactOf } from '../core/impact/impact.js';\nimport { ProjectModel } from '../core/model/project-model.js';\nimport { headMovement, type CommitSummary } from '../core/git/git.js';\nimport { athenaDir, backupCorruptedState, buildFileIndex, diffFileIndex, readState, writeState, type AthenaState } from '../core/state/state.js';\nimport { readTextIfExists, sha256, writeFileAtomic } from '../core/util/fs.js';\nimport { AthenaError, conflict } from './errors.js';\nimport { composeState, indexWithIntegrations } from './pipeline.js';\n\nconst IGNORE_FILE = '.sync-ignore.json';\nconst MAX_DIFF_CHARS = 60_000;\n\nexport interface FileChanges {\n added: string[];\n modified: string[];\n deleted: string[];\n /** Detected by identical content hash between a deleted and an added path. */\n renamed: Array<{ from: string; to: string }>;\n}\n\nexport interface GitMovement {\n isRepo: boolean;\n previousHead: string | null;\n head: string | null;\n previousBranch: string | null;\n branch: string | null;\n branchChanged: boolean;\n commits: CommitSummary[];\n diverged: boolean;\n truncated: boolean;\n}\n\nexport interface ProposedDocument {\n id: GeneratedDocId;\n file: string;\n title: string;\n status: 'created' | 'updated';\n /** Why this document is affected: model evidence first, then path heuristics. */\n reasons: string[];\n changedSections: string[];\n /** Developer-edited sections that stay untouched. */\n preservedSections: string[];\n /** Unified diff of the file (truncated for very large changes). */\n diff: string;\n diffTruncated: boolean;\n additions: number;\n deletions: number;\n /** Hash of the file when the plan was made; apply refuses if it changed. */\n baseHash: string | null;\n}\n\nexport interface SyncPlan {\n /** Stable fingerprint of the proposed document contents. */\n id: string;\n createdAt: string;\n previousAnalysisAt: string | null;\n upToDate: boolean;\n fileChanges: FileChanges;\n git: GitMovement;\n modelChanges: ModelChange[];\n documents: ProposedDocument[];\n /** Documents that path heuristics flagged but whose content did not actually change. */\n checkedUnchanged: string[];\n ignored: boolean;\n durationMs: number;\n warnings: string[];\n}\n\ninterface PlanInternals {\n analysis: AnalysisResult;\n plans: DocPlan[];\n prevState: AthenaState | null;\n}\n\nconst internals = new WeakMap<SyncPlan, PlanInternals>();\n\nconst hashOf = (text: string | null) => (text === null ? null : sha256(text).slice(0, 16));\n\nfunction countLines(patch: string): { additions: number; deletions: number } {\n let additions = 0;\n let deletions = 0;\n for (const line of patch.split('\\n')) {\n if (line.startsWith('+') && !line.startsWith('+++')) additions++;\n else if (line.startsWith('-') && !line.startsWith('---')) deletions++;\n }\n return { additions, deletions };\n}\n\nfunction detectRenames(prev: AthenaState['fileIndex'], next: AthenaState['fileIndex'], added: string[], deleted: string[]): FileChanges {\n const byHash = new Map<string, string[]>();\n for (const d of deleted) {\n const h = prev[d]?.h;\n if (h && !h.startsWith('meta:')) byHash.set(h, [...(byHash.get(h) ?? []), d]);\n }\n const renamed: FileChanges['renamed'] = [];\n const remainingAdded: string[] = [];\n const usedDeleted = new Set<string>();\n for (const a of added) {\n const candidates = byHash.get(next[a]?.h ?? '')?.filter((d) => !usedDeleted.has(d));\n if (candidates?.length) {\n usedDeleted.add(candidates[0]!);\n renamed.push({ from: candidates[0]!, to: a });\n } else remainingAdded.push(a);\n }\n return { added: remainingAdded, modified: [], deleted: deleted.filter((d) => !usedDeleted.has(d)), renamed };\n}\n\nasync function readPreviousModel(dir: string): Promise<ProjectModel | null> {\n const raw = await readTextIfExists(path.join(dir, 'model.json'));\n if (!raw) return null;\n try {\n const parsed = ProjectModel.safeParse(JSON.parse(raw));\n return parsed.success ? parsed.data : null;\n } catch {\n return null;\n }\n}\n\nasync function readIgnored(dir: string): Promise<string | null> {\n const raw = await readTextIfExists(path.join(dir, IGNORE_FILE));\n if (!raw) return null;\n try {\n const j = JSON.parse(raw) as { planId?: unknown };\n return typeof j.planId === 'string' ? j.planId : null;\n } catch {\n return null;\n }\n}\n\nexport interface PlanOptions {\n signal?: AbortSignal;\n force?: boolean;\n}\n\n/**\n * Compute what synchronizing knowledge would change — without writing anything.\n * Only documents whose generated content would actually differ are proposed.\n */\nexport async function planSync(root: string, opts: PlanOptions = {}): Promise<SyncPlan> {\n const started = Date.now();\n const dir = athenaDir(root);\n const st = await readState(dir);\n if (st.kind === 'missing' && !(await readTextIfExists(path.join(dir, 'rules.md')))) {\n throw new AthenaError('Athena is not initialized in this project.', 'Run `athena init` first.', 3);\n }\n const prevState = st.kind === 'ok' ? st.state : null;\n const warnings: string[] = [];\n if (st.kind === 'corrupted') warnings.push(`state.json is corrupted (${st.reason}); it will be rebuilt on apply.`);\n\n const [prevModel, analysis] = await Promise.all([readPreviousModel(dir), analyzeProject(root, { signal: opts.signal, reuse: prevState?.fileIndex })]);\n opts.signal?.throwIfAborted();\n\n const previousBlocks = prevState ? Object.fromEntries(Object.entries(prevState.documents).map(([k, v]) => [k, v.blocks])) : undefined;\n const plans = await planKnowledge(dir, analysis.model, { force: opts.force, previousBlocks });\n\n const nextIndex = buildFileIndex(analysis.files);\n const prevIndex = prevState?.fileIndex ?? {};\n const rawDiff = diffFileIndex(prevIndex, nextIndex);\n // Agent integration files that Athena manages are tracked by state; don't report them as developer changes.\n const managed = new Set(Object.values(prevState?.agents ?? {}).flatMap((a) => a.files));\n const idxChanges = { added: rawDiff.added.filter((p) => !managed.has(p)), modified: rawDiff.modified.filter((p) => !managed.has(p)), deleted: rawDiff.deleted.filter((p) => !managed.has(p)) };\n const renames = detectRenames(prevIndex, nextIndex, idxChanges.added, idxChanges.deleted);\n const fileChanges: FileChanges = { ...renames, modified: idxChanges.modified };\n\n const modelChanges = diffModels(prevModel, analysis.model);\n const allPaths = [...fileChanges.added, ...fileChanges.modified, ...fileChanges.deleted, ...fileChanges.renamed.flatMap((r) => [r.from, r.to])];\n const pathImpact = impactOf(allPaths, { structural: [...fileChanges.added, ...fileChanges.deleted, ...fileChanges.renamed.map((r) => r.to)] });\n\n const documents: ProposedDocument[] = [];\n for (const p of plans) {\n if (p.status === 'unchanged') continue;\n const doc = KNOWLEDGE_DOCS.find((d) => d.id === p.id)!;\n const reasons = [\n ...modelChanges.filter((c) => c.docs.includes(p.id)).map((c) => `${c.label}: ${c.summary}`),\n ...(pathImpact.reasons[p.id] ?? []).map((r) => `Changed files (${r})`),\n ];\n if (p.status === 'created') reasons.unshift('Document is missing and will be recreated');\n if (!reasons.length) reasons.push('Rendered content differs from the file on disk (for example after an Athena upgrade or a manual edit outside sections)');\n let patch = createTwoFilesPatch(`a/.athena/${p.file}`, `b/.athena/${p.file}`, p.before ?? '', p.after, undefined, undefined, { context: 3 });\n const counts = countLines(patch);\n const diffTruncated = patch.length > MAX_DIFF_CHARS;\n if (diffTruncated) patch = `${patch.slice(0, MAX_DIFF_CHARS)}\\n… diff truncated …\\n`;\n documents.push({\n id: p.id,\n file: p.file,\n title: doc.title,\n status: p.status,\n reasons: [...new Set(reasons)],\n changedSections: p.changedBlocks,\n preservedSections: p.preservedModified,\n diff: patch,\n diffTruncated,\n ...counts,\n baseHash: hashOf(p.before),\n });\n }\n\n const git: GitMovement = {\n isRepo: analysis.model.git.isRepo,\n previousHead: prevState?.git.head ?? null,\n head: analysis.model.git.head ?? null,\n previousBranch: prevState?.git.branch ?? null,\n branch: analysis.model.git.branch ?? null,\n branchChanged: Boolean(prevState?.git.branch && analysis.model.git.branch && prevState.git.branch !== analysis.model.git.branch),\n commits: [],\n diverged: false,\n truncated: false,\n };\n if (git.isRepo && git.previousHead && git.head && git.previousHead !== git.head) {\n const mv = await headMovement(root, git.previousHead, git.head);\n if (mv) Object.assign(git, { commits: mv.commits, diverged: mv.diverged, truncated: mv.truncated });\n }\n\n const id = sha256(JSON.stringify(documents.map((d) => [d.file, d.baseHash, hashOf(plans.find((p) => p.id === d.id)!.after)]))).slice(0, 16);\n const upToDate = documents.length === 0;\n const plan: SyncPlan = {\n id,\n createdAt: new Date().toISOString(),\n previousAnalysisAt: prevState?.analyzedAt ?? null,\n upToDate,\n fileChanges,\n git,\n modelChanges: prevModel ? modelChanges : [],\n documents,\n checkedUnchanged: pathImpact.docs.map((d) => KNOWLEDGE_DOCS.find((k) => k.id === d)!.file).filter((f) => !documents.some((d) => d.file === f)),\n ignored: !upToDate && (await readIgnored(dir)) === id,\n durationMs: Date.now() - started,\n warnings,\n };\n internals.set(plan, { analysis, plans, prevState });\n return plan;\n}\n\nexport interface ApplyResult {\n applied: string[];\n preserved: Array<{ file: string; sections: string[] }>;\n analyzedAt: string;\n}\n\n/**\n * Apply a plan produced by planSync. Refuses (409) if any affected document changed\n * on disk after the plan was made. Always refreshes the file index and model so\n * the project is marked synchronized.\n */\nexport async function applySync(root: string, plan: SyncPlan): Promise<ApplyResult> {\n const inner = internals.get(plan);\n if (!inner) throw new AthenaError('This sync plan is no longer available.', 'Create a new plan and try again.', 1, 'conflict');\n const dir = athenaDir(root);\n\n for (const d of plan.documents) {\n const current = hashOf(await readTextIfExists(path.join(dir, d.file)));\n if (current !== d.baseHash) {\n throw conflict(`${d.file} changed after the sync plan was created.`, 'Review the new plan before applying.', { file: d.file });\n }\n }\n\n const st = await readState(dir);\n if (st.kind === 'corrupted') await backupCorruptedState(dir);\n const prevState = st.kind === 'ok' ? st.state : inner.prevState;\n\n await fs.mkdir(dir, { recursive: true });\n const docs = await writePlannedKnowledge(dir, inner.plans);\n docs.push(await ensureRules(dir, inner.analysis.model));\n await writeFileAtomic(path.join(dir, 'model.json'), `${JSON.stringify(inner.analysis.model, null, 2)}\\n`);\n const managedFiles = Object.values(prevState?.agents ?? {}).flatMap((a) => a.files);\n const state = composeState({\n prevState,\n analysis: inner.analysis,\n docs,\n agents: prevState?.agents ?? {},\n fileIndex: await indexWithIntegrations(root, inner.analysis.files, managedFiles),\n });\n await writeState(dir, state);\n await fs.rm(path.join(dir, IGNORE_FILE), { force: true });\n internals.delete(plan);\n return {\n applied: plan.documents.map((d) => d.file),\n preserved: plan.documents.filter((d) => d.preservedSections.length).map((d) => ({ file: d.file, sections: d.preservedSections })),\n analyzedAt: state.analyzedAt,\n };\n}\n\n/** Remember that the developer dismissed this exact proposal; it resurfaces once content changes again. */\nexport async function ignorePlan(root: string, planId: string): Promise<void> {\n if (!/^[a-f0-9]{16}$/.test(planId)) throw new AthenaError('Invalid plan id');\n await writeFileAtomic(path.join(athenaDir(root), IGNORE_FILE), `${JSON.stringify({ planId, ignoredAt: new Date().toISOString() }, null, 2)}\\n`);\n}\n\nexport function fileChangeCount(plan: SyncPlan): number {\n const c = plan.fileChanges;\n return c.added.length + c.modified.length + c.deleted.length + c.renamed.length;\n}\n\n/** True when files changed but no knowledge document needs updating: only the index/model need refreshing. */\nexport function needsIndexRefreshOnly(plan: SyncPlan): boolean {\n return plan.upToDate && (fileChangeCount(plan) > 0 || plan.git.head !== plan.git.previousHead);\n}\n\nexport function summarizePlan(plan: SyncPlan) {\n const { documents, ...rest } = plan;\n return { ...rest, documents: documents.map(({ diff: _diff, ...d }) => d) };\n}\n","import type { DocId } from '../knowledge/documents.js';\nimport type { ProjectModel } from '../model/project-model.js';\n\n/**\n * Semantic impact: which parts of the structured project model changed between two\n * analyses, and which knowledge documents consume those parts. This complements the\n * path heuristics in impact.ts with evidence (\"2 routes added\") instead of guesses.\n */\n\ntype Key = keyof ProjectModel;\n\ninterface SectionSpec {\n label: string;\n keys: Key[];\n docs: DocId[];\n /** Identity of an array item, for added/removed summaries. */\n identity?: (item: Record<string, unknown>) => string;\n /** Human label for an item in summaries (defaults to identity). */\n display?: (item: Record<string, unknown>) => string;\n unit?: [singular: string, plural: string];\n}\n\nconst named = (i: Record<string, unknown>) => String(i.name ?? i.path ?? JSON.stringify(i));\n\nexport const MODEL_SECTIONS: SectionSpec[] = [\n { label: 'Project identity', keys: ['name', 'description'], docs: ['project'] },\n { label: 'Languages', keys: ['languages'], docs: ['project'], identity: named, unit: ['language', 'languages'] },\n { label: 'Project structure', keys: ['topLevelDirs', 'stats'], docs: ['project'] },\n { label: 'Dependencies & manifests', keys: ['manifests'], docs: ['project', 'security'], identity: (i) => String(i.path), unit: ['manifest', 'manifests'] },\n { label: 'Package managers & build tools', keys: ['packageManagers', 'buildSystems'], docs: ['project'], identity: named, unit: ['tool', 'tools'] },\n { label: 'Workspace packages', keys: ['workspace'], docs: ['project', 'architecture', 'code-review', 'testing'] },\n { label: 'Frameworks', keys: ['frameworks'], docs: ['project', 'architecture', 'api', 'security', 'code-review', 'performance'], identity: (i) => `${i.name}@${i.root}`, display: (i) => String(i.name), unit: ['framework', 'frameworks'] },\n { label: 'Entry points', keys: ['entryPoints'], docs: ['project'], identity: (i) => String(i.path), unit: ['entry point', 'entry points'] },\n { label: 'Commands', keys: ['commands'], docs: ['project', 'testing', 'debugging', 'deployment', 'code-review', 'database'], identity: (i) => `${i.source}:${i.name}`, display: (i) => String(i.name), unit: ['command', 'commands'] },\n { label: 'Database technology', keys: ['databases'], docs: ['database', 'architecture', 'security', 'code-review', 'performance'], identity: named, unit: ['technology', 'technologies'] },\n { label: 'Database schema', keys: ['dbEntities'], docs: ['database', 'auth', 'performance'], identity: (i) => `${i.name}@${i.file}`, display: (i) => String(i.name), unit: ['entity', 'entities'] },\n { label: 'Migrations', keys: ['migrations'], docs: ['database', 'deployment'], identity: (i) => `${i.tool}:${i.path}`, display: (i) => String(i.path), unit: ['migration directory', 'migration directories'] },\n { label: 'API routes', keys: ['routes'], docs: ['api', 'security', 'testing', 'code-review'], identity: (i) => `${i.method} ${i.path} ${i.file}`, display: (i) => `${i.method} ${i.path}`, unit: ['route', 'routes'] },\n { label: 'API specifications', keys: ['apiSpecs'], docs: ['api', 'security'], identity: (i) => String(i.path), unit: ['spec', 'specs'] },\n { label: 'Authentication', keys: ['auth'], docs: ['auth', 'security', 'architecture'], identity: named, unit: ['auth signal', 'auth signals'] },\n { label: 'Containers', keys: ['containers'], docs: ['deployment', 'architecture', 'security'] },\n { label: 'Infrastructure', keys: ['infrastructure'], docs: ['deployment', 'architecture'], identity: (i) => `${i.name}@${i.file}`, display: (i) => String(i.name), unit: ['resource', 'resources'] },\n { label: 'CI/CD', keys: ['ci'], docs: ['deployment'], identity: (i) => `${i.system}:${i.file}:${i.name}`, unit: ['CI job', 'CI jobs'] },\n { label: 'Tests', keys: ['tests'], docs: ['testing', 'code-review'] },\n { label: 'Environment variables', keys: ['env'], docs: ['deployment', 'project', 'security'] },\n { label: 'Security findings & controls', keys: ['security'], docs: ['security'] },\n { label: 'Caching & queues', keys: ['caching', 'queues'], docs: ['performance', 'architecture', 'security'], identity: named, unit: ['technology', 'technologies'] },\n { label: 'Observability', keys: ['observability'], docs: ['debugging', 'architecture'], identity: named, unit: ['tool', 'tools'] },\n { label: 'Git hotspots', keys: ['git'], docs: ['debugging'] },\n { label: 'Analysis warnings', keys: ['warnings'], docs: ['project'] },\n];\n\nexport interface ModelChange {\n label: string;\n summary: string;\n docs: DocId[];\n}\n\nfunction stable(v: unknown): string {\n return JSON.stringify(v, (_k, val: unknown) => (val && typeof val === 'object' && !Array.isArray(val) ? Object.fromEntries(Object.entries(val as Record<string, unknown>).sort(([a], [b]) => a.localeCompare(b))) : val));\n}\n\n/** Git fields that change on every commit and don't affect rendered knowledge. */\nfunction normalize(key: Key, value: unknown): unknown {\n if (key === 'git' && value && typeof value === 'object') return { hotspots: (value as ProjectModel['git']).hotspots };\n if (key === 'root') return null;\n return value;\n}\n\nexport function diffModels(prev: ProjectModel | null, next: ProjectModel): ModelChange[] {\n if (!prev) return [{ label: 'Previous analysis', summary: 'no previous model.json to compare against — full comparison of rendered documents used', docs: [] }];\n const changes: ModelChange[] = [];\n for (const spec of MODEL_SECTIONS) {\n const differing = spec.keys.filter((k) => stable(normalize(k, prev[k])) !== stable(normalize(k, next[k])));\n if (!differing.length) continue;\n const parts: string[] = [];\n for (const k of differing) {\n const a = prev[k];\n const b = next[k];\n if (Array.isArray(a) && Array.isArray(b) && spec.identity) {\n const labels = new Map<string, string>();\n const ids = (xs: unknown[]) =>\n new Map(\n xs.map((x) => {\n const item = x as Record<string, unknown>;\n const id = spec.identity!(item);\n labels.set(id, (spec.display ?? spec.identity)!(item));\n return [id, stable(x)];\n }),\n );\n const ma = ids(a);\n const mb = ids(b);\n const show = (xs: string[]) => [...new Set(xs.map((x) => labels.get(x) ?? x))];\n const added = show([...mb.keys()].filter((x) => !ma.has(x)));\n const removed = show([...ma.keys()].filter((x) => !mb.has(x)));\n const changed = show([...mb.keys()].filter((x) => ma.has(x) && ma.get(x) !== mb.get(x)));\n const [one, many] = spec.unit ?? ['item', 'items'];\n const fmt = (n: number, verb: string, list: string[]) => (n ? `${n} ${n === 1 ? one : many} ${verb}${list.length <= 3 ? ` (${list.join(', ')})` : ''}` : '');\n parts.push(...[fmt(added.length, 'added', added), fmt(removed.length, 'removed', removed), fmt(changed.length, 'changed', changed)].filter(Boolean));\n } else if (k === 'stats') {\n const sa = a as ProjectModel['stats'];\n const sb = b as ProjectModel['stats'];\n if (sa.filesScanned !== sb.filesScanned) parts.push(`files analyzed ${sa.filesScanned} → ${sb.filesScanned}`);\n else parts.push('file statistics changed');\n } else {\n parts.push(describeObjectChange(k, a, b));\n }\n }\n changes.push({ label: spec.label, summary: parts.join('; ') || 'changed', docs: spec.docs });\n }\n return changes;\n}\n\nfunction names(xs: Array<{ name: string }>): Set<string> {\n return new Set(xs.map((x) => x.name));\n}\n\nfunction setDelta(label: string, a: Set<string>, b: Set<string>): string[] {\n const added = [...b].filter((x) => !a.has(x));\n const removed = [...a].filter((x) => !b.has(x));\n const out: string[] = [];\n const list = (xs: string[]) => (xs.length <= 3 ? ` (${xs.join(', ')})` : '');\n if (added.length) out.push(`${added.length} ${label} added${list(added)}`);\n if (removed.length) out.push(`${removed.length} ${label} removed${list(removed)}`);\n return out;\n}\n\nfunction describeObjectChange(key: Key, a: unknown, b: unknown): string {\n const parts: string[] = [];\n switch (key) {\n case 'env': {\n const ea = a as ProjectModel['env'];\n const eb = b as ProjectModel['env'];\n parts.push(...setDelta('variable name(s)', names(ea.vars), names(eb.vars)));\n parts.push(...setDelta('env file(s)', new Set(ea.envFilesPresent), new Set(eb.envFilesPresent)));\n if (!parts.length) parts.push('variable references moved');\n break;\n }\n case 'security': {\n const sa = a as ProjectModel['security'];\n const sb = b as ProjectModel['security'];\n if (sa.secrets.length !== sb.secrets.length) parts.push(`potential secrets ${sa.secrets.length} → ${sb.secrets.length}`);\n parts.push(...setDelta('control(s)', names(sa.controls), names(sb.controls)));\n parts.push(...setDelta('tool(s)', names(sa.tooling), names(sb.tooling)));\n if (!parts.length) parts.push('evidence locations changed');\n break;\n }\n case 'tests': {\n const ta = a as ProjectModel['tests'];\n const tb = b as ProjectModel['tests'];\n if (ta.testFileCount !== tb.testFileCount) parts.push(`test files ${ta.testFileCount} → ${tb.testFileCount}`);\n parts.push(...setDelta('framework(s)', names(ta.frameworks), names(tb.frameworks)));\n if (!parts.length) parts.push('test layout changed');\n break;\n }\n case 'containers': {\n const ca = a as ProjectModel['containers'];\n const cb = b as ProjectModel['containers'];\n parts.push(...setDelta('Dockerfile(s)', new Set(ca.dockerfiles.map((d) => d.path)), new Set(cb.dockerfiles.map((d) => d.path))));\n parts.push(...setDelta('service(s)', names(ca.services), names(cb.services)));\n if (!parts.length) parts.push('container configuration changed');\n break;\n }\n case 'workspace': {\n const wa = a as ProjectModel['workspace'];\n const wb = b as ProjectModel['workspace'];\n parts.push(...setDelta('package(s)', names(wa.packages), names(wb.packages)));\n if (!parts.length) parts.push('package dependencies changed');\n break;\n }\n case 'topLevelDirs':\n parts.push(...setDelta('top-level director(ies)', new Set(a as string[]), new Set(b as string[])));\n break;\n case 'git':\n parts.push('change hotspots updated from recent commits');\n break;\n case 'name':\n case 'description':\n parts.push(`${key} changed`);\n break;\n default:\n parts.push(`${String(key)} changed`);\n }\n return parts.join('; ');\n}\n","import { execFile } from 'node:child_process';\nimport { ProjectModel } from '../core/model/project-model.js';\nimport { SEVERITY_ORDER, type SecurityScan, type Severity, type ToolResult, type Vulnerability } from '../core/model/security-scan.js';\nimport { whichExecutable } from './which.js';\n\nexport { loadScan, saveScan, totalFindings, meetsThreshold, SCAN_FILE, SEVERITY_ORDER } from '../core/model/security-scan.js';\nexport type { SecurityScan, Severity, ToolResult, Vulnerability } from '../core/model/security-scan.js';\n\ninterface Runner {\n tool: string;\n ecosystem: string;\n command: string;\n args: string[];\n /** Run only when this returns true for the project. */\n applies(model: ProjectModel, has: (file: string) => boolean): boolean;\n parse(stdout: string, stderr: string): Vulnerability[];\n}\n\nconst asRecord = (v: unknown): Record<string, unknown> => (v && typeof v === 'object' ? (v as Record<string, unknown>) : {});\nconst sev = (s: unknown): Severity => {\n const v = String(s ?? '').toLowerCase();\n if (v === 'critical') return 'critical';\n if (v === 'high') return 'high';\n if (v === 'moderate' || v === 'medium') return 'moderate';\n if (v === 'low') return 'low';\n return 'unknown';\n};\n\nfunction parseNpmAudit(stdout: string): Vulnerability[] {\n const json = JSON.parse(stdout) as Record<string, unknown>;\n const vulns = asRecord(json.vulnerabilities);\n const out: Vulnerability[] = [];\n for (const [name, raw] of Object.entries(vulns)) {\n const v = asRecord(raw);\n const via = Array.isArray(v.via) ? v.via : [];\n const advisory = via.find((x) => x && typeof x === 'object') as Record<string, unknown> | undefined;\n out.push({\n package: name,\n severity: sev(v.severity),\n title: String(advisory?.title ?? `Vulnerable dependency: ${name}`),\n id: advisory?.source !== undefined ? String(advisory.source) : undefined,\n url: typeof advisory?.url === 'string' ? advisory.url : undefined,\n vulnerableRange: typeof v.range === 'string' ? v.range : undefined,\n fixAvailable: Boolean(v.fixAvailable),\n });\n }\n return out;\n}\n\nfunction parsePipAudit(stdout: string): Vulnerability[] {\n const json = JSON.parse(stdout) as Record<string, unknown>;\n const deps = Array.isArray(json.dependencies) ? json.dependencies : Array.isArray(json) ? json : [];\n const out: Vulnerability[] = [];\n for (const raw of deps) {\n const d = asRecord(raw);\n for (const vRaw of Array.isArray(d.vulns) ? d.vulns : []) {\n const v = asRecord(vRaw);\n out.push({\n package: String(d.name ?? 'unknown'),\n severity: 'unknown', // pip-audit does not report severity\n title: String(v.description ?? v.id ?? 'Known vulnerability'),\n id: typeof v.id === 'string' ? v.id : undefined,\n vulnerableRange: typeof d.version === 'string' ? `installed ${d.version}` : undefined,\n fixAvailable: Array.isArray(v.fix_versions) && v.fix_versions.length > 0,\n });\n }\n }\n return out;\n}\n\nfunction parseGovulncheck(stdout: string): Vulnerability[] {\n const out = new Map<string, Vulnerability>();\n for (const line of stdout.split('\\n')) {\n if (!line.trim().startsWith('{')) continue;\n try {\n const msg = asRecord(JSON.parse(line));\n const finding = asRecord(msg.finding);\n const osv = asRecord(msg.osv);\n if (typeof osv.id === 'string') {\n out.set(osv.id, {\n package: String(asRecord(asRecord(osv.affected?.[0 as keyof typeof osv.affected]).package).name ?? 'unknown'),\n severity: 'unknown',\n title: String(osv.summary ?? osv.id),\n id: osv.id,\n url: `https://pkg.go.dev/vuln/${osv.id}`,\n });\n }\n if (typeof finding.osv === 'string' && out.has(finding.osv)) {\n const trace = Array.isArray(finding.trace) ? asRecord(finding.trace[0]) : {};\n const pkg = typeof trace.module === 'string' ? trace.module : undefined;\n if (pkg) out.set(finding.osv, { ...out.get(finding.osv)!, package: pkg });\n }\n } catch {\n /* skip non-JSON lines */\n }\n }\n return [...out.values()];\n}\n\nfunction parseCargoAudit(stdout: string): Vulnerability[] {\n const json = asRecord(JSON.parse(stdout));\n const list = Array.isArray(asRecord(json.vulnerabilities).list) ? (asRecord(json.vulnerabilities).list as unknown[]) : [];\n return list.map((raw) => {\n const v = asRecord(raw);\n const advisory = asRecord(v.advisory);\n const pkg = asRecord(v.package);\n return {\n package: String(pkg.name ?? 'unknown'),\n severity: sev(asRecord(advisory.cvss).severity ?? advisory.severity),\n title: String(advisory.title ?? 'Known vulnerability'),\n id: typeof advisory.id === 'string' ? advisory.id : undefined,\n url: typeof advisory.url === 'string' ? advisory.url : undefined,\n };\n });\n}\n\nfunction parseComposerAudit(stdout: string): Vulnerability[] {\n const json = asRecord(JSON.parse(stdout));\n const advisories = asRecord(json.advisories);\n const out: Vulnerability[] = [];\n for (const [pkg, raw] of Object.entries(advisories)) {\n for (const aRaw of Array.isArray(raw) ? raw : []) {\n const a = asRecord(aRaw);\n out.push({\n package: pkg,\n severity: sev(a.severity),\n title: String(a.title ?? 'Known vulnerability'),\n id: typeof a.cve === 'string' ? a.cve : typeof a.advisoryId === 'string' ? a.advisoryId : undefined,\n url: typeof a.link === 'string' ? a.link : undefined,\n vulnerableRange: typeof a.affectedVersions === 'string' ? a.affectedVersions : undefined,\n });\n }\n }\n return out;\n}\n\nexport const RUNNERS: Runner[] = [\n {\n tool: 'npm audit',\n ecosystem: 'npm',\n command: 'npm',\n args: ['audit', '--json', '--audit-level=low'],\n applies: (_m, has) => has('package-lock.json') || has('npm-shrinkwrap.json'),\n parse: parseNpmAudit,\n },\n {\n tool: 'pnpm audit',\n ecosystem: 'npm',\n command: 'pnpm',\n args: ['audit', '--json'],\n applies: (_m, has) => has('pnpm-lock.yaml'),\n parse: parseNpmAudit,\n },\n {\n tool: 'pip-audit',\n ecosystem: 'python',\n command: 'pip-audit',\n args: ['--format=json', '--progress-spinner=off'],\n applies: (m) => m.manifests.some((x) => x.ecosystem === 'python'),\n parse: parsePipAudit,\n },\n {\n tool: 'govulncheck',\n ecosystem: 'go',\n command: 'govulncheck',\n args: ['-format=json', './...'],\n applies: (_m, has) => has('go.mod'),\n parse: parseGovulncheck,\n },\n {\n tool: 'cargo audit',\n ecosystem: 'cargo',\n command: 'cargo',\n args: ['audit', '--json'],\n applies: (_m, has) => has('Cargo.lock'),\n parse: parseCargoAudit,\n },\n {\n tool: 'composer audit',\n ecosystem: 'composer',\n command: 'composer',\n args: ['audit', '--format=json'],\n applies: (_m, has) => has('composer.lock'),\n parse: parseComposerAudit,\n },\n];\n\nfunction run(command: string, args: string[], cwd: string, timeoutMs: number): Promise<{ stdout: string; stderr: string; timedOut: boolean; error: Error | null }> {\n return new Promise((resolve) => {\n execFile(command, args, { cwd, timeout: timeoutMs, maxBuffer: 32 * 1024 * 1024, windowsHide: true, env: { ...process.env, NO_COLOR: '1', npm_config_color: 'false' } }, (error, stdout, stderr) => {\n const timedOut = Boolean(error && (error as NodeJS.ErrnoException).code === 'ETIMEDOUT');\n resolve({ stdout: String(stdout ?? ''), stderr: String(stderr ?? ''), timedOut, error: error ?? null });\n });\n });\n}\n\nexport interface ScanOptions {\n signal?: AbortSignal;\n /** Per-tool timeout. */\n timeoutMs?: number;\n /** Skip dependency audits (secrets only). */\n skipAudit?: boolean;\n onTool?: (tool: string) => void;\n}\n\n/**\n * Run the audit tools the project's ecosystems provide. Athena never bundles a\n * vulnerability database: findings are attributed to the tool that produced them,\n * and a missing tool is reported as \"not installed\" rather than \"no problems\".\n */\nexport async function runSecurityScan(root: string, model: ProjectModel, opts: ScanOptions = {}): Promise<SecurityScan> {\n const started = Date.now();\n const timeoutMs = opts.timeoutMs ?? 120_000;\n const files = new Set(model.manifests.map((m) => m.path));\n for (const pm of model.packageManagers) for (const e of pm.provenance.evidence) files.add(e.file);\n const has = (file: string) => files.has(file);\n\n const tools: ToolResult[] = [];\n if (!opts.skipAudit) {\n for (const runner of RUNNERS) {\n if (!runner.applies(model, has)) continue;\n opts.signal?.throwIfAborted();\n const t = Date.now();\n opts.onTool?.(runner.tool);\n const bin = await whichExecutable(runner.command);\n if (!bin) {\n tools.push({ tool: runner.tool, ecosystem: runner.ecosystem, status: 'unavailable', message: `${runner.command} is not installed or not on PATH`, durationMs: Date.now() - t, findings: [] });\n continue;\n }\n const r = await run(runner.command, runner.args, root, timeoutMs);\n if (r.timedOut) {\n tools.push({ tool: runner.tool, ecosystem: runner.ecosystem, status: 'timeout', message: `Timed out after ${timeoutMs / 1000}s`, durationMs: Date.now() - t, findings: [] });\n continue;\n }\n try {\n // Audit tools exit non-zero when they find something; parse output regardless.\n const findings = runner.parse(r.stdout, r.stderr);\n tools.push({ tool: runner.tool, ecosystem: runner.ecosystem, status: 'ok', durationMs: Date.now() - t, findings });\n } catch {\n const reason = r.stderr.trim().split('\\n')[0] ?? r.error?.message ?? 'unreadable output';\n tools.push({ tool: runner.tool, ecosystem: runner.ecosystem, status: 'failed', message: `Could not parse output: ${reason.slice(0, 200)}`, durationMs: Date.now() - t, findings: [] });\n }\n }\n }\n\n const counts: Record<Severity, number> = { critical: 0, high: 0, moderate: 0, low: 0, unknown: 0 };\n for (const t of tools) for (const f of t.findings) counts[f.severity]++;\n\n const scan: SecurityScan = {\n schemaVersion: 1,\n scannedAt: new Date().toISOString(),\n durationMs: Date.now() - started,\n tools,\n counts,\n secrets: { count: model.security.secrets.length, files: [...new Set(model.security.secrets.map((s) => s.file))].slice(0, 50) },\n };\n return scan;\n}\n\n","import path from 'node:path';\nimport { changesSince, git, isSafeRef, workingChanges, type ChangedFile } from '../core/git/git.js';\nimport { listRules, parseRules, type Rule } from '../core/knowledge/rules.js';\nimport { scanText } from '../core/security/secrets.js';\nimport { athenaDir } from '../core/state/state.js';\nimport { readTextIfExists } from '../core/util/fs.js';\nimport { AthenaError } from './errors.js';\nimport { loadScan } from '../core/model/security-scan.js';\n\nexport type FindingLevel = 'blocker' | 'warning' | 'info';\n\nexport interface ReviewFinding {\n level: FindingLevel;\n check: string;\n message: string;\n files: string[];\n hint?: string;\n}\n\nexport interface ReviewResult {\n base: string;\n changedFiles: ChangedFile[];\n findings: ReviewFinding[];\n /** Enabled rules from rules.md — a checklist for the human or agent, not automated. */\n rules: Rule[];\n checklist: string[];\n knowledgeInSync: boolean | null;\n stats: { added: number; removed: number; files: number };\n}\n\nconst TEST_FILE = /(^|\\/)(__tests__|tests?|spec|specs|e2e)\\/|\\.(test|spec|e2e)\\.[cm]?[jt]sx?$|(^|\\/)test_[^/]+\\.py$|_test\\.(py|go|exs)$|_spec\\.rb$|Tests?\\.(java|kt|cs)$/;\nconst SOURCE_FILE = /\\.(m|c)?(t|j)sx?$|\\.(py|go|rs|java|kt|cs|php|rb|dart|ex|swift|vue|svelte)$/;\nconst ROUTE_FILE = /(^|\\/)(routes?|controllers?|handlers?|api|endpoints?|resolvers?)\\/|(^|\\/)(urls\\.py|routes\\.rb)$|(^|\\/)app\\/(.+\\/)?route\\.(t|j)sx?$/i;\nconst SCHEMA_FILE = /\\.prisma$|\\.sql$|(^|\\/)(migrations?|migrate|alembic)\\/|(^|\\/)models(\\.py|\\/)/i;\nconst AUTH_FILE = /(auth|session|login|oauth|jwt|guard|permission|rbac|acl|polic(y|ies)|middleware)/i;\nconst ENV_FILE = /(^|\\/)\\.env(\\.(local|production|development|prod|dev|staging))?$/;\nconst MANIFEST_FILE = /(^|\\/)(package\\.json|pyproject\\.toml|requirements[^/]*\\.txt|go\\.mod|Cargo\\.toml|composer\\.json|Gemfile|pubspec\\.yaml|pom\\.xml|build\\.gradle(\\.kts)?)$/;\nconst LARGE_ADDED_BYTES = 512 * 1024;\n\n/** Added lines from a unified diff (content only, no metadata). */\nfunction addedLines(patch: string): Array<{ file: string; line: number; text: string }> {\n const out: Array<{ file: string; line: number; text: string }> = [];\n let file = '';\n let lineNo = 0;\n for (const raw of patch.split('\\n')) {\n if (raw.startsWith('+++ b/')) {\n file = raw.slice(6);\n continue;\n }\n const h = /^@@ -\\d+(?:,\\d+)? \\+(\\d+)(?:,\\d+)? @@/.exec(raw);\n if (h) {\n lineNo = Number(h[1]);\n continue;\n }\n if (raw.startsWith('+') && !raw.startsWith('+++')) {\n out.push({ file, line: lineNo++, text: raw.slice(1) });\n } else if (!raw.startsWith('-') && !raw.startsWith('\\\\')) lineNo++;\n }\n return out;\n}\n\nfunction depsOf(manifest: string, text: string): Set<string> {\n const names = new Set<string>();\n try {\n if (manifest.endsWith('package.json')) {\n const j = JSON.parse(text) as Record<string, unknown>;\n for (const key of ['dependencies', 'devDependencies', 'peerDependencies']) {\n const deps = j[key];\n if (deps && typeof deps === 'object') for (const n of Object.keys(deps)) names.add(n);\n }\n return names;\n }\n } catch {\n return names;\n }\n for (const m of text.matchAll(/^\\s*[\"']?([A-Za-z0-9._@/-]+)[\"']?\\s*[=:><~^]/gm)) names.add(m[1]!);\n return names;\n}\n\nexport interface ReviewOptions {\n /** Git ref to compare against; default: working tree vs HEAD. */\n base?: string;\n signal?: AbortSignal;\n /** Whether knowledge sync state should be checked (can be slow). */\n checkSync?: (root: string) => Promise<boolean>;\n}\n\n/**\n * Deterministic pre-review of the current change. Athena runs no AI here: every\n * finding is a fact about the diff. The project's own rules and review checklist\n * are listed for the human (or agent) to apply.\n */\nexport async function reviewChanges(root: string, opts: ReviewOptions = {}): Promise<ReviewResult> {\n const isRepo = (await git(root, ['rev-parse', '--is-inside-work-tree'])).stdout.trim() === 'true';\n if (!isRepo) throw new AthenaError('`athena review` needs a Git repository.', 'Initialize Git, or review changes manually.');\n\n const base = opts.base ?? 'HEAD';\n if (opts.base && !isSafeRef(opts.base)) throw new AthenaError(`Invalid base ref: ${opts.base}`);\n\n const changed = opts.base ? await changesSince(root, opts.base).catch(() => null) : await workingChanges(root);\n const changedFiles = (changed ?? []).filter((f) => !f.path.startsWith('.athena/'));\n\n const diffArgs = opts.base ? ['diff', '-M', `${opts.base}...HEAD`] : ['diff', 'HEAD'];\n const patch = (await git(root, [...diffArgs, '--', '.'])).stdout;\n const untracked = changedFiles.filter((f) => f.status === 'untracked');\n let extra = '';\n for (const f of untracked.slice(0, 200)) {\n const text = await readTextIfExists(path.join(root, f.path));\n if (text && text.length < 512 * 1024) extra += `+++ b/${f.path}\\n@@ -0,0 +1,${text.split('\\n').length} @@\\n${text.split('\\n').map((l) => `+${l}`).join('\\n')}\\n`;\n }\n const added = addedLines(patch + extra);\n // Untracked files never appear in git numstat; count their lines as additions.\n let untrackedAdded = 0;\n for (const f of untracked) {\n const text = await readTextIfExists(path.join(root, f.path));\n if (text) untrackedAdded += text.split('\\n').filter((l) => l.length > 0).length;\n }\n const numstat = (await git(root, [...diffArgs, '--numstat', '--', '.'])).stdout;\n let addedCount = 0;\n let removedCount = 0;\n for (const line of numstat.split('\\n')) {\n const [a, r] = line.split('\\t');\n if (a && r && a !== '-' ) {\n addedCount += Number(a) || 0;\n removedCount += Number(r) || 0;\n }\n }\n\n const findings: ReviewFinding[] = [];\n const paths = changedFiles.map((f) => f.path);\n const add = (f: ReviewFinding) => findings.push(f);\n\n // 1. Secrets in added lines — the only blocker Athena raises on its own.\n const secretHits = new Map<string, Set<string>>();\n for (const l of added) {\n for (const m of scanText(l.text)) {\n const key = `${m.type}`;\n if (!secretHits.has(key)) secretHits.set(key, new Set());\n secretHits.get(key)!.add(`${l.file}:${l.line}`);\n }\n }\n for (const [type, locations] of secretHits) {\n add({ level: 'blocker', check: 'secrets', message: `Possible ${type} added`, files: [...locations].slice(0, 10), hint: 'Remove the value, use an environment variable, and rotate the credential if it was real.' });\n }\n\n // 2. Env files\n const envFiles = paths.filter((p) => ENV_FILE.test(p));\n if (envFiles.length) add({ level: 'blocker', check: 'env-file', message: 'Environment file included in the change', files: envFiles, hint: 'Add it to .gitignore and commit a .env.example with names only.' });\n\n // 3. New dependencies\n for (const p of paths.filter((x) => MANIFEST_FILE.test(x))) {\n const now = await readTextIfExists(path.join(root, p));\n const before = (await git(root, ['show', `${opts.base ?? 'HEAD'}:${p}`])).stdout;\n if (!now || !before) continue;\n const newDeps = [...depsOf(p, now)].filter((d) => !depsOf(p, before).has(d));\n if (newDeps.length) add({ level: 'info', check: 'dependencies', message: `New dependencies: ${newDeps.slice(0, 10).join(', ')}${newDeps.length > 10 ? ` +${newDeps.length - 10}` : ''}`, files: [p], hint: 'Justify each addition; check licence, maintenance and size.' });\n }\n\n // 4. Source without tests (structural only)\n const changedSource = paths.filter((p) => SOURCE_FILE.test(p) && !TEST_FILE.test(p));\n const changedTests = paths.filter((p) => TEST_FILE.test(p));\n if (changedSource.length && !changedTests.length) {\n add({ level: 'warning', check: 'tests', message: `${changedSource.length} source file(s) changed with no test file changes`, files: changedSource.slice(0, 10), hint: 'See `.athena/testing.md` for the project test commands and layout.' });\n }\n\n // 5. Routes / schema / auth touchpoints\n const routeFiles = changedSource.filter((p) => ROUTE_FILE.test(p));\n if (routeFiles.length) add({ level: 'info', check: 'api', message: 'API surface changed', files: routeFiles.slice(0, 10), hint: 'Check auth/authorization and error handling (`.athena/api.md`, `.athena/auth.md`).' });\n const schemaFiles = paths.filter((p) => SCHEMA_FILE.test(p));\n if (schemaFiles.length) add({ level: 'info', check: 'database', message: 'Database schema or migrations changed', files: schemaFiles.slice(0, 10), hint: 'Check indexes, constraints and backward compatibility (`.athena/database.md`).' });\n const authFiles = changedSource.filter((p) => AUTH_FILE.test(p));\n if (authFiles.length) add({ level: 'warning', check: 'auth', message: 'Authentication/authorization code changed', files: authFiles.slice(0, 10), hint: 'Review against `.athena/auth.md` and `.athena/security.md`.' });\n\n // 6. Large added files\n const large: string[] = [];\n for (const f of changedFiles.filter((x) => x.status === 'added' || x.status === 'untracked')) {\n const text = await readTextIfExists(path.join(root, f.path)).catch(() => null);\n if (text && Buffer.byteLength(text) > LARGE_ADDED_BYTES) large.push(f.path);\n }\n if (large.length) add({ level: 'warning', check: 'large-files', message: 'Large files added', files: large, hint: 'Consider whether these belong in Git.' });\n\n // 7. Debug leftovers in added lines\n const debugHits = added.filter((l) => /\\b(TODO|FIXME|XXX|console\\.log|debugger|print\\(|binding\\.pry|dd\\()/.test(l.text) && SOURCE_FILE.test(l.file));\n if (debugHits.length) {\n add({ level: 'info', check: 'leftovers', message: `${debugHits.length} added line(s) contain TODO/FIXME or debug statements`, files: [...new Set(debugHits.map((l) => `${l.file}:${l.line}`))].slice(0, 10) });\n }\n\n // 8. Known vulnerable dependencies from the last scan\n const scan = await loadScan(root);\n if (scan) {\n const vulnerable = scan.tools.flatMap((t) => t.findings).filter((f) => ['critical', 'high'].includes(f.severity));\n if (vulnerable.length) add({ level: 'warning', check: 'vulnerabilities', message: `${vulnerable.length} high/critical dependency advisor${vulnerable.length === 1 ? 'y' : 'ies'} from the last scan (${scan.scannedAt.slice(0, 10)})`, files: [], hint: 'Run `athena security` for details.' });\n }\n\n // 9. Knowledge freshness\n let knowledgeInSync: boolean | null = null;\n if (opts.checkSync) {\n knowledgeInSync = await opts.checkSync(root).catch(() => null);\n if (knowledgeInSync === false) add({ level: 'info', check: 'knowledge', message: 'Athena knowledge is out of date for these changes', files: [], hint: 'Run `athena sync` so agents read current context.' });\n }\n\n const rulesText = await readTextIfExists(path.join(athenaDir(root), 'rules.md'));\n const rules = rulesText ? listRules(parseRules(rulesText)).filter((r) => r.enabled) : [];\n const reviewDoc = await readTextIfExists(path.join(athenaDir(root), 'code-review.md'));\n const checklist = reviewDoc\n ? [...reviewDoc.matchAll(/^- \\[ \\] (.+)$/gm)].map((m) => m[1]!.trim())\n : [];\n\n return { base, changedFiles, findings, rules, checklist, knowledgeInSync, stats: { added: addedCount + untrackedAdded, removed: removedCount, files: changedFiles.length } };\n}\n\nexport function hasBlockers(result: ReviewResult): boolean {\n return result.findings.some((f) => f.level === 'blocker');\n}\n","import path from 'node:path';\nimport { analyzeProject } from '../core/analyzer/analyze.js';\nimport { buildGraph, loadGraph, saveGraph, type ProjectGraph } from '../core/graph/graph.js';\nimport { KNOWLEDGE_DOCS, type DocId } from '../core/knowledge/documents.js';\nimport { documentSections, formatContext, selectContext, type RelevantContext } from '../core/context/context-engine.js';\nimport { ProjectModel } from '../core/model/project-model.js';\nimport { athenaDir, readState } from '../core/state/state.js';\nimport { readTextIfExists } from '../core/util/fs.js';\nimport { AthenaError } from './errors.js';\n\nexport { formatContext } from '../core/context/context-engine.js';\nexport type { RelevantContext } from '../core/context/context-engine.js';\n\nasync function loadModel(root: string): Promise<ProjectModel | null> {\n const raw = await readTextIfExists(path.join(athenaDir(root), 'model.json'));\n if (!raw) return null;\n try {\n const parsed = ProjectModel.safeParse(JSON.parse(raw));\n return parsed.success ? parsed.data : null;\n } catch {\n return null;\n }\n}\n\n/** Build (or rebuild) the project graph from the current analysis. */\nexport async function refreshGraph(root: string, opts: { signal?: AbortSignal } = {}): Promise<ProjectGraph> {\n const st = await readState(athenaDir(root));\n const analysis = await analyzeProject(root, { signal: opts.signal, reuse: st.kind === 'ok' ? st.state.fileIndex : undefined });\n const files = analysis.files.map((f) => f.path);\n const graph = await buildGraph(analysis.model, {\n files,\n signal: opts.signal,\n read: async (rel) => readTextIfExists(path.join(root, rel)).catch(() => null),\n });\n await saveGraph(root, graph);\n return graph;\n}\n\nexport async function getGraph(root: string, opts: { build?: boolean; signal?: AbortSignal } = {}): Promise<ProjectGraph | null> {\n const existing = await loadGraph(root);\n if (existing) return existing;\n return opts.build ? refreshGraph(root, { signal: opts.signal }) : null;\n}\n\nexport interface ContextOptions {\n maxChars?: number;\n /** Build the graph if it is missing. */\n buildGraph?: boolean;\n signal?: AbortSignal;\n}\n\n/**\n * Pick the knowledge an agent should read for a task. Deterministic: same task,\n * same project state, same answer.\n */\nexport async function getRelevantContext(root: string, task: string, opts: ContextOptions = {}): Promise<RelevantContext> {\n if (!task.trim()) throw new AthenaError('Describe the task to get relevant context.', 'For example: athena context \"add refunds to the payments API\"');\n const dir = athenaDir(root);\n const documents: Array<{ id: DocId; file: string; sections: Array<{ id: string; content: string }> }> = [];\n for (const d of KNOWLEDGE_DOCS) {\n if (d.id === 'rules') continue;\n const text = await readTextIfExists(path.join(dir, d.file));\n if (text) documents.push({ id: d.id, file: d.file, sections: documentSections(text) });\n }\n if (!documents.length) throw new AthenaError('No knowledge documents found.', 'Run `athena init` first.', 3);\n\n return selectContext({\n task,\n documents,\n rulesMarkdown: await readTextIfExists(path.join(dir, 'rules.md')),\n graph: await getGraph(root, { build: opts.buildGraph, signal: opts.signal }),\n maxChars: opts.maxChars,\n });\n}\n\n/** Summary of the project graph for the UI/CLI. */\nexport async function graphSummary(root: string): Promise<{ built: boolean; builtAt: string | null; stats: ProjectGraph['stats'] | null; model: { hasModel: boolean } }> {\n const graph = await loadGraph(root);\n return { built: Boolean(graph), builtAt: graph?.builtAt ?? null, stats: graph?.stats ?? null, model: { hasModel: Boolean(await loadModel(root)) } };\n}\n","import { z } from 'zod';\nimport path from 'node:path';\nimport { ProjectModel } from '../model/project-model.js';\nimport { readTextIfExists, writeFileAtomic } from '../util/fs.js';\nimport { athenaDir } from '../state/state.js';\nimport { toPosix } from '../util/paths.js';\n\n/**\n * The project graph: a structured view of what the analysis found and how the\n * pieces connect. It is derived entirely from the model and the files the model\n * already points at — no claim here goes beyond DETECTED evidence.\n */\n\nexport const NodeKind = z.enum(['package', 'file', 'route', 'entity', 'framework', 'command', 'infra', 'doc']);\nexport type NodeKind = z.infer<typeof NodeKind>;\n\nexport const EdgeKind = z.enum(['contains', 'imports', 'handles', 'defines', 'depends_on', 'documents', 'runs']);\nexport type EdgeKind = z.infer<typeof EdgeKind>;\n\nexport const GraphNode = z.object({\n id: z.string(),\n kind: NodeKind,\n name: z.string(),\n path: z.string().optional(),\n meta: z.record(z.string(), z.union([z.string(), z.number(), z.boolean()])).default({}),\n});\nexport type GraphNode = z.infer<typeof GraphNode>;\n\nexport const GraphEdge = z.object({ from: z.string(), to: z.string(), kind: EdgeKind });\nexport type GraphEdge = z.infer<typeof GraphEdge>;\n\nexport const ProjectGraph = z.object({\n schemaVersion: z.literal(1),\n builtAt: z.string(),\n nodes: z.array(GraphNode),\n edges: z.array(GraphEdge),\n stats: z.object({ nodes: z.number(), edges: z.number(), byKind: z.record(z.string(), z.number()) }),\n});\nexport type ProjectGraph = z.infer<typeof ProjectGraph>;\n\nexport const GRAPH_FILE = 'graph.json';\n\nexport const nodeId = (kind: NodeKind, key: string) => `${kind}:${key}`;\n\nconst IMPORT_RE = /^\\s*(?:import\\s[^'\"]*from\\s*['\"]([^'\"]+)['\"]|import\\s*['\"]([^'\"]+)['\"]|export\\s[^'\"]*from\\s*['\"]([^'\"]+)['\"]|(?:const|let|var)\\s[^=]*=\\s*require\\(\\s*['\"]([^'\"]+)['\"]\\s*\\))/gm;\nconst PY_IMPORT_RE = /^\\s*(?:from\\s+([.\\w]+)\\s+import|import\\s+([.\\w]+))/gm;\n\nexport interface BuildOptions {\n /** Read a project file (repo-relative POSIX). */\n read(rel: string): Promise<string | null>;\n /** All indexed file paths, used to resolve imports. */\n files: string[];\n /** Maximum files to parse for import edges. */\n maxImportFiles?: number;\n signal?: AbortSignal;\n}\n\nfunction resolveImport(fromFile: string, spec: string, fileSet: Set<string>): string | null {\n if (!spec.startsWith('.')) return null; // package import, not a project file\n const base = toPosix(path.posix.normalize(path.posix.join(path.posix.dirname(fromFile), spec)));\n const candidates = [base, ...['.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs', '.mts', '.py', '.vue', '.svelte'].flatMap((ext) => [`${base}${ext}`, `${base}/index${ext}`, `${base}/__init__${ext}`])];\n return candidates.find((c) => fileSet.has(c)) ?? null;\n}\n\n/** Build the graph from an analyzed model. Import edges are parsed only for files the model references. */\nexport async function buildGraph(model: ProjectModel, opts: BuildOptions): Promise<ProjectGraph> {\n const nodes = new Map<string, GraphNode>();\n const edges: GraphEdge[] = [];\n const fileSet = new Set(opts.files);\n const addNode = (n: GraphNode) => {\n if (!nodes.has(n.id)) nodes.set(n.id, n);\n return n.id;\n };\n const addEdge = (from: string, to: string, kind: EdgeKind) => {\n if (from === to || !nodes.has(from) || !nodes.has(to)) return;\n if (!edges.some((e) => e.from === from && e.to === to && e.kind === kind)) edges.push({ from, to, kind });\n };\n const fileNode = (p: string) => addNode({ id: nodeId('file', p), kind: 'file', name: path.posix.basename(p), path: p, meta: {} });\n\n // Packages\n for (const pkg of model.workspace.packages) {\n addNode({ id: nodeId('package', pkg.name), kind: 'package', name: pkg.name, path: pkg.path, meta: { kind: pkg.kind, ecosystem: pkg.ecosystem } });\n }\n for (const pkg of model.workspace.packages) {\n for (const dep of pkg.internalDependencies) addEdge(nodeId('package', pkg.name), nodeId('package', dep), 'depends_on');\n }\n\n // Frameworks\n for (const f of model.frameworks) {\n const id = addNode({ id: nodeId('framework', `${f.name}@${f.root}`), kind: 'framework', name: f.name, path: f.root, meta: { category: f.category, status: f.provenance.status, confidence: f.provenance.confidence } });\n const owner = model.workspace.packages.find((p) => p.path === f.root);\n if (owner) addEdge(nodeId('package', owner.name), id, 'contains');\n }\n\n // Routes → handler files\n for (const r of model.routes) {\n const id = addNode({ id: nodeId('route', `${r.method} ${r.path} ${r.file}`), kind: 'route', name: `${r.method} ${r.path}`, path: r.file, meta: { method: r.method, framework: r.framework, ...(r.line ? { line: r.line } : {}) } });\n addEdge(id, fileNode(r.file), 'handles');\n }\n\n // Entities → defining files\n for (const e of model.dbEntities) {\n const id = addNode({ id: nodeId('entity', `${e.name}@${e.file}`), kind: 'entity', name: e.name, path: e.file, meta: { kind: e.kind, fields: e.fields.length, indexes: e.indexes.length } });\n addEdge(id, fileNode(e.file), 'defines');\n for (const rel of e.relations) {\n const target = rel.split('→')[1]?.trim();\n const other = target ? model.dbEntities.find((x) => x.name.toLowerCase() === target.toLowerCase()) : undefined;\n if (other) addEdge(id, nodeId('entity', `${other.name}@${other.file}`), 'depends_on');\n }\n }\n\n // Entry points, commands, infrastructure\n for (const e of model.entryPoints) fileNode(e.path);\n for (const c of model.commands) {\n const id = addNode({ id: nodeId('command', `${c.source}:${c.name}`), kind: 'command', name: c.name, path: c.source, meta: { purpose: c.purpose, command: c.command.slice(0, 120) } });\n addEdge(id, fileNode(c.source), 'runs');\n }\n for (const i of model.infrastructure) addNode({ id: nodeId('infra', `${i.name}@${i.file}`), kind: 'infra', name: i.name, path: i.file, meta: { kind: i.kind } });\n for (const d of model.containers.dockerfiles) addNode({ id: nodeId('infra', `Dockerfile@${d.path}`), kind: 'infra', name: 'Dockerfile', path: d.path, meta: { kind: 'container' } });\n for (const s of model.containers.services) addNode({ id: nodeId('infra', `service:${s.name}@${s.file}`), kind: 'infra', name: s.name, path: s.file, meta: { kind: 'service', image: s.image ?? '' } });\n\n // File → package membership\n for (const n of [...nodes.values()].filter((x) => x.kind === 'file' && x.path)) {\n const owner = model.workspace.packages\n .filter((p) => p.path !== '.' && n.path!.startsWith(`${p.path}/`))\n .sort((a, b) => b.path.length - a.path.length)[0];\n if (owner) addEdge(nodeId('package', owner.name), n.id, 'contains');\n }\n\n // Import edges between files the graph already knows about\n const maxImportFiles = opts.maxImportFiles ?? 2000;\n const queue = [...nodes.values()].filter((n) => n.kind === 'file').map((n) => n.path!);\n const parsed = new Set<string>();\n while (queue.length && parsed.size < maxImportFiles) {\n opts.signal?.throwIfAborted();\n const p = queue.shift()!;\n if (parsed.has(p)) continue;\n parsed.add(p);\n const n = { id: nodeId('file', p) };\n if (!/\\.(m|c)?(t|j)sx?$|\\.py$/.test(p)) continue;\n const text = await opts.read(p);\n if (!text) continue;\n const specs: string[] = [];\n for (const m of text.matchAll(IMPORT_RE)) specs.push((m[1] ?? m[2] ?? m[3] ?? m[4])!);\n if (p.endsWith('.py')) for (const m of text.matchAll(PY_IMPORT_RE)) specs.push(((m[1] ?? m[2])!).replace(/\\./g, '/'));\n for (const spec of specs.slice(0, 200)) {\n const target = resolveImport(p, spec, fileSet);\n // Imported project files become nodes too, so the graph reaches beyond the\n // files the model happened to reference directly.\n if (!target) continue;\n addEdge(n.id, fileNode(target), 'imports');\n if (!parsed.has(target)) queue.push(target);\n }\n }\n\n const byKind: Record<string, number> = {};\n for (const n of nodes.values()) byKind[n.kind] = (byKind[n.kind] ?? 0) + 1;\n return {\n schemaVersion: 1,\n builtAt: new Date().toISOString(),\n nodes: [...nodes.values()].sort((a, b) => a.id.localeCompare(b.id)),\n edges: edges.sort((a, b) => a.from.localeCompare(b.from) || a.to.localeCompare(b.to)),\n stats: { nodes: nodes.size, edges: edges.length, byKind },\n };\n}\n\nexport async function saveGraph(root: string, graph: ProjectGraph): Promise<void> {\n await writeFileAtomic(path.join(athenaDir(root), GRAPH_FILE), `${JSON.stringify(graph, null, 2)}\\n`);\n}\n\nexport async function loadGraph(root: string): Promise<ProjectGraph | null> {\n const raw = await readTextIfExists(path.join(athenaDir(root), GRAPH_FILE));\n if (!raw) return null;\n try {\n const parsed = ProjectGraph.safeParse(JSON.parse(raw));\n return parsed.success ? parsed.data : null;\n } catch {\n return null;\n }\n}\n\nexport interface Neighborhood {\n node: GraphNode;\n edges: Array<{ edge: GraphEdge; other: GraphNode; direction: 'out' | 'in' }>;\n}\n\n/** Nodes directly connected to `id`, in both directions. */\nexport function neighbors(graph: ProjectGraph, id: string): Neighborhood | null {\n const node = graph.nodes.find((n) => n.id === id);\n if (!node) return null;\n const byId = new Map(graph.nodes.map((n) => [n.id, n]));\n const out: Neighborhood['edges'] = [];\n for (const e of graph.edges) {\n if (e.from === id && byId.has(e.to)) out.push({ edge: e, other: byId.get(e.to)!, direction: 'out' });\n else if (e.to === id && byId.has(e.from)) out.push({ edge: e, other: byId.get(e.from)!, direction: 'in' });\n }\n return { node, edges: out };\n}\n\n/** Nodes within `depth` hops of any of the given files (used to expand task context). */\nexport function expandFromFiles(graph: ProjectGraph, files: string[], depth = 1, limit = 40): GraphNode[] {\n const byId = new Map(graph.nodes.map((n) => [n.id, n]));\n const seed = graph.nodes.filter((n) => n.path && files.includes(n.path));\n const seen = new Set(seed.map((n) => n.id));\n let frontier = [...seen];\n for (let d = 0; d < depth; d++) {\n const next: string[] = [];\n for (const e of graph.edges) {\n if (frontier.includes(e.from) && !seen.has(e.to)) {\n seen.add(e.to);\n next.push(e.to);\n } else if (frontier.includes(e.to) && !seen.has(e.from)) {\n seen.add(e.from);\n next.push(e.from);\n }\n }\n frontier = next;\n if (!frontier.length) break;\n }\n return [...seen]\n .map((id) => byId.get(id))\n .filter((n): n is GraphNode => Boolean(n))\n .slice(0, limit);\n}\n","import { KNOWLEDGE_DOCS, RELEVANCE_MAP, type DocId } from '../knowledge/documents.js';\nimport { parseBlocks } from '../knowledge/managed-blocks.js';\nimport { listRules, parseRules, type Rule } from '../knowledge/rules.js';\nimport { expandFromFiles, type GraphNode, type ProjectGraph } from '../graph/graph.js';\n\n/**\n * Deterministic context selection: given a task description, decide which parts of\n * the knowledge base an agent should read. No AI, no guessing about the code —\n * keyword matching over the developer's own documents plus the project graph.\n */\n\nexport interface TaskArea {\n id: DocId;\n score: number;\n why: string[];\n}\n\nexport interface ContextSection {\n doc: DocId;\n file: string;\n section: string;\n content: string;\n score: number;\n}\n\nexport interface RelevantContext {\n task: string;\n /** Documents ranked by relevance, with the reason each was chosen. */\n areas: TaskArea[];\n sections: ContextSection[];\n rules: Rule[];\n graphNodes: GraphNode[];\n /** Files the task text referred to directly. */\n mentionedFiles: string[];\n truncated: boolean;\n approxChars: number;\n}\n\n/** Keywords that map a task to knowledge areas. Extend here, not in the renderers. */\nconst AREA_KEYWORDS: Array<{ id: DocId; words: RegExp }> = [\n { id: 'database', words: /\\b(database|db|schema|migration|migrate|sql|query|queries|table|column|index|prisma|orm|entity|model|postgres|mysql|mongo|supabase)\\b/i },\n { id: 'api', words: /\\b(api|endpoint|route|router|controller|handler|rest|graphql|grpc|request|response|webhook|http|status code)\\b/i },\n { id: 'auth', words: /\\b(auth|authentication|authorization|login|logout|session|token|jwt|oauth|sso|permission|role|rbac|acl|password|mfa|2fa)\\b/i },\n { id: 'security', words: /\\b(security|secure|vulnerab|xss|csrf|ssrf|injection|sanitiz|escape|secret|credential|encrypt|audit|cors|rate limit)\\b/i },\n { id: 'testing', words: /\\b(test|tests|testing|spec|coverage|e2e|unit|integration|mock|fixture|vitest|jest|pytest|playwright|cypress)\\b/i },\n { id: 'performance', words: /\\b(performance|perf|slow|fast|latency|cache|caching|queue|worker|background job|optimi[sz]|n\\+1|bottleneck|memory|profil)\\b/i },\n { id: 'deployment', words: /\\b(deploy|deployment|docker|container|kubernetes|k8s|ci|cd|pipeline|release|env var|environment variable|infra|terraform|vercel|hosting)\\b/i },\n { id: 'debugging', words: /\\b(bug|debug|error|exception|crash|stack trace|failing|broken|regression|log|logging|troubleshoot)\\b/i },\n { id: 'architecture', words: /\\b(architecture|structure|module|package|refactor|boundary|layer|service layer|dependency|monorepo|design)\\b/i },\n { id: 'code-review', words: /\\b(review|pull request|pr|merge|checklist|convention|style guide)\\b/i },\n { id: 'project', words: /\\b(setup|install|build|command|script|getting started|onboard|dependency|dependencies|tooling)\\b/i },\n];\n\nconst UI_WORDS = /\\b(ui|css|style|styling|layout|component|button|form|page|responsive|dark mode|design|frontend|tailwind)\\b/i;\nconst SMALL_WORDS = /\\b(typo|rename|comment|whitespace|format|wording|copy|spelling)\\b/i;\nconst STOP = new Set(['the', 'and', 'for', 'with', 'that', 'this', 'from', 'into', 'add', 'new', 'use', 'using', 'make', 'need', 'should', 'when', 'what', 'where', 'which', 'must', 'have', 'has', 'are', 'was', 'can', 'will', 'our', 'their', 'its', 'not', 'all', 'any', 'get', 'set', 'run']);\n\nexport function tokenize(task: string): string[] {\n return [...new Set(task.toLowerCase().match(/[a-z0-9_./-]{3,}/g) ?? [])].filter((w) => !STOP.has(w));\n}\n\n/** File-like tokens in the task (\"src/api/payments.ts\", \"payments.ts\"). */\nexport function mentionedFiles(task: string, knownFiles: string[]): string[] {\n const candidates = task.match(/[\\w./-]+\\.[a-z]{1,5}\\b/gi) ?? [];\n const out: string[] = [];\n for (const c of candidates) {\n const norm = c.replace(/^\\.\\//, '');\n const exact = knownFiles.find((f) => f === norm || f.endsWith(`/${norm}`));\n if (exact) out.push(exact);\n }\n return [...new Set(out)];\n}\n\nexport interface SelectOptions {\n task: string;\n /** Section text per document, as parsed from .athena/*.md. */\n documents: Array<{ id: DocId; file: string; sections: Array<{ id: string; content: string }> }>;\n rulesMarkdown: string | null;\n graph?: ProjectGraph | null;\n /** Character budget for returned sections. */\n maxChars?: number;\n}\n\nexport function selectContext(opts: SelectOptions): RelevantContext {\n const task = opts.task.trim();\n const words = tokenize(task);\n const maxChars = opts.maxChars ?? 12_000;\n\n // 1. Areas from keywords, with the mapped task types as a fallback.\n const areas = new Map<DocId, TaskArea>();\n const bump = (id: DocId, score: number, why: string) => {\n const cur = areas.get(id) ?? { id, score: 0, why: [] };\n cur.score += score;\n if (!cur.why.includes(why)) cur.why.push(why);\n areas.set(id, cur);\n };\n for (const { id, words: re } of AREA_KEYWORDS) {\n const hit = task.match(re);\n if (hit) bump(id, 10, `task mentions \"${hit[0]}\"`);\n }\n if (UI_WORDS.test(task)) {\n for (const id of ['project', 'architecture'] as DocId[]) bump(id, 6, 'frontend/UI task');\n }\n if (!areas.size && !SMALL_WORDS.test(task)) {\n for (const id of RELEVANCE_MAP.find((r) => r.task.startsWith('New feature'))!.docs) bump(id, 3, 'no specific area detected — using the broad feature set');\n }\n // Security and testing ride along with database/API/auth work.\n if (areas.has('database') || areas.has('api') || areas.has('auth')) {\n bump('security', 4, 'security implications of data/API changes');\n bump('testing', 3, 'tests for changed behavior');\n }\n\n // 2. Files and graph\n const knownFiles = opts.graph?.nodes.filter((n) => n.path).map((n) => n.path!) ?? [];\n const files = mentionedFiles(task, knownFiles);\n const graphNodes = opts.graph ? expandFromFiles(opts.graph, files, 1, 30) : [];\n for (const n of graphNodes) {\n if (n.kind === 'route') bump('api', 5, `task touches route ${n.name}`);\n if (n.kind === 'entity') bump('database', 5, `task touches entity ${n.name}`);\n }\n // Graph nodes matching task words (e.g. \"payments\" → entity Payment)\n if (opts.graph) {\n for (const n of opts.graph.nodes) {\n if (graphNodes.some((g) => g.id === n.id)) continue;\n const hay = `${n.name} ${n.path ?? ''}`.toLowerCase();\n if (words.some((w) => w.length > 3 && hay.includes(w))) {\n graphNodes.push(n);\n if (graphNodes.length >= 40) break;\n }\n }\n }\n\n // 3. Score sections within the chosen documents\n const ranked = [...areas.values()].sort((a, b) => b.score - a.score);\n const sections: ContextSection[] = [];\n for (const area of ranked) {\n const doc = opts.documents.find((d) => d.id === area.id);\n if (!doc) continue;\n for (const s of doc.sections) {\n if (s.id === 'about') continue;\n const text = s.content.toLowerCase();\n const matches = words.filter((w) => text.includes(w)).length;\n const score = area.score + matches * 2;\n sections.push({ doc: doc.id, file: doc.file, section: s.id, content: s.content, score });\n }\n }\n sections.sort((a, b) => b.score - a.score);\n\n let used = 0;\n const kept: ContextSection[] = [];\n let truncated = false;\n for (const s of sections) {\n if (used + s.content.length > maxChars) {\n truncated = true;\n continue;\n }\n kept.push(s);\n used += s.content.length;\n }\n\n const rules = opts.rulesMarkdown ? listRules(parseRules(opts.rulesMarkdown)).filter((r) => r.enabled) : [];\n return {\n task,\n areas: ranked,\n sections: kept.sort((a, b) => a.doc.localeCompare(b.doc) || b.score - a.score),\n rules,\n graphNodes: graphNodes.slice(0, 40),\n mentionedFiles: files,\n truncated,\n approxChars: used,\n };\n}\n\n/** Parse a knowledge document into its generated sections plus developer notes. */\nexport function documentSections(markdown: string): Array<{ id: string; content: string }> {\n const blocks = parseBlocks(markdown);\n const sections = blocks.map((b) => ({ id: b.id, content: b.content }));\n // Developer content after the last generated block is high-value context.\n const last = blocks.at(-1);\n const tail = last ? markdown.slice(last.end) : markdown;\n const notes = tail.replace(/^#+ Developer Notes\\s*/im, '').replace(/<!--[\\s\\S]*?-->/g, '').trim();\n if (notes) sections.push({ id: 'developer-notes', content: `## Developer Notes\\n\\n${notes}` });\n return sections;\n}\n\n/** Render selected context as Markdown for an agent. */\nexport function formatContext(ctx: RelevantContext): string {\n const out: string[] = [`# Athena context for: ${ctx.task}`, ''];\n out.push('_Selected deterministically from this project\\'s knowledge. Statements keep their FACT/DETECTED/INFERRED/UNKNOWN labels; verify anything not marked FACT or DETECTED._', '');\n\n if (ctx.rules.length) {\n out.push('## Project rules (always apply)', '');\n for (const r of ctx.rules) out.push(`- [${r.section}] ${r.text}`);\n out.push('');\n }\n if (ctx.areas.length) {\n out.push(`## Why these documents`, '');\n for (const a of ctx.areas) out.push(`- **${KNOWLEDGE_DOCS.find((d) => d.id === a.id)!.file}** — ${a.why.join('; ')}`);\n out.push('');\n }\n if (ctx.mentionedFiles.length || ctx.graphNodes.length) {\n out.push('## Related code (from the project graph)', '');\n for (const f of ctx.mentionedFiles) out.push(`- file: \\`${f}\\` (named in the task)`);\n for (const n of ctx.graphNodes.filter((n) => !ctx.mentionedFiles.includes(n.path ?? ''))) {\n out.push(`- ${n.kind}: ${n.name}${n.path ? ` (\\`${n.path}\\`)` : ''}`);\n }\n out.push('');\n }\n let currentDoc = '';\n for (const s of ctx.sections) {\n if (s.doc !== currentDoc) {\n currentDoc = s.doc;\n out.push(`## From ${s.file}`, '');\n }\n out.push(s.content.trim(), '');\n }\n if (ctx.truncated) out.push('_Some lower-ranked sections were omitted to stay within the context budget._');\n return out.join('\\n');\n}\n","import path from 'node:path';\nimport { loadConfig } from '../core/config.js';\nimport { KNOWLEDGE_DOCS } from '../core/knowledge/documents.js';\nimport { redact, scanText } from '../core/security/secrets.js';\nimport { athenaDir } from '../core/state/state.js';\nimport { readTextIfExists, writeFileAtomic } from '../core/util/fs.js';\nimport { AiConfig, AiError, type AIProvider, type Availability } from '../ai/provider.js';\nimport { getProvider, PROVIDERS } from '../ai/providers.js';\nimport { AthenaError } from './errors.js';\n\nexport const SUGGESTIONS_FILE = 'ai-suggestions.md';\n\nexport interface AiStatus {\n configured: AiConfig;\n providers: Array<{ id: string; name: string; remote: boolean; defaultModel: string; keyEnvVar?: string; availability: Availability; selected: boolean }>;\n consent: boolean;\n}\n\nexport async function aiConfig(root: string): Promise<AiConfig> {\n const { config } = await loadConfig(root);\n return AiConfig.parse(config.ai ?? {});\n}\n\nexport async function aiStatus(root: string): Promise<AiStatus> {\n const cfg = await aiConfig(root);\n const providers = [];\n for (const p of PROVIDERS) providers.push({ id: p.id, name: p.name, remote: p.remote, defaultModel: p.defaultModel, keyEnvVar: p.keyEnvVar, availability: await p.available(cfg), selected: p.id === cfg.provider });\n return { configured: cfg, providers, consent: cfg.consent };\n}\n\nexport interface EnrichPayload {\n /** Exactly what would be sent, after redaction. */\n content: string;\n chars: number;\n documents: string[];\n provider: AIProvider;\n endpoint: string;\n remote: boolean;\n model: string;\n}\n\n/**\n * Build the payload for enrichment: knowledge documents only — never source code —\n * passed through the secret redactor, and capped by config.\n */\nexport async function buildEnrichPayload(root: string, opts: { docs?: string[] } = {}): Promise<EnrichPayload> {\n const cfg = await aiConfig(root);\n const provider = getProvider(cfg.provider);\n const wanted = opts.docs?.length ? opts.docs : ['project', 'architecture', 'database', 'api'];\n const parts: string[] = [];\n const included: string[] = [];\n for (const id of wanted) {\n const doc = KNOWLEDGE_DOCS.find((d) => d.id === id);\n if (!doc) throw new AthenaError(`Unknown document: ${id}`, `Available: ${KNOWLEDGE_DOCS.map((d) => d.id).join(', ')}`);\n const text = await readTextIfExists(path.join(athenaDir(root), doc.file));\n if (!text) continue;\n included.push(doc.file);\n parts.push(`--- ${doc.file} ---\\n${text.replace(/<!--[\\s\\S]*?-->/g, '').trim()}`);\n }\n if (!included.length) throw new AthenaError('No knowledge documents to send.', 'Run `athena init` first.', 3);\n\n let content = redact(parts.join('\\n\\n'));\n if (content.length > cfg.maxChars) content = `${content.slice(0, cfg.maxChars)}\\n\\n[truncated to ${cfg.maxChars} characters]`;\n // Defense in depth: never send content that still looks like it holds a secret.\n const leftover = scanText(content);\n if (leftover.length) throw new AthenaError('Refusing to send: the knowledge still contains values that look like secrets.', 'Fix them in .athena/*.md first.');\n\n const availability = await provider.available(cfg);\n return { content, chars: content.length, documents: included, provider, endpoint: availability.endpoint, remote: provider.remote, model: cfg.model ?? provider.defaultModel };\n}\n\nconst SYSTEM = [\n 'You help maintain a project knowledge base for AI coding agents.',\n 'You will be given generated documentation about a software project.',\n 'Suggest concise, high-value additions a developer might record: the project purpose, architectural decisions worth documenting, risky areas, and candidate project rules.',\n 'Rules: never invent facts that are not supported by the provided material; where you are unsure, say what is unknown and what would confirm it; do not restate the documents; no code.',\n 'Output GitHub-flavoured Markdown with these sections: \"## Suggested project summary\", \"## Questions Athena could not answer\", \"## Candidate rules\" (as a bullet list).',\n].join(' ');\n\nexport interface EnrichResult {\n markdown: string;\n file: string;\n provider: string;\n model: string;\n chars: number;\n documents: string[];\n}\n\n/**\n * Ask the configured provider for suggestions and write them to a clearly-labelled,\n * gitignored file. Nothing is added to the knowledge base automatically: AI output\n * is INFERRED, and the developer decides what (if anything) to keep.\n */\nexport async function enrich(root: string, opts: { docs?: string[]; consent?: boolean; signal?: AbortSignal } = {}): Promise<EnrichResult> {\n const cfg = await aiConfig(root);\n const payload = await buildEnrichPayload(root, { docs: opts.docs });\n const availability = await payload.provider.available(cfg);\n if (!availability.ok) throw new AthenaError(`${payload.provider.name} is not available: ${availability.reason}`, payload.provider.keyEnvVar ? `Set ${payload.provider.keyEnvVar}, or choose another provider in .athena/config.json.` : undefined);\n if (payload.remote && !cfg.consent && !opts.consent) {\n throw new AthenaError(\n `Sending project knowledge to ${payload.endpoint} requires consent.`,\n 'Re-run with --consent, or set \"ai\": { \"consent\": true } in .athena/config.json. Use the ollama provider to keep everything local.',\n );\n }\n\n let result;\n try {\n result = await payload.provider.complete(cfg, { system: SYSTEM, prompt: payload.content, maxTokens: 2000, signal: opts.signal });\n } catch (err) {\n if (err instanceof AiError) throw new AthenaError(err.message, err.hint);\n throw err;\n }\n const body = redact(result.text.trim());\n if (!body) throw new AthenaError('The provider returned an empty response.');\n\n const markdown = [\n '# AI suggestions (INFERRED — not project knowledge)',\n '',\n `> Generated ${new Date().toISOString()} by ${result.provider} (${result.model}) from ${payload.documents.join(', ')}.`,\n '>',\n '> **Status: INFERRED.** Nothing here was verified against the code. Move anything useful into a document\\'s Developer Notes or `rules.md` yourself; Athena will not do it for you.',\n '',\n body,\n '',\n ].join('\\n');\n const file = path.join(athenaDir(root), SUGGESTIONS_FILE);\n await writeFileAtomic(file, markdown);\n return { markdown, file: SUGGESTIONS_FILE, provider: result.provider, model: result.model, chars: payload.chars, documents: payload.documents };\n}\n","import { z } from 'zod';\n\n/**\n * Provider abstraction. Athena never requires AI: analysis, sync, context and MCP\n * are all deterministic. AI is opt-in enrichment, and anything it produces is\n * labelled INFERRED and reviewed by the developer before it becomes knowledge.\n */\n\nexport const AiConfig = z.object({\n provider: z.enum(['anthropic', 'openai', 'google', 'ollama']).default('anthropic'),\n model: z.string().optional(),\n /** cloud: a hosted API · local: a model on this machine (Ollama). */\n mode: z.enum(['cloud', 'local']).default('cloud'),\n /** Must be true (or --consent passed) before any project content leaves the machine. */\n consent: z.boolean().default(false),\n /** Upper bound on characters of knowledge sent in one request. */\n maxChars: z.number().int().min(500).max(200_000).default(24_000),\n /** Ollama base URL, or a custom compatible endpoint. */\n baseUrl: z.string().optional(),\n});\nexport type AiConfig = z.infer<typeof AiConfig>;\n\nexport interface CompletionRequest {\n system: string;\n prompt: string;\n maxTokens?: number;\n signal?: AbortSignal;\n timeoutMs?: number;\n}\n\nexport interface CompletionResult {\n text: string;\n model: string;\n provider: string;\n usage?: { inputTokens?: number; outputTokens?: number };\n}\n\nexport interface Availability {\n ok: boolean;\n /** Why the provider cannot be used (missing key, unreachable host…). */\n reason?: string;\n /** Where data would be sent. \"local\" for on-device models. */\n endpoint: string;\n keyEnvVar?: string;\n}\n\nexport interface AIProvider {\n id: AiConfig['provider'];\n name: string;\n /** True when project content would leave this machine. */\n remote: boolean;\n defaultModel: string;\n keyEnvVar?: string;\n available(config: AiConfig): Promise<Availability>;\n complete(config: AiConfig, req: CompletionRequest): Promise<CompletionResult>;\n}\n\nexport class AiError extends Error {\n constructor(\n message: string,\n readonly hint?: string,\n ) {\n super(message);\n this.name = 'AiError';\n }\n}\n\nexport async function postJson(url: string, body: unknown, headers: Record<string, string>, req: CompletionRequest): Promise<Record<string, unknown>> {\n const timeout = AbortSignal.timeout(req.timeoutMs ?? 120_000);\n const signal = req.signal ? AbortSignal.any([req.signal, timeout]) : timeout;\n let res: Response;\n try {\n res = await fetch(url, { method: 'POST', headers: { 'content-type': 'application/json', ...headers }, body: JSON.stringify(body), signal });\n } catch (err) {\n throw new AiError(`Could not reach ${new URL(url).host}: ${(err as Error).message}`);\n }\n const text = await res.text();\n if (!res.ok) {\n const detail = text.slice(0, 300);\n throw new AiError(`${new URL(url).host} returned ${res.status}`, detail || undefined);\n }\n try {\n return JSON.parse(text) as Record<string, unknown>;\n } catch {\n throw new AiError('Provider returned a non-JSON response');\n }\n}\n\nexport function envKey(name: string | undefined): string | undefined {\n return name ? process.env[name]?.trim() || undefined : undefined;\n}\n","import { AiError, envKey, postJson, type AIProvider, type AiConfig, type Availability, type CompletionRequest, type CompletionResult } from './provider.js';\n\nconst str = (v: unknown): string => (typeof v === 'string' ? v : '');\n\nfunction keyAvailability(provider: AIProvider, endpoint: string): Availability {\n const key = envKey(provider.keyEnvVar);\n return key ? { ok: true, endpoint, keyEnvVar: provider.keyEnvVar } : { ok: false, reason: `${provider.keyEnvVar} is not set`, endpoint, keyEnvVar: provider.keyEnvVar };\n}\n\nexport const anthropicProvider: AIProvider = {\n id: 'anthropic',\n name: 'Anthropic (Claude)',\n remote: true,\n defaultModel: 'claude-sonnet-5',\n keyEnvVar: 'ANTHROPIC_API_KEY',\n async available(config) {\n return keyAvailability(anthropicProvider, config.baseUrl ?? 'https://api.anthropic.com');\n },\n async complete(config, req) {\n const key = envKey(anthropicProvider.keyEnvVar);\n if (!key) throw new AiError('ANTHROPIC_API_KEY is not set');\n const model = config.model ?? anthropicProvider.defaultModel;\n const json = await postJson(\n `${config.baseUrl ?? 'https://api.anthropic.com'}/v1/messages`,\n { model, max_tokens: req.maxTokens ?? 2000, system: req.system, messages: [{ role: 'user', content: req.prompt }] },\n { 'x-api-key': key, 'anthropic-version': '2023-06-01' },\n req,\n );\n const content = Array.isArray(json.content) ? json.content : [];\n const text = content.map((c) => (c && typeof c === 'object' ? str((c as Record<string, unknown>).text) : '')).join('');\n const usage = (json.usage ?? {}) as Record<string, number>;\n return { text, model: str(json.model) || model, provider: 'anthropic', usage: { inputTokens: usage.input_tokens, outputTokens: usage.output_tokens } };\n },\n};\n\nexport const openaiProvider: AIProvider = {\n id: 'openai',\n name: 'OpenAI',\n remote: true,\n defaultModel: 'gpt-4.1-mini',\n keyEnvVar: 'OPENAI_API_KEY',\n async available(config) {\n return keyAvailability(openaiProvider, config.baseUrl ?? 'https://api.openai.com');\n },\n async complete(config, req) {\n const key = envKey(openaiProvider.keyEnvVar);\n if (!key) throw new AiError('OPENAI_API_KEY is not set');\n const model = config.model ?? openaiProvider.defaultModel;\n const json = await postJson(\n `${config.baseUrl ?? 'https://api.openai.com'}/v1/chat/completions`,\n { model, max_completion_tokens: req.maxTokens ?? 2000, messages: [{ role: 'system', content: req.system }, { role: 'user', content: req.prompt }] },\n { authorization: `Bearer ${key}` },\n req,\n );\n const choices = Array.isArray(json.choices) ? json.choices : [];\n const first = (choices[0] ?? {}) as Record<string, unknown>;\n const message = (first.message ?? {}) as Record<string, unknown>;\n const usage = (json.usage ?? {}) as Record<string, number>;\n return { text: str(message.content), model: str(json.model) || model, provider: 'openai', usage: { inputTokens: usage.prompt_tokens, outputTokens: usage.completion_tokens } };\n },\n};\n\nexport const googleProvider: AIProvider = {\n id: 'google',\n name: 'Google (Gemini)',\n remote: true,\n defaultModel: 'gemini-2.5-flash',\n keyEnvVar: 'GEMINI_API_KEY',\n async available(config) {\n const key = envKey('GEMINI_API_KEY') ?? envKey('GOOGLE_API_KEY');\n const endpoint = config.baseUrl ?? 'https://generativelanguage.googleapis.com';\n return key ? { ok: true, endpoint, keyEnvVar: 'GEMINI_API_KEY' } : { ok: false, reason: 'GEMINI_API_KEY (or GOOGLE_API_KEY) is not set', endpoint, keyEnvVar: 'GEMINI_API_KEY' };\n },\n async complete(config, req) {\n const key = envKey('GEMINI_API_KEY') ?? envKey('GOOGLE_API_KEY');\n if (!key) throw new AiError('GEMINI_API_KEY is not set');\n const model = config.model ?? googleProvider.defaultModel;\n const json = await postJson(\n `${config.baseUrl ?? 'https://generativelanguage.googleapis.com'}/v1beta/models/${encodeURIComponent(model)}:generateContent`,\n { systemInstruction: { parts: [{ text: req.system }] }, contents: [{ role: 'user', parts: [{ text: req.prompt }] }], generationConfig: { maxOutputTokens: req.maxTokens ?? 2000 } },\n { 'x-goog-api-key': key },\n req,\n );\n const candidates = Array.isArray(json.candidates) ? json.candidates : [];\n const parts = ((candidates[0] as Record<string, unknown> | undefined)?.content as Record<string, unknown> | undefined)?.parts;\n const text = Array.isArray(parts) ? parts.map((p) => str((p as Record<string, unknown>).text)).join('') : '';\n return { text, model, provider: 'google' };\n },\n};\n\nexport const ollamaProvider: AIProvider = {\n id: 'ollama',\n name: 'Ollama (local)',\n remote: false,\n defaultModel: 'llama3.1',\n async available(config) {\n const endpoint = config.baseUrl ?? (process.env.OLLAMA_HOST?.trim() || 'http://127.0.0.1:11434');\n try {\n const res = await fetch(`${endpoint}/api/tags`, { signal: AbortSignal.timeout(2000) });\n if (!res.ok) return { ok: false, reason: `Ollama responded ${res.status}`, endpoint };\n const json = (await res.json()) as { models?: Array<{ name?: string }> };\n const models = (json.models ?? []).map((m) => m.name).filter(Boolean);\n return models.length ? { ok: true, endpoint } : { ok: false, reason: 'Ollama is running but has no models pulled (try `ollama pull llama3.1`)', endpoint };\n } catch {\n return { ok: false, reason: 'Ollama is not reachable (start it with `ollama serve`)', endpoint };\n }\n },\n async complete(config, req) {\n const endpoint = config.baseUrl ?? (process.env.OLLAMA_HOST?.trim() || 'http://127.0.0.1:11434');\n const model = config.model ?? ollamaProvider.defaultModel;\n const json = await postJson(\n `${endpoint}/api/chat`,\n { model, stream: false, options: { num_predict: req.maxTokens ?? 2000 }, messages: [{ role: 'system', content: req.system }, { role: 'user', content: req.prompt }] },\n {},\n req,\n );\n const message = (json.message ?? {}) as Record<string, unknown>;\n return { text: str(message.content), model, provider: 'ollama' };\n },\n};\n\nexport const PROVIDERS: AIProvider[] = [anthropicProvider, openaiProvider, googleProvider, ollamaProvider];\n\nexport function getProvider(id: AiConfig['provider']): AIProvider {\n const p = PROVIDERS.find((x) => x.id === id);\n if (!p) throw new AiError(`Unknown AI provider: ${id}`, `Supported: ${PROVIDERS.map((x) => x.id).join(', ')}`);\n return p;\n}\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { watch as chokidarWatch, type FSWatcher } from 'chokidar';\nimport { loadConfig } from '../core/config.js';\nimport { IgnoreMatcher } from '../core/fs/ignore.js';\nimport { git } from '../core/git/git.js';\nimport { toPosix } from '../core/util/paths.js';\nimport { applySync, needsIndexRefreshOnly, planSync, type ApplyResult, type SyncPlan } from './sync.js';\n\nexport interface WatchEvent {\n type: 'changes' | 'planning' | 'plan' | 'applied' | 'refreshed' | 'git-head' | 'error' | 'ready';\n paths?: string[];\n plan?: SyncPlan;\n result?: ApplyResult;\n head?: { from: string | null; to: string | null };\n error?: Error;\n}\n\nexport interface WatchOptions {\n /** Quiet period after the last change before planning (ms). */\n debounceMs?: number;\n /** Plan at the latest this long after the first change of a burst (ms). */\n maxWaitMs?: number;\n /** Apply plans automatically. Default: propose only. */\n autoApply?: boolean;\n onEvent: (e: WatchEvent) => void;\n signal?: AbortSignal;\n}\n\nexport interface ProjectWatcher {\n /** Plan immediately (skipping the debounce). Resolves with the plan. */\n planNow(): Promise<SyncPlan | null>;\n latestPlan(): SyncPlan | null;\n close(): Promise<void>;\n}\n\nasync function gitDir(root: string): Promise<string | null> {\n const r = await git(root, ['rev-parse', '--absolute-git-dir']);\n return r.ok ? r.stdout.trim() : null;\n}\n\n/**\n * Watches a project and turns bursts of file changes into sync plans.\n * By default it never writes knowledge documents; it only proposes. When no\n * document would change, it refreshes the file index silently (safe: state only).\n */\nexport async function watchProject(root: string, opts: WatchOptions): Promise<ProjectWatcher> {\n const debounceMs = opts.debounceMs ?? 1500;\n const maxWaitMs = opts.maxWaitMs ?? 10_000;\n const { config } = await loadConfig(root);\n const matcher = await IgnoreMatcher.load(root, config);\n const pending = new Set<string>();\n let timer: NodeJS.Timeout | null = null;\n let firstChangeAt = 0;\n let running: Promise<SyncPlan | null> | null = null;\n let rerun = false;\n let latest: SyncPlan | null = null;\n let closed = false;\n\n const toRel = (abs: string) => toPosix(path.relative(root, abs));\n\n const run = async (): Promise<SyncPlan | null> => {\n if (closed) return null;\n if (running) {\n rerun = true;\n return running;\n }\n const paths = [...pending];\n pending.clear();\n firstChangeAt = 0;\n running = (async () => {\n opts.onEvent({ type: 'planning', paths });\n try {\n const plan = await planSync(root, { signal: opts.signal });\n if (closed) return null;\n latest = plan;\n if (plan.upToDate) {\n latest = null;\n if (needsIndexRefreshOnly(plan)) {\n const result = await applySync(root, plan);\n opts.onEvent({ type: 'refreshed', plan, result });\n } else {\n opts.onEvent({ type: 'plan', plan });\n }\n return plan;\n }\n if (opts.autoApply && !plan.ignored) {\n const result = await applySync(root, plan);\n latest = null;\n opts.onEvent({ type: 'applied', plan, result });\n return plan;\n }\n opts.onEvent({ type: 'plan', plan });\n return plan;\n } catch (err) {\n if (!closed && !opts.signal?.aborted) opts.onEvent({ type: 'error', error: err as Error });\n return null;\n } finally {\n running = null;\n if (rerun && !closed) {\n rerun = false;\n schedule();\n }\n }\n })();\n return running;\n };\n\n const schedule = () => {\n if (closed) return;\n const now = Date.now();\n if (!firstChangeAt) firstChangeAt = now;\n if (timer) clearTimeout(timer);\n const wait = Math.max(0, Math.min(debounceMs, firstChangeAt + maxWaitMs - now));\n timer = setTimeout(() => {\n timer = null;\n void run();\n }, wait);\n };\n\n const onPath = (abs: string) => {\n const rel = toRel(abs);\n if (!rel || rel.startsWith('..')) return;\n if (rel === '.gitignore' || rel.endsWith('/.gitignore')) {\n const dir = rel === '.gitignore' ? '' : rel.slice(0, -'/.gitignore'.length);\n void fs\n .readFile(abs, 'utf8')\n .then((text) => matcher.setGitignore(dir, text))\n .catch(() => matcher.removeGitignore(dir));\n }\n pending.add(rel);\n opts.onEvent({ type: 'changes', paths: [rel] });\n schedule();\n };\n\n const watcher: FSWatcher = chokidarWatch(root, {\n ignoreInitial: true,\n persistent: true,\n followSymlinks: false,\n ignored: (abs, stats) => {\n const rel = toRel(abs);\n if (!rel || rel === '.') return false;\n if (rel.startsWith('..')) return true;\n if (rel === '.git' || rel.startsWith('.git/')) return true;\n if (stats) return matcher.ignores(rel, stats.isDirectory());\n return matcher.ignores(rel, false) || matcher.ignores(rel, true);\n },\n });\n // Subscribe to 'ready' immediately: it can fire before any later await resolves.\n const ready = new Promise<void>((resolve) => watcher.once('ready', () => resolve()));\n watcher.on('add', onPath).on('change', onPath).on('unlink', onPath).on('addDir', onPath).on('unlinkDir', onPath);\n watcher.on('error', (err) => opts.onEvent({ type: 'error', error: err as Error }));\n\n // Git HEAD moves (commit, checkout, pull) are relevant even when the working tree is unchanged.\n let headWatcher: FSWatcher | null = null;\n const gd = await gitDir(root);\n let lastHead: string | null = null;\n if (gd) {\n lastHead = (await git(root, ['rev-parse', 'HEAD'])).stdout.trim() || null;\n headWatcher = chokidarWatch([path.join(gd, 'HEAD'), path.join(gd, 'refs', 'heads')], { ignoreInitial: true, persistent: true, depth: 5 });\n headWatcher.on('all', () => {\n void git(root, ['rev-parse', 'HEAD']).then((r) => {\n const head = r.ok ? r.stdout.trim() : null;\n if (head && head !== lastHead) {\n opts.onEvent({ type: 'git-head', head: { from: lastHead, to: head } });\n lastHead = head;\n schedule();\n }\n });\n });\n headWatcher.on('error', () => {});\n }\n\n await ready;\n opts.onEvent({ type: 'ready' });\n\n const close = async () => {\n if (closed) return;\n closed = true;\n if (timer) clearTimeout(timer);\n await Promise.all([watcher.close(), headWatcher?.close()]);\n };\n opts.signal?.addEventListener('abort', () => void close(), { once: true });\n\n return {\n planNow: () => {\n if (timer) clearTimeout(timer);\n timer = null;\n return run();\n },\n latestPlan: () => latest,\n close,\n };\n}\n","import crypto from 'node:crypto';\n\n/**\n * Only events Athena actually observes are ever emitted. `source` states who did\n * it; AI agent events will only exist once a real integration (hooks) reports them.\n */\nexport type EventSource = 'athena' | 'web-ui' | 'filesystem' | 'agent';\n\nexport interface AthenaEvent {\n id: string;\n ts: string;\n source: EventSource;\n type: string;\n message: string;\n level: 'info' | 'success' | 'warn' | 'error';\n data?: Record<string, unknown>;\n}\n\n/** States the activity indicator can show. Agent work states require an agent integration. */\nexport type ActivityState = 'IDLE' | 'ANALYZING' | 'PLANNING' | 'CODING' | 'TESTING' | 'REVIEWING' | 'SUCCESS' | 'ERROR';\n\nexport interface Activity {\n state: ActivityState;\n /** Who the current state describes. */\n actor: 'athena' | 'agent' | 'none';\n task: string | null;\n reading: string[];\n since: string;\n}\n\ntype Listener = (e: AthenaEvent | { type: '__activity'; activity: Activity }) => void;\n\nexport class EventBus {\n private readonly buffer: AthenaEvent[] = [];\n private readonly listeners = new Set<Listener>();\n private current: Activity = { state: 'IDLE', actor: 'none', task: null, reading: [], since: new Date().toISOString() };\n private settleTimer: NodeJS.Timeout | null = null;\n\n constructor(private readonly capacity = 500) {}\n\n emit(e: Omit<AthenaEvent, 'id' | 'ts'> & { id?: string; ts?: string }): AthenaEvent {\n const event: AthenaEvent = { id: e.id ?? crypto.randomUUID(), ts: e.ts ?? new Date().toISOString(), ...e };\n this.buffer.push(event);\n if (this.buffer.length > this.capacity) this.buffer.splice(0, this.buffer.length - this.capacity);\n for (const l of this.listeners) l(event);\n return event;\n }\n\n /** Add historical events (e.g. from the agent log) without notifying listeners. */\n seed(events: AthenaEvent[]): void {\n this.buffer.push(...events);\n this.buffer.sort((a, b) => a.ts.localeCompare(b.ts));\n if (this.buffer.length > this.capacity) this.buffer.splice(0, this.buffer.length - this.capacity);\n }\n\n has(id: string): boolean {\n return this.buffer.some((e) => e.id === id);\n }\n\n recent(limit = 200): AthenaEvent[] {\n return this.buffer.slice(-limit);\n }\n\n activity(): Activity {\n return this.current;\n }\n\n setActivity(next: Omit<Activity, 'since'>, settleToIdleMs?: number): void {\n if (this.settleTimer) clearTimeout(this.settleTimer);\n this.settleTimer = null;\n this.current = { ...next, since: new Date().toISOString() };\n for (const l of this.listeners) l({ type: '__activity', activity: this.current });\n if (settleToIdleMs) {\n this.settleTimer = setTimeout(() => this.setActivity({ state: 'IDLE', actor: 'none', task: null, reading: [] }), settleToIdleMs);\n this.settleTimer.unref();\n }\n }\n\n subscribe(l: Listener): () => void {\n this.listeners.add(l);\n return () => this.listeners.delete(l);\n }\n\n close(): void {\n if (this.settleTimer) clearTimeout(this.settleTimer);\n this.listeners.clear();\n }\n}\n","import crypto from 'node:crypto';\nimport type { FastifyReply, FastifyRequest } from 'fastify';\n\nexport function generateToken(): string {\n return crypto.randomBytes(32).toString('base64url');\n}\n\nexport function tokensEqual(a: string, b: string): boolean {\n const ab = Buffer.from(a);\n const bb = Buffer.from(b);\n return ab.length === bb.length && crypto.timingSafeEqual(ab, bb);\n}\n\nexport function isLoopbackHost(host: string): boolean {\n return host === '127.0.0.1' || host === '::1' || host === 'localhost';\n}\n\nexport const SECURITY_HEADERS: Record<string, string> = {\n // Scripts only from our own origin. Inline styles are required by CodeMirror and Mermaid SVG output.\n 'Content-Security-Policy': \"default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self' data:; connect-src 'self'; object-src 'none'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'\",\n 'X-Content-Type-Options': 'nosniff',\n 'X-Frame-Options': 'DENY',\n 'Referrer-Policy': 'no-referrer',\n 'Cross-Origin-Opener-Policy': 'same-origin',\n 'Cross-Origin-Resource-Policy': 'same-origin',\n 'Permissions-Policy': 'camera=(), microphone=(), geolocation=()',\n};\n\nexport interface GuardOptions {\n token: string;\n /** Allowed Host header values, e.g. \"127.0.0.1:7432\". Empty = allow any (explicit remote mode). */\n allowedHosts: Set<string>;\n allowedOrigins: Set<string>;\n}\n\nconst UNSAFE_METHODS = new Set(['POST', 'PUT', 'PATCH', 'DELETE']);\n\n/**\n * Request guard:\n * - Host allowlist defeats DNS rebinding.\n * - Bearer token on every /api route (except health) defeats other local sites and processes.\n * - Origin check + JSON-only bodies on unsafe methods add CSRF defense in depth.\n */\nexport function makeGuard(opts: GuardOptions) {\n return async function guard(req: FastifyRequest, reply: FastifyReply): Promise<void> {\n const host = (req.headers.host ?? '').toLowerCase();\n if (opts.allowedHosts.size && !opts.allowedHosts.has(host)) {\n await reply.code(421).send({ error: 'Host not allowed' });\n return;\n }\n const url = req.url.split('?')[0]!;\n if (!url.startsWith('/api/') || url === '/api/health') return;\n\n const auth = req.headers.authorization ?? '';\n const token = auth.startsWith('Bearer ') ? auth.slice(7) : '';\n if (!token || !tokensEqual(token, opts.token)) {\n await reply.code(401).send({ error: 'Unauthorized', hint: 'Open the URL printed by `athena open`.' });\n return;\n }\n if (UNSAFE_METHODS.has(req.method)) {\n const origin = req.headers.origin;\n if (origin && opts.allowedOrigins.size && !opts.allowedOrigins.has(origin.toLowerCase())) {\n await reply.code(403).send({ error: 'Origin not allowed' });\n return;\n }\n const ct = req.headers['content-type'] ?? '';\n const hasBody = Number(req.headers['content-length'] ?? 0) > 0 || req.headers['transfer-encoding'];\n if (hasBody && !ct.toLowerCase().startsWith('application/json')) {\n await reply.code(415).send({ error: 'Content-Type must be application/json' });\n return;\n }\n }\n };\n}\n\nexport function allowedHostsFor(host: string, port: number): Set<string> {\n const hosts = new Set<string>();\n const names = isLoopbackHost(host) ? ['127.0.0.1', 'localhost', '[::1]'] : [host];\n for (const n of names) hosts.add(`${n}:${port}`.toLowerCase());\n return hosts;\n}\n\nexport function allowedOriginsFor(host: string, port: number): Set<string> {\n return new Set([...allowedHostsFor(host, port)].map((h) => `http://${h}`));\n}\n","import { promises as fs } from 'node:fs';\nimport path from 'node:path';\n\nconst TYPES: Record<string, string> = {\n '.html': 'text/html; charset=utf-8',\n '.js': 'text/javascript; charset=utf-8',\n '.mjs': 'text/javascript; charset=utf-8',\n '.css': 'text/css; charset=utf-8',\n '.svg': 'image/svg+xml',\n '.png': 'image/png',\n '.ico': 'image/x-icon',\n '.json': 'application/json; charset=utf-8',\n '.woff2': 'font/woff2',\n '.txt': 'text/plain; charset=utf-8',\n '.map': 'application/json; charset=utf-8',\n};\n\nexport interface StaticAsset {\n abs: string;\n type: string;\n immutable: boolean;\n}\n\n/**\n * Build an allowlist of servable files at startup. Requests are looked up in this\n * map by exact URL path — request input is never joined into a filesystem path.\n */\nexport async function buildAssetMap(webDir: string): Promise<Map<string, StaticAsset> | null> {\n try {\n await fs.access(path.join(webDir, 'index.html'));\n } catch {\n return null;\n }\n const map = new Map<string, StaticAsset>();\n async function walk(dir: string): Promise<void> {\n for (const ent of await fs.readdir(dir, { withFileTypes: true })) {\n const abs = path.join(dir, ent.name);\n if (ent.isDirectory()) await walk(abs);\n else if (ent.isFile()) {\n const ext = path.extname(ent.name).toLowerCase();\n const type = TYPES[ext];\n if (!type) continue;\n const urlPath = `/${path.relative(webDir, abs).split(path.sep).join('/')}`;\n map.set(urlPath, { abs, type, immutable: urlPath.startsWith('/assets/') });\n }\n }\n }\n await walk(webDir);\n return map;\n}\n\nexport const MISSING_UI_HTML = `<!doctype html><html><head><meta charset=\"utf-8\"><title>Athena</title></head>\n<body style=\"font-family:system-ui;background:#0b0d10;color:#e6e8eb;padding:48px\">\n<h1>Athena web UI assets not found</h1>\n<p>The API is running, but the UI has not been built. From the Athena repository run <code>npm run build</code>.</p>\n</body></html>`;\n","import net from 'node:net';\n\nexport const DEFAULT_PORT = 7432;\n\nexport function isPortFree(port: number, host: string): Promise<boolean> {\n return new Promise((resolve) => {\n const srv = net.createServer();\n srv.unref();\n srv.once('error', () => resolve(false));\n srv.listen({ port, host, exclusive: true }, () => srv.close(() => resolve(true)));\n });\n}\n\n/** First free port at or after `start`. Never silently binds a port another process owns. */\nexport async function findAvailablePort(host: string, start = DEFAULT_PORT, attempts = 100): Promise<number> {\n for (let p = start; p < start + attempts && p <= 65535; p++) {\n if (await isPortFree(p, host)) return p;\n }\n throw new Error(`No free port found in ${start}-${start + attempts - 1} on ${host}`);\n}\n","import { applySync, fileChangeCount, needsIndexRefreshOnly, planSync, summarizePlan, type SyncPlan } from '../../services/sync.js';\nimport { EXIT } from '../../services/errors.js';\nimport { requireProjectRoot, type GlobalOptions } from '../context.js';\nimport { confirm } from './clean.js';\nimport * as ui from '../ui/term.js';\n\nexport interface SyncOptions extends GlobalOptions {\n yes?: boolean;\n dryRun?: boolean;\n check?: boolean;\n diff?: boolean;\n force?: boolean;\n signal?: AbortSignal;\n}\n\nexport function colorDiff(patch: string): string {\n return patch\n .split('\\n')\n .map((l) => (l.startsWith('+++') || l.startsWith('---') ? ui.c.bold(l) : l.startsWith('+') ? ui.c.green(l) : l.startsWith('-') ? ui.c.red(l) : l.startsWith('@@') ? ui.c.cyan(l) : l))\n .join('\\n');\n}\n\nexport function printPlan(plan: SyncPlan, opts: { diff?: boolean } = {}): void {\n const fc = plan.fileChanges;\n const count = fileChangeCount(plan);\n ui.heading('Changes since last analysis');\n if (count) {\n const parts = [fc.modified.length && `${fc.modified.length} modified`, fc.added.length && `${fc.added.length} added`, fc.deleted.length && `${fc.deleted.length} deleted`, fc.renamed.length && `${fc.renamed.length} renamed`].filter(Boolean);\n ui.line(` ${count} file${count === 1 ? '' : 's'} ${ui.dim(`(${parts.join(' · ')})`)}`);\n const sample = [...fc.modified.map((p) => `M ${p}`), ...fc.added.map((p) => `A ${p}`), ...fc.deleted.map((p) => `D ${p}`), ...fc.renamed.map((r) => `R ${r.from} → ${r.to}`)];\n for (const s of sample.slice(0, 8)) ui.line(` ${ui.dim(s)}`);\n if (sample.length > 8) ui.line(ui.dim(` +${sample.length - 8} more`));\n } else {\n ui.line(ui.dim(' No file changes.'));\n }\n const g = plan.git;\n if (g.isRepo && g.previousHead && g.head && g.previousHead !== g.head) {\n if (g.branchChanged) ui.line(` Git: branch changed ${ui.c.bold(g.previousBranch ?? '?')} → ${ui.c.bold(g.branch ?? '?')}`);\n if (g.diverged) ui.line(` Git: HEAD moved to ${g.head.slice(0, 8)} ${ui.dim('(not a descendant of the last analyzed commit — rebase, reset or checkout)')}`);\n else if (g.commits.length) {\n ui.line(` Git: ${g.commits.length}${g.truncated ? '+' : ''} new commit${g.commits.length === 1 ? '' : 's'}`);\n for (const c of g.commits.slice(0, 5)) ui.line(` ${ui.dim(`${c.sha.slice(0, 8)} ${c.subject}`)}`);\n }\n }\n\n if (plan.modelChanges.length) {\n ui.line();\n ui.heading('Detected project changes');\n for (const m of plan.modelChanges) ui.bullet(`${m.label}: ${ui.dim(m.summary)}`);\n }\n\n ui.line();\n if (plan.upToDate) {\n ui.ok('Knowledge already reflects these changes — no document needs updating.');\n if (plan.checkedUnchanged.length) ui.line(ui.dim(` Checked: ${plan.checkedUnchanged.join(', ')}`));\n return;\n }\n ui.heading('Knowledge to update');\n const width = Math.max(...plan.documents.map((d) => d.file.length));\n for (const d of plan.documents) {\n const sign = d.status === 'created' ? ui.c.green('+') : ui.c.yellow('~');\n ui.line(` ${sign} ${d.file.padEnd(width)} ${ui.c.green(`+${d.additions}`)} ${ui.c.red(`−${d.deletions}`)} ${ui.dim(d.changedSections.join(', '))}`);\n for (const r of d.reasons.slice(0, 3)) ui.line(` ${ui.dim(`${ui.sym.arrow} ${r}`)}`);\n if (d.preservedSections.length) ui.line(` ${ui.c.yellow(ui.sym.warn)} ${ui.dim(`your edits kept in: ${d.preservedSections.join(', ')}`)}`);\n }\n if (plan.checkedUnchanged.length) ui.line(ui.dim(` Checked and unchanged: ${plan.checkedUnchanged.join(', ')}`));\n if (plan.ignored) ui.line(ui.dim(' (You previously ignored this exact proposal.)'));\n if (opts.diff) {\n for (const d of plan.documents) {\n ui.line();\n ui.line(colorDiff(d.diff.replace(/^=+\\n/m, '')));\n }\n }\n}\n\nexport async function syncCommand(opts: SyncOptions): Promise<number> {\n const root = await requireProjectRoot(opts);\n const sp = ui.spinner('Checking for changes...');\n let plan: SyncPlan;\n try {\n plan = await planSync(root, { signal: opts.signal, force: opts.force });\n sp.stop();\n } catch (err) {\n sp.stop();\n throw err;\n }\n\n if (ui.isJson() && (opts.dryRun || opts.check)) {\n ui.json({ ...summarizePlan(plan), ...(opts.diff ? { diffs: Object.fromEntries(plan.documents.map((d) => [d.file, d.diff])) } : {}) });\n return opts.check && !plan.upToDate ? 1 : EXIT.OK;\n }\n if (!ui.isJson() && !ui.isQuiet()) {\n ui.heading('Athena Sync');\n ui.line();\n printPlan(plan, { diff: opts.diff });\n ui.line();\n } else if (!ui.isJson() && !plan.upToDate) {\n ui.line(`Proposed: ${plan.documents.map((d) => d.file).join(', ')}`);\n }\n\n if (opts.check) {\n if (!ui.isJson()) ui.line(plan.upToDate ? ui.c.green('Knowledge is synchronized.') : ui.c.yellow('Knowledge is out of date. Run `athena sync` to review and apply.'));\n return plan.upToDate ? EXIT.OK : 1;\n }\n if (opts.dryRun) {\n if (!ui.isJson()) ui.line(ui.dim('Dry run — nothing was written.'));\n return EXIT.OK;\n }\n\n if (plan.upToDate) {\n if (needsIndexRefreshOnly(plan)) {\n const r = await applySync(root, plan);\n if (ui.isJson()) ui.json({ ...summarizePlan(plan), applied: r });\n else ui.info(ui.dim('File index refreshed.'));\n } else if (ui.isJson()) ui.json(summarizePlan(plan));\n return EXIT.OK;\n }\n\n let approved = Boolean(opts.yes);\n if (!approved) {\n if (!process.stdin.isTTY) {\n if (ui.isJson()) ui.json(summarizePlan(plan));\n else ui.line(ui.c.yellow('Not applied: confirmation required. Re-run with --yes to apply, or --diff to inspect changes.'));\n return EXIT.OK;\n }\n approved = await confirm(`Apply updates to ${plan.documents.length} document${plan.documents.length === 1 ? '' : 's'}?`);\n }\n if (!approved) {\n ui.line('Not applied.');\n return EXIT.OK;\n }\n const result = await applySync(root, plan);\n if (ui.isJson()) ui.json({ ...summarizePlan(plan), applied: result });\n else {\n ui.ok(`Updated ${result.applied.join(', ')}`);\n for (const p of result.preserved) ui.warn(`${p.file}: kept your edits in ${p.sections.join(', ')} ${ui.dim('(use `athena analyze --force` to regenerate)')}`);\n }\n return EXIT.OK;\n}\n","import path from 'node:path';\nimport { appendEvent } from '../../services/agent-activity.js';\nimport { findProjectRoot } from '../../services/project.js';\nimport { normalizeHookEvent } from '../../agents/common/hook-events.js';\n\nexport interface EventOptions {\n agent?: string;\n hook?: string;\n cwd?: string;\n verbose?: boolean;\n}\n\nconst STDIN_TIMEOUT_MS = 2000;\nconst MAX_PAYLOAD_BYTES = 256 * 1024;\n\nasync function readStdin(): Promise<string> {\n if (process.stdin.isTTY) return '';\n return new Promise((resolve) => {\n let data = '';\n let done = false;\n const finish = () => {\n if (done) return;\n done = true;\n process.stdin.removeAllListeners();\n resolve(data);\n };\n const timer = setTimeout(finish, STDIN_TIMEOUT_MS);\n timer.unref();\n process.stdin.setEncoding('utf8');\n process.stdin.on('data', (chunk: string) => {\n data += chunk;\n if (data.length > MAX_PAYLOAD_BYTES) finish();\n });\n process.stdin.on('end', () => {\n clearTimeout(timer);\n finish();\n });\n process.stdin.on('error', () => {\n clearTimeout(timer);\n finish();\n });\n });\n}\n\n/**\n * Record one agent hook event. Designed to be called by coding agents:\n * it never writes to stdout (agents may parse it), never blocks the agent,\n * and always exits 0 so a failure here cannot break someone's session.\n */\nexport async function eventCommand(opts: EventOptions): Promise<void> {\n try {\n const raw = await readStdin();\n let payload: Record<string, unknown> = {};\n if (raw.trim().startsWith('{')) {\n try {\n payload = JSON.parse(raw) as Record<string, unknown>;\n } catch {\n payload = {};\n }\n }\n const cwdCandidates = [opts.cwd, typeof payload.cwd === 'string' ? payload.cwd : undefined, Array.isArray(payload.workspace_roots) ? (payload.workspace_roots as unknown[]).find((x) => typeof x === 'string') as string | undefined : undefined, process.cwd()];\n let root: string | null = null;\n for (const c of cwdCandidates) {\n if (!c) continue;\n root = await findProjectRoot(path.resolve(c));\n if (root) break;\n }\n if (!root) return; // project not initialized: nothing to record\n\n const event = normalizeHookEvent(opts.agent ?? 'unknown', opts.hook ?? '', payload);\n if (!event) return;\n await appendEvent(root, event);\n } catch (err) {\n if (opts.verbose) process.stderr.write(`athena event: ${(err as Error).message}\\n`);\n }\n}\n","import { readRecentEvents, summarizeSessions } from '../../services/agent-activity.js';\nimport { listAgents } from '../../services/agents.js';\nimport { requireProjectRoot, type GlobalOptions } from '../context.js';\nimport * as ui from '../ui/term.js';\n\nexport interface ActivityOptions extends GlobalOptions {\n limit?: string;\n agent?: string;\n}\n\nconst STATE_COLOR: Record<string, (s: string) => string> = {\n ANALYZING: ui.c.cyan,\n PLANNING: ui.c.magenta,\n CODING: ui.c.blue,\n TESTING: ui.c.yellow,\n REVIEWING: ui.c.cyan,\n SUCCESS: ui.c.green,\n IDLE: ui.c.dim,\n};\n\nexport async function activityCommand(opts: ActivityOptions): Promise<void> {\n const root = await requireProjectRoot(opts);\n const limit = Math.min(Math.max(Number(opts.limit ?? 30) || 30, 1), 500);\n const all = await readRecentEvents(root, 500);\n const events = (opts.agent ? all.filter((e) => e.agent === opts.agent) : all).slice(-limit);\n\n if (ui.isJson()) {\n ui.json({ events, sessions: summarizeSessions(all) });\n return;\n }\n ui.heading('AI Agent Activity');\n ui.line();\n if (!events.length) {\n const agents = await listAgents(root);\n const reporting = agents.filter((a) => a.activityObservation === 'hooks');\n ui.line(ui.dim('No agent activity recorded yet.'));\n ui.line(ui.dim(reporting.length ? `Hooks are installed for: ${reporting.map((a) => a.name).join(', ')}. Events appear once an agent runs in this project.` : 'Install hooks with `athena agents add claude-code` (or cursor) to record agent activity.'));\n return;\n }\n for (const e of events) {\n const time = new Date(e.ts).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false });\n const color = STATE_COLOR[e.state] ?? ((s: string) => s);\n ui.line(`${ui.dim(time)} ${color(ui.sym.dot)} ${ui.c.bold(e.agent)} ${ui.dim('·')} ${e.message}`);\n }\n ui.line();\n for (const s of summarizeSessions(all).slice(0, 5)) {\n ui.line(ui.dim(`${s.agent} ${s.session ? `(${s.session.slice(0, 8)})` : ''}: ${s.events} events, last ${ui.relativeTime(s.lastEventAt)}`));\n }\n ui.line(ui.dim('Only hook-reported tool use is shown. Athena cannot see agent reasoning.'));\n}\n","import path from 'node:path';\nimport { ProjectModel } from '../../core/model/project-model.js';\nimport { readTextIfExists } from '../../core/util/fs.js';\nimport { athenaDir } from '../../core/state/state.js';\nimport { analyzeProject } from '../../core/analyzer/analyze.js';\nimport { loadScan, meetsThreshold, runSecurityScan, saveScan, SEVERITY_ORDER, type SecurityScan, type Severity } from '../../services/security.js';\nimport { AthenaError, EXIT } from '../../services/errors.js';\nimport { requireProjectRoot, type GlobalOptions } from '../context.js';\nimport * as ui from '../ui/term.js';\n\nexport interface SecurityOptions extends GlobalOptions {\n noAudit?: boolean;\n failOn?: string;\n last?: boolean;\n signal?: AbortSignal;\n}\n\nconst TONE: Record<Severity, (s: string) => string> = {\n critical: ui.c.red,\n high: ui.c.red,\n moderate: ui.c.yellow,\n low: ui.c.cyan,\n unknown: ui.c.dim,\n};\n\nasync function loadModel(root: string, signal?: AbortSignal): Promise<ProjectModel> {\n const raw = await readTextIfExists(path.join(athenaDir(root), 'model.json'));\n if (raw) {\n try {\n const parsed = ProjectModel.safeParse(JSON.parse(raw));\n if (parsed.success) return parsed.data;\n } catch {\n /* fall through to a fresh analysis */\n }\n }\n return (await analyzeProject(root, { signal })).model;\n}\n\nexport function printScan(scan: SecurityScan, model: ProjectModel): void {\n ui.heading('Secrets');\n if (scan.secrets.count) {\n ui.warn(`${scan.secrets.count} potential hardcoded secret(s) in ${scan.secrets.files.length} file(s)`);\n for (const f of scan.secrets.files.slice(0, 8)) ui.line(` ${ui.dim(f)}`);\n ui.line(ui.dim(' Values are never stored. See .athena/security.md for types and locations.'));\n } else {\n ui.ok('No likely secrets matched Athena\\'s patterns in scanned files');\n ui.line(ui.dim(' Gitignored and oversized files are not scanned — this is not proof that none exist.'));\n }\n\n ui.line();\n ui.heading('Dependency audit');\n if (!scan.tools.length) {\n ui.line(ui.dim(' No auditable ecosystems detected (no lockfiles or supported manifests).'));\n }\n for (const t of scan.tools) {\n if (t.status !== 'ok') {\n ui.line(`${ui.c.dim(ui.sym.ring)} ${t.tool} ${ui.dim(`— ${t.status}: ${t.message ?? ''}`)}`);\n continue;\n }\n if (!t.findings.length) {\n ui.ok(`${t.tool} ${ui.dim(`— no known vulnerable dependencies (${(t.durationMs / 1000).toFixed(1)}s)`)}`);\n continue;\n }\n const bySeverity = SEVERITY_ORDER.map((s) => [s, t.findings.filter((f) => f.severity === s).length] as const).filter(([, n]) => n > 0);\n ui.warn(`${t.tool} — ${t.findings.length} finding(s): ${bySeverity.map(([s, n]) => TONE[s](`${n} ${s}`)).join(', ')}`);\n for (const f of t.findings.slice(0, 12)) {\n ui.line(` ${TONE[f.severity](f.severity.padEnd(8))} ${ui.c.bold(f.package)} ${ui.dim(f.title.slice(0, 70))}${f.fixAvailable ? ui.c.green(' (fix available)') : ''}`);\n }\n if (t.findings.length > 12) ui.line(ui.dim(` +${t.findings.length - 12} more — see .athena/security-scan.json`));\n }\n\n ui.line();\n ui.heading('Declared security controls');\n ui.line(model.security.controls.length ? ` ${model.security.controls.map((c) => c.name).join(', ')}` : ui.dim(' None detected'));\n ui.line(ui.dim(` Security tooling: ${model.security.tooling.length ? [...new Set(model.security.tooling.map((t) => t.name))].join(', ') : 'none detected'}`));\n ui.line();\n ui.line(ui.dim('Findings come from the tools above. Athena has no vulnerability database of its own, and a clean audit is not proof that the project is secure.'));\n}\n\nexport async function securityCommand(opts: SecurityOptions): Promise<number> {\n const root = await requireProjectRoot(opts);\n let scan: SecurityScan | null = null;\n let model: ProjectModel;\n\n if (opts.last) {\n scan = await loadScan(root);\n if (!scan) throw new AthenaError('No previous scan found.', 'Run `athena security` to scan now.');\n model = await loadModel(root, opts.signal);\n } else {\n const sp = ui.spinner('Analyzing project...');\n try {\n model = await loadModel(root, opts.signal);\n scan = await runSecurityScan(root, model, { signal: opts.signal, skipAudit: opts.noAudit, onTool: (tool) => sp.update(`Running ${tool}...`) });\n sp.succeed(`Security scan finished in ${(scan.durationMs / 1000).toFixed(1)}s`);\n } catch (err) {\n sp.stop();\n throw err;\n }\n await saveScan(root, scan);\n }\n\n if (ui.isJson()) ui.json(scan);\n else {\n ui.heading('Athena Security');\n ui.line(ui.dim(`Scanned ${ui.relativeTime(scan.scannedAt)}${opts.last ? ' (cached result)' : ''}`));\n ui.line();\n printScan(scan, model);\n if (!opts.last) ui.line(ui.dim('\\nRun `athena sync` to record these results in .athena/security.md.'));\n }\n\n if (opts.failOn) {\n const level = opts.failOn.toLowerCase() as Severity;\n if (!SEVERITY_ORDER.includes(level)) throw new AthenaError(`Invalid --fail-on value: ${opts.failOn}`, `Use one of: ${SEVERITY_ORDER.join(', ')}`);\n if (scan.secrets.count > 0 || meetsThreshold(scan, level)) return 1;\n }\n return EXIT.OK;\n}\n","import { hasBlockers, reviewChanges, type ReviewFinding } from '../../services/review.js';\nimport { planSync } from '../../services/sync.js';\nimport { EXIT } from '../../services/errors.js';\nimport { requireProjectRoot, type GlobalOptions } from '../context.js';\nimport * as ui from '../ui/term.js';\n\nexport interface ReviewOptions extends GlobalOptions {\n base?: string;\n noSync?: boolean;\n noFail?: boolean;\n signal?: AbortSignal;\n}\n\nconst LEVEL: Record<ReviewFinding['level'], { icon: () => string; label: string }> = {\n blocker: { icon: () => ui.c.red(ui.sym.err), label: 'blocker' },\n warning: { icon: () => ui.c.yellow(ui.sym.warn), label: 'warning' },\n info: { icon: () => ui.c.cyan(ui.sym.info), label: 'info' },\n};\n\nexport async function reviewCommand(opts: ReviewOptions): Promise<number> {\n const root = await requireProjectRoot(opts);\n const sp = ui.spinner('Reviewing changes...');\n let result;\n try {\n result = await reviewChanges(root, {\n base: opts.base,\n signal: opts.signal,\n checkSync: opts.noSync ? undefined : async (r) => (await planSync(r, { signal: opts.signal })).upToDate,\n });\n sp.stop();\n } catch (err) {\n sp.stop();\n throw err;\n }\n\n if (ui.isJson()) {\n ui.json(result);\n return !opts.noFail && hasBlockers(result) ? 1 : EXIT.OK;\n }\n\n ui.heading('Athena Review');\n ui.line();\n if (!result.changedFiles.length) {\n ui.line(ui.dim(opts.base ? `No changes between ${opts.base} and HEAD.` : 'No uncommitted changes.'));\n return EXIT.OK;\n }\n ui.line(`${result.stats.files} file${result.stats.files === 1 ? '' : 's'} changed ${ui.dim(`(${ui.c.green(`+${result.stats.added}`)} ${ui.c.red(`−${result.stats.removed}`)}${opts.base ? ` vs ${opts.base}` : ' in the working tree'})`)}`);\n ui.line();\n\n if (result.findings.length) {\n ui.heading('Automated checks');\n for (const f of result.findings) {\n ui.line(`${LEVEL[f.level].icon()} ${ui.c.bold(f.message)} ${ui.dim(`[${f.check}]`)}`);\n for (const file of f.files.slice(0, 6)) ui.line(` ${ui.dim(file)}`);\n if (f.files.length > 6) ui.line(ui.dim(` +${f.files.length - 6} more`));\n if (f.hint) ui.line(` ${ui.dim(f.hint)}`);\n }\n } else {\n ui.ok('Automated checks found nothing to flag.');\n }\n\n if (result.rules.length) {\n ui.line();\n ui.heading('Project rules to verify (from rules.md)');\n for (const r of result.rules.slice(0, 20)) ui.line(` ${ui.dim('[ ]')} ${r.text} ${ui.dim(`(${r.section})`)}`);\n if (result.rules.length > 20) ui.line(ui.dim(` +${result.rules.length - 20} more`));\n }\n if (result.checklist.length) {\n ui.line();\n ui.heading('Review checklist (from code-review.md)');\n for (const c of result.checklist.slice(0, 12)) ui.line(` ${ui.dim('[ ]')} ${c}`);\n if (result.checklist.length > 12) ui.line(ui.dim(` +${result.checklist.length - 12} more`));\n }\n\n ui.line();\n ui.line(ui.dim('Athena checks facts about the diff. Rules and checklist items are for you or your agent to apply — Athena does not judge whether they are met.'));\n const blockers = result.findings.filter((f) => f.level === 'blocker').length;\n if (blockers) ui.line(ui.c.red(`\\n${blockers} blocker${blockers === 1 ? '' : 's'} found.`));\n return !opts.noFail && hasBlockers(result) ? 1 : EXIT.OK;\n}\n","import { formatContext, getRelevantContext, graphSummary, refreshGraph } from '../../services/context.js';\nimport { loadGraph, neighbors } from '../../core/graph/graph.js';\nimport { AthenaError } from '../../services/errors.js';\nimport { requireProjectRoot, type GlobalOptions } from '../context.js';\nimport * as ui from '../ui/term.js';\n\nexport interface ContextCommandOptions extends GlobalOptions {\n maxChars?: string;\n full?: boolean;\n signal?: AbortSignal;\n}\n\nexport async function contextCommand(task: string, opts: ContextCommandOptions): Promise<void> {\n const root = await requireProjectRoot(opts);\n const maxChars = opts.maxChars ? Number(opts.maxChars) : undefined;\n if (maxChars !== undefined && (!Number.isInteger(maxChars) || maxChars < 500)) throw new AthenaError('--max-chars must be an integer of at least 500');\n const ctx = await getRelevantContext(root, task, { maxChars, buildGraph: true, signal: opts.signal });\n\n if (ui.isJson()) {\n ui.json(ctx);\n return;\n }\n if (opts.full) {\n ui.line(formatContext(ctx));\n return;\n }\n ui.heading(`Context for: ${task}`);\n ui.line();\n ui.heading('Documents to read');\n for (const a of ctx.areas) ui.bullet(`${ui.c.bold(a.id)} ${ui.dim(`— ${a.why.join('; ')}`)}`);\n if (ctx.mentionedFiles.length) {\n ui.line();\n ui.heading('Files named in the task');\n for (const f of ctx.mentionedFiles) ui.line(` ${ui.dim(f)}`);\n }\n if (ctx.graphNodes.length) {\n ui.line();\n ui.heading('Related code (project graph)');\n for (const n of ctx.graphNodes.slice(0, 12)) ui.line(` ${ui.dim(`${n.kind}:`)} ${n.name}${n.path ? ui.dim(` (${n.path})`) : ''}`);\n if (ctx.graphNodes.length > 12) ui.line(ui.dim(` +${ctx.graphNodes.length - 12} more`));\n }\n ui.line();\n ui.heading('Sections selected');\n for (const s of ctx.sections) ui.line(` ${ui.dim(`${s.file} →`)} ${s.section}`);\n ui.line();\n ui.line(ui.dim(`${ctx.sections.length} sections · ~${ctx.approxChars} characters · ${ctx.rules.length} rules${ctx.truncated ? ' · some sections omitted for budget' : ''}`));\n ui.line(ui.dim('Use --full to print the context an agent would read, or --json for tooling.'));\n}\n\nexport interface GraphCommandOptions extends GlobalOptions {\n build?: boolean;\n node?: string;\n kind?: string;\n search?: string;\n signal?: AbortSignal;\n}\n\nexport async function graphCommand(opts: GraphCommandOptions): Promise<void> {\n const root = await requireProjectRoot(opts);\n if (opts.build) {\n const sp = ui.spinner('Building project graph...');\n try {\n const graph = await refreshGraph(root, { signal: opts.signal });\n sp.succeed(`Graph built: ${graph.stats.nodes} nodes, ${graph.stats.edges} relationships`);\n } catch (err) {\n sp.stop();\n throw err;\n }\n }\n const graph = await loadGraph(root);\n if (!graph) throw new AthenaError('No project graph yet.', 'Run `athena graph --build`.');\n\n if (opts.node) {\n const hood = neighbors(graph, opts.node) ?? neighbors(graph, graph.nodes.find((n) => n.name === opts.node || n.path === opts.node)?.id ?? '');\n if (!hood) throw new AthenaError(`No graph node matches \"${opts.node}\".`, 'Use `athena graph --search <term>` to find one.');\n if (ui.isJson()) {\n ui.json(hood);\n return;\n }\n ui.heading(`${hood.node.kind}: ${hood.node.name}`);\n if (hood.node.path) ui.line(ui.dim(hood.node.path));\n ui.line();\n for (const e of hood.edges) ui.line(` ${e.direction === 'out' ? ui.sym.arrow : '←'} ${ui.dim(e.edge.kind)} ${e.other.kind}: ${e.other.name}${e.other.path ? ui.dim(` (${e.other.path})`) : ''}`);\n return;\n }\n\n const q = opts.search?.toLowerCase();\n const nodes = graph.nodes.filter((n) => (!opts.kind || n.kind === opts.kind) && (!q || `${n.name} ${n.path ?? ''}`.toLowerCase().includes(q)));\n if (ui.isJson()) {\n ui.json({ stats: graph.stats, builtAt: graph.builtAt, nodes: nodes.slice(0, 200) });\n return;\n }\n ui.heading('Project graph');\n ui.line(ui.dim(`Built ${ui.relativeTime(graph.builtAt)} · ${graph.stats.nodes} nodes · ${graph.stats.edges} relationships`));\n ui.line();\n for (const [kind, count] of Object.entries(graph.stats.byKind).sort((a, b) => b[1] - a[1])) ui.line(` ${String(count).padStart(5)} ${kind}`);\n if (q || opts.kind) {\n ui.line();\n ui.heading(`Matching nodes (${nodes.length})`);\n for (const n of nodes.slice(0, 30)) ui.line(` ${ui.dim(`${n.kind}:`)} ${n.name}${n.path ? ui.dim(` (${n.path})`) : ''}`);\n if (nodes.length > 30) ui.line(ui.dim(` +${nodes.length - 30} more`));\n }\n}\n\nexport async function architectureCommand(opts: GlobalOptions & { signal?: AbortSignal }): Promise<void> {\n const root = await requireProjectRoot(opts);\n const summary = await graphSummary(root);\n if (ui.isJson()) {\n ui.json(summary);\n return;\n }\n if (!summary.built) {\n ui.line(ui.dim('No project graph yet. Run `athena graph --build`.'));\n return;\n }\n ui.heading('Architecture (from the project graph)');\n ui.line(ui.dim(`Built ${ui.relativeTime(summary.builtAt!)}`));\n ui.line();\n for (const [kind, count] of Object.entries(summary.stats!.byKind).sort((a, b) => b[1] - a[1])) ui.line(` ${String(count).padStart(5)} ${kind}`);\n ui.line();\n ui.line(ui.dim('See .athena/architecture.md for the written architecture, and `athena graph --search <term>` to explore.'));\n}\n","import { aiStatus, buildEnrichPayload, enrich } from '../../services/ai.js';\nimport { requireProjectRoot, type GlobalOptions } from '../context.js';\nimport * as ui from '../ui/term.js';\n\nexport interface AiOptions extends GlobalOptions {\n docs?: string;\n consent?: boolean;\n dryRun?: boolean;\n signal?: AbortSignal;\n}\n\nexport async function aiStatusCommand(opts: GlobalOptions): Promise<void> {\n const root = await requireProjectRoot(opts);\n const status = await aiStatus(root);\n if (ui.isJson()) {\n ui.json(status);\n return;\n }\n ui.heading('AI providers');\n ui.line();\n for (const p of status.providers) {\n const icon = p.availability.ok ? ui.c.green(ui.sym.ok) : ui.c.dim(ui.sym.ring);\n ui.line(`${icon} ${ui.c.bold(p.name)}${p.selected ? ui.c.cyan(' (selected)') : ''}`);\n ui.line(` ${ui.dim(`${p.remote ? 'sends data to' : 'runs locally at'} ${p.availability.endpoint} · default model ${p.defaultModel}`)}`);\n if (!p.availability.ok) ui.line(` ${ui.dim(p.availability.reason ?? '')}`);\n }\n ui.line();\n ui.line(`Consent to send project knowledge: ${status.consent ? ui.c.green('granted in config') : ui.c.yellow('not granted')}`);\n ui.line(ui.dim('Athena never needs AI: analysis, sync, context and MCP are deterministic. AI only produces INFERRED suggestions you review.'));\n ui.line(ui.dim('Configure in .athena/config.json → \"ai\": { \"provider\": \"ollama\" } for a fully local setup.'));\n}\n\nexport async function aiEnrichCommand(opts: AiOptions): Promise<number> {\n const root = await requireProjectRoot(opts);\n const docs = opts.docs?.split(',').map((d) => d.trim()).filter(Boolean);\n const payload = await buildEnrichPayload(root, { docs });\n\n if (!ui.isJson()) {\n ui.heading('AI enrichment');\n ui.line();\n ui.line(`Provider: ${ui.c.bold(payload.provider.name)} ${ui.dim(`(${payload.model})`)}`);\n ui.line(`Sends to: ${payload.remote ? ui.c.yellow(payload.endpoint) : ui.c.green(`${payload.endpoint} (local)`)}`);\n ui.line(`Content: ${payload.documents.join(', ')} ${ui.dim(`(${payload.chars} characters, redacted knowledge only — no source code)`)}`);\n ui.line();\n }\n if (opts.dryRun) {\n if (ui.isJson()) ui.json({ ...payload, provider: payload.provider.id });\n else ui.line(ui.dim('Dry run — nothing was sent.'));\n return 0;\n }\n\n const sp = ui.spinner(`Asking ${payload.provider.name}...`);\n let result;\n try {\n result = await enrich(root, { docs, consent: opts.consent, signal: opts.signal });\n sp.succeed(`Suggestions written to .athena/${result.file}`);\n } catch (err) {\n sp.stop();\n throw err;\n }\n if (ui.isJson()) ui.json(result);\n else {\n ui.line();\n ui.line(result.markdown.split('\\n').slice(0, 40).join('\\n'));\n ui.line();\n ui.line(ui.dim(`Full suggestions: .athena/${result.file} (gitignored). These are INFERRED — nothing was added to your knowledge base.`));\n }\n return 0;\n}\n","import path from 'node:path';\nimport { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';\nimport { z } from 'zod';\nimport { KNOWLEDGE_DOCS, RELEVANCE_MAP } from '../core/knowledge/documents.js';\nimport { athenaDir, readState } from '../core/state/state.js';\nimport { readTextIfExists } from '../core/util/fs.js';\nimport { listRules, parseRules } from '../core/knowledge/rules.js';\nimport { formatContext, getGraph, getRelevantContext, graphSummary } from '../services/context.js';\nimport { buildStatus } from '../services/status.js';\nimport { planSync, applySync, summarizePlan } from '../services/sync.js';\nimport { loadScan } from '../core/model/security-scan.js';\nimport { ATHENA_VERSION } from '../services/version.js';\n\n/**\n * MCP server exposing Athena's project intelligence to any MCP-capable agent.\n *\n * Read-only by default: `update_knowledge` only *proposes* changes unless the\n * server was started with --allow-write, so an agent can never silently rewrite\n * a developer's knowledge base.\n */\n\nexport interface McpOptions {\n root: string;\n allowWrite?: boolean;\n}\n\nconst textResult = (text: string) => ({ content: [{ type: 'text' as const, text }] });\n\nasync function docText(root: string, file: string): Promise<string> {\n const text = await readTextIfExists(path.join(athenaDir(root), file));\n return text ?? `${file} does not exist yet. Run \\`athena init\\` or \\`athena analyze\\` in this project.`;\n}\n\nexport function createMcpServer(opts: McpOptions): McpServer {\n const { root } = opts;\n const server = new McpServer(\n { name: 'athena', version: ATHENA_VERSION },\n {\n instructions: [\n 'Athena provides maintained project knowledge for this repository.',\n 'Call get_relevant_context with the task you were given before making significant changes — it returns only the knowledge that matters for that task, plus the project rules.',\n 'Every statement carries a label: FACT and DETECTED are evidence-backed; INFERRED and UNKNOWN are not — verify those in the code before relying on them.',\n 'get_project_rules returns rules the developer expects you to follow.',\n ].join(' '),\n },\n );\n\n server.registerTool(\n 'get_relevant_context',\n {\n title: 'Get relevant project context for a task',\n description: 'Given a task description, return only the knowledge sections that matter for it, the project rules, and related code from the project graph. Prefer this over reading whole documents.',\n inputSchema: { task: z.string().min(3).describe('What you are about to do, e.g. \"add refunds to the payments API\"'), maxChars: z.number().int().min(500).max(60_000).optional() },\n },\n async ({ task, maxChars }) => textResult(formatContext(await getRelevantContext(root, task, { maxChars, buildGraph: true }))),\n );\n\n server.registerTool(\n 'get_project_context',\n { title: 'Project overview', description: 'Technologies, structure, entry points and commands (project.md).', inputSchema: {} },\n async () => textResult(await docText(root, 'project.md')),\n );\n\n server.registerTool(\n 'get_architecture',\n { title: 'Architecture', description: 'System and module architecture, service topology and data flow (architecture.md).', inputSchema: {} },\n async () => textResult(await docText(root, 'architecture.md')),\n );\n\n server.registerTool(\n 'get_database_schema',\n { title: 'Database schema', description: 'Databases, entities, relationships, indexes and migrations (database.md).', inputSchema: {} },\n async () => textResult(await docText(root, 'database.md')),\n );\n\n server.registerTool(\n 'get_api_context',\n { title: 'API context', description: 'Detected endpoints, API specifications and error handling notes (api.md).', inputSchema: {} },\n async () => textResult(await docText(root, 'api.md')),\n );\n\n server.registerTool(\n 'get_security_context',\n { title: 'Security context', description: 'Attack surface, controls, potential secrets and dependency audit results (security.md).', inputSchema: {} },\n async () => {\n const scan = await loadScan(root);\n const doc = await docText(root, 'security.md');\n const suffix = scan ? `\\n\\n_Last dependency scan: ${scan.scannedAt}._` : '\\n\\n_No dependency audit has been run (`athena security`)._';\n return textResult(doc + suffix);\n },\n );\n\n server.registerTool(\n 'get_project_rules',\n { title: 'Project rules', description: 'Developer-defined rules this project expects agents to follow. Disabled rules are excluded.', inputSchema: {} },\n async () => {\n const text = await readTextIfExists(path.join(athenaDir(root), 'rules.md'));\n if (!text) return textResult('No rules.md found. Run `athena init` in this project.');\n const rules = listRules(parseRules(text)).filter((r) => r.enabled);\n return textResult(rules.length ? ['# Project rules (all apply)', '', ...rules.map((r) => `- [${r.section}] ${r.text}`)].join('\\n') : 'rules.md contains no enabled rules.');\n },\n );\n\n server.registerTool(\n 'get_knowledge_document',\n {\n title: 'Read one knowledge document',\n description: `Read a full Athena document. Available: ${KNOWLEDGE_DOCS.map((d) => d.id).join(', ')}.`,\n inputSchema: { document: z.enum(KNOWLEDGE_DOCS.map((d) => d.id) as [string, ...string[]]) },\n },\n async ({ document }) => textResult(await docText(root, KNOWLEDGE_DOCS.find((d) => d.id === document)!.file)),\n );\n\n server.registerTool(\n 'get_project_changes',\n { title: 'Project changes since the last analysis', description: 'Files changed since Athena last analyzed the project, and which knowledge may be affected.', inputSchema: {} },\n async () => {\n const status = await buildStatus(root);\n const c = status.changes;\n return textResult(\n [\n `Knowledge health: ${status.health}; synchronization: ${status.sync}.`,\n `Changed since last analysis: ${c.modified.length} modified, ${c.added.length} added, ${c.deleted.length} deleted.`,\n c.modified.length ? `Modified: ${c.modified.slice(0, 40).join(', ')}` : '',\n c.added.length ? `Added: ${c.added.slice(0, 40).join(', ')}` : '',\n c.deleted.length ? `Deleted: ${c.deleted.slice(0, 40).join(', ')}` : '',\n status.affectedDocuments.length ? `Possibly affected knowledge: ${status.affectedDocuments.map((a) => `${a.file} (${a.reasons.join(', ')})`).join('; ')}` : 'No knowledge documents look affected.',\n ]\n .filter(Boolean)\n .join('\\n'),\n );\n },\n );\n\n server.registerTool(\n 'get_project_graph',\n {\n title: 'Project graph',\n description: 'Structured nodes (packages, files, routes, entities, frameworks) and their relationships. Optionally filter by kind or a search term.',\n inputSchema: { kind: z.enum(['package', 'file', 'route', 'entity', 'framework', 'command', 'infra']).optional(), search: z.string().optional(), limit: z.number().int().min(1).max(200).optional() },\n },\n async ({ kind, search, limit }) => {\n const graph = await getGraph(root, { build: true });\n if (!graph) return textResult('The project graph is not available. Run `athena analyze` first.');\n const q = search?.toLowerCase();\n const nodes = graph.nodes\n .filter((n) => (!kind || n.kind === kind) && (!q || `${n.name} ${n.path ?? ''}`.toLowerCase().includes(q)))\n .slice(0, limit ?? 60);\n const summary = Object.entries(graph.stats.byKind).map(([k, n]) => `${n} ${k}`).join(', ');\n return textResult([`Graph built ${graph.builtAt} — ${summary}; ${graph.stats.edges} relationships.`, '', ...nodes.map((n) => `- ${n.kind}: ${n.name}${n.path ? ` (${n.path})` : ''}`)].join('\\n'));\n },\n );\n\n server.registerTool(\n 'update_knowledge',\n {\n title: 'Update Athena knowledge',\n description: opts.allowWrite\n ? 'Re-analyze the project and update knowledge documents whose content changed.'\n : 'Check what a knowledge update would change. This server is read-only, so nothing is written — report the proposal to the developer, who can apply it with `athena sync`.',\n inputSchema: { apply: z.boolean().optional().describe('Apply the update (only permitted when the server runs with --allow-write)') },\n },\n async ({ apply }) => {\n const plan = await planSync(root);\n if (plan.upToDate) return textResult('Knowledge is already up to date; nothing to change.');\n const summary = [`${plan.documents.length} document(s) would change:`, ...plan.documents.map((d) => `- ${d.file}: ${d.reasons[0] ?? 'content differs'}`)].join('\\n');\n if (!apply) return textResult(`${summary}\\n\\nNothing was written. Run \\`athena sync\\` to review and apply.`);\n if (!opts.allowWrite) {\n return { ...textResult(`${summary}\\n\\nRefused: this MCP server is read-only. Ask the developer to run \\`athena sync\\`.`), isError: true };\n }\n const result = await applySync(root, plan);\n return textResult(`Updated: ${result.applied.join(', ')}.${result.preserved.length ? ` Developer-edited sections preserved in ${result.preserved.map((p) => p.file).join(', ')}.` : ''}`);\n },\n );\n\n server.registerTool(\n 'get_athena_status',\n { title: 'Athena status', description: 'Whether Athena knowledge exists, when it was last analyzed, and what it covers.', inputSchema: {} },\n async () => {\n const st = await readState(athenaDir(root));\n if (st.kind !== 'ok') return textResult(`Athena state is ${st.kind}. Run \\`athena init\\` (or \\`athena analyze\\`) in ${root}.`);\n const graph = await graphSummary(root);\n const plan = await planSync(root).catch(() => null);\n return textResult(\n [\n `Project: ${st.state.projectName} (${root})`,\n `Last analyzed: ${st.state.analyzedAt}`,\n `Documents: ${Object.keys(st.state.documents).length}`,\n graph.built ? `Graph: ${graph.stats!.nodes} nodes, ${graph.stats!.edges} edges (built ${graph.builtAt})` : 'Graph: not built yet',\n plan ? (plan.upToDate ? 'Knowledge is in sync with the code.' : `Knowledge is out of date: ${plan.documents.map((d) => d.file).join(', ')} would change.`) : '',\n `Relevance map: ${RELEVANCE_MAP.length} task types.`,\n ]\n .filter(Boolean)\n .join('\\n'),\n );\n },\n );\n\n return server;\n}\n\n/** Connect over stdio and resolve when the client disconnects (or `signal` aborts). */\nexport async function runMcpServer(opts: McpOptions & { signal?: AbortSignal }): Promise<void> {\n const server = createMcpServer(opts);\n const transport = new StdioServerTransport();\n const closed = new Promise<void>((resolve) => {\n transport.onclose = () => resolve();\n opts.signal?.addEventListener('abort', () => resolve(), { once: true });\n });\n await server.connect(transport);\n await closed;\n await server.close().catch(() => {});\n}\n\nexport { summarizePlan };\n","import { runMcpServer } from '../../mcp/server.js';\nimport { requireProjectRoot, type GlobalOptions } from '../context.js';\n\nexport interface McpCommandOptions extends GlobalOptions {\n allowWrite?: boolean;\n signal?: AbortSignal;\n}\n\n/**\n * Serve Athena knowledge over MCP on stdio. Nothing may be written to stdout\n * except protocol messages, so this command prints no banner or logs.\n */\nexport async function mcpCommand(opts: McpCommandOptions): Promise<void> {\n const root = await requireProjectRoot(opts);\n await runMcpServer({ root, allowWrite: opts.allowWrite, signal: opts.signal });\n}\n","import { watchProject, type WatchEvent } from '../../services/watch.js';\nimport { AthenaError } from '../../services/errors.js';\nimport { requireProjectRoot, type GlobalOptions } from '../context.js';\nimport * as ui from '../ui/term.js';\n\nexport interface WatchOptions extends GlobalOptions {\n autoApply?: boolean;\n debounce?: string;\n signal: AbortSignal;\n}\n\nconst time = () => new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false });\n\nexport async function watchCommand(opts: WatchOptions): Promise<void> {\n const root = await requireProjectRoot(opts);\n let debounceMs: number | undefined;\n if (opts.debounce !== undefined) {\n debounceMs = Number(opts.debounce);\n if (!Number.isInteger(debounceMs) || debounceMs < 100 || debounceMs > 60_000) throw new AthenaError('--debounce must be between 100 and 60000 ms');\n }\n const burst = new Set<string>();\n\n const log = (line: string) => {\n if (ui.isJson()) return;\n ui.line(`${ui.dim(time())} ${line}`);\n };\n\n const onEvent = (e: WatchEvent) => {\n if (ui.isJson()) {\n const { plan, error, ...rest } = e;\n if (e.type !== 'changes') process.stdout.write(`${JSON.stringify({ ...rest, ts: new Date().toISOString(), ...(plan ? { planId: plan.id, upToDate: plan.upToDate, documents: plan.documents.map((d) => ({ file: d.file, reasons: d.reasons })) } : {}), ...(error ? { error: error.message } : {}) })}\\n`);\n return;\n }\n switch (e.type) {\n case 'changes':\n for (const p of e.paths ?? []) burst.add(p);\n break;\n case 'git-head':\n log(`${ui.c.cyan('git')} HEAD moved ${ui.dim(`${e.head?.from?.slice(0, 8) ?? '?'} → ${e.head?.to?.slice(0, 8) ?? '?'}`)}`);\n break;\n case 'planning': {\n const n = burst.size;\n if (n) log(`${n} file${n === 1 ? '' : 's'} changed ${ui.dim(`(${[...burst].slice(0, 3).join(', ')}${n > 3 ? ', …' : ''})`)} — checking knowledge…`);\n burst.clear();\n break;\n }\n case 'refreshed':\n log(`${ui.c.green(ui.sym.ok)} Knowledge up to date ${ui.dim('(index refreshed)')}`);\n break;\n case 'plan': {\n const plan = e.plan!;\n if (plan.upToDate) {\n log(`${ui.c.green(ui.sym.ok)} Knowledge up to date`);\n break;\n }\n if (plan.ignored) {\n log(ui.dim(`Proposal unchanged since you ignored it (${plan.documents.map((d) => d.file).join(', ')})`));\n break;\n }\n log(`${ui.c.yellow(ui.sym.dot)} Update proposed for ${ui.c.bold(plan.documents.map((d) => d.file).join(', '))}`);\n for (const d of plan.documents) log(` ${ui.dim(`${d.file}: ${d.reasons[0] ?? ''}`)}`);\n log(ui.dim(' Review and apply with `athena sync` (or in the web UI).'));\n break;\n }\n case 'applied':\n log(`${ui.c.green(ui.sym.ok)} Applied ${e.result?.applied.join(', ')} ${ui.dim('(auto-apply)')}`);\n for (const p of e.result?.preserved ?? []) log(` ${ui.c.yellow(ui.sym.warn)} ${p.file}: kept your edits in ${p.sections.join(', ')}`);\n break;\n case 'error':\n log(`${ui.c.red(ui.sym.err)} ${e.error?.message ?? 'Watcher error'}`);\n break;\n default:\n break;\n }\n };\n\n const watcher = await watchProject(root, { autoApply: opts.autoApply, debounceMs, onEvent, signal: opts.signal });\n ui.setInterruptMessage('Stopped watching.');\n if (!ui.isJson()) {\n ui.line(`${ui.c.bold('Athena is watching')} ${ui.dim(root)}`);\n ui.line(opts.autoApply ? ui.c.yellow('Auto-apply is ON: knowledge updates are written automatically (your edited sections are still preserved).') : ui.dim('Proposals only — no knowledge document is changed without your review. Press Ctrl+C to stop.'));\n ui.line();\n }\n // Check once at startup so changes made while Athena wasn't running are caught.\n await watcher.planNow();\n\n await new Promise<void>((resolve) => {\n if (opts.signal.aborted) resolve();\n opts.signal.addEventListener('abort', () => resolve(), { once: true });\n });\n await watcher.close();\n}\n","import { configureAgents, listAgents, removeAgents } from '../../services/agents.js';\nimport { requireProjectRoot, type GlobalOptions } from '../context.js';\nimport * as ui from '../ui/term.js';\n\nexport async function agentsListCommand(opts: GlobalOptions): Promise<void> {\n const root = await requireProjectRoot(opts);\n const rows = await listAgents(root);\n if (ui.isJson()) {\n ui.json(rows);\n return;\n }\n ui.heading('AI Agent Integrations');\n ui.line();\n for (const r of rows) {\n const icon = r.configured ? ui.c.green(ui.sym.dot) : ui.c.dim(ui.sym.ring);\n ui.line(`${icon} ${ui.c.bold(r.name)} ${ui.dim(`(${r.id})`)} — ${r.configured ? 'configured' : 'not configured'}${r.detectedInProject ? ui.dim(` · detected: ${r.evidence.join(', ')}`) : ''}`);\n ui.line(` ${ui.dim(r.note)}`);\n }\n ui.line();\n ui.line(ui.dim('\"Configured\" means Athena instruction files are in place. Agents with hooks also report their tool use — see `athena activity`.'));\n}\n\nexport async function agentsAddCommand(names: string[], opts: GlobalOptions): Promise<void> {\n const root = await requireProjectRoot(opts);\n const results = await configureAgents(root, names);\n if (ui.isJson()) ui.json({ ok: true, agents: results });\n else for (const r of results) ui.ok(`${r.id}: ${r.files.map((f) => `${f.path} (${f.action})`).join(', ')}`);\n}\n\nexport async function agentsRemoveCommand(names: string[], opts: GlobalOptions): Promise<void> {\n const root = await requireProjectRoot(opts);\n const removed = await removeAgents(root, names);\n if (ui.isJson()) ui.json({ ok: true, removed });\n else ui.ok(removed.length ? `Removed Athena integration from ${removed.join(', ')}` : 'Nothing to remove');\n}\n"],"mappings":";;;AAAA,SAAS,WAAAA,UAAS,cAAc;;;ACAhC,SAAS,qBAAqB;AAGvB,IAAM,eAAe;AAE5B,SAAS,cAAsB;AAC7B,MAAI;AACF,UAAMC,WAAU,cAAc,YAAY,GAAG;AAE7C,eAAW,KAAK,CAAC,mBAAmB,oBAAoB,GAAG;AACzD,UAAI;AACF,cAAM,MAAMA,SAAQ,CAAC;AACrB,YAAI,IAAI,SAAS,gBAAgB,IAAI,QAAS,QAAO,IAAI;AAAA,MAC3D,QAAQ;AAAA,MAER;AAAA,IACF;AAAA,EACF,QAAQ;AAAA,EAER;AACA,SAAO;AACT;AAEO,IAAM,iBAAiB,YAAY;;;ACvBnC,IAAM,OAAO;AAAA,EAClB,IAAI;AAAA,EACJ,OAAO;AAAA,EACP,eAAe;AAAA,EACf,iBAAiB;AAAA,EACjB,aAAa;AACf;AAMO,IAAM,cA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IACH;AAAA,EACJ;AACA,SAAO;AACT;AAEA,eAAe,OAAsB;AACnC,QAAM,UAAU,aAAa;AAC7B,MAAI;AACF,UAAM,QAAQ,WAAW,QAAQ,IAAI;AAAA,EACvC,SAAS,KAAK;AACZ,QAAI,QAAQ,OAAO,MAAO,SAAQ,OAAO,MAAM,WAAW;AAC1D,QAAI,WAAW,OAAO,SAAS;AAC7B,cAAQ,WAAW,KAAK;AACxB;AAAA,IACF;AACA,QAAI,eAAe,aAAa;AAC9B,UAAO,OAAO,EAAG,CAAG,KAAK,EAAE,OAAO,IAAI,SAAS,MAAM,IAAI,KAAK,CAAC;AAAA,WAC1D;AACH,gBAAQ,OAAO,MAAM,GAAM,EAAE,IAAI,GAAM,IAAI,GAAG,IAAI,IAAI,OAAO,EAAE,CAAC;AAAA,CAAI;AACpE,YAAI,IAAI,KAAM,SAAQ,OAAO,MAAM,KAAQ,IAAI,IAAI,IAAI,CAAC;AAAA,CAAI;AAAA,MAC9D;AACA,cAAQ,WAAW,IAAI;AACvB;AAAA,IACF;AACA,YAAQ,OAAO,MAAM,GAAM,EAAE,IAAI,GAAM,IAAI,GAAG,sBAAuB,IAAc,OAAO,EAAE,CAAC;AAAA,CAAI;AACjG,QAAI,QAAQ,IAAI,aAAc,SAAQ,OAAO,MAAM,GAAI,IAAc,KAAK;AAAA,CAAI;AAAA,QACzE,SAAQ,OAAO,MAAM,KAAQ,IAAI,iEAAiE,CAAC;AAAA,CAAI;AAC5G,YAAQ,WAAW,KAAK;AAAA,EAC1B;AACF;AAEA,MAAM,KAAK;","names":["Command","require","path","fs","path","z","path","path","z","path","fs","json","fs","path","path","path","path","fs","path","fs","path","mutate","path","fs","path","fs","path","fs","out","crypto","out","c","path","fs","path","MCP_FILE","fs","path","path","RULE_FILE","path","names","out","c","fs","path","fs","path","crypto","path","fs","fs","path","crypto","fs","path","fs","path","fs","path","crypto","out","z","z","z","fs","path","ignoreFactory","json","line","ignoreFactory","names","table","cur","fs","path","c","out","fs","path","parseYaml","isObj","out","parseYaml","c","out","line","c","c","line","out","fw","resolve","info","line","path","out","code","exists","fs","path","walk","out","path","c","c","c","MAX_ROUTES","c","c","names","names","c","c","out","z","path","z","path","athenaDir","path","path","fs","agentChanges","crypto","c","fs","path","fs","path","fs","path","path","fs","path","c","path","path","walk","git","fs","path","out","relativeTime","fs","path","path","info","fs","fs","path","fs","path","path","fs","out","line","c","fs","relativeTime","path","c","path","path","out","path","line","path","out","view","fs","fs","execFile","fs","path","fs","crypto","path","names","out","c","path","path","c","fs","path","out","line","path","c","git","fs","execFile","json","out","line","resolve","execFile","path","out","names","path","line","path","z","path","z","path","c","out","out","c","n","path","path","z","json","c","path","fs","path","path","run","fs","resolve","crypto","crypto","auth","names","fs","path","walk","crypto","status","parseIndex","fs","path","resolve","path","info","fs","execFile","resolve","c","path","resolve","c","path","time","path","loadModel","path","c","c","graph","status","path","z","path","z","status","c","resolve","line","resolve","names","run","code","Command","names"]}
|