@chrisdudek/yg 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/README.md +81 -0
- package/dist/bin.d.ts +1 -0
- package/dist/bin.js +3294 -0
- package/dist/bin.js.map +1 -0
- package/dist/templates/default-config.ts +55 -0
- package/dist/templates/platform.ts +257 -0
- package/dist/templates/rules.ts +142 -0
- package/graph-templates/aspect.yaml +2 -0
- package/graph-templates/flow.yaml +8 -0
- package/graph-templates/knowledge-scope-nodes.yaml +5 -0
- package/graph-templates/knowledge-scope-tags.yaml +3 -0
- package/graph-templates/knowledge.yaml +2 -0
- package/graph-templates/library.yaml +22 -0
- package/graph-templates/module.yaml +18 -0
- package/graph-templates/node.yaml +17 -0
- package/graph-templates/service.yaml +30 -0
- package/package.json +69 -0
package/dist/bin.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/bin.ts","../src/cli/init.ts","../src/templates/default-config.ts","../src/templates/platform.ts","../src/templates/rules.ts","../src/core/graph-loader.ts","../src/io/config-parser.ts","../src/io/node-parser.ts","../src/io/aspect-parser.ts","../src/io/artifact-reader.ts","../src/io/flow-parser.ts","../src/io/knowledge-parser.ts","../src/io/template-parser.ts","../src/utils/paths.ts","../src/core/context-builder.ts","../src/utils/tokens.ts","../src/core/validator.ts","../src/utils/git.ts","../src/formatters/markdown.ts","../src/cli/build-context.ts","../src/cli/validate.ts","../src/cli/drift.ts","../src/io/drift-state-store.ts","../src/utils/hash.ts","../src/core/drift-detector.ts","../src/cli/drift-sync.ts","../src/cli/status.ts","../src/cli/tree.ts","../src/cli/owner.ts","../src/core/dependency-resolver.ts","../src/cli/deps.ts","../src/core/graph-from-git.ts","../src/cli/impact.ts","../src/io/journal-store.ts","../src/cli/journal-add.ts","../src/cli/journal-read.ts","../src/cli/journal-archive.ts"],"sourcesContent":["#!/usr/bin/env node\nimport { Command } from 'commander';\nimport { registerInitCommand } from './cli/init.js';\nimport { registerBuildCommand } from './cli/build-context.js';\nimport { registerValidateCommand } from './cli/validate.js';\nimport { registerDriftCommand } from './cli/drift.js';\nimport { registerDriftSyncCommand } from './cli/drift-sync.js';\nimport { registerStatusCommand } from './cli/status.js';\nimport { registerTreeCommand } from './cli/tree.js';\nimport { registerOwnerCommand } from './cli/owner.js';\nimport { registerDepsCommand } from './cli/deps.js';\nimport { registerImpactCommand } from './cli/impact.js';\nimport { registerJournalAddCommand } from './cli/journal-add.js';\nimport { registerJournalReadCommand } from './cli/journal-read.js';\nimport { registerJournalArchiveCommand } from './cli/journal-archive.js';\n\nconst program = new Command();\n\nprogram\n .name('yg')\n .description('Yggdrasil — architectural knowledge infrastructure for AI agents')\n .version('0.1.0');\n\nregisterInitCommand(program);\nregisterBuildCommand(program);\nregisterValidateCommand(program);\nregisterDriftCommand(program);\nregisterDriftSyncCommand(program);\nregisterStatusCommand(program);\nregisterTreeCommand(program);\nregisterOwnerCommand(program);\nregisterDepsCommand(program);\nregisterImpactCommand(program);\nregisterJournalAddCommand(program);\nregisterJournalReadCommand(program);\nregisterJournalArchiveCommand(program);\n\nprogram.parse();\n","import { Command } from 'commander';\nimport { mkdir, writeFile, readdir, readFile, stat } from 'node:fs/promises';\nimport path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { DEFAULT_CONFIG } from '../templates/default-config.js';\nimport { installRulesForPlatform, PLATFORMS, type Platform } from '../templates/platform.js';\n\nfunction getGraphTemplatesDir(): string {\n const currentDir = path.dirname(fileURLToPath(import.meta.url));\n const packageRoot = path.join(currentDir, '..');\n return path.join(packageRoot, 'graph-templates');\n}\n\nconst GITIGNORE_CONTENT = `.journal.yaml\njournals-archive/\n`;\n\nexport function registerInitCommand(program: Command): void {\n program\n .command('init')\n .description('Initialize Yggdrasil graph in current project')\n .option(\n '--platform <name>',\n 'Agent platform: cursor, claude-code, copilot, cline, roocode, codex, windsurf, aider, gemini, amp, generic',\n 'generic',\n )\n .option('--upgrade', 'Refresh rules only (when .yggdrasil/ already exists)')\n .action(async (options: { platform?: string; upgrade?: boolean }) => {\n const projectRoot = process.cwd();\n const yggRoot = path.join(projectRoot, '.yggdrasil');\n\n let upgradeMode = false;\n try {\n const statResult = await stat(yggRoot);\n if (!statResult.isDirectory()) {\n process.stderr.write('Error: .yggdrasil exists but is not a directory.\\n');\n process.exit(1);\n }\n if (options.upgrade) {\n upgradeMode = true;\n } else {\n process.stderr.write(\n 'Error: .yggdrasil/ already exists. Use --upgrade to refresh rules only.\\n',\n );\n process.exit(1);\n }\n } catch {\n // Directory does not exist — proceed with full init\n }\n\n const platform = (options.platform ?? 'generic') as Platform;\n if (!PLATFORMS.includes(platform)) {\n process.stderr.write(\n `Error: Unknown platform '${platform}'. Use: ${PLATFORMS.join(', ')}\\n`,\n );\n process.exit(1);\n }\n\n if (upgradeMode) {\n const rulesPath = await installRulesForPlatform(projectRoot, platform);\n process.stdout.write('✓ Rules refreshed.\\n');\n process.stdout.write(` ${path.relative(projectRoot, rulesPath)}\\n`);\n return;\n }\n\n await mkdir(path.join(yggRoot, 'model'), { recursive: true });\n await mkdir(path.join(yggRoot, 'aspects'), { recursive: true });\n await mkdir(path.join(yggRoot, 'flows'), { recursive: true });\n await mkdir(path.join(yggRoot, 'knowledge', 'decisions'), { recursive: true });\n await mkdir(path.join(yggRoot, 'knowledge', 'patterns'), { recursive: true });\n await mkdir(path.join(yggRoot, 'knowledge', 'invariants'), { recursive: true });\n const templatesDir = path.join(yggRoot, 'templates');\n await mkdir(templatesDir, { recursive: true });\n\n const graphTemplatesDir = getGraphTemplatesDir();\n try {\n const entries = await readdir(graphTemplatesDir, { withFileTypes: true });\n const templateFiles = entries.filter((e) => e.isFile()).map((e) => e.name);\n for (const file of templateFiles) {\n const srcPath = path.join(graphTemplatesDir, file);\n const content = await readFile(srcPath, 'utf-8');\n await writeFile(path.join(templatesDir, file), content, 'utf-8');\n }\n } catch (err) {\n process.stderr.write(\n `Warning: Could not copy graph templates from ${graphTemplatesDir}: ${(err as Error).message}\\n`,\n );\n }\n\n await writeFile(path.join(yggRoot, 'config.yaml'), DEFAULT_CONFIG, 'utf-8');\n await writeFile(path.join(yggRoot, '.gitignore'), GITIGNORE_CONTENT, 'utf-8');\n\n const rulesPath = await installRulesForPlatform(projectRoot, platform);\n\n process.stdout.write('✓ Yggdrasil initialized.\\n\\n');\n process.stdout.write('Created:\\n');\n process.stdout.write(' .yggdrasil/config.yaml\\n');\n process.stdout.write(' .yggdrasil/.gitignore\\n');\n process.stdout.write(' .yggdrasil/model/\\n');\n process.stdout.write(' .yggdrasil/aspects/\\n');\n process.stdout.write(' .yggdrasil/flows/\\n');\n process.stdout.write(' .yggdrasil/knowledge/ (decisions, patterns, invariants)\\n');\n process.stdout.write(\n ' .yggdrasil/templates/ (module, service, library, node, aspect, flow, knowledge)\\n',\n );\n process.stdout.write(` ${path.relative(projectRoot, rulesPath)} (rules)\\n\\n`);\n process.stdout.write('Next steps:\\n');\n process.stdout.write(' 1. Edit .yggdrasil/config.yaml — set name, stack, standards\\n');\n process.stdout.write(' 2. Create nodes under .yggdrasil/model/\\n');\n process.stdout.write(' 3. Run: yg validate\\n');\n });\n}\n","export const DEFAULT_CONFIG = `name: \"\"\n\nstack:\n language: \"\"\n runtime: \"\"\n\nstandards: \"\"\n\ntags: []\n\nnode_types:\n - module\n - service\n - library\n\nartifacts:\n responsibility.md:\n required: always\n description: \"What this node is responsible for, and what it is not\"\n interface.md:\n required:\n when: has_incoming_relations\n description: \"Public API — methods, parameters, return types, contracts\"\n structural_context: true\n constraints.md:\n required: never\n description: \"Validation rules, business rules, invariants\"\n errors.md:\n required:\n when: has_incoming_relations\n description: \"Error conditions, codes, recovery behavior\"\n structural_context: true\n state.md:\n required: never\n description: \"State machines, lifecycle, transitions\"\n decisions.md:\n required: never\n description: \"Local design decisions and rationale\"\n\nknowledge_categories:\n - name: decisions\n description: \"Global semantic decisions and their rationale\"\n - name: patterns\n description: \"Implementation conventions with examples\"\n - name: invariants\n description: \"System truths that must never be violated\"\n\nquality:\n min_artifact_length: 50\n max_direct_relations: 10\n context_budget:\n warning: 5000\n error: 10000\n knowledge_staleness_days: 90\n`;\n","import { readFile, writeFile, mkdir } from 'node:fs/promises';\nimport path from 'node:path';\nimport { AGENT_RULES_CONTENT } from './rules.js';\n\nconst AGENT_RULES_IMPORT = '@.yggdrasil/agent-rules.md';\nconst YGGDRASIL_START = '<!-- yggdrasil:start -->';\nconst YGGDRASIL_END = '<!-- yggdrasil:end -->';\nconst YGGDRASIL_SECTION = `## Yggdrasil\\n\\n${AGENT_RULES_CONTENT}`;\nconst YGGDRASIL_BLOCK = `${YGGDRASIL_START}\\n${YGGDRASIL_SECTION}\\n${YGGDRASIL_END}`;\n\nexport type Platform =\n | 'cursor'\n | 'claude-code'\n | 'copilot'\n | 'cline'\n | 'roocode'\n | 'codex'\n | 'windsurf'\n | 'aider'\n | 'gemini'\n | 'amp'\n | 'generic';\n\nexport const PLATFORMS: Platform[] = [\n 'cursor',\n 'claude-code',\n 'copilot',\n 'cline',\n 'roocode',\n 'codex',\n 'windsurf',\n 'aider',\n 'gemini',\n 'amp',\n 'generic',\n];\n\nexport async function installRulesForPlatform(\n projectRoot: string,\n platform: Platform,\n): Promise<string> {\n const agentRulesPath = path.join(projectRoot, '.yggdrasil', 'agent-rules.md');\n\n switch (platform) {\n case 'cursor':\n return installForCursor(projectRoot);\n case 'claude-code':\n return installForClaudeCode(projectRoot, agentRulesPath);\n case 'copilot':\n return installForCopilot(projectRoot);\n case 'cline':\n return installForCline(projectRoot);\n case 'roocode':\n return installForRooCode(projectRoot);\n case 'codex':\n return installForCodex(projectRoot);\n case 'windsurf':\n return installForWindsurf(projectRoot);\n case 'aider':\n return installForAider(projectRoot, agentRulesPath);\n case 'gemini':\n return installForGemini(projectRoot, agentRulesPath);\n case 'amp':\n return installForAmp(projectRoot, agentRulesPath);\n case 'generic':\n default:\n return installForGeneric(projectRoot);\n }\n}\n\nasync function ensureAgentRules(agentRulesPath: string): Promise<void> {\n await mkdir(path.dirname(agentRulesPath), { recursive: true });\n await writeFile(agentRulesPath, AGENT_RULES_CONTENT, 'utf-8');\n}\n\nasync function installForCursor(projectRoot: string): Promise<string> {\n const dir = path.join(projectRoot, '.cursor', 'rules');\n await mkdir(dir, { recursive: true });\n const filePath = path.join(dir, 'yggdrasil.mdc');\n const content = `---\ndescription: Yggdrasil — semantic memory of the repository\nalwaysApply: true\n---\n\n${AGENT_RULES_CONTENT}`;\n await writeFile(filePath, content, 'utf-8');\n return filePath;\n}\n\nasync function installForClaudeCode(projectRoot: string, agentRulesPath: string): Promise<string> {\n await ensureAgentRules(agentRulesPath);\n const filePath = path.join(projectRoot, 'CLAUDE.md');\n let existing = '';\n try {\n existing = await readFile(filePath, 'utf-8');\n } catch {\n /* file doesn't exist */\n }\n const importLine = AGENT_RULES_IMPORT;\n if (existing.includes(importLine)) {\n return agentRulesPath;\n }\n const content = existing.trimEnd() ? `${existing.trimEnd()}\\n${importLine}\\n` : `${importLine}\\n`;\n await writeFile(filePath, content, 'utf-8');\n return agentRulesPath;\n}\n\nasync function installForCopilot(projectRoot: string): Promise<string> {\n const dir = path.join(projectRoot, '.github');\n await mkdir(dir, { recursive: true });\n const filePath = path.join(dir, 'copilot-instructions.md');\n let existing = '';\n try {\n existing = await readFile(filePath, 'utf-8');\n } catch {\n /* file doesn't exist */\n }\n let content: string;\n if (existing.includes(YGGDRASIL_START) && existing.includes(YGGDRASIL_END)) {\n content = existing.replace(\n new RegExp(`${escapeRegex(YGGDRASIL_START)}[\\\\s\\\\S]*?${escapeRegex(YGGDRASIL_END)}`, 'g'),\n YGGDRASIL_BLOCK,\n );\n } else {\n content = existing.trimEnd()\n ? `${existing.trimEnd()}\\n\\n${YGGDRASIL_BLOCK}\\n`\n : `${YGGDRASIL_BLOCK}\\n`;\n }\n await writeFile(filePath, content, 'utf-8');\n return filePath;\n}\n\nasync function installForCline(projectRoot: string): Promise<string> {\n const dir = path.join(projectRoot, '.clinerules');\n await mkdir(dir, { recursive: true });\n const filePath = path.join(dir, 'yggdrasil.md');\n await writeFile(filePath, AGENT_RULES_CONTENT, 'utf-8');\n return filePath;\n}\n\nasync function installForRooCode(projectRoot: string): Promise<string> {\n const dir = path.join(projectRoot, '.roo', 'rules');\n await mkdir(dir, { recursive: true });\n const filePath = path.join(dir, 'yggdrasil.md');\n await writeFile(filePath, AGENT_RULES_CONTENT, 'utf-8');\n return filePath;\n}\n\nasync function installForCodex(projectRoot: string): Promise<string> {\n const filePath = path.join(projectRoot, 'AGENTS.md');\n let existing = '';\n try {\n existing = await readFile(filePath, 'utf-8');\n } catch {\n /* file doesn't exist */\n }\n let content: string;\n if (existing.includes(YGGDRASIL_START) && existing.includes(YGGDRASIL_END)) {\n content = existing.replace(\n new RegExp(`${escapeRegex(YGGDRASIL_START)}[\\\\s\\\\S]*?${escapeRegex(YGGDRASIL_END)}`, 'g'),\n YGGDRASIL_BLOCK,\n );\n } else {\n content = existing.trimEnd()\n ? `${existing.trimEnd()}\\n\\n${YGGDRASIL_BLOCK}\\n`\n : `${YGGDRASIL_BLOCK}\\n`;\n }\n await writeFile(filePath, content, 'utf-8');\n return filePath;\n}\n\nasync function installForWindsurf(projectRoot: string): Promise<string> {\n const dir = path.join(projectRoot, '.windsurf', 'rules');\n await mkdir(dir, { recursive: true });\n const filePath = path.join(dir, 'yggdrasil.md');\n await writeFile(filePath, AGENT_RULES_CONTENT, 'utf-8');\n return filePath;\n}\n\nasync function installForAider(projectRoot: string, agentRulesPath: string): Promise<string> {\n await ensureAgentRules(agentRulesPath);\n const filePath = path.join(projectRoot, '.aider.conf.yml');\n const entry = '.yggdrasil/agent-rules.md';\n let existing = '';\n try {\n existing = await readFile(filePath, 'utf-8');\n } catch {\n /* file doesn't exist */\n }\n if (existing.includes(entry)) {\n return agentRulesPath;\n }\n const content = appendAiderReadEntry(existing, entry);\n await writeFile(filePath, content, 'utf-8');\n return agentRulesPath;\n}\n\nfunction appendAiderReadEntry(existing: string, entry: string): string {\n const newItem = ` - ${entry} # added by yg init\\n`;\n const readBlock = /^read:\\s*\\n((?:\\s+-\\s+[^\\n]+\\n)*)/m;\n const match = existing.match(readBlock);\n if (match) {\n return existing.replace(match[0], `read:\\n${match[1]}${newItem}`);\n }\n const readEmpty = /^read:\\s*$/m;\n if (readEmpty.test(existing)) {\n return existing.replace(readEmpty, `read:\\n${newItem}`);\n }\n const trimmed = existing.trimEnd();\n return trimmed ? `${trimmed}\\n\\nread:\\n${newItem}` : `read:\\n${newItem}`;\n}\n\nasync function installForGemini(projectRoot: string, agentRulesPath: string): Promise<string> {\n await ensureAgentRules(agentRulesPath);\n const filePath = path.join(projectRoot, 'GEMINI.md');\n let existing = '';\n try {\n existing = await readFile(filePath, 'utf-8');\n } catch {\n /* file doesn't exist */\n }\n const importLine = AGENT_RULES_IMPORT;\n if (existing.includes(importLine)) {\n return agentRulesPath;\n }\n const content = existing.trimEnd() ? `${existing.trimEnd()}\\n${importLine}\\n` : `${importLine}\\n`;\n await writeFile(filePath, content, 'utf-8');\n return agentRulesPath;\n}\n\nasync function installForAmp(projectRoot: string, agentRulesPath: string): Promise<string> {\n await ensureAgentRules(agentRulesPath);\n const filePath = path.join(projectRoot, 'AGENTS.md');\n let existing = '';\n try {\n existing = await readFile(filePath, 'utf-8');\n } catch {\n /* file doesn't exist */\n }\n const importLine = AGENT_RULES_IMPORT;\n if (existing.includes(importLine)) {\n return agentRulesPath;\n }\n const content = existing.trimEnd() ? `${existing.trimEnd()}\\n${importLine}\\n` : `${importLine}\\n`;\n await writeFile(filePath, content, 'utf-8');\n return agentRulesPath;\n}\n\nasync function installForGeneric(projectRoot: string): Promise<string> {\n const filePath = path.join(projectRoot, '.yggdrasil', 'agent-rules.md');\n await ensureAgentRules(filePath);\n return filePath;\n}\n\nfunction escapeRegex(s: string): string {\n return s.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n","/**\n * Canonical agent rules content — hand-tuned, do not generate programmatically.\n *\n * Operating manual for agents: graph-first, exhaustive coverage, context is sufficient.\n */\nexport const AGENT_RULES_CONTENT = `# Yggdrasil - System Semantic Memory (Operating Manual)\n\nYou are working in a repository managed by Yggdrasil.\nYggdrasil is a persistent, structured semantic memory graph stored in \\`.yggdrasil/\\`. It maps the repository, dictates system rules, and assembles implementation contexts.\n\nTHIS PROMPT IS YOUR ENTIRE OPERATING MANUAL. Read it carefully. Follow it strictly.\n\n---\n\n## 1. CORE PRINCIPLES (NON-NEGOTIABLE)\n\n1. **Graph First, Always:** Before answering a question, modifying code, or planning a feature, you MUST consult the graph.\n2. **Context is Sufficient:** If you feel the need to randomly explore source files to understand what a node should do, the graph is incomplete. **Fix the graph** (add decisions, interface details, constraints). Do not bypass the graph by reading raw code.\n3. **Graph is Intended Truth:** If the code and graph diverge, the graph is the truth. If a code change is deliberate, update the graph to match.\n4. **Exhaustive Coverage:** Every source file MUST belong to exactly one graph node. No orphaned files.\n5. **Tools Read, You Write:** The \\`yg\\` CLI tools only read, validate, and manage metadata. YOU must create and edit graph directories, \\`.yaml\\` files, and \\`.md\\` artifacts manually.\n6. **English Only for Artifacts:** All graph artifact files (filenames from \\`config.artifacts\\`, in the same directory as \\`node.yaml\\`) MUST be written in English. Conversation can be in the user's language.\n7. **Never Touch Operational Metadata:** NEVER manually edit \\`.yggdrasil/.drift-state\\` or \\`.yggdrasil/.journal.yaml\\`.\n\n---\n\n## 2. CONVERSATION LIFECYCLE (YOUR HABITS)\n\nYou do not need explicit \"session\" commands. Follow these conversational triggers:\n\n### A. Preflight (First message of the conversation)\nAlways execute these commands before doing anything else:\n1. \\`yg journal-read\\` -> If entries exist, consolidate them into the graph, then \\`yg journal-archive\\`.\n2. \\`yg drift\\` -> If divergence is detected, present states (\\`ok\\`, \\`drift\\`, \\`missing\\`, \\`unmaterialized\\`). Ask the user: Absorb (update graph) or Reject (re-materialize code from graph)?\n3. \\`yg status\\` -> Report graph health.\n4. \\`yg validate\\` -> If W008 stale-knowledge appears, update the knowledge artifacts to reflect current node state.\n\n### B. Wrap-up (User signals closing the topic)\nTriggered by phrases like: \"kończymy\", \"wrap up\", \"to tyle\", \"gotowe\".\n**Note: The graph should ALREADY be up to date. Do not wait for wrap-up to update graph artifacts.**\n1. If iterative journal mode was used: consolidate notes to the graph, then \\`yg journal-archive\\`.\n2. \\`yg drift\\` -> Check if files changed manually during the conversation.\n3. \\`yg validate\\` -> Fix any structural errors.\n4. Report exactly what nodes and files were changed.\n\n---\n\n## 3. WORKFLOW: MODIFYING OR CREATING FILES\n\nYou are NOT ALLOWED to edit or create source code without establishing graph coverage first.\n\n**Step 1: Check coverage** -> Run \\`yg owner --file <path>\\`\n\n**Step 2: If Owner FOUND (The Execution Checklist)**\nWhenever you write or edit source code, you MUST output this exact checklist in your response to the user, and execute each step BEFORE finishing your turn. This forces you to remember the graph:\n\n- [x] 1. Read Specification (ran \\`yg build-context\\`)\n- [x] 2. Modify Source Code\n- [x] 3. Sync Graph Artifacts (manually edit the node's artifact files — filenames from \\`config.artifacts\\` — IMMEDIATELY to match new code behavior)\n- [x] 4. Baseline Hash (ran \\`yg drift-sync\\` ONLY AFTER updating the graph)\n\n*If you do not print this checklist and check off step 3, you have failed the core directive of Yggdrasil.*\n\n**Step 3: If Owner NOT FOUND (Uncovered Area)**\nSTOP. Do not modify the code. First determine: **Is this greenfield (empty or new code to be created)?**\n\n* **If GREENFIELD (empty directory, new project, code not yet written):** Do NOT offer blackbox. Use Option 1 only — create proper nodes (reverse engineering or upfront design) before implementing. Blackbox is forbidden for new code.\n* **If EXISTING CODE (legacy, third-party, shipped-but-unmapped):** Present the user with 3 options and wait for their decision:\n * **Option 1: Reverse Engineering:** Create/extend standard nodes to map the area fully before modifying.\n * **Option 2: Blackbox Coverage:** Create a \\`blackbox: true\\` node at a user-chosen granularity to establish ownership without deep semantic exploration.\n * **Option 3: Abort/Change Plan:** Do not touch the file.\n\n\n---\n\n## 4. WORKFLOW: MODIFYING THE GRAPH & BLAST RADIUS\n\nWhen adding features or changing architecture, update the graph FIRST.\n\n**DO NOT DEFER GRAPH UPDATES:**\n* **DO NOT wait for the user to confirm if a change is \"final\".** The graph must evolve continuously with your code edits.\n* **Default Behavior:** If iterative journal mode is OFF, you MUST write structural and semantic changes directly to the graph files (\\`node.yaml\\`, artifacts or other files like aspects or flows, etc.) IMMEDIATELY. Suppress your innate safety bias to wait for permission.\n\n1. **Check Blast Radius:** Before modifying a node that others depend on, run \\`yg impact --node <node_path> --simulate\\`. Report the impact to the user.\n2. **Read Config & Templates:**\n * Check \\`.yggdrasil/config.yaml\\` for allowed \\`node_types\\` and \\`tags\\`.\n * **CRITICAL:** ALWAYS read the required schema files in \\`.yggdrasil/templates/\\` (e.g., \\`node.yaml\\`, \\`service.yaml\\`) to know the exact fields and structure before creating or editing any graph file.\n3. **Validate & Fix:** Run \\`yg validate\\`. You must fix all E-codes (Errors).\n4. **Token Economy & W-codes (Warnings):**\n * If you see \\`W005 budget-warning\\` or \\`W006 budget-error\\`, the context package is too large. You MUST consider splitting the node or reducing dependencies.\n * If you see \\`W008 stale-knowledge\\`, the semantic memory is outdated compared to the code. Update the knowledge artifacts.\n * **Smallest Viable Scope:** Prefer \\`scope: nodes\\` over \\`scope: tags\\`. Prefer tags over \\`scope: global\\`. Global scope costs token budget in EVERY context package.\n\n**Journaling (Iterative Mode):**\n* **Default:** Write changes directly to graph files immediately.\n* **Opt-in:** ONLY if the user says \"tryb iteracyjny\" or \"użyj journala\", use \\`yg journal-add --note \"...\"\\` to buffer intent during fast ping-pong changes.\n\n---\n\n## 5. PATH CONVENTIONS (CRITICAL)\n\nTo avoid broken references (\\`E004\\`, \\`E005\\`), use correct relative paths:\n* **Node paths** (used in CLI, relations, flow nodes): Relative to \\`.yggdrasil/model/\\` (e.g., \\`orders/order-service\\`).\n* **File paths** (used in mapping, \\`yg owner\\`): Relative to the repository root (e.g., \\`src/modules/orders/order.service.ts\\`).\n* **Knowledge paths** (used in node explicit refs): Relative to \\`.yggdrasil/knowledge/\\` (e.g., \\`decisions/001-event-sourcing\\`).\n\n---\n\n## 6. GRAPH STRUCTURE, CONFIG & TEMPLATES CHEAT SHEET\n\nThe graph lives entirely under \\`.yggdrasil/\\`. You NEVER guess structure. You MUST ALWAYS read the corresponding schema reference in \\`.yggdrasil/templates/\\` before creating or editing any graph file.\n\n* **\\`.yggdrasil/config.yaml\\`**: The ONLY config file. Defines \\`node_types\\`, \\`tags\\`, \\`artifacts\\`, \\`knowledge_categories\\`, and quality thresholds. Read this before any graph work.\n* **\\`.yggdrasil/templates/\\`**: The SINGLE place for all templates and schemas.\n * Contains node-type templates (e.g., \\`service.yaml\\`, \\`module.yaml\\`) with suggested artifacts and guidance.\n * Contains schema references (\\`node.yaml\\`, \\`aspect.yaml\\`, \\`flow.yaml\\`, \\`knowledge.yaml\\`) showing exact file structures.\n* **\\`.yggdrasil/model/\\`**: Node tree. Each node is a directory with \\`node.yaml\\` and artifact files (filenames from \\`config.artifacts\\`; required ones depend on config).\n* **\\`.yggdrasil/aspects/\\`**: Cross-cutting rules. Directory contains \\`aspect.yaml\\` (binds via \\`tag: <name>\\`) and \\`.md\\` content.\n* **\\`.yggdrasil/flows/\\`**: End-to-end processes. Directory contains \\`flow.yaml\\` (lists \\`nodes: [paths]\\` and \\`knowledge: [paths]\\`) and \\`.md\\` content.\n* **\\`.yggdrasil/knowledge/\\`**: Repo-wide wisdom (\\`decisions/\\`, \\`patterns/\\`, \\`invariants/\\`). Directory contains \\`knowledge.yaml\\` and \\`.md\\` content.\n\n---\n\n## 7. CLI TOOLS REFERENCE (\\`yg\\`)\n\nAlways use these exact commands.\n\n* \\`yg owner --file <file_path>\\` -> Find owning node.\n* \\`yg build-context --node <node_path>\\` -> Assemble strict specification.\n* \\`yg tree [--root <node_path>] [--depth N]\\` -> Print graph structure.\n* \\`yg deps --node <node_path> [--type structural|event|all]\\` -> Show dependencies.\n* \\`yg impact --node <node_path> --simulate\\` -> Simulate blast radius.\n* \\`yg status\\` -> Graph health metrics.\n* \\`yg validate [--scope <node_path>|all]\\` -> Compile/check graph. Run after EVERY graph edit.\n* \\`yg drift [--scope <node_path>|all]\\` -> Check code vs graph baseline.\n* \\`yg drift-sync --node <node_path>\\` -> Save current file hash as new baseline. Run ONLY after ensuring graph artifacts match the code.\n\n*(Iterative mode only)*\n* \\`yg journal-read\\`\n* \\`yg journal-add --note \"<content>\" [--target <node_path>]\\`\n* \\`yg journal-archive\\`\n`;\n","import { readdir } from 'node:fs/promises';\nimport path from 'node:path';\nimport type {\n Graph,\n GraphNode,\n AspectDef,\n FlowDef,\n KnowledgeItem,\n TemplateDef,\n YggConfig,\n} from '../model/types.js';\nimport { parseConfig } from '../io/config-parser.js';\nimport { parseNodeYaml } from '../io/node-parser.js';\nimport { parseAspect } from '../io/aspect-parser.js';\nimport { parseFlow } from '../io/flow-parser.js';\nimport { parseKnowledge } from '../io/knowledge-parser.js';\nimport { parseTemplate } from '../io/template-parser.js';\nimport { readArtifacts } from '../io/artifact-reader.js';\nimport { findYggRoot } from '../utils/paths.js';\n\nfunction toModelPath(absolutePath: string, modelDir: string): string {\n return path.relative(modelDir, absolutePath).split(path.sep).join('/');\n}\n\nconst FALLBACK_CONFIG: YggConfig = {\n name: '',\n stack: {},\n standards: '',\n tags: [],\n node_types: [],\n artifacts: {},\n knowledge_categories: [],\n};\n\nexport async function loadGraph(\n projectRoot: string,\n options: { tolerateInvalidConfig?: boolean } = {},\n): Promise<Graph> {\n const yggRoot = await findYggRoot(projectRoot);\n let configError: string | undefined;\n let config = FALLBACK_CONFIG;\n try {\n config = await parseConfig(path.join(yggRoot, 'config.yaml'));\n } catch (error) {\n if (!options.tolerateInvalidConfig) {\n throw error;\n }\n configError = (error as Error).message;\n }\n\n const modelDir = path.join(yggRoot, 'model');\n const nodes = new Map<string, GraphNode>();\n const nodeParseErrors: Array<{ nodePath: string; message: string }> = [];\n const artifactFilenames = Object.keys(config.artifacts ?? {});\n try {\n await scanModelDirectory(modelDir, modelDir, null, nodes, nodeParseErrors, artifactFilenames);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') {\n throw new Error(`Directory .yggdrasil/model/ does not exist. Run 'yg init' first.`, {\n cause: err,\n });\n }\n throw err;\n }\n\n const aspects = await loadAspects(path.join(yggRoot, 'aspects'));\n const flows = await loadFlows(path.join(yggRoot, 'flows'));\n const knowledge = await loadKnowledge(\n path.join(yggRoot, 'knowledge'),\n config.knowledge_categories,\n );\n const templates = await loadTemplates(path.join(yggRoot, 'templates'));\n\n return {\n config,\n configError,\n nodeParseErrors: nodeParseErrors.length > 0 ? nodeParseErrors : undefined,\n nodes,\n aspects,\n flows,\n knowledge,\n templates,\n rootPath: yggRoot,\n };\n}\n\nasync function scanModelDirectory(\n dirPath: string,\n modelDir: string,\n parent: GraphNode | null,\n nodes: Map<string, GraphNode>,\n nodeParseErrors: Array<{ nodePath: string; message: string }>,\n artifactFilenames: string[],\n): Promise<void> {\n const entries = await readdir(dirPath, { withFileTypes: true });\n const hasNodeYaml = entries.some((e) => e.isFile() && e.name === 'node.yaml');\n\n if (!hasNodeYaml && dirPath !== modelDir) {\n return;\n }\n\n if (hasNodeYaml) {\n const graphPath = toModelPath(dirPath, modelDir);\n let meta;\n try {\n meta = await parseNodeYaml(path.join(dirPath, 'node.yaml'));\n } catch (err) {\n nodeParseErrors.push({\n nodePath: graphPath,\n message: (err as Error).message,\n });\n return;\n }\n const artifacts = await readArtifacts(dirPath, ['node.yaml'], artifactFilenames);\n\n const node: GraphNode = {\n path: graphPath,\n meta,\n artifacts,\n children: [],\n parent,\n };\n\n nodes.set(graphPath, node);\n if (parent) {\n parent.children.push(node);\n }\n\n for (const entry of entries) {\n if (!entry.isDirectory()) continue;\n if (entry.name.startsWith('.')) continue;\n\n await scanModelDirectory(\n path.join(dirPath, entry.name),\n modelDir,\n node,\n nodes,\n nodeParseErrors,\n artifactFilenames,\n );\n }\n } else {\n for (const entry of entries) {\n if (!entry.isDirectory()) continue;\n if (entry.name.startsWith('.')) continue;\n\n await scanModelDirectory(\n path.join(dirPath, entry.name),\n modelDir,\n null,\n nodes,\n nodeParseErrors,\n artifactFilenames,\n );\n }\n }\n}\n\nasync function loadAspects(aspectsDir: string): Promise<AspectDef[]> {\n try {\n const entries = await readdir(aspectsDir, { withFileTypes: true });\n const aspects: AspectDef[] = [];\n for (const entry of entries) {\n if (!entry.isDirectory()) continue;\n const aspectYamlPath = path.join(aspectsDir, entry.name, 'aspect.yaml');\n const aspect = await parseAspect(path.join(aspectsDir, entry.name), aspectYamlPath);\n aspects.push(aspect);\n }\n return aspects;\n } catch {\n return [];\n }\n}\n\nasync function loadFlows(flowsDir: string): Promise<FlowDef[]> {\n try {\n const entries = await readdir(flowsDir, { withFileTypes: true });\n const flows: FlowDef[] = [];\n for (const entry of entries) {\n if (!entry.isDirectory()) continue;\n const flowYamlPath = path.join(flowsDir, entry.name, 'flow.yaml');\n const flow = await parseFlow(path.join(flowsDir, entry.name), flowYamlPath);\n flows.push(flow);\n }\n return flows;\n } catch {\n return [];\n }\n}\n\nasync function loadKnowledge(\n knowledgeDir: string,\n categories: Array<{ name: string }>,\n): Promise<KnowledgeItem[]> {\n const items: KnowledgeItem[] = [];\n const categorySet = new Set(categories.map((c) => c.name));\n\n try {\n const catEntries = await readdir(knowledgeDir, { withFileTypes: true });\n for (const catEntry of catEntries) {\n if (!catEntry.isDirectory()) continue;\n if (!categorySet.has(catEntry.name)) continue;\n\n const catPath = path.join(knowledgeDir, catEntry.name);\n const itemEntries = await readdir(catPath, { withFileTypes: true });\n\n for (const itemEntry of itemEntries) {\n if (!itemEntry.isDirectory()) continue;\n const itemDir = path.join(catPath, itemEntry.name);\n const knowledgeYamlPath = path.join(itemDir, 'knowledge.yaml');\n const relativePath = `${catEntry.name}/${itemEntry.name}`;\n const item = await parseKnowledge(itemDir, knowledgeYamlPath, catEntry.name, relativePath);\n items.push(item);\n }\n }\n } catch {\n // knowledge/ may not exist\n }\n\n return items;\n}\n\nasync function loadTemplates(templatesDir: string): Promise<TemplateDef[]> {\n try {\n const entries = await readdir(templatesDir, { withFileTypes: true });\n const templates: TemplateDef[] = [];\n for (const entry of entries) {\n if (!entry.isFile()) continue;\n if (!entry.name.endsWith('.yaml') && !entry.name.endsWith('.yml')) continue;\n const t = await parseTemplate(path.join(templatesDir, entry.name));\n templates.push(t);\n }\n return templates;\n } catch {\n return [];\n }\n}\n","import { readFile } from 'node:fs/promises';\nimport { parse as parseYaml } from 'yaml';\nimport type {\n YggConfig,\n ArtifactConfig,\n KnowledgeCategory,\n QualityConfig,\n} from '../model/types.js';\n\nconst DEFAULT_QUALITY: QualityConfig = {\n min_artifact_length: 50,\n max_direct_relations: 10,\n context_budget: { warning: 5000, error: 10000 },\n knowledge_staleness_days: 90,\n};\n\nexport async function parseConfig(filePath: string): Promise<YggConfig> {\n const content = await readFile(filePath, 'utf-8');\n const raw = parseYaml(content) as Record<string, unknown>;\n\n if (!raw.name || typeof raw.name !== 'string' || raw.name.trim() === '') {\n throw new Error(`config.yaml: missing or invalid 'name' field`);\n }\n\n const nodeTypes = raw.node_types;\n if (!Array.isArray(nodeTypes) || nodeTypes.length === 0) {\n throw new Error(`config.yaml: 'node_types' must be a non-empty array`);\n }\n\n const artifacts = raw.artifacts;\n if (\n !artifacts ||\n typeof artifacts !== 'object' ||\n Array.isArray(artifacts) ||\n Object.keys(artifacts).length === 0\n ) {\n throw new Error(`config.yaml: 'artifacts' must be a non-empty object`);\n }\n\n const artifactsMap: Record<string, ArtifactConfig> = {};\n for (const [key, val] of Object.entries(artifacts)) {\n if (key === 'node') {\n throw new Error(`config.yaml: artifact name 'node' is reserved`);\n }\n const a = val as Record<string, unknown>;\n const required = a.required;\n if (\n required !== 'always' &&\n required !== 'never' &&\n (typeof required !== 'object' || !required || !('when' in required))\n ) {\n throw new Error(`config.yaml: artifact '${key}' has invalid 'required' field`);\n }\n if (typeof required === 'object' && required && 'when' in required) {\n const when = (required as { when: string }).when;\n const validWhen =\n when === 'has_incoming_relations' ||\n when === 'has_outgoing_relations' ||\n (typeof when === 'string' && when.startsWith('has_tag:'));\n if (!validWhen) {\n throw new Error(\n `config.yaml: artifact '${key}' has invalid 'required.when': must be has_incoming_relations, has_outgoing_relations, or has_tag:<name>`,\n );\n }\n }\n artifactsMap[key] = {\n required: required as ArtifactConfig['required'],\n description: (a.description as string) ?? '',\n structural_context: (a.structural_context as boolean) ?? false,\n };\n }\n\n if (!('knowledge_categories' in raw)) {\n throw new Error(\n `config.yaml: missing 'knowledge_categories' field (required, may be empty list)`,\n );\n }\n const knowledgeCategoriesRaw = raw.knowledge_categories;\n if (!Array.isArray(knowledgeCategoriesRaw)) {\n throw new Error(`config.yaml: 'knowledge_categories' must be an array`);\n }\n const knowledgeCategories = knowledgeCategoriesRaw as KnowledgeCategory[];\n const categoryNames = new Set<string>();\n for (const kc of knowledgeCategories) {\n if (!kc?.name || typeof kc.name !== 'string') continue;\n if (categoryNames.has(kc.name)) {\n throw new Error(`config.yaml: duplicate knowledge category '${kc.name}'`);\n }\n categoryNames.add(kc.name);\n }\n\n const qualityRaw = raw.quality as Record<string, unknown> | undefined;\n const quality: QualityConfig = qualityRaw\n ? {\n min_artifact_length:\n (qualityRaw.min_artifact_length as number) ?? DEFAULT_QUALITY.min_artifact_length,\n max_direct_relations:\n (qualityRaw.max_direct_relations as number) ?? DEFAULT_QUALITY.max_direct_relations,\n context_budget: {\n warning:\n (qualityRaw.context_budget as Record<string, number>)?.warning ??\n DEFAULT_QUALITY.context_budget.warning,\n error:\n (qualityRaw.context_budget as Record<string, number>)?.error ??\n DEFAULT_QUALITY.context_budget.error,\n },\n knowledge_staleness_days:\n (qualityRaw.knowledge_staleness_days as number) ??\n DEFAULT_QUALITY.knowledge_staleness_days,\n }\n : DEFAULT_QUALITY;\n\n if (quality.context_budget.error < quality.context_budget.warning) {\n throw new Error(\n `config.yaml: quality.context_budget.error (${quality.context_budget.error}) must be >= warning (${quality.context_budget.warning})`,\n );\n }\n\n if (!('tags' in raw)) {\n throw new Error(`config.yaml: missing 'tags' field (required, may be empty list)`);\n }\n const tags = raw.tags;\n if (!Array.isArray(tags)) {\n throw new Error(`config.yaml: 'tags' must be an array`);\n }\n const tagsList = (tags as unknown[]).filter((t): t is string => typeof t === 'string');\n\n return {\n name: (raw.name as string).trim(),\n stack: (raw.stack as Record<string, string>) ?? {},\n standards: typeof raw.standards === 'string' ? raw.standards : '',\n tags: tagsList,\n node_types: nodeTypes as string[],\n artifacts: artifactsMap,\n knowledge_categories: knowledgeCategories.filter((kc) => kc?.name),\n quality,\n };\n}\n","import { readFile } from 'node:fs/promises';\nimport { parse as parseYaml } from 'yaml';\nimport type { NodeMeta, NodeMapping, Relation, RelationType } from '../model/types.js';\n\nconst RELATION_TYPES: RelationType[] = [\n 'uses',\n 'calls',\n 'extends',\n 'implements',\n 'emits',\n 'listens',\n];\n\nfunction isValidRelationType(t: unknown): t is RelationType {\n return typeof t === 'string' && RELATION_TYPES.includes(t as RelationType);\n}\n\nexport async function parseNodeYaml(filePath: string): Promise<NodeMeta> {\n const content = await readFile(filePath, 'utf-8');\n const raw = parseYaml(content) as Record<string, unknown>;\n\n if (!raw.name || typeof raw.name !== 'string' || raw.name.trim() === '') {\n throw new Error(`node.yaml at ${filePath}: missing or empty 'name'`);\n }\n if (!raw.type || typeof raw.type !== 'string' || raw.type.trim() === '') {\n throw new Error(`node.yaml at ${filePath}: missing or empty 'type'`);\n }\n\n const relations = parseRelations(raw.relations, filePath);\n const mapping = parseMapping(raw.mapping, filePath);\n\n return {\n name: (raw.name as string).trim(),\n type: (raw.type as string).trim(),\n tags: parseStringArray(raw.tags),\n blackbox: (raw.blackbox as boolean) ?? false,\n relations: relations.length > 0 ? relations : undefined,\n knowledge: parseStringArray(raw.knowledge),\n mapping,\n };\n}\n\nfunction parseStringArray(val: unknown): string[] | undefined {\n if (!Array.isArray(val)) return undefined;\n const arr = val.filter((v): v is string => typeof v === 'string');\n return arr.length > 0 ? arr : undefined;\n}\n\nfunction parseRelations(raw: unknown, filePath: string): Relation[] {\n if (raw === undefined) return [];\n if (!Array.isArray(raw)) {\n throw new Error(`node.yaml at ${filePath}: 'relations' must be an array`);\n }\n\n const result: Relation[] = [];\n for (let index = 0; index < raw.length; index++) {\n const r = raw[index];\n if (typeof r !== 'object' || r === null) {\n throw new Error(`node.yaml at ${filePath}: relations[${index}] must be an object`);\n }\n const obj = r as Record<string, unknown>;\n const target = obj.target;\n const type = obj.type;\n\n if (typeof target !== 'string' || target.trim() === '') {\n throw new Error(\n `node.yaml at ${filePath}: relations[${index}].target must be a non-empty string`,\n );\n }\n if (!isValidRelationType(type)) {\n throw new Error(`node.yaml at ${filePath}: relations[${index}].type is invalid`);\n }\n\n const rel: Relation = {\n target: target.trim(),\n type: type as RelationType,\n };\n if (Array.isArray(obj.consumes)) {\n rel.consumes = (obj.consumes as unknown[]).filter((c): c is string => typeof c === 'string');\n }\n if (typeof obj.failure === 'string') {\n rel.failure = obj.failure;\n }\n if (typeof obj.event_name === 'string' && obj.event_name.trim()) {\n rel.event_name = obj.event_name.trim();\n }\n result.push(rel);\n }\n return result;\n}\n\nfunction validateRelativePath(pathValue: string, filePath: string, fieldName: string): string {\n const normalized = pathValue.trim();\n if (normalized === '') {\n throw new Error(`node.yaml at ${filePath}: '${fieldName}' must be non-empty`);\n }\n if (normalized.startsWith('/')) {\n throw new Error(`node.yaml at ${filePath}: '${fieldName}' must be relative to repository root`);\n }\n return normalized;\n}\n\nfunction parseMapping(rawMapping: unknown, filePath: string): NodeMapping | undefined {\n if (!rawMapping || typeof rawMapping !== 'object') return undefined;\n\n const obj = rawMapping as Record<string, unknown>;\n\n // Unified format: mapping.paths — list of files and/or directories (type auto-detected at runtime)\n if (Array.isArray(obj.paths) && obj.paths.length > 0) {\n const paths = (obj.paths as unknown[])\n .filter((p): p is string => typeof p === 'string')\n .map((p) => validateRelativePath(p, filePath, 'mapping.paths[]'));\n if (paths.length === 0) {\n throw new Error(`node.yaml at ${filePath}: mapping.paths must be a non-empty array`);\n }\n return { paths };\n }\n\n if (obj.paths !== undefined || obj.type !== undefined || obj.path !== undefined) {\n throw new Error(\n `node.yaml at ${filePath}: mapping must have paths (array of file/directory paths)`,\n );\n }\n\n return undefined;\n}\n","import { readFile } from 'node:fs/promises';\nimport { parse as parseYaml } from 'yaml';\nimport type { AspectDef } from '../model/types.js';\nimport { readArtifacts } from './artifact-reader.js';\n\nexport async function parseAspect(aspectDir: string, aspectYamlPath: string): Promise<AspectDef> {\n const content = await readFile(aspectYamlPath, 'utf-8');\n const raw = parseYaml(content) as Record<string, unknown>;\n\n if (!raw.name || typeof raw.name !== 'string' || raw.name.trim() === '') {\n throw new Error(`Aspect file ${aspectYamlPath}: missing or empty 'name'`);\n }\n if (!raw.tag || typeof raw.tag !== 'string' || raw.tag.trim() === '') {\n throw new Error(`Aspect file ${aspectYamlPath}: missing or empty 'tag'`);\n }\n\n const artifacts = await readArtifacts(aspectDir, ['aspect.yaml']);\n\n return {\n name: (raw.name as string).trim(),\n tag: (raw.tag as string).trim(),\n artifacts,\n };\n}\n","import { readFile, readdir } from 'node:fs/promises';\nimport path from 'node:path';\nimport type { Artifact } from '../model/types.js';\n\nexport async function readArtifacts(\n dirPath: string,\n excludeFiles: string[] = ['node.yaml'],\n includeFiles?: string[],\n): Promise<Artifact[]> {\n const entries = await readdir(dirPath, { withFileTypes: true });\n const artifacts: Artifact[] = [];\n const includeSet = includeFiles && includeFiles.length > 0 ? new Set(includeFiles) : null;\n\n for (const entry of entries) {\n if (!entry.isFile()) continue;\n if (excludeFiles.includes(entry.name)) continue;\n if (includeSet && !includeSet.has(entry.name)) continue;\n\n const filePath = path.join(dirPath, entry.name);\n const content = await readFile(filePath, 'utf-8');\n artifacts.push({ filename: entry.name, content });\n }\n\n // Sort by filename for deterministic output\n artifacts.sort((a, b) => a.filename.localeCompare(b.filename));\n return artifacts;\n}\n","import { readFile } from 'node:fs/promises';\nimport { parse as parseYaml } from 'yaml';\nimport type { FlowDef } from '../model/types.js';\nimport { readArtifacts } from './artifact-reader.js';\n\nexport async function parseFlow(flowDir: string, flowYamlPath: string): Promise<FlowDef> {\n const content = await readFile(flowYamlPath, 'utf-8');\n const raw = parseYaml(content) as Record<string, unknown>;\n\n if (!raw.name || typeof raw.name !== 'string' || raw.name.trim() === '') {\n throw new Error(`flow.yaml at ${flowYamlPath}: missing or empty 'name'`);\n }\n\n const nodes = raw.nodes;\n if (!Array.isArray(nodes) || nodes.length === 0) {\n throw new Error(`flow.yaml at ${flowYamlPath}: 'nodes' must be a non-empty array`);\n }\n\n const nodePaths = (nodes as unknown[]).filter((n): n is string => typeof n === 'string');\n if (nodePaths.length === 0) {\n throw new Error(`flow.yaml at ${flowYamlPath}: 'nodes' must contain string node paths`);\n }\n const knowledge = Array.isArray(raw.knowledge)\n ? (raw.knowledge as unknown[]).filter((k): k is string => typeof k === 'string')\n : undefined;\n\n const artifacts = await readArtifacts(flowDir, ['flow.yaml']);\n\n return {\n name: (raw.name as string).trim(),\n nodes: nodePaths,\n knowledge,\n artifacts,\n };\n}\n","import { readFile } from 'node:fs/promises';\nimport { parse as parseYaml } from 'yaml';\nimport type { KnowledgeItem } from '../model/types.js';\nimport { readArtifacts } from './artifact-reader.js';\n\nexport type KnowledgeScope = 'global' | { tags: string[] } | { nodes: string[] };\n\nexport async function parseKnowledge(\n knowledgeDir: string,\n knowledgeYamlPath: string,\n category: string,\n relativePath: string,\n): Promise<KnowledgeItem> {\n const content = await readFile(knowledgeYamlPath, 'utf-8');\n const raw = parseYaml(content) as Record<string, unknown>;\n\n if (!raw.name || typeof raw.name !== 'string' || raw.name.trim() === '') {\n throw new Error(`knowledge.yaml at ${knowledgeYamlPath}: missing or empty 'name'`);\n }\n\n const scope = parseScope(raw.scope, knowledgeYamlPath);\n\n const artifacts = await readArtifacts(knowledgeDir, ['knowledge.yaml']);\n\n return {\n name: (raw.name as string).trim(),\n scope,\n category,\n path: relativePath,\n artifacts,\n };\n}\n\nfunction parseScope(raw: unknown, filePath: string): KnowledgeItem['scope'] {\n if (raw === 'global') {\n return 'global';\n }\n\n if (raw && typeof raw === 'object') {\n const obj = raw as Record<string, unknown>;\n if (Array.isArray(obj.tags)) {\n const tags = (obj.tags as unknown[]).filter((t): t is string => typeof t === 'string');\n if (tags.length === 0) {\n throw new Error(`knowledge.yaml at ${filePath}: scope.tags must be a non-empty array`);\n }\n return { tags };\n }\n if (Array.isArray(obj.nodes)) {\n const nodes = (obj.nodes as unknown[]).filter((n): n is string => typeof n === 'string');\n if (nodes.length === 0) {\n throw new Error(`knowledge.yaml at ${filePath}: scope.nodes must be a non-empty array`);\n }\n return { nodes };\n }\n }\n\n throw new Error(`knowledge.yaml at ${filePath}: invalid 'scope' value`);\n}\n","import { readFile } from 'node:fs/promises';\nimport { parse as parseYaml } from 'yaml';\nimport type { TemplateDef } from '../model/types.js';\n\nexport async function parseTemplate(filePath: string): Promise<TemplateDef> {\n const content = await readFile(filePath, 'utf-8');\n const raw = parseYaml(content) as Record<string, unknown>;\n\n if (!raw.node_type || typeof raw.node_type !== 'string' || raw.node_type.trim() === '') {\n throw new Error(`template at ${filePath}: missing or empty 'node_type'`);\n }\n\n const suggestedArtifacts = Array.isArray(raw.suggested_artifacts)\n ? (raw.suggested_artifacts as unknown[]).filter((a): a is string => typeof a === 'string')\n : undefined;\n\n return {\n nodeType: (raw.node_type as string).trim(),\n suggestedArtifacts:\n suggestedArtifacts && suggestedArtifacts.length > 0 ? suggestedArtifacts : undefined,\n guidance: typeof raw.guidance === 'string' ? raw.guidance : undefined,\n };\n}\n","import path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { stat } from 'node:fs/promises';\n\n/**\n * Directory containing the CLI package (dist/ when bundled).\n * Uses import.meta.url so it works when installed globally.\n */\nexport function getPackageRoot(): string {\n return path.dirname(fileURLToPath(import.meta.url));\n}\n\n/**\n * Find the .yggdrasil/ directory starting from projectRoot.\n * Searches upward through parent directories until found or filesystem root.\n * Returns the absolute path to the .yggdrasil/ directory.\n */\nexport async function findYggRoot(projectRoot: string): Promise<string> {\n let current = path.resolve(projectRoot);\n const root = path.parse(current).root;\n\n while (true) {\n const yggPath = path.join(current, '.yggdrasil');\n try {\n const st = await stat(yggPath);\n if (!st.isDirectory()) {\n throw new Error(\n `.yggdrasil exists but is not a directory (${yggPath}). Run 'yg init' in a clean location.`,\n );\n }\n return yggPath;\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') {\n if (current === root) {\n throw new Error(`No .yggdrasil/ directory found. Run 'yg init' first.`, { cause: err });\n }\n current = path.dirname(current);\n continue;\n }\n throw err;\n }\n }\n}\n\nimport type { NodeMapping } from '../model/types.js';\n\n/**\n * Normalize a mapping to always return an array of paths (relative to project root).\n * Each path can be a file or directory — type is detected at runtime by hash/owner.\n */\nexport function normalizeMappingPaths(mapping: NodeMapping | undefined): string[] {\n if (!mapping?.paths?.length) return [];\n return mapping.paths.map((p) => p.trim()).filter(Boolean);\n}\n\n/**\n * Convert a node's directory path to its graph path.\n * E.g., \"/abs/path/.yggdrasil/orders/order-service\" → \"orders/order-service\"\n */\nexport function toGraphPath(absolutePath: string, yggRoot: string): string {\n return path.relative(yggRoot, absolutePath).split(path.sep).join('/');\n}\n\n/**\n * Normalize a user-provided path to project-relative POSIX form.\n * Throws when the target path points outside the project root.\n */\nexport function normalizeProjectRelativePath(projectRoot: string, rawPath: string): string {\n const normalizedInput = rawPath.trim().replace(/\\\\/g, '/');\n if (normalizedInput.length === 0) {\n throw new Error('Path cannot be empty');\n }\n\n const absolute = path.resolve(projectRoot, normalizedInput);\n const relative = path.relative(projectRoot, absolute);\n const isOutside = relative.startsWith('..') || path.isAbsolute(relative);\n if (isOutside) {\n throw new Error(`Path is outside project root: ${rawPath}`);\n }\n\n return relative.split(path.sep).join('/');\n}\n","import { readFile } from 'node:fs/promises';\nimport path from 'node:path';\nimport type {\n Graph,\n GraphNode,\n ContextPackage,\n ContextLayer,\n ContextSection,\n YggConfig,\n AspectDef,\n KnowledgeItem,\n FlowDef,\n Relation,\n} from '../model/types.js';\nimport { normalizeMappingPaths } from '../utils/paths.js';\nimport { estimateTokens } from '../utils/tokens.js';\n\nconst STRUCTURAL_RELATION_TYPES = new Set(['uses', 'calls', 'extends', 'implements']);\nconst EVENT_RELATION_TYPES = new Set(['emits', 'listens']);\n\nexport async function buildContext(graph: Graph, nodePath: string): Promise<ContextPackage> {\n const node = graph.nodes.get(nodePath);\n if (!node) {\n throw new Error(`Node not found: ${nodePath}`);\n }\n\n const nodeTags = new Set(node.meta.tags ?? []);\n const seenKnowledge = new Set<string>();\n const layers: ContextLayer[] = [];\n\n // 1. Global\n layers.push(buildGlobalLayer(graph.config));\n\n // 2–5. Knowledge (with deduplication)\n for (const k of collectKnowledgeItems(graph, nodePath, nodeTags, seenKnowledge)) {\n layers.push(buildKnowledgeLayer(k));\n }\n\n // 6. Hierarchy (only configured artifacts that exist in ancestor's directory)\n const ancestors = collectAncestors(node);\n for (const ancestor of ancestors) {\n layers.push(buildHierarchyLayer(ancestor, graph.config));\n }\n\n // 7. Own (node.yaml + configured artifacts)\n layers.push(await buildOwnLayer(node, graph.config, graph.rootPath));\n\n // 8. Relational (structural + event, with consumes/failure)\n for (const relation of node.meta.relations ?? []) {\n const target = graph.nodes.get(relation.target);\n if (!target) {\n throw new Error(`Broken relation: ${nodePath} -> ${relation.target} (target not found)`);\n }\n if (STRUCTURAL_RELATION_TYPES.has(relation.type)) {\n layers.push(buildStructuralRelationLayer(target, relation, graph.config));\n } else if (EVENT_RELATION_TYPES.has(relation.type)) {\n layers.push(buildEventRelationLayer(target, relation));\n }\n }\n\n // 9. Aspects\n for (const tag of nodeTags) {\n for (const aspect of graph.aspects) {\n if (aspect.tag === tag) {\n layers.push(buildAspectLayer(aspect));\n }\n }\n }\n\n // 10. Flows\n for (const flow of collectParticipatingFlows(graph, nodePath)) {\n layers.push(buildFlowLayer(flow));\n for (const kPath of flow.knowledge ?? []) {\n const norm = kPath.replace(/\\/$/, '');\n const k = graph.knowledge.find((item) => item.path === norm || item.path === kPath);\n if (k && !seenKnowledge.has(k.path)) {\n seenKnowledge.add(k.path);\n layers.push(buildKnowledgeLayer(k, true));\n }\n }\n }\n\n const fullText = layers.map((l) => l.content).join('\\n\\n');\n const tokenCount = estimateTokens(fullText);\n const mapping = normalizeMappingPaths(node.meta.mapping);\n const sections = buildSections(layers, mapping.length > 0 ? mapping : null);\n\n return {\n nodePath,\n nodeName: node.meta.name,\n layers,\n sections,\n mapping: mapping.length > 0 ? mapping : null,\n tokenCount,\n };\n}\n\nfunction collectKnowledgeItems(\n graph: Graph,\n nodePath: string,\n nodeTags: Set<string>,\n seenKnowledge: Set<string>,\n): KnowledgeItem[] {\n const result: KnowledgeItem[] = [];\n\n // 2. scope global\n for (const k of graph.knowledge) {\n if (k.scope === 'global' && !seenKnowledge.has(k.path)) {\n seenKnowledge.add(k.path);\n result.push(k);\n }\n }\n\n // 3. scope tags\n for (const k of graph.knowledge) {\n if (typeof k.scope === 'object' && 'tags' in k.scope) {\n const overlap = k.scope.tags.some((t) => nodeTags.has(t));\n if (overlap && !seenKnowledge.has(k.path)) {\n seenKnowledge.add(k.path);\n result.push(k);\n }\n }\n }\n\n // 4. scope nodes\n for (const k of graph.knowledge) {\n if (typeof k.scope === 'object' && 'nodes' in k.scope) {\n if (k.scope.nodes.includes(nodePath) && !seenKnowledge.has(k.path)) {\n seenKnowledge.add(k.path);\n result.push(k);\n }\n }\n }\n\n // 5. declared by node\n const node = graph.nodes.get(nodePath);\n if (node?.meta.knowledge) {\n for (const kPath of node.meta.knowledge) {\n const norm = kPath.replace(/\\/$/, '');\n const k = graph.knowledge.find((item) => item.path === norm || item.path === kPath);\n if (k && !seenKnowledge.has(k.path)) {\n seenKnowledge.add(k.path);\n result.push(k);\n }\n }\n }\n\n return result;\n}\n\nfunction collectParticipatingFlows(graph: Graph, nodePath: string): FlowDef[] {\n return graph.flows.filter((f) => f.nodes.includes(nodePath));\n}\n\n// --- Layer builders (exported for testing) ---\n\nexport function buildGlobalLayer(config: YggConfig): ContextLayer {\n let content = `**Project:** ${config.name}\\n\\n`;\n content += `**Stack:**\\n`;\n for (const [key, value] of Object.entries(config.stack)) {\n content += `- ${key}: ${value}\\n`;\n }\n content += `\\n**Standards:**\\n${config.standards || '(none)'}\\n`;\n return { type: 'global', label: 'Global Context', content };\n}\n\nexport function buildKnowledgeLayer(k: KnowledgeItem, fromFlow?: boolean): ContextLayer {\n const categoryLabel = k.category.charAt(0).toUpperCase() + k.category.slice(1);\n const content = k.artifacts.map((a) => `### ${a.filename}\\n${a.content}`).join('\\n\\n');\n const label = fromFlow\n ? `Long-term Memory (from flow): ${k.name}`\n : `${categoryLabel}: ${k.name}`;\n return {\n type: 'knowledge',\n label,\n content,\n };\n}\n\nfunction filterArtifactsByConfig(\n artifacts: Array<{ filename: string; content: string }>,\n config: YggConfig,\n): Array<{ filename: string; content: string }> {\n const allowed = new Set(Object.keys(config.artifacts ?? {}));\n return artifacts.filter((a) => allowed.has(a.filename));\n}\n\nexport function buildHierarchyLayer(ancestor: GraphNode, config: YggConfig): ContextLayer {\n const filtered = filterArtifactsByConfig(ancestor.artifacts, config);\n const content = filtered.map((a) => `### ${a.filename}\\n${a.content}`).join('\\n\\n');\n return {\n type: 'hierarchy',\n label: `Module Context (${ancestor.path}/)`,\n content,\n };\n}\n\nexport async function buildOwnLayer(\n node: GraphNode,\n config: YggConfig,\n graphRootPath: string,\n): Promise<ContextLayer> {\n const parts: string[] = [];\n\n const nodeYamlPath = path.join(graphRootPath, 'model', node.path, 'node.yaml');\n try {\n const nodeYamlContent = await readFile(nodeYamlPath, 'utf-8');\n parts.push(`### node.yaml\\n${nodeYamlContent.trim()}`);\n } catch {\n parts.push(`### node.yaml\\n(not found)`);\n }\n\n const filtered = filterArtifactsByConfig(node.artifacts, config);\n for (const a of filtered) {\n parts.push(`### ${a.filename}\\n${a.content}`);\n }\n\n const content = parts.join('\\n\\n');\n return {\n type: 'own',\n label: `Node: ${node.meta.name}`,\n content,\n };\n}\n\nexport function buildStructuralRelationLayer(\n target: GraphNode,\n relation: Relation,\n config: YggConfig,\n): ContextLayer {\n let content = '';\n if (relation.consumes?.length) {\n content += `Consumes: ${relation.consumes.join(', ')}\\n\\n`;\n }\n if (relation.failure) {\n content += `On failure: ${relation.failure}\\n\\n`;\n }\n\n const structuralArtifactFilenames = Object.entries(config.artifacts ?? {})\n .filter(([, c]) => c.structural_context)\n .map(([filename]) => filename);\n\n const structuralArts = structuralArtifactFilenames\n .map((filename) => {\n const art = target.artifacts.find((a) => a.filename === filename);\n return art ? { filename: art.filename, content: art.content } : null;\n })\n .filter((a): a is { filename: string; content: string } => a !== null);\n\n if (structuralArts.length > 0) {\n content += structuralArts.map((a) => `### ${a.filename}\\n${a.content}`).join('\\n\\n');\n } else {\n const filtered = filterArtifactsByConfig(target.artifacts, config);\n content += filtered.map((a) => `### ${a.filename}\\n${a.content}`).join('\\n\\n');\n }\n\n return {\n type: 'relational',\n label: `Dependency: ${target.meta.name} (${relation.type}) — ${target.path}`,\n content: content.trim(),\n };\n}\n\nexport function buildEventRelationLayer(target: GraphNode, relation: Relation): ContextLayer {\n const eventName = relation.event_name ?? target.meta.name;\n const isEmit = relation.type === 'emits';\n let content = isEmit\n ? `Target: ${target.path}\\nYou publish ${eventName}.`\n : `Source: ${target.path}\\nYou listen for ${eventName}.`;\n if (relation.consumes?.length) {\n content += `\\nConsumes: ${relation.consumes.join(', ')}`;\n }\n return {\n type: 'relational',\n label: `Event: ${eventName} [${relation.type}]`,\n content,\n };\n}\n\nexport function buildAspectLayer(aspect: AspectDef): ContextLayer {\n const content = aspect.artifacts.map((a) => `### ${a.filename}\\n${a.content}`).join('\\n\\n');\n return {\n type: 'aspects',\n label: `${aspect.name} (tag: ${aspect.tag})`,\n content,\n };\n}\n\nfunction buildFlowLayer(flow: FlowDef): ContextLayer {\n const content = flow.artifacts.map((a) => `### ${a.filename}\\n${a.content}`).join('\\n\\n');\n return {\n type: 'flows',\n label: `Flow: ${flow.name}`,\n content: content || '(no artifacts)',\n };\n}\n\nfunction buildSections(layers: ContextLayer[], mapping: string[] | null): ContextSection[] {\n const ownLayers = layers.filter((layer) => layer.type === 'own');\n if (mapping && mapping.length > 0) {\n ownLayers.push({\n type: 'own',\n label: 'Materialization Target',\n content: mapping.join(', '),\n });\n }\n\n return [\n { key: 'Global', layers: layers.filter((l) => l.type === 'global') },\n { key: 'Knowledge', layers: layers.filter((l) => l.type === 'knowledge') },\n { key: 'Hierarchy', layers: layers.filter((l) => l.type === 'hierarchy') },\n { key: 'OwnArtifacts', layers: ownLayers },\n { key: 'Dependencies', layers: layers.filter((l) => l.type === 'relational') },\n { key: 'Aspects', layers: layers.filter((l) => l.type === 'aspects') },\n { key: 'Flows', layers: layers.filter((l) => l.type === 'flows') },\n ];\n}\n\n// --- Helpers (exported for testing) ---\n\nexport function collectAncestors(node: GraphNode): GraphNode[] {\n const ancestors: GraphNode[] = [];\n let current = node.parent;\n while (current) {\n ancestors.unshift(current);\n current = current.parent;\n }\n return ancestors;\n}\n","/**\n * Estimate token count for a string.\n * Heuristic: ~4 characters per token (no tokenizer dependency).\n */\nexport function estimateTokens(text: string): number {\n return Math.ceil(text.length / 4);\n}\n","import { readdir } from 'node:fs/promises';\nimport path from 'node:path';\nimport type { Graph, ValidationResult, ValidationIssue, ArtifactConfig } from '../model/types.js';\nimport { getLastCommitTimestamp } from '../utils/git.js';\nimport { buildContext } from './context-builder.js';\nimport { normalizeMappingPaths } from '../utils/paths.js';\n\n/** Reserved directories that are NOT nodes (within model/) */\nconst RESERVED_DIRS = new Set<string>();\n\nexport async function validate(graph: Graph, scope: string = 'all'): Promise<ValidationResult> {\n const issues: ValidationIssue[] = [];\n\n if (graph.configError) {\n issues.push({\n severity: 'error',\n code: 'E012',\n rule: 'invalid-config',\n message: graph.configError,\n });\n }\n\n for (const { nodePath, message } of graph.nodeParseErrors ?? []) {\n issues.push({\n severity: 'error',\n code: 'E001',\n rule: 'invalid-node-yaml',\n message,\n nodePath,\n });\n }\n\n if (!graph.configError) {\n issues.push(...checkNodeTypes(graph));\n issues.push(...checkTagsDefined(graph));\n issues.push(...checkAspectTags(graph));\n issues.push(...checkAspectTagUniqueness(graph));\n issues.push(...checkRequiredArtifacts(graph));\n issues.push(...(await checkUnknownKnowledgeCategories(graph)));\n issues.push(...checkInvalidArtifactConditions(graph));\n issues.push(...checkScopeTagsDefined(graph));\n issues.push(...(await checkMissingPatternExamples(graph)));\n issues.push(...(await checkContextBudget(graph)));\n issues.push(...checkHighFanOut(graph));\n issues.push(...(await checkStaleKnowledge(graph)));\n issues.push(...checkTemplates(graph));\n }\n\n issues.push(...checkRelationTargets(graph));\n issues.push(...checkNoCycles(graph));\n issues.push(...checkMappingOverlap(graph));\n issues.push(...checkBrokenKnowledgeRefs(graph));\n issues.push(...checkBrokenFlowRefs(graph));\n issues.push(...checkBrokenScopeRefs(graph));\n issues.push(...(await checkDirectoriesHaveNodeYaml(graph)));\n issues.push(...(await checkShallowArtifacts(graph)));\n issues.push(...(await checkUnreachableKnowledge(graph)));\n issues.push(...checkUnpairedEvents(graph));\n\n let filtered = issues;\n let nodesScanned = graph.nodes.size;\n if (scope !== 'all' && scope.trim()) {\n if (!graph.nodes.has(scope)) {\n return {\n issues: [{ severity: 'error', rule: 'invalid-scope', message: `Node not found: ${scope}` }],\n nodesScanned: 0,\n };\n }\n filtered = issues.filter((i) => !i.nodePath || i.nodePath === scope);\n nodesScanned = 1;\n }\n\n return { issues: filtered, nodesScanned };\n}\n\n// --- Rule 0: Node types from config ---\n\nfunction checkNodeTypes(graph: Graph): ValidationIssue[] {\n const issues: ValidationIssue[] = [];\n const allowedTypes = new Set(graph.config.node_types ?? []);\n for (const [nodePath, node] of graph.nodes) {\n if (!allowedTypes.has(node.meta.type)) {\n issues.push({\n severity: 'error',\n code: 'E002',\n rule: 'unknown-node-type',\n message: `Node type '${node.meta.type}' not in config.node_types (${[...allowedTypes].join(', ')})`,\n nodePath,\n });\n }\n }\n return issues;\n}\n\n// --- Rule 1: Relation targets exist ---\n\nfunction findSimilar(target: string, candidates: string[]): string | null {\n if (candidates.length === 0) return null;\n\n let best: string | null = null;\n let bestScore = -1;\n\n for (const c of candidates) {\n if (c === target) return c;\n // Simple similarity: shared path segments\n const targetParts = target.split('/');\n const candParts = c.split('/');\n let score = 0;\n for (let i = 0; i < Math.min(targetParts.length, candParts.length); i++) {\n if (targetParts[i] === candParts[i]) score++;\n else break;\n }\n if (score > bestScore && score > 0) {\n bestScore = score;\n best = c;\n }\n }\n return best;\n}\n\nfunction checkRelationTargets(graph: Graph): ValidationIssue[] {\n const issues: ValidationIssue[] = [];\n const nodePaths = [...graph.nodes.keys()];\n for (const [nodePath, node] of graph.nodes) {\n for (const rel of node.meta.relations ?? []) {\n if (!graph.nodes.has(rel.target)) {\n const suggestion = findSimilar(rel.target, nodePaths);\n const parts = rel.target.split('/');\n const parentPrefix = parts.length > 1 ? parts.slice(0, -1).join('/') + '/' : '';\n const existingInParent = nodePaths\n .filter((p) => p.startsWith(parentPrefix) && p !== rel.target)\n .map((p) => {\n const rest = p.slice(parentPrefix.length);\n return rest.split('/')[0];\n })\n .filter((v, i, a) => a.indexOf(v) === i)\n .sort();\n const existingLine =\n existingInParent.length > 0\n ? `\\n Existing nodes in ${parentPrefix || 'model/'}: ${existingInParent.join(', ')}`\n : '';\n const hint = suggestion ? `\\n Did you mean '${suggestion}'?` : '';\n issues.push({\n severity: 'error',\n code: 'E004',\n rule: 'broken-relation',\n message: `Relation target '${rel.target}' does not exist${existingLine}${hint}`,\n nodePath,\n });\n }\n }\n }\n return issues;\n}\n\n// --- Rule 2: Tags defined in config.yaml ---\n\nfunction checkTagsDefined(graph: Graph): ValidationIssue[] {\n const issues: ValidationIssue[] = [];\n const definedTags = new Set(graph.config.tags ?? []);\n for (const [nodePath, node] of graph.nodes) {\n for (const tag of node.meta.tags ?? []) {\n if (!definedTags.has(tag)) {\n issues.push({\n severity: 'error',\n code: 'E003',\n rule: 'unknown-tag',\n message: `Tag '${tag}' not defined in config.yaml`,\n nodePath,\n });\n }\n }\n }\n return issues;\n}\n\n// --- Rule 3: Aspects reference valid tags ---\n\nfunction checkAspectTags(graph: Graph): ValidationIssue[] {\n const issues: ValidationIssue[] = [];\n const definedTags = new Set(graph.config.tags ?? []);\n for (const aspect of graph.aspects) {\n if (!definedTags.has(aspect.tag)) {\n issues.push({\n severity: 'error',\n code: 'E007',\n rule: 'broken-aspect-tag',\n message: `Aspect '${aspect.name}' references undefined tag '${aspect.tag}'`,\n });\n }\n }\n return issues;\n}\n\nfunction checkAspectTagUniqueness(graph: Graph): ValidationIssue[] {\n const issues: ValidationIssue[] = [];\n const byTag = new Map<string, string[]>();\n for (const aspect of graph.aspects) {\n const names = byTag.get(aspect.tag) ?? [];\n names.push(aspect.name);\n byTag.set(aspect.tag, names);\n }\n for (const [tag, names] of byTag) {\n if (names.length <= 1) continue;\n issues.push({\n severity: 'error',\n code: 'E014',\n rule: 'duplicate-aspect-binding',\n message: `Tag '${tag}' is bound to multiple aspects (${names.join(', ')})`,\n });\n }\n return issues;\n}\n\n// --- Rule 4: No circular dependencies (cycles involving blackbox are tolerated) ---\n\nfunction checkNoCycles(graph: Graph): ValidationIssue[] {\n const WHITE = 0;\n const GRAY = 1;\n const BLACK = 2;\n const color = new Map<string, number>();\n for (const p of graph.nodes.keys()) color.set(p, WHITE);\n\n const issues: ValidationIssue[] = [];\n\n function dfs(nodePath: string, pathSegments: string[]): boolean {\n color.set(nodePath, GRAY);\n const node = graph.nodes.get(nodePath)!;\n const structuralTypes = new Set(['uses', 'calls', 'extends', 'implements']);\n for (const rel of node.meta.relations ?? []) {\n const targetNode = graph.nodes.get(rel.target);\n if (!targetNode) continue;\n if (!structuralTypes.has(rel.type)) continue;\n if (color.get(rel.target) === GRAY) {\n const cyclePath = [...pathSegments, nodePath, rel.target];\n const cycleNodes = pathSegments.slice(pathSegments.indexOf(rel.target)).concat(nodePath);\n const hasBlackboxInCycle = cycleNodes.some(\n (p) => graph.nodes.get(p)?.meta.blackbox === true,\n );\n if (!hasBlackboxInCycle) {\n issues.push({\n severity: 'error',\n code: 'E010',\n rule: 'structural-cycle',\n message: `Circular dependency: ${cyclePath.join(' -> ')}`,\n });\n }\n return true;\n }\n if (color.get(rel.target) === WHITE) {\n if (dfs(rel.target, [...pathSegments, nodePath])) return true;\n }\n }\n color.set(nodePath, BLACK);\n return false;\n }\n\n for (const nodePath of graph.nodes.keys()) {\n if (color.get(nodePath) === WHITE) {\n dfs(nodePath, []);\n }\n }\n\n return issues;\n}\n\n// --- Rule 5: Mapping ownership overlap ---\n\nfunction normalizePathForCompare(mappingPath: string): string {\n return mappingPath.replace(/\\\\/g, '/').replace(/\\/+$/, '');\n}\n\nfunction arePathsOverlapping(pathA: string, pathB: string): boolean {\n if (pathA === pathB) return true;\n return pathA.startsWith(pathB + '/') || pathB.startsWith(pathA + '/');\n}\n\nfunction checkMappingOverlap(graph: Graph): ValidationIssue[] {\n const issues: ValidationIssue[] = [];\n const ownership: Array<{ nodePath: string; mappingPath: string }> = [];\n\n for (const [nodePath, node] of graph.nodes) {\n const mappingPaths = normalizeMappingPaths(node.meta.mapping)\n .map(normalizePathForCompare)\n .filter((mappingPath) => mappingPath.length > 0);\n for (const mappingPath of mappingPaths) {\n ownership.push({ nodePath, mappingPath });\n }\n }\n\n for (let index = 0; index < ownership.length; index++) {\n const current = ownership[index];\n for (let nestedIndex = index + 1; nestedIndex < ownership.length; nestedIndex++) {\n const candidate = ownership[nestedIndex];\n if (current.nodePath === candidate.nodePath) continue;\n if (!arePathsOverlapping(current.mappingPath, candidate.mappingPath)) continue;\n\n issues.push({\n severity: 'error',\n code: 'E009',\n rule: 'overlapping-mapping',\n message:\n `Mapping paths '${current.mappingPath}' (${current.nodePath}) and ` +\n `'${candidate.mappingPath}' (${candidate.nodePath}) overlap. ` +\n `Keep one owner mapping and model other concerns via relations.`,\n nodePath: candidate.nodePath,\n });\n }\n }\n\n return issues;\n}\n\n// --- Rule 6: Required artifacts per config.artifacts (W001) ---\n\nfunction getIncomingRelationSources(graph: Graph, nodePath: string): string[] {\n const sources: string[] = [];\n for (const [srcPath, node] of graph.nodes) {\n for (const rel of node.meta.relations ?? []) {\n if (rel.target === nodePath) sources.push(srcPath);\n }\n }\n return sources;\n}\n\nfunction artifactRequiredReason(\n graph: Graph,\n nodePath: string,\n node: {\n meta: { relations?: Array<{ target: string }>; tags?: string[]; blackbox?: boolean };\n artifacts: Array<{ filename: string }>;\n },\n required: ArtifactConfig['required'],\n): string | null {\n if (required === 'never') return null;\n if (required === 'always') {\n return node.meta.blackbox ? null : 'required: always';\n }\n const when = (required as { when: string }).when;\n if (when === 'has_incoming_relations') {\n const sources = getIncomingRelationSources(graph, nodePath);\n return sources.length > 0\n ? `${sources.length} incoming relation(s): ${sources.join(', ')}`\n : null;\n }\n if (when === 'has_outgoing_relations') {\n const count = node.meta.relations?.length ?? 0;\n return count > 0 ? `${count} outgoing relation(s)` : null;\n }\n if (when.startsWith('has_tag:')) {\n const tag = when.slice(8);\n return (node.meta.tags ?? []).includes(tag) ? `node has tag '${tag}'` : null;\n }\n return null;\n}\n\nfunction getIncomingRelations(graph: Graph, nodePath: string): string[] {\n const incoming: string[] = [];\n for (const [fromPath, node] of graph.nodes) {\n for (const rel of node.meta.relations ?? []) {\n if (rel.target === nodePath) {\n incoming.push(fromPath);\n break;\n }\n }\n }\n return incoming.sort();\n}\n\nfunction checkRequiredArtifacts(graph: Graph): ValidationIssue[] {\n const issues: ValidationIssue[] = [];\n const artifacts = graph.config.artifacts ?? {};\n\n for (const [nodePath, node] of graph.nodes) {\n for (const [filename, config] of Object.entries(artifacts)) {\n const hasArtifact = node.artifacts.some((a) => a.filename === filename);\n const reason = artifactRequiredReason(graph, nodePath, node, config.required);\n\n if (reason && !hasArtifact) {\n const action = config.description ?? '';\n const incoming = getIncomingRelations(graph, nodePath);\n const incomingStr =\n incoming.length > 0\n ? ` Node has ${incoming.length} incoming relation(s): ${incoming.slice(0, 5).join(', ')}${incoming.length > 5 ? '...' : ''}.`\n : '';\n const msg = action\n ? `Missing required artifact '${filename}' (${reason}).${incomingStr} ${action}`\n : `Missing required artifact '${filename}' (${reason}).${incomingStr}`;\n issues.push({\n severity: 'warning',\n code: 'W001',\n rule: 'missing-artifact',\n message: msg.trim(),\n nodePath,\n });\n }\n }\n }\n\n return issues;\n}\n\n// --- E005: Broken knowledge refs (node.meta.knowledge) ---\n\nfunction checkBrokenKnowledgeRefs(graph: Graph): ValidationIssue[] {\n const issues: ValidationIssue[] = [];\n const knowledgePaths = new Set(graph.knowledge.map((k) => k.path));\n for (const [nodePath, node] of graph.nodes) {\n for (const kPath of node.meta.knowledge ?? []) {\n const norm = kPath.replace(/\\/$/, '');\n if (!knowledgePaths.has(norm) && !knowledgePaths.has(kPath)) {\n issues.push({\n severity: 'error',\n code: 'E005',\n rule: 'broken-knowledge-ref',\n message: `Knowledge ref '${kPath}' does not resolve to existing knowledge item`,\n nodePath,\n });\n }\n }\n }\n return issues;\n}\n\n// --- E006: Broken flow refs (flow.nodes, flow.knowledge) ---\n\nfunction checkBrokenFlowRefs(graph: Graph): ValidationIssue[] {\n const issues: ValidationIssue[] = [];\n const nodePaths = new Set(graph.nodes.keys());\n const knowledgePaths = new Set(graph.knowledge.map((k) => k.path));\n for (const flow of graph.flows) {\n for (const n of flow.nodes) {\n if (!nodePaths.has(n)) {\n issues.push({\n severity: 'error',\n code: 'E006',\n rule: 'broken-flow-ref',\n message: `Flow '${flow.name}' references non-existent node '${n}'`,\n });\n }\n }\n for (const kPath of flow.knowledge ?? []) {\n const norm = kPath.replace(/\\/$/, '');\n if (!knowledgePaths.has(norm) && !knowledgePaths.has(kPath)) {\n issues.push({\n severity: 'error',\n code: 'E005',\n rule: 'broken-knowledge-ref',\n message: `Flow '${flow.name}' references non-existent knowledge '${kPath}'`,\n nodePath: `flows/${flow.name}`,\n });\n }\n }\n }\n return issues;\n}\n\n// --- E008: Broken scope refs (knowledge scope.nodes) ---\n\nfunction checkBrokenScopeRefs(graph: Graph): ValidationIssue[] {\n const issues: ValidationIssue[] = [];\n const nodePaths = new Set(graph.nodes.keys());\n for (const k of graph.knowledge) {\n if (typeof k.scope === 'object' && 'nodes' in k.scope) {\n for (const n of k.scope.nodes) {\n if (!nodePaths.has(n)) {\n issues.push({\n severity: 'error',\n code: 'E008',\n rule: 'broken-scope-ref',\n message: `Knowledge '${k.path}' scope references non-existent node '${n}'`,\n });\n }\n }\n }\n }\n return issues;\n}\n\nfunction checkScopeTagsDefined(graph: Graph): ValidationIssue[] {\n const issues: ValidationIssue[] = [];\n const definedTags = new Set(graph.config.tags ?? []);\n for (const k of graph.knowledge) {\n if (typeof k.scope !== 'object' || !('tags' in k.scope)) continue;\n for (const tag of k.scope.tags) {\n if (definedTags.has(tag)) continue;\n issues.push({\n severity: 'error',\n code: 'E008',\n rule: 'broken-scope-ref',\n message: `Knowledge '${k.path}' scope references undefined tag '${tag}'`,\n });\n }\n }\n return issues;\n}\n\n// --- E011: Unknown knowledge categories (dirs under knowledge/ not in config) ---\n// --- E017: Missing knowledge category dir (category in config but no knowledge/<cat>/) ---\n\nasync function checkUnknownKnowledgeCategories(graph: Graph): Promise<ValidationIssue[]> {\n const issues: ValidationIssue[] = [];\n const categorySet = new Set((graph.config.knowledge_categories ?? []).map((c) => c.name));\n const knowledgeDir = path.join(graph.rootPath, 'knowledge');\n const existingDirs = new Set<string>();\n try {\n const entries = await readdir(knowledgeDir, { withFileTypes: true });\n for (const e of entries) {\n if (!e.isDirectory()) continue;\n if (e.name.startsWith('.')) continue;\n existingDirs.add(e.name);\n if (!categorySet.has(e.name)) {\n issues.push({\n severity: 'error',\n code: 'E011',\n rule: 'unknown-knowledge-category',\n message: `Directory knowledge/${e.name}/ does not match any config.knowledge_categories`,\n });\n }\n }\n } catch {\n // knowledge/ may not exist\n }\n\n for (const cat of graph.config.knowledge_categories ?? []) {\n if (!existingDirs.has(cat.name)) {\n issues.push({\n severity: 'error',\n code: 'E017',\n rule: 'missing-knowledge-category-dir',\n message: `Category '${cat.name}' in config has no knowledge/${cat.name}/ directory`,\n });\n }\n }\n\n return issues;\n}\n\n// --- E013: Invalid artifact condition (has_tag:X where X not in config.tags) ---\n\nfunction checkInvalidArtifactConditions(graph: Graph): ValidationIssue[] {\n const issues: ValidationIssue[] = [];\n const definedTags = new Set(graph.config.tags ?? []);\n const artifacts = graph.config.artifacts ?? {};\n for (const [artifactName, config] of Object.entries(artifacts)) {\n const required = config.required;\n if (typeof required === 'object' && required && 'when' in required) {\n const when = (required as { when: string }).when;\n if (when.startsWith('has_tag:')) {\n const tag = when.slice(8);\n if (!definedTags.has(tag)) {\n issues.push({\n severity: 'error',\n code: 'E013',\n rule: 'invalid-artifact-condition',\n message: `Artifact '${artifactName}' condition has_tag:${tag} references undefined tag`,\n });\n }\n }\n }\n }\n return issues;\n}\n\n// --- W002: Shallow artifacts (below min_artifact_length) ---\n\nasync function checkShallowArtifacts(graph: Graph): Promise<ValidationIssue[]> {\n const issues: ValidationIssue[] = [];\n const minLen = graph.config.quality?.min_artifact_length ?? 50;\n for (const [nodePath, node] of graph.nodes) {\n for (const art of node.artifacts) {\n if (art.content.trim().length < minLen) {\n issues.push({\n severity: 'warning',\n code: 'W002',\n rule: 'shallow-artifact',\n message: `Artifact '${art.filename}' is below minimum length (${art.content.length} < ${minLen})`,\n nodePath,\n });\n }\n }\n }\n return issues;\n}\n\n// --- W003: Unreachable knowledge (does not reach any context package) ---\n\nasync function checkUnreachableKnowledge(graph: Graph): Promise<ValidationIssue[]> {\n const issues: ValidationIssue[] = [];\n const nodePaths = new Set(graph.nodes.keys());\n const nodeTags = new Map<string, Set<string>>();\n for (const [p, n] of graph.nodes) {\n nodeTags.set(p, new Set(n.meta.tags ?? []));\n }\n const knowledgeReachable = new Set<string>();\n for (const k of graph.knowledge) {\n if (k.scope === 'global') {\n knowledgeReachable.add(k.path);\n continue;\n }\n if (typeof k.scope === 'object' && 'tags' in k.scope) {\n for (const [, tags] of nodeTags) {\n if (k.scope.tags.some((t) => tags.has(t))) {\n knowledgeReachable.add(k.path);\n break;\n }\n }\n }\n if (typeof k.scope === 'object' && 'nodes' in k.scope) {\n if (k.scope.nodes.some((n) => nodePaths.has(n))) {\n knowledgeReachable.add(k.path);\n }\n }\n }\n for (const [, node] of graph.nodes) {\n for (const kPath of node.meta.knowledge ?? []) {\n const k = graph.knowledge.find(\n (i) => i.path === kPath || i.path === kPath.replace(/\\/$/, ''),\n );\n if (k) knowledgeReachable.add(k.path);\n }\n }\n for (const flow of graph.flows) {\n for (const kPath of flow.knowledge ?? []) {\n const k = graph.knowledge.find(\n (i) => i.path === kPath || i.path === kPath.replace(/\\/$/, ''),\n );\n if (k) knowledgeReachable.add(k.path);\n }\n }\n for (const k of graph.knowledge) {\n if (!knowledgeReachable.has(k.path)) {\n issues.push({\n severity: 'warning',\n code: 'W003',\n rule: 'unreachable-knowledge',\n message: `Knowledge '${k.path}' does not reach any context package`,\n });\n }\n }\n return issues;\n}\n\n// --- W004: Pattern without example file ---\n\nasync function checkMissingPatternExamples(graph: Graph): Promise<ValidationIssue[]> {\n const issues: ValidationIssue[] = [];\n const hasPatterns = (graph.config.knowledge_categories ?? []).some((c) => c.name === 'patterns');\n if (!hasPatterns) return issues;\n const patternsDir = path.join(graph.rootPath, 'knowledge', 'patterns');\n try {\n const entries = await readdir(patternsDir, { withFileTypes: true });\n const exampleExtensions = new Set([\n '.ts',\n '.js',\n '.tsx',\n '.jsx',\n '.py',\n '.go',\n '.rs',\n '.java',\n '.kt',\n ]);\n for (const e of entries) {\n if (!e.isDirectory()) continue;\n const itemDir = path.join(patternsDir, e.name);\n const itemEntries = await readdir(itemDir, { withFileTypes: true });\n const hasExample = itemEntries.some(\n (f) =>\n f.isFile() &&\n f.name !== 'knowledge.yaml' &&\n (f.name.startsWith('example') ||\n exampleExtensions.has(path.extname(f.name).toLowerCase())),\n );\n if (!hasExample) {\n issues.push({\n severity: 'warning',\n code: 'W004',\n rule: 'missing-example',\n message: `Pattern 'patterns/${e.name}' has no example file`,\n });\n }\n }\n } catch {\n // patterns/ may not exist\n }\n return issues;\n}\n\n// --- W007: High fan-out (exceeds max_direct_relations) ---\n\nfunction checkHighFanOut(graph: Graph): ValidationIssue[] {\n const issues: ValidationIssue[] = [];\n const maxRel = graph.config.quality?.max_direct_relations ?? 10;\n for (const [nodePath, node] of graph.nodes) {\n const count = node.meta.relations?.length ?? 0;\n if (count > maxRel) {\n issues.push({\n severity: 'warning',\n code: 'W007',\n rule: 'high-fan-out',\n message: `Node has ${count} direct relations (max: ${maxRel})`,\n nodePath,\n });\n }\n }\n return issues;\n}\n\n// --- W008: Stale knowledge (Proxy: Git commit timestamps, not file mtime) ---\n\nfunction getNodesInScope(\n k: { scope: 'global' | { tags?: string[]; nodes?: string[] } },\n graph: Graph,\n): string[] {\n if (k.scope === 'global') {\n return [...graph.nodes.keys()];\n }\n if (typeof k.scope === 'object' && 'nodes' in k.scope && k.scope.nodes) {\n return k.scope.nodes.filter((p) => graph.nodes.has(p));\n }\n if (typeof k.scope === 'object' && 'tags' in k.scope && k.scope.tags) {\n const tagSet = new Set(k.scope.tags);\n return [...graph.nodes.keys()].filter((p) => {\n const node = graph.nodes.get(p)!;\n return (node.meta.tags ?? []).some((t) => tagSet.has(t));\n });\n }\n return [];\n}\n\nasync function checkStaleKnowledge(graph: Graph): Promise<ValidationIssue[]> {\n const issues: ValidationIssue[] = [];\n const stalenessDays = graph.config.quality?.knowledge_staleness_days ?? 90;\n const projectRoot = path.dirname(graph.rootPath);\n const yggRel = path.relative(projectRoot, graph.rootPath).replace(/\\\\/g, '/') || '.yggdrasil';\n\n for (const k of graph.knowledge) {\n const scopeNodes = getNodesInScope(k, graph);\n if (scopeNodes.length === 0) continue;\n\n const kPath = `${yggRel}/knowledge/${k.path}`;\n const tK = getLastCommitTimestamp(projectRoot, kPath);\n if (tK === null) continue;\n\n let maxTp = 0;\n let latestNode = '';\n for (const nodePath of scopeNodes) {\n const nodePathRel = `${yggRel}/model/${nodePath}`;\n const tP = getLastCommitTimestamp(projectRoot, nodePathRel);\n if (tP !== null && tP > maxTp) {\n maxTp = tP;\n latestNode = nodePath;\n }\n }\n if (maxTp === 0) continue;\n\n const diffDays = (maxTp - tK) / (60 * 60 * 24);\n if (diffDays > stalenessDays) {\n issues.push({\n severity: 'warning',\n code: 'W008',\n rule: 'stale-knowledge',\n message: `Knowledge '${k.path}' may be stale: node '${latestNode}' modified ${Math.floor(diffDays)} days later (Git commits)`,\n nodePath: latestNode,\n });\n }\n }\n return issues;\n}\n\n// --- W009: Unpaired event relations (emits without listens or vice versa) ---\n\nfunction checkUnpairedEvents(graph: Graph): ValidationIssue[] {\n const issues: ValidationIssue[] = [];\n const emitsTo = new Map<string, Set<string>>();\n const listensFrom = new Map<string, Set<string>>();\n for (const [nodePath, node] of graph.nodes) {\n for (const rel of node.meta.relations ?? []) {\n if (rel.type === 'emits') {\n const set = emitsTo.get(nodePath) ?? new Set();\n set.add(rel.target);\n emitsTo.set(nodePath, set);\n }\n if (rel.type === 'listens') {\n const set = listensFrom.get(nodePath) ?? new Set();\n set.add(rel.target);\n listensFrom.set(nodePath, set);\n }\n }\n }\n for (const [emitter, targets] of emitsTo) {\n for (const target of targets) {\n const listenerSet = listensFrom.get(target);\n if (!listenerSet?.has(emitter)) {\n issues.push({\n severity: 'warning',\n code: 'W009',\n rule: 'unpaired-event',\n message: `Node '${emitter}' emits to '${target}' but '${target}' has no listens from '${emitter}'`,\n nodePath: emitter,\n });\n }\n }\n }\n for (const [listener, sources] of listensFrom) {\n for (const source of sources) {\n const emitterSet = emitsTo.get(source);\n if (!emitterSet?.has(listener)) {\n issues.push({\n severity: 'warning',\n code: 'W009',\n rule: 'unpaired-event',\n message: `Node '${listener}' listens from '${source}' but '${source}' has no emits to '${listener}'`,\n nodePath: listener,\n });\n }\n }\n }\n return issues;\n}\n\n// --- Template validation (node_type in config, suggested_artifacts in config, one per type) ---\n\nfunction checkTemplates(graph: Graph): ValidationIssue[] {\n const issues: ValidationIssue[] = [];\n const allowedTypes = new Set(graph.config.node_types ?? []);\n const allowedArtifacts = new Set(Object.keys(graph.config.artifacts ?? {}));\n const typeToTemplate = new Map<string, string>();\n\n for (const template of graph.templates) {\n if (!allowedTypes.has(template.nodeType)) {\n issues.push({\n severity: 'error',\n code: 'E002',\n rule: 'unknown-node-type',\n message: `Template for '${template.nodeType}' references node_type not in config.node_types (${[...allowedTypes].join(', ')})`,\n });\n }\n\n for (const artifact of template.suggestedArtifacts ?? []) {\n if (!allowedArtifacts.has(artifact)) {\n issues.push({\n severity: 'warning',\n code: 'W001',\n rule: 'missing-artifact',\n message: `Template for '${template.nodeType}' suggests artifact '${artifact}' not defined in config.artifacts`,\n });\n }\n }\n\n const existing = typeToTemplate.get(template.nodeType);\n if (existing) {\n issues.push({\n severity: 'error',\n code: 'E016',\n rule: 'duplicate-template',\n message: `Multiple templates for node_type '${template.nodeType}'`,\n });\n } else {\n typeToTemplate.set(template.nodeType, template.nodeType);\n }\n }\n\n return issues;\n}\n\n// --- Directories have node.yaml ---\n\nasync function checkDirectoriesHaveNodeYaml(graph: Graph): Promise<ValidationIssue[]> {\n const issues: ValidationIssue[] = [];\n const modelDir = path.join(graph.rootPath, 'model');\n\n async function scanDir(dirPath: string, segments: string[]): Promise<void> {\n const entries = await readdir(dirPath, { withFileTypes: true });\n const hasNodeYaml = entries.some((e) => e.isFile() && e.name === 'node.yaml');\n const dirName = path.basename(dirPath);\n\n if (RESERVED_DIRS.has(dirName)) return;\n\n const hasContent = entries.some((e) => e.isFile()) || entries.some((e) => e.isDirectory());\n const graphPath = segments.join('/');\n\n if (hasContent && !hasNodeYaml && graphPath !== '') {\n issues.push({\n severity: 'error',\n code: 'E015',\n rule: 'missing-node-yaml',\n message: `Directory '${graphPath}' has content but no node.yaml`,\n nodePath: graphPath,\n });\n }\n\n for (const entry of entries) {\n if (!entry.isDirectory()) continue;\n if (RESERVED_DIRS.has(entry.name)) continue;\n if (entry.name.startsWith('.')) continue;\n await scanDir(path.join(dirPath, entry.name), [...segments, entry.name]);\n }\n }\n\n try {\n const rootEntries = await readdir(modelDir, { withFileTypes: true });\n for (const entry of rootEntries) {\n if (!entry.isDirectory()) continue;\n if (entry.name.startsWith('.')) continue;\n await scanDir(path.join(modelDir, entry.name), [entry.name]);\n }\n } catch {\n // model/ may not exist\n }\n\n return issues;\n}\n\n// --- Context budget (W005 warning, W006 error) ---\n\nasync function checkContextBudget(graph: Graph): Promise<ValidationIssue[]> {\n const issues: ValidationIssue[] = [];\n const warningThreshold = graph.config.quality?.context_budget.warning ?? 5000;\n const errorThreshold = graph.config.quality?.context_budget.error ?? 10000;\n\n for (const [nodePath, node] of graph.nodes) {\n if (node.meta.blackbox) continue;\n try {\n const pkg = await buildContext(graph, nodePath);\n if (pkg.tokenCount >= errorThreshold) {\n issues.push({\n severity: 'warning',\n code: 'W006',\n rule: 'budget-error',\n message: `Context is ${pkg.tokenCount.toLocaleString()} tokens (error threshold: ${errorThreshold.toLocaleString()}) — blocks materialization, node must be split`,\n nodePath,\n });\n } else if (pkg.tokenCount >= warningThreshold) {\n issues.push({\n severity: 'warning',\n code: 'W005',\n rule: 'budget-warning',\n message: `Context is ${pkg.tokenCount.toLocaleString()} tokens (warning threshold: ${warningThreshold.toLocaleString()}). Consider splitting the node or reducing dependencies.`,\n nodePath,\n });\n }\n } catch {\n // If context building fails, other rules will catch it\n }\n }\n return issues;\n}\n","import { execSync } from 'node:child_process';\nimport path from 'node:path';\n\n/**\n * Returns Unix timestamp (seconds) of the last commit touching the given path,\n * or null if not a git repo or path has no commits.\n * Path is relative to projectRoot.\n */\nexport function getLastCommitTimestamp(projectRoot: string, relativePath: string): number | null {\n const normalized = path.normalize(relativePath).replace(/\\\\/g, '/');\n try {\n const out = execSync(`git log -1 --format=%ct -- \"${normalized}\"`, {\n cwd: projectRoot,\n encoding: 'utf-8',\n stdio: ['pipe', 'pipe', 'pipe'],\n });\n const ts = parseInt(out.trim(), 10);\n return Number.isNaN(ts) ? null : ts;\n } catch {\n return null;\n }\n}\n","import type { ContextPackage } from '../model/types.js';\n\nexport function formatContextMarkdown(pkg: ContextPackage): string {\n let md = '';\n\n md += `# Context Package: ${pkg.nodeName}\\n`;\n md += `# Path: ${pkg.nodePath}\\n`;\n md += `# Generated: ${new Date().toISOString()}\\n\\n`;\n md += `---\\n\\n`;\n\n for (const section of pkg.sections) {\n if (section.layers.length === 0) continue;\n\n md += `## ${section.key}\\n\\n`;\n for (const layer of section.layers) {\n md += `### ${layer.label}\\n\\n`;\n md += layer.content;\n md += `\\n\\n`;\n }\n md += `---\\n\\n`;\n }\n\n // Footer\n md += `Context size: ${pkg.tokenCount.toLocaleString()} tokens\\n`;\n md += `Layers: ${pkg.layers.map((l) => l.type).join(', ')}\\n`;\n\n return md;\n}\n","import { Command } from 'commander';\nimport { loadGraph } from '../core/graph-loader.js';\nimport { buildContext } from '../core/context-builder.js';\nimport { validate } from '../core/validator.js';\nimport { formatContextMarkdown } from '../formatters/markdown.js';\n\nexport function registerBuildCommand(program: Command): void {\n program\n .command('build-context')\n .description('Assemble a context package for one node')\n .requiredOption('--node <node-path>', 'Node path relative to .yggdrasil/model/')\n .action(async (options: { node: string }) => {\n try {\n const graph = await loadGraph(process.cwd());\n const validationResult = await validate(graph, 'all');\n const structuralErrors = validationResult.issues.filter(\n (issue) => issue.severity === 'error',\n );\n if (structuralErrors.length > 0) {\n process.stderr.write(\n `Error: build-context requires a structurally valid graph (${structuralErrors.length} errors found).\\n`,\n );\n process.exit(1);\n }\n\n const nodePath = options.node.trim().replace(/\\/$/, '');\n const pkg = await buildContext(graph, nodePath);\n const warningThreshold = graph.config.quality?.context_budget.warning ?? 5000;\n const errorThreshold = graph.config.quality?.context_budget.error ?? 10000;\n const budgetStatus =\n pkg.tokenCount >= errorThreshold\n ? 'error'\n : pkg.tokenCount >= warningThreshold\n ? 'warning'\n : 'ok';\n\n let output = formatContextMarkdown(pkg);\n output += `Budget status: ${budgetStatus}\\n`;\n process.stdout.write(output);\n\n if (budgetStatus === 'error') {\n process.stderr.write(\n `Error: context package exceeds error budget (${pkg.tokenCount} >= ${errorThreshold}).\\n`,\n );\n process.exit(1);\n }\n } catch (error) {\n process.stderr.write(`Error: ${(error as Error).message}\\n`);\n process.exit(1);\n }\n });\n}\n","import { Command } from 'commander';\nimport chalk from 'chalk';\nimport { loadGraph } from '../core/graph-loader.js';\nimport { validate } from '../core/validator.js';\n\nexport function registerValidateCommand(program: Command): void {\n program\n .command('validate')\n .description('Validate graph structural integrity and completeness signals')\n .option('--scope <scope>', 'Scope: all or node-path (default: all)', 'all')\n .action(async (options: { scope: string }) => {\n try {\n const graph = await loadGraph(process.cwd(), { tolerateInvalidConfig: true });\n const scope = (options.scope ?? 'all').trim() || 'all';\n const result = await validate(graph, scope);\n process.stdout.write(`${result.nodesScanned} nodes scanned\\n\\n`);\n const errors = result.issues.filter((i) => i.severity === 'error');\n const warnings = result.issues.filter((i) => i.severity === 'warning');\n for (const issue of errors) {\n const code = issue.code ?? '';\n const loc = issue.nodePath ?? '';\n const prefix = loc ? `${code} ${loc} -> ` : `${code} `;\n process.stdout.write(chalk.red(`✗ ${prefix}${issue.message}\\n`));\n }\n for (const issue of warnings) {\n const code = issue.code ?? '';\n const loc = issue.nodePath ?? '';\n const prefix = loc ? `${code} ${loc} -> ` : `${code} `;\n process.stdout.write(chalk.yellow(`⚠ ${prefix}${issue.message}\\n`));\n }\n if (errors.length === 0 && warnings.length === 0) {\n process.stdout.write(chalk.green('✓ No issues found.\\n'));\n } else {\n process.stdout.write(`\\n${errors.length} errors, ${warnings.length} warnings.\\n`);\n }\n\n const hasErrors = result.issues.some((i) => i.severity === 'error');\n process.exit(hasErrors ? 1 : 0);\n } catch (error) {\n process.stderr.write(`Error: ${(error as Error).message}\\n`);\n process.exit(1);\n }\n });\n}\n","import { Command } from 'commander';\nimport chalk from 'chalk';\nimport { loadGraph } from '../core/graph-loader.js';\nimport { detectDrift } from '../core/drift-detector.js';\n\nexport function registerDriftCommand(program: Command): void {\n program\n .command('drift')\n .description('Detect divergence between graph and code')\n .option('--scope <scope>', 'Scope: all or node-path (default: all)', 'all')\n .action(async (options: { scope?: string }) => {\n try {\n const graph = await loadGraph(process.cwd());\n const scope = (options.scope ?? 'all').trim() || 'all';\n if (scope && scope !== 'all' && !graph.nodes.has(scope)) {\n process.stderr.write(`Error: Node not found: ${scope}\\n`);\n process.exit(1);\n }\n if (scope && scope !== 'all') {\n const scopedNode = graph.nodes.get(scope)!;\n if (!scopedNode.meta.mapping) {\n process.stderr.write(\n `Error: Node has no mapping (does not participate in drift detection): ${options.scope}\\n`,\n );\n process.exit(1);\n }\n }\n const scopeNode = scope === 'all' ? undefined : scope;\n const report = await detectDrift(graph, scopeNode);\n process.stdout.write('Drift:\\n');\n for (const entry of report.entries) {\n const paths = entry.mappingPaths.join(', ');\n switch (entry.status) {\n case 'ok':\n process.stdout.write(chalk.green(` ok ${entry.nodePath} -> ${paths}\\n`));\n break;\n case 'drift':\n process.stdout.write(chalk.red(` drift ${entry.nodePath} -> ${paths}\\n`));\n if (entry.details) process.stdout.write(` ${entry.details}\\n`);\n break;\n case 'missing':\n process.stdout.write(chalk.yellow(` missing ${entry.nodePath} -> ${paths}\\n`));\n break;\n case 'unmaterialized':\n process.stdout.write(chalk.dim(` unmat. ${entry.nodePath} -> ${paths}\\n`));\n break;\n }\n }\n process.stdout.write(\n `\\nSummary: ${report.driftCount} drift, ${report.missingCount} missing, ${report.unmaterializedCount} unmaterialized, ${report.okCount} ok\\n`,\n );\n\n if (report.driftCount > 0 || report.missingCount > 0 || report.unmaterializedCount > 0) {\n process.exit(1);\n }\n process.exit(0);\n } catch (error) {\n process.stderr.write(`Error: ${(error as Error).message}\\n`);\n process.exit(1);\n }\n });\n}\n","import { readFile, writeFile } from 'node:fs/promises';\nimport { parse as parseYaml, stringify as stringifyYaml } from 'yaml';\nimport path from 'node:path';\nimport type { DriftState, DriftNodeState } from '../model/types.js';\n\nconst DRIFT_STATE_FILE = '.drift-state';\n\nexport function getCanonicalHash(entry: string | DriftNodeState): string {\n return typeof entry === 'string' ? entry : entry.hash;\n}\n\nexport function getFileHashes(entry: string | DriftNodeState): Record<string, string> | undefined {\n return typeof entry === 'object' ? entry.files : undefined;\n}\n\nexport async function readDriftState(yggRoot: string): Promise<DriftState> {\n const filePath = path.join(yggRoot, DRIFT_STATE_FILE);\n try {\n const content = await readFile(filePath, 'utf-8');\n const raw = parseYaml(content);\n if (raw && typeof raw === 'object' && !Array.isArray(raw)) {\n const result: DriftState = {};\n for (const [k, v] of Object.entries(raw)) {\n if (typeof k === 'string' && typeof v === 'string') {\n result[k] = v;\n } else if (typeof k === 'string' && typeof v === 'object' && v !== null && 'hash' in v) {\n result[k] = v as DriftNodeState;\n }\n }\n return result;\n }\n return {};\n } catch {\n return {};\n }\n}\n\nexport async function writeDriftState(yggRoot: string, state: DriftState): Promise<void> {\n const filePath = path.join(yggRoot, DRIFT_STATE_FILE);\n const content = stringifyYaml(state);\n await writeFile(filePath, content, 'utf-8');\n}\n","import { readFile, readdir, stat } from 'node:fs/promises';\nimport path from 'node:path';\nimport { createHash } from 'node:crypto';\nimport { createRequire } from 'node:module';\nimport { type Ignore, type Options as IgnoreOptions } from 'ignore';\n\nconst require = createRequire(import.meta.url);\nconst ignoreFactory = require('ignore') as (options?: IgnoreOptions) => Ignore;\n\ntype HashPathOptions = {\n projectRoot?: string;\n};\n\nexport async function hashFile(filePath: string): Promise<string> {\n const content = await readFile(filePath);\n return createHash('sha256').update(content).digest('hex');\n}\n\nexport async function hashPath(targetPath: string, options: HashPathOptions = {}): Promise<string> {\n const projectRoot = options.projectRoot ? path.resolve(options.projectRoot) : undefined;\n const gitignoreMatcher = await loadGitignoreMatcher(projectRoot);\n const targetStat = await stat(targetPath);\n\n if (targetStat.isFile()) {\n if (isIgnoredPath(targetPath, projectRoot, gitignoreMatcher)) {\n return hashString('');\n }\n return hashFile(targetPath);\n }\n\n if (targetStat.isDirectory()) {\n const fileHashes = await collectDirectoryFileHashes(targetPath, targetPath, {\n projectRoot,\n gitignoreMatcher,\n });\n const digestInput = fileHashes\n .sort((a, b) => a.path.localeCompare(b.path))\n .map((entry) => `${entry.path}:${entry.hash}`)\n .join('\\n');\n return hashString(digestInput);\n }\n\n throw new Error(`Unsupported mapping path type: ${targetPath}`);\n}\n\nasync function collectDirectoryFileHashes(\n directoryPath: string,\n rootDirectoryPath: string,\n options: { projectRoot?: string; gitignoreMatcher?: Ignore },\n): Promise<Array<{ path: string; hash: string }>> {\n const entries = await readdir(directoryPath, { withFileTypes: true });\n const result: Array<{ path: string; hash: string }> = [];\n\n for (const entry of entries) {\n const absoluteChildPath = path.join(directoryPath, entry.name);\n\n if (isIgnoredPath(absoluteChildPath, options.projectRoot, options.gitignoreMatcher)) {\n continue;\n }\n\n if (entry.isDirectory()) {\n const nested = await collectDirectoryFileHashes(\n absoluteChildPath,\n rootDirectoryPath,\n options,\n );\n for (const nestedEntry of nested) {\n result.push({\n path: path.relative(rootDirectoryPath, path.join(absoluteChildPath, nestedEntry.path)),\n hash: nestedEntry.hash,\n });\n }\n continue;\n }\n\n if (!entry.isFile()) {\n continue;\n }\n\n result.push({\n path: path.relative(rootDirectoryPath, absoluteChildPath),\n hash: await hashFile(absoluteChildPath),\n });\n }\n\n return result;\n}\n\nasync function loadGitignoreMatcher(projectRoot?: string): Promise<Ignore | undefined> {\n if (!projectRoot) {\n return undefined;\n }\n\n try {\n const gitignorePath = path.join(projectRoot, '.gitignore');\n const gitignoreContent = await readFile(gitignorePath, 'utf-8');\n const matcher = ignoreFactory();\n matcher.add(gitignoreContent);\n return matcher;\n } catch {\n return undefined;\n }\n}\n\nfunction isIgnoredPath(candidatePath: string, projectRoot?: string, matcher?: Ignore): boolean {\n if (!projectRoot || !matcher) {\n return false;\n }\n\n const relativePath = path.relative(projectRoot, candidatePath);\n if (relativePath === '' || relativePath.startsWith('..')) {\n return false;\n }\n\n return matcher.ignores(relativePath) || matcher.ignores(relativePath + '/');\n}\n\nexport function hashString(content: string): string {\n return createHash('sha256').update(content).digest('hex');\n}\n\n/** Compute per-file hashes for a mapping. Used for diagnostics (which files changed). */\nexport async function perFileHashes(\n projectRoot: string,\n mapping: { paths?: string[] },\n): Promise<Array<{ path: string; hash: string }>> {\n const root = path.resolve(projectRoot);\n const paths = mapping.paths ?? [];\n if (paths.length === 0) return [];\n\n const result: Array<{ path: string; hash: string }> = [];\n const gitignoreMatcher = await loadGitignoreMatcher(root);\n\n for (const p of paths) {\n const absPath = path.join(root, p);\n const st = await stat(absPath);\n if (st.isFile()) {\n result.push({ path: p, hash: await hashFile(absPath) });\n } else if (st.isDirectory()) {\n const hashes = await collectDirectoryFileHashes(absPath, absPath, {\n projectRoot: root,\n gitignoreMatcher,\n });\n for (const h of hashes) {\n result.push({\n path: path.join(p, h.path).split(path.sep).join('/'),\n hash: h.hash,\n });\n }\n }\n }\n\n return result;\n}\n\n/** Compute drift hash for a node mapping. Returns hex. */\nexport async function hashForMapping(\n projectRoot: string,\n mapping: { paths?: string[] },\n): Promise<string> {\n const root = path.resolve(projectRoot);\n const paths = mapping.paths ?? [];\n if (paths.length === 0) throw new Error('Invalid mapping for hash: no paths');\n\n const pairs: Array<{ path: string; hash: string }> = [];\n\n for (const p of paths) {\n const absPath = path.join(root, p);\n const st = await stat(absPath);\n if (st.isFile()) {\n pairs.push({ path: p, hash: await hashFile(absPath) });\n } else if (st.isDirectory()) {\n const dirHash = await hashPath(absPath, { projectRoot: root });\n pairs.push({ path: p, hash: dirHash });\n }\n }\n\n const digestInput = pairs\n .sort((a, b) => a.path.localeCompare(b.path))\n .map((e) => `${e.path}:${e.hash}`)\n .join('\\n');\n return createHash('sha256').update(digestInput).digest('hex');\n}\n","import type {\n Graph,\n DriftReport,\n DriftEntry,\n DriftStatus,\n DriftNodeState,\n} from '../model/types.js';\nimport {\n readDriftState,\n writeDriftState,\n getCanonicalHash,\n getFileHashes,\n} from '../io/drift-state-store.js';\nimport { hashForMapping, perFileHashes } from '../utils/hash.js';\nimport { normalizeMappingPaths } from '../utils/paths.js';\nimport { access } from 'node:fs/promises';\nimport path from 'node:path';\n\nexport async function detectDrift(graph: Graph, filterNodePath?: string): Promise<DriftReport> {\n const projectRoot = path.dirname(graph.rootPath);\n const driftState = await readDriftState(graph.rootPath);\n const entries: DriftEntry[] = [];\n\n for (const [nodePath, node] of graph.nodes) {\n if (filterNodePath && nodePath !== filterNodePath) continue;\n const mapping = node.meta.mapping;\n if (!mapping) continue;\n\n const mappingPaths = normalizeMappingPaths(mapping);\n if (mappingPaths.length === 0) continue;\n\n const storedEntry = driftState[nodePath];\n\n if (!storedEntry) {\n const allMissing = await allPathsMissing(projectRoot, mappingPaths);\n entries.push({\n nodePath,\n mappingPaths,\n status: allMissing ? 'unmaterialized' : 'drift',\n details: allMissing\n ? 'No drift state recorded, files do not exist'\n : 'No drift state recorded, files exist (run drift-sync after materialization)',\n });\n continue;\n }\n\n const storedHash = getCanonicalHash(storedEntry);\n let status: DriftStatus = 'ok';\n let details = '';\n\n try {\n const currentHash = await hashForMapping(projectRoot, mapping);\n if (currentHash !== storedHash) {\n status = 'drift';\n const changedFiles = await diagnoseChangedFiles(\n projectRoot,\n mapping,\n getFileHashes(storedEntry),\n );\n details =\n changedFiles.length > 0\n ? `Changed files: ${changedFiles.join(', ')}`\n : 'File(s) modified since last sync';\n }\n } catch {\n status = 'missing';\n details = 'Mapped path(s) do not exist';\n }\n\n entries.push({ nodePath, mappingPaths, status, details });\n }\n\n return {\n entries,\n totalChecked: entries.length,\n okCount: entries.filter((e) => e.status === 'ok').length,\n driftCount: entries.filter((e) => e.status === 'drift').length,\n missingCount: entries.filter((e) => e.status === 'missing').length,\n unmaterializedCount: entries.filter((e) => e.status === 'unmaterialized').length,\n };\n}\n\nasync function diagnoseChangedFiles(\n projectRoot: string,\n mapping: { paths?: string[] },\n storedFileHashes: Record<string, string> | undefined,\n): Promise<string[]> {\n try {\n const currentHashes = await perFileHashes(projectRoot, mapping);\n if (!storedFileHashes) {\n return currentHashes.map((h) => h.path).sort();\n }\n\n const changed: string[] = [];\n const storedPaths = new Set(Object.keys(storedFileHashes));\n\n for (const { path: filePath, hash } of currentHashes) {\n const stored = storedFileHashes[filePath];\n if (!stored || stored !== hash) {\n changed.push(filePath);\n }\n storedPaths.delete(filePath);\n }\n\n for (const removed of storedPaths) {\n changed.push(`${removed} (deleted)`);\n }\n\n return changed.sort();\n } catch {\n return [];\n }\n}\n\nasync function allPathsMissing(projectRoot: string, mappingPaths: string[]): Promise<boolean> {\n for (const mp of mappingPaths) {\n const absPath = path.join(projectRoot, mp);\n try {\n await access(absPath);\n return false;\n } catch {\n // path missing\n }\n }\n return true;\n}\n\nexport async function syncDriftState(\n graph: Graph,\n nodePath: string,\n): Promise<{ previousHash?: string; currentHash: string }> {\n const projectRoot = path.dirname(graph.rootPath);\n const node = graph.nodes.get(nodePath);\n if (!node) throw new Error(`Node not found: ${nodePath}`);\n const mapping = node.meta.mapping;\n if (!mapping) throw new Error(`Node has no mapping: ${nodePath}`);\n\n const currentHash = await hashForMapping(projectRoot, mapping);\n const driftState = await readDriftState(graph.rootPath);\n const previousEntry = driftState[nodePath];\n const previousHash = previousEntry ? getCanonicalHash(previousEntry) : undefined;\n\n const fileHashes = await perFileHashes(projectRoot, mapping);\n const files: Record<string, string> = {};\n for (const fh of fileHashes) {\n files[fh.path] = fh.hash;\n }\n\n const newEntry: DriftNodeState = { hash: currentHash, files };\n driftState[nodePath] = newEntry;\n await writeDriftState(graph.rootPath, driftState);\n return { previousHash, currentHash };\n}\n","import { Command } from 'commander';\nimport chalk from 'chalk';\nimport { loadGraph } from '../core/graph-loader.js';\nimport { syncDriftState } from '../core/drift-detector.js';\n\nexport function registerDriftSyncCommand(program: Command): void {\n program\n .command('drift-sync')\n .description('Record current file hash after resolving drift')\n .requiredOption('--node <path>', 'Node path to sync')\n .action(async (options: { node: string }) => {\n try {\n const graph = await loadGraph(process.cwd());\n const nodePath = options.node.trim().replace(/\\/$/, '');\n const { previousHash, currentHash } = await syncDriftState(graph, nodePath);\n process.stdout.write(chalk.green(`Synchronized: ${nodePath}\\n`));\n process.stdout.write(\n ` Hash: ${previousHash ? previousHash.slice(0, 8) : 'none'} -> ${currentHash.slice(0, 8)}\\n`,\n );\n } catch (error) {\n process.stderr.write(`Error: ${(error as Error).message}\\n`);\n process.exit(1);\n }\n });\n}\n","import { Command } from 'commander';\nimport { loadGraph } from '../core/graph-loader.js';\nimport { detectDrift } from '../core/drift-detector.js';\nimport { validate } from '../core/validator.js';\n\nexport function registerStatusCommand(program: Command): void {\n program\n .command('status')\n .description('Show graph summary')\n .action(async () => {\n try {\n const graph = await loadGraph(process.cwd());\n\n // Count nodes by type\n const typeCounts = new Map<string, number>();\n let blackboxCount = 0;\n\n for (const node of graph.nodes.values()) {\n typeCounts.set(node.meta.type, (typeCounts.get(node.meta.type) ?? 0) + 1);\n if (node.meta.blackbox) blackboxCount++;\n }\n\n // Count relations\n let structuralRelations = 0;\n let eventRelations = 0;\n const structuralTypes = new Set(['uses', 'calls', 'extends', 'implements']);\n for (const node of graph.nodes.values()) {\n for (const rel of node.meta.relations ?? []) {\n if (structuralTypes.has(rel.type)) structuralRelations += 1;\n else eventRelations += 1;\n }\n }\n\n const flowCount = graph.flows.length;\n const knowledgeCount = graph.knowledge.length;\n\n const drift = await detectDrift(graph);\n const validation = await validate(graph, 'all');\n const errorCount = validation.issues.filter((issue) => issue.severity === 'error').length;\n const warningCount = validation.issues.filter(\n (issue) => issue.severity === 'warning',\n ).length;\n\n process.stdout.write(`Graph: ${graph.config.name}\\n`);\n const pluralize = (word: string, count: number) =>\n count === 1 ? word : word.endsWith('y') ? word.slice(0, -1) + 'ies' : word + 's';\n const typeStr = [...typeCounts.entries()]\n .map(([t, c]) => `${c} ${pluralize(t, c)}`)\n .join(', ');\n process.stdout.write(\n `Nodes: ${graph.nodes.size} (${typeStr}) + ${blackboxCount} blackbox\\n`,\n );\n process.stdout.write(\n `Relations: ${structuralRelations} structural, ${eventRelations} event\\n`,\n );\n process.stdout.write(\n `Aspects: ${graph.aspects.length} Flows: ${flowCount} Knowledge: ${knowledgeCount}\\n`,\n );\n process.stdout.write(\n `Drift: ${drift.driftCount} drift, ${drift.missingCount} missing, ${drift.unmaterializedCount} unmaterialized, ${drift.okCount} ok\\n`,\n );\n process.stdout.write(`Validation: ${errorCount} errors, ${warningCount} warnings\\n`);\n } catch (error) {\n process.stderr.write(`Error: ${(error as Error).message}\\n`);\n process.exit(1);\n }\n });\n}\n","import { Command } from 'commander';\nimport { loadGraph } from '../core/graph-loader.js';\nimport type { GraphNode } from '../model/types.js';\n\nexport function registerTreeCommand(program: Command): void {\n program\n .command('tree')\n .description('Display graph structure as a tree')\n .option('--root <path>', 'Show only subtree rooted at this path')\n .option('--depth <n>', 'Maximum depth', (v) => parseInt(v, 10))\n .action(async (options: { root?: string; depth?: number }) => {\n try {\n const graph = await loadGraph(process.cwd());\n\n let roots: GraphNode[];\n let showProjectName: boolean;\n\n if (options.root?.trim()) {\n const path = options.root.trim().replace(/\\/$/, '');\n const node = graph.nodes.get(path);\n if (!node) {\n process.stderr.write(`Error: path '${path}' not found\\n`);\n process.exit(1);\n }\n roots = [node];\n showProjectName = false;\n } else {\n roots = [...graph.nodes.values()]\n .filter((n) => n.parent === null)\n .sort((a, b) => a.path.localeCompare(b.path));\n showProjectName = true;\n }\n\n if (showProjectName) {\n process.stdout.write('model/\\n');\n }\n\n for (let i = 0; i < roots.length; i++) {\n const isLast = i === roots.length - 1;\n printNode(roots[i], '', isLast, 1, options.depth);\n }\n } catch (error) {\n process.stderr.write(`Error: ${(error as Error).message}\\n`);\n process.exit(1);\n }\n });\n}\n\nfunction printNode(\n node: GraphNode,\n prefix: string,\n isLast: boolean,\n depth: number,\n maxDepth: number | undefined,\n): void {\n const connector = isLast ? '└── ' : '├── ';\n const name = node.path.split('/').pop() ?? node.path;\n const type = `[${node.meta.type}]`;\n const tags = node.meta.tags?.length ? ` tags:${node.meta.tags.join(',')}` : '';\n const blackbox = node.meta.blackbox ? ' ■ blackbox' : '';\n const relationCount = node.meta.relations?.length ?? 0;\n\n process.stdout.write(\n `${prefix}${connector}${name}/ ${type}${tags}${blackbox} -> ${relationCount} relations\\n`,\n );\n\n const childPrefix = prefix + (isLast ? ' ' : '│ ');\n\n // Recurse into children\n if (maxDepth !== undefined && depth >= maxDepth) return;\n\n const children = [...node.children].sort((a, b) => a.path.localeCompare(b.path));\n for (let i = 0; i < children.length; i++) {\n printNode(children[i], childPrefix, i === children.length - 1, depth + 1, maxDepth);\n }\n}\n","import { Command } from 'commander';\nimport { loadGraph } from '../core/graph-loader.js';\nimport type { Graph, OwnerResult } from '../model/types.js';\nimport { normalizeMappingPaths, normalizeProjectRelativePath } from '../utils/paths.js';\n\nfunction normalizeForMatch(inputPath: string): string {\n return inputPath.replace(/\\\\/g, '/').replace(/\\/+$/, '');\n}\n\nexport function findOwner(graph: Graph, projectRoot: string, rawPath: string): OwnerResult {\n const file = normalizeForMatch(normalizeProjectRelativePath(projectRoot, rawPath));\n let best: { nodePath: string; mappingPath: string; exact: boolean } | null = null;\n\n for (const [nodePath, node] of graph.nodes) {\n const mappingPaths = normalizeMappingPaths(node.meta.mapping)\n .map(normalizeForMatch)\n .filter((mappingPath) => mappingPath.length > 0);\n\n for (const mappingPath of mappingPaths) {\n if (file === mappingPath) {\n return { file, nodePath, mappingPath };\n }\n if (file.startsWith(mappingPath + '/')) {\n if (!best || (best && mappingPath.length > best.mappingPath.length)) {\n best = { nodePath, mappingPath, exact: false };\n }\n }\n }\n }\n\n return best\n ? { file, nodePath: best.nodePath, mappingPath: best.mappingPath }\n : { file, nodePath: null };\n}\n\nexport function registerOwnerCommand(program: Command): void {\n program\n .command('owner')\n .description('Find which graph node owns a source file')\n .requiredOption('--file <path>', 'File path (relative to repository root)')\n .action(async (options: { file: string }) => {\n try {\n const projectRoot = process.cwd();\n const graph = await loadGraph(projectRoot);\n const result = findOwner(graph, projectRoot, options.file);\n\n if (!result.nodePath) {\n process.stdout.write(`${result.file} -> no graph coverage\\n`);\n } else {\n process.stdout.write(`${result.file} -> ${result.nodePath}\\n`);\n }\n } catch (error) {\n process.stderr.write(`Error: ${(error as Error).message}\\n`);\n process.exit(1);\n }\n });\n}\n","import type { Graph, Stage } from '../model/types.js';\nimport { execSync } from 'node:child_process';\nimport path from 'node:path';\n\nexport interface ResolveOptions {\n mode: 'all' | 'changed' | 'node';\n nodePath?: string; // required when mode === 'node'\n ref?: string; // git ref for --changed mode (default: HEAD)\n depth?: number; // max depth for tree (when mode === 'node')\n relationType?: 'structural' | 'event' | 'all'; // filter for tree\n}\n\nconst STRUCTURAL_RELATION_TYPES = new Set(['uses', 'calls', 'extends', 'implements']);\nconst EVENT_RELATION_TYPES = new Set(['emits', 'listens']);\n\n/** Expand changed set with direct dependents only (one level, no cascade) */\nfunction expandWithDependents(graph: Graph, changed: string[]): string[] {\n const dependents = new Map<string, string[]>();\n for (const [nodePath, node] of graph.nodes) {\n for (const rel of node.meta.relations ?? []) {\n if (!STRUCTURAL_RELATION_TYPES.has(rel.type)) continue;\n const deps = dependents.get(rel.target) ?? [];\n deps.push(nodePath);\n dependents.set(rel.target, deps);\n }\n }\n\n const result = new Set<string>(changed);\n for (const node of changed) {\n for (const dep of dependents.get(node) ?? []) {\n result.add(dep);\n }\n }\n\n return [...result];\n}\n\n/** Find nodes whose graph files have changed according to git */\nexport function findChangedNodes(graph: Graph, ref?: string): string[] {\n const gitRef = ref ?? 'HEAD';\n const yggDirName = path.basename(graph.rootPath);\n const projectRoot = path.dirname(graph.rootPath);\n\n let changedFiles: string[];\n try {\n const output = execSync(`git diff --name-only ${gitRef} -- ${yggDirName}/`, {\n cwd: projectRoot,\n encoding: 'utf-8',\n }).trim();\n changedFiles = output ? output.split('\\n') : [];\n } catch {\n // If git diff fails (no commits, not a repo, etc.), fall back to empty\n changedFiles = [];\n }\n\n // Map changed file paths back to node paths\n const changedNodePaths = new Set<string>();\n for (const filePath of changedFiles) {\n // filePath is like \".yggdrasil/auth/login-service/node.yaml\"\n // Strip the yggdrasil dir prefix to get \"auth/login-service/node.yaml\"\n const relative = filePath.startsWith(yggDirName + '/')\n ? filePath.slice(yggDirName.length + 1)\n : filePath;\n\n // Walk up directories to find matching node paths (nodes are under model/)\n const parts = relative.split('/');\n const modelIdx = parts.indexOf('model');\n const startIdx = modelIdx >= 0 ? modelIdx + 1 : 0;\n for (let i = parts.length - 1; i >= startIdx + 1; i--) {\n const candidate = parts.slice(startIdx, i).join('/');\n if (graph.nodes.has(candidate)) {\n changedNodePaths.add(candidate);\n break;\n }\n }\n }\n\n return expandWithDependents(graph, [...changedNodePaths]);\n}\n\n/** Collect node and its transitive dependencies (for --node mode) */\nexport function collectTransitiveDeps(graph: Graph, nodePath: string): string[] {\n return collectTransitiveDepsFiltered(graph, nodePath, undefined, 'structural');\n}\n\n/** Filter relation types for inclusion */\nfunction filterRelationType(relType: string, filter: 'structural' | 'event' | 'all'): boolean {\n if (filter === 'all') return true;\n if (filter === 'structural') return STRUCTURAL_RELATION_TYPES.has(relType);\n if (filter === 'event') return EVENT_RELATION_TYPES.has(relType);\n return false;\n}\n\n/** Collect transitive deps with depth and type filter */\nfunction collectTransitiveDepsFiltered(\n graph: Graph,\n nodePath: string,\n maxDepth: number | undefined,\n relationType: 'structural' | 'event' | 'all',\n): string[] {\n const node = graph.nodes.get(nodePath);\n if (!node) {\n throw new Error(`Node not found: ${nodePath}`);\n }\n\n const result = new Set<string>();\n const queue: Array<{ path: string; depth: number }> = [{ path: nodePath, depth: 0 }];\n\n while (queue.length > 0) {\n const { path: p, depth } = queue.shift()!;\n if (result.has(p)) continue;\n result.add(p);\n if (maxDepth !== undefined && depth >= maxDepth) continue;\n\n const n = graph.nodes.get(p)!;\n for (const rel of n.meta.relations ?? []) {\n if (!filterRelationType(rel.type, relationType)) continue;\n if (!graph.nodes.has(rel.target)) {\n throw new Error(`Relation target not found: ${rel.target}`);\n }\n if (!result.has(rel.target)) {\n queue.push({ path: rel.target, depth: depth + 1 });\n }\n }\n }\n\n return [...result];\n}\n\n/** Tree node for dependency tree output */\nexport interface DepTreeNode {\n nodePath: string;\n relationType: string;\n relationTarget?: string;\n blackbox: boolean;\n children: DepTreeNode[];\n}\n\n/** Build dependency tree for a node (spec format) */\nexport function buildDependencyTree(\n graph: Graph,\n nodePath: string,\n options: { depth?: number; relationType?: 'structural' | 'event' | 'all' } = {},\n): DepTreeNode[] {\n const node = graph.nodes.get(nodePath);\n if (!node) {\n throw new Error(`Node not found: ${nodePath}`);\n }\n\n const maxDepth = options.depth ?? Infinity;\n const typeFilter = options.relationType ?? 'all';\n\n function buildChildren(\n fromPath: string,\n currentDepth: number,\n branch: Set<string>,\n ): DepTreeNode[] {\n if (currentDepth >= maxDepth) return [];\n const fromNode = graph.nodes.get(fromPath)!;\n const children: DepTreeNode[] = [];\n for (const rel of fromNode.meta.relations ?? []) {\n if (!filterRelationType(rel.type, typeFilter)) continue;\n if (!graph.nodes.has(rel.target)) continue;\n if (branch.has(rel.target)) continue;\n const targetNode = graph.nodes.get(rel.target)!;\n const nextBranch = new Set(branch);\n nextBranch.add(rel.target);\n children.push({\n nodePath: rel.target,\n relationType: rel.type,\n relationTarget: fromPath,\n blackbox: targetNode.meta.blackbox ?? false,\n children: buildChildren(rel.target, currentDepth + 1, nextBranch),\n });\n }\n return children;\n }\n\n return buildChildren(nodePath, 0, new Set([nodePath]));\n}\n\n/** Format tree as text (spec format) */\nexport function formatDependencyTree(\n graph: Graph,\n nodePath: string,\n options: { depth?: number; relationType?: 'structural' | 'event' | 'all' } = {},\n): string {\n const roots = buildDependencyTree(graph, nodePath, options);\n const lines: string[] = [nodePath];\n\n function formatNode(node: DepTreeNode, prefix: string, isLast: boolean): void {\n const connector = isLast ? '└── ' : '├── ';\n const blackbox = node.blackbox ? ' ■ blackbox' : '';\n lines.push(`${prefix}${connector}${node.relationType} ${node.nodePath}${blackbox}`);\n const childPrefix = prefix + (isLast ? ' ' : '│ ');\n const lastIdx = node.children.length - 1;\n node.children.forEach((c, i) => formatNode(c, childPrefix, i === lastIdx));\n }\n\n roots.forEach((r, i) => formatNode(r, '', i === roots.length - 1));\n return lines.join('\\n');\n}\n\nexport async function resolveDeps(graph: Graph, options: ResolveOptions): Promise<Stage[]> {\n let candidatePaths: string[];\n\n switch (options.mode) {\n case 'all':\n candidatePaths = [...graph.nodes.keys()];\n break;\n case 'changed':\n candidatePaths = findChangedNodes(graph, options.ref);\n break;\n case 'node':\n candidatePaths = collectTransitiveDeps(graph, options.nodePath!);\n break;\n }\n\n candidatePaths = candidatePaths.filter((p) => {\n const node = graph.nodes.get(p)!;\n return !node.meta.blackbox && node.meta.mapping;\n });\n\n if (candidatePaths.length === 0) return [];\n\n const candidateSet = new Set(candidatePaths);\n\n // Validate relations: broken relation = target not in graph\n for (const p of candidatePaths) {\n const node = graph.nodes.get(p)!;\n for (const rel of node.meta.relations ?? []) {\n if (!graph.nodes.has(rel.target)) {\n throw new Error(`Relation target not found: ${rel.target}`);\n }\n }\n }\n\n const inDegree = new Map<string, number>();\n const dependents = new Map<string, string[]>();\n\n for (const p of candidatePaths) {\n inDegree.set(p, 0);\n dependents.set(p, []);\n }\n\n for (const p of candidatePaths) {\n const node = graph.nodes.get(p)!;\n for (const rel of node.meta.relations ?? []) {\n if (!STRUCTURAL_RELATION_TYPES.has(rel.type)) continue;\n if (candidateSet.has(rel.target)) {\n inDegree.set(p, (inDegree.get(p) ?? 0) + 1);\n dependents.get(rel.target)!.push(p);\n }\n }\n }\n\n const stages: Stage[] = [];\n let queue = candidatePaths.filter((p) => inDegree.get(p) === 0);\n let stageNum = 1;\n const processed = new Set<string>();\n\n while (queue.length > 0) {\n stages.push({\n stage: stageNum,\n parallel: queue.length > 1,\n nodes: [...queue],\n });\n\n const nextQueue: string[] = [];\n for (const nodePath of queue) {\n processed.add(nodePath);\n for (const dep of dependents.get(nodePath) ?? []) {\n inDegree.set(dep, (inDegree.get(dep) ?? 0) - 1);\n if (inDegree.get(dep) === 0) {\n nextQueue.push(dep);\n }\n }\n }\n\n queue = nextQueue;\n stageNum++;\n }\n\n if (processed.size < candidatePaths.length) {\n const cycleNodes = candidatePaths.filter((p) => !processed.has(p));\n throw new Error(`Circular dependency detected involving: ${cycleNodes.join(', ')}`);\n }\n\n return stages;\n}\n","import { Command } from 'commander';\nimport { loadGraph } from '../core/graph-loader.js';\nimport { formatDependencyTree } from '../core/dependency-resolver.js';\n\nexport function registerDepsCommand(program: Command): void {\n program\n .command('deps')\n .description('Show direct and transitive node dependencies')\n .requiredOption('--node <path>', 'Node path relative to .yggdrasil/model/')\n .option('--depth <n>', 'Maximum depth for tree (when using --node)', (v) => parseInt(v, 10))\n .option('--type <type>', 'Relation type filter: structural, event, all (default: all)', 'all')\n .action(async (options: { node: string; depth?: number; type?: string }) => {\n try {\n const graph = await loadGraph(process.cwd());\n const typeFilter =\n options.type === 'structural' || options.type === 'event' || options.type === 'all'\n ? options.type\n : 'all';\n const nodePath = options.node.trim().replace(/\\/$/, '');\n const text = formatDependencyTree(graph, nodePath, {\n depth: options.depth,\n relationType: typeFilter,\n });\n process.stdout.write(text + '\\n');\n } catch (error) {\n process.stderr.write(`Error: ${(error as Error).message}\\n`);\n process.exit(1);\n }\n });\n}\n","import { mkdtemp, rm } from 'node:fs/promises';\nimport { tmpdir } from 'node:os';\nimport path from 'node:path';\nimport { execSync } from 'node:child_process';\nimport { loadGraph } from './graph-loader.js';\nimport type { Graph } from '../model/types.js';\n\n/**\n * Load graph from a git ref (e.g. HEAD) by extracting .yggdrasil to temp dir.\n * Returns null if not a git repo, ref doesn't exist, or .yggdrasil not in ref.\n */\nexport async function loadGraphFromRef(\n projectRoot: string,\n ref: string = 'HEAD',\n): Promise<Graph | null> {\n const yggPath = '.yggdrasil';\n let tmpDir: string | null = null;\n\n try {\n execSync(`git rev-parse ${ref}`, { cwd: projectRoot, stdio: 'pipe' });\n } catch {\n return null;\n }\n\n try {\n tmpDir = await mkdtemp(path.join(tmpdir(), 'ygg-git-'));\n const archivePath = path.join(tmpDir, 'archive.tar');\n execSync(`git archive ${ref} ${yggPath} -o \"${archivePath}\"`, {\n cwd: projectRoot,\n stdio: 'pipe',\n });\n execSync(`tar -xf \"${archivePath}\" -C \"${tmpDir}\"`, { stdio: 'pipe' });\n const graph = await loadGraph(tmpDir);\n return graph;\n } catch {\n return null;\n } finally {\n if (tmpDir) {\n await rm(tmpDir, { recursive: true, force: true });\n }\n }\n}\n","import { Command } from 'commander';\nimport { loadGraph } from '../core/graph-loader.js';\nimport { loadGraphFromRef } from '../core/graph-from-git.js';\nimport { buildContext } from '../core/context-builder.js';\nimport { detectDrift } from '../core/drift-detector.js';\nimport type { Graph } from '../model/types.js';\n\nconst STRUCTURAL_TYPES = new Set(['uses', 'calls', 'extends', 'implements']);\n\nfunction collectReverseDependents(\n graph: Graph,\n targetNode: string,\n): {\n direct: string[];\n transitive: string[];\n reverse: Map<string, Set<string>>;\n relationFrom: Map<string, { type: string; consumes?: string[] }>;\n} {\n const reverse = new Map<string, Set<string>>();\n const relationFrom = new Map<string, { type: string; consumes?: string[] }>();\n for (const [nodePath, node] of graph.nodes) {\n for (const rel of node.meta.relations ?? []) {\n if (!STRUCTURAL_TYPES.has(rel.type)) continue;\n const deps = reverse.get(rel.target) ?? new Set<string>();\n deps.add(nodePath);\n reverse.set(rel.target, deps);\n relationFrom.set(`${nodePath}->${rel.target}`, {\n type: rel.type,\n consumes: rel.consumes,\n });\n }\n }\n\n const direct = [...(reverse.get(targetNode) ?? [])].sort();\n const seen = new Set<string>(direct);\n const queue = [...direct];\n while (queue.length > 0) {\n const current = queue.shift()!;\n for (const next of reverse.get(current) ?? []) {\n if (seen.has(next)) continue;\n seen.add(next);\n queue.push(next);\n }\n }\n\n return {\n direct,\n transitive: [...seen].sort(),\n reverse,\n relationFrom,\n };\n}\n\nfunction buildTransitiveChains(\n targetNode: string,\n direct: string[],\n transitive: string[],\n reverse: Map<string, Set<string>>,\n): string[] {\n const directSet = new Set(direct);\n const transitiveOnly = transitive.filter((t) => !directSet.has(t));\n if (transitiveOnly.length === 0) return [];\n\n const parent = new Map<string, string>();\n const queue: string[] = [targetNode];\n const visited = new Set<string>([targetNode]);\n while (queue.length > 0) {\n const current = queue.shift()!;\n for (const next of reverse.get(current) ?? []) {\n if (visited.has(next)) continue;\n visited.add(next);\n parent.set(next, current);\n queue.push(next);\n }\n }\n\n const chains: string[] = [];\n for (const node of transitiveOnly) {\n const path: string[] = [];\n let current: string | undefined = node;\n while (current) {\n path.unshift(current);\n current = parent.get(current);\n }\n if (path.length >= 2) {\n chains.push(path.map((p) => `<- ${p}`).join(' '));\n }\n }\n return chains.sort();\n}\n\nexport function registerImpactCommand(program: Command): void {\n program\n .command('impact')\n .description('Show reverse dependency impact for a node')\n .requiredOption('--node <path>', 'Node path relative to .yggdrasil/model/')\n .option('--simulate', 'Simulate context package impact (compare HEAD vs current)')\n .action(async (options: { node: string; simulate?: boolean }) => {\n try {\n const graph = await loadGraph(process.cwd());\n const nodePath = options.node.trim().replace(/\\/$/, '');\n\n if (!graph.nodes.has(nodePath)) {\n process.stderr.write(`Node not found: ${nodePath}\\n`);\n process.exit(1);\n }\n\n const { direct, transitive, reverse, relationFrom } = collectReverseDependents(\n graph,\n nodePath,\n );\n const chains = buildTransitiveChains(nodePath, direct, transitive, reverse);\n\n const flows: string[] = [];\n for (const flow of graph.flows) {\n if (flow.nodes.includes(nodePath)) {\n flows.push(flow.name);\n }\n }\n\n const aspectsInScope: string[] = [];\n const targetNode = graph.nodes.get(nodePath)!;\n const targetTags = new Set(targetNode.meta.tags ?? []);\n for (const aspect of graph.aspects) {\n if (targetTags.has(aspect.tag)) {\n aspectsInScope.push(aspect.name);\n }\n }\n\n const knowledgeInScope: string[] = [];\n for (const k of graph.knowledge) {\n if (k.scope === 'global') {\n knowledgeInScope.push(k.path);\n continue;\n }\n if (typeof k.scope === 'object' && 'tags' in k.scope) {\n if (k.scope.tags.some((t) => targetTags.has(t))) {\n knowledgeInScope.push(k.path);\n }\n continue;\n }\n if (typeof k.scope === 'object' && 'nodes' in k.scope) {\n if (k.scope.nodes.includes(nodePath)) {\n knowledgeInScope.push(k.path);\n }\n }\n }\n\n const budget = graph.config.quality?.context_budget ?? { warning: 5000, error: 10000 };\n process.stdout.write(`Impact of changes in ${nodePath}:\\n\\n`);\n process.stdout.write('Directly dependent:\\n');\n if (direct.length === 0) {\n process.stdout.write(' (none)\\n');\n } else {\n for (const dep of direct) {\n const rel = relationFrom.get(`${dep}->${nodePath}`);\n const annot = rel?.consumes?.length\n ? ` (${rel.type}, you consume: ${rel.consumes.join(', ')})`\n : rel\n ? ` (${rel.type})`\n : '';\n process.stdout.write(` <- ${dep}${annot}\\n`);\n }\n }\n process.stdout.write('\\nTransitively dependent:\\n');\n if (chains.length === 0) {\n process.stdout.write(' (none)\\n');\n } else {\n for (const chain of chains) {\n process.stdout.write(` ${chain}\\n`);\n }\n }\n process.stdout.write(`\\nFlows: ${flows.length > 0 ? flows.join(', ') : '(none)'}\\n`);\n process.stdout.write(\n `Aspects (scope covers node): ${aspectsInScope.length > 0 ? aspectsInScope.join(', ') : '(none)'}\\n`,\n );\n process.stdout.write(\n `Knowledge (scope covers node): ${knowledgeInScope.length > 0 ? knowledgeInScope.join(', ') : '(none)'}\\n`,\n );\n process.stdout.write(\n `\\nTotal scope: ${transitive.length} nodes, ${flows.length} flows, ${aspectsInScope.length} aspects, ${knowledgeInScope.length} knowledge\\n`,\n );\n\n if (options.simulate && transitive.length > 0) {\n process.stdout.write('\\nChanges in context packages:\\n\\n');\n const baselineGraph = await loadGraphFromRef(process.cwd(), 'HEAD');\n const driftReport = await detectDrift(graph);\n const driftByNode = new Map(driftReport.entries.map((e) => [e.nodePath, e]));\n\n for (const dep of transitive) {\n try {\n const pkg = await buildContext(graph, dep);\n const status =\n pkg.tokenCount >= budget.error\n ? 'error'\n : pkg.tokenCount >= budget.warning\n ? 'warning'\n : 'ok';\n\n let baselineTokens: number | null = null;\n if (baselineGraph?.nodes.has(dep)) {\n try {\n const baselinePkg = await buildContext(baselineGraph, dep);\n baselineTokens = baselinePkg.tokenCount;\n } catch {\n /* ignore */\n }\n }\n\n const hasDepOnTarget = graph.nodes\n .get(dep)\n ?.meta.relations?.some(\n (r) => r.target === nodePath && STRUCTURAL_TYPES.has(r.type),\n );\n const changedLine = hasDepOnTarget\n ? ` + Changed dependency interface: ${nodePath}\\n`\n : '';\n\n const budgetLine =\n baselineTokens !== null\n ? ` Budget: ${baselineTokens} -> ${pkg.tokenCount} tokens (${status})\\n`\n : ` Budget: ${pkg.tokenCount} tokens (${status})\\n`;\n\n const driftEntry = driftByNode.get(dep);\n const driftLine =\n driftEntry && driftEntry.status !== 'ok'\n ? ` Mapped files (on-disk): ${driftEntry.status}${driftEntry.details ? ` (${driftEntry.details})` : ''}\\n`\n : driftEntry\n ? ` Mapped files (on-disk): ok\\n`\n : '';\n\n process.stdout.write(`${dep}:\\n${changedLine}${budgetLine}${driftLine}\\n`);\n } catch {\n process.stdout.write(`${dep}:\\n failed to build context\\n\\n`);\n }\n }\n }\n } catch (error) {\n process.stderr.write(`Error: ${(error as Error).message}\\n`);\n process.exit(1);\n }\n });\n}\n","import { readFile, writeFile, mkdir, rename, access } from 'node:fs/promises';\nimport { parse as parseYaml, stringify as stringifyYaml } from 'yaml';\nimport path from 'node:path';\nimport type { JournalEntry } from '../model/types.js';\n\nconst JOURNAL_FILE = '.journal.yaml';\nconst ARCHIVE_DIR = 'journals-archive';\n\nexport async function readJournal(yggRoot: string): Promise<JournalEntry[]> {\n const filePath = path.join(yggRoot, JOURNAL_FILE);\n try {\n const content = await readFile(filePath, 'utf-8');\n const raw = parseYaml(content) as { entries?: JournalEntry[] };\n const entries = raw.entries ?? [];\n return Array.isArray(entries) ? entries : [];\n } catch {\n return [];\n }\n}\n\nexport async function appendJournalEntry(\n yggRoot: string,\n note: string,\n target?: string,\n): Promise<JournalEntry> {\n const entries = await readJournal(yggRoot);\n const at = new Date().toISOString();\n const entry: JournalEntry = target ? { at, target, note } : { at, note };\n\n entries.push(entry);\n\n const filePath = path.join(yggRoot, JOURNAL_FILE);\n const content = stringifyYaml({ entries });\n await writeFile(filePath, content, 'utf-8');\n\n return entry;\n}\n\nexport async function archiveJournal(\n yggRoot: string,\n): Promise<{ archiveName: string; entryCount: number } | null> {\n const journalPath = path.join(yggRoot, JOURNAL_FILE);\n try {\n await access(journalPath);\n } catch {\n return null;\n }\n\n const entries = await readJournal(yggRoot);\n if (entries.length === 0) return null;\n\n const archiveDir = path.join(yggRoot, ARCHIVE_DIR);\n await mkdir(archiveDir, { recursive: true });\n\n const now = new Date();\n const timestamp =\n `${now.getUTCFullYear()}` +\n `${String(now.getUTCMonth() + 1).padStart(2, '0')}` +\n `${String(now.getUTCDate()).padStart(2, '0')}` +\n `-` +\n `${String(now.getUTCHours()).padStart(2, '0')}` +\n `${String(now.getUTCMinutes()).padStart(2, '0')}` +\n `${String(now.getUTCSeconds()).padStart(2, '0')}`;\n const archiveName = `.journal.${timestamp}.yaml`;\n const archivePath = path.join(archiveDir, archiveName);\n\n await rename(journalPath, archivePath);\n\n return { archiveName, entryCount: entries.length };\n}\n","import { Command } from 'commander';\nimport { findYggRoot } from '../utils/paths.js';\nimport { appendJournalEntry, readJournal } from '../io/journal-store.js';\n\nexport function registerJournalAddCommand(program: Command): void {\n program\n .command('journal-add')\n .description('Add a note to the session journal')\n .requiredOption('--note <text>', 'Note content')\n .option('--target <node-path>', 'Node path this note relates to')\n .action(async (options: { note: string; target?: string }) => {\n try {\n const projectRoot = process.cwd();\n const yggRoot = await findYggRoot(projectRoot);\n await appendJournalEntry(yggRoot, options.note, options.target);\n const entries = await readJournal(yggRoot);\n process.stdout.write(`Note added to journal (${entries.length} entries total)\\n`);\n } catch (error) {\n process.stderr.write(`Error: ${(error as Error).message}\\n`);\n process.exit(1);\n }\n });\n}\n","import { Command } from 'commander';\nimport { findYggRoot } from '../utils/paths.js';\nimport { readJournal } from '../io/journal-store.js';\n\nexport function registerJournalReadCommand(program: Command): void {\n program\n .command('journal-read')\n .description('List pending journal entries')\n .action(async () => {\n try {\n const projectRoot = process.cwd();\n const yggRoot = await findYggRoot(projectRoot);\n const entries = await readJournal(yggRoot);\n\n if (entries.length === 0) {\n process.stdout.write('Session journal: empty (clean state)\\n');\n return;\n }\n\n process.stdout.write(`Session journal (${entries.length} entries):\\n\\n`);\n for (const e of entries) {\n const date = e.at.slice(0, 19).replace('T', ' ');\n const target = e.target ? ` ${e.target}` : '';\n process.stdout.write(`[${date}]${target}\\n ${e.note}\\n\\n`);\n }\n } catch (error) {\n process.stderr.write(`Error: ${(error as Error).message}\\n`);\n process.exit(1);\n }\n });\n}\n","import { Command } from 'commander';\nimport { findYggRoot } from '../utils/paths.js';\nimport { archiveJournal } from '../io/journal-store.js';\n\nexport function registerJournalArchiveCommand(program: Command): void {\n program\n .command('journal-archive')\n .description('Archive journal after consolidating notes to graph')\n .action(async () => {\n try {\n const projectRoot = process.cwd();\n const yggRoot = await findYggRoot(projectRoot);\n const result = await archiveJournal(yggRoot);\n\n if (!result) {\n process.stdout.write('No active journal - nothing to archive.\\n');\n return;\n }\n\n process.stdout.write(\n `Archived journal (${result.entryCount} entries) -> journals-archive/${result.archiveName}\\n`,\n );\n } catch (error) {\n process.stderr.write(`Error: ${(error as Error).message}\\n`);\n process.exit(1);\n }\n });\n}\n"],"mappings":";;;AACA,SAAS,eAAe;;;ACAxB,SAAS,SAAAA,QAAO,aAAAC,YAAW,SAAS,YAAAC,WAAU,YAAY;AAC1D,OAAOC,WAAU;AACjB,SAAS,qBAAqB;;;ACHvB,IAAM,iBAAiB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACA9B,SA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,QAAQ;AACX,gBAAQ,OAAO,MAAM,2CAA2C;AAChE;AAAA,MACF;AAEA,cAAQ,OAAO;AAAA,QACb,qBAAqB,OAAO,UAAU,iCAAiC,OAAO,WAAW;AAAA;AAAA,MAC3F;AAAA,IACF,SAAS,OAAO;AACd,cAAQ,OAAO,MAAM,UAAW,MAAgB,OAAO;AAAA,CAAI;AAC3D,cAAQ,KAAK,CAAC;AAAA,IAChB;AAAA,EACF,CAAC;AACL;;;ApCXA,IAAM,UAAU,IAAI,QAAQ;AAE5B,QACG,KAAK,IAAI,EACT,YAAY,uEAAkE,EAC9E,QAAQ,OAAO;AAElB,oBAAoB,OAAO;AAC3B,qBAAqB,OAAO;AAC5B,wBAAwB,OAAO;AAC/B,qBAAqB,OAAO;AAC5B,yBAAyB,OAAO;AAChC,sBAAsB,OAAO;AAC7B,oBAAoB,OAAO;AAC3B,qBAAqB,OAAO;AAC5B,oBAAoB,OAAO;AAC3B,sBAAsB,OAAO;AAC7B,0BAA0B,OAAO;AACjC,2BAA2B,OAAO;AAClC,8BAA8B,OAAO;AAErC,QAAQ,MAAM;","names":["mkdir","writeFile","readFile","path","path","program","rulesPath","mkdir","readFile","writeFile","readdir","path","readFile","readFile","parseYaml","readFile","parseYaml","readFile","readdir","path","readFile","parseYaml","readFile","parseYaml","readFile","parseYaml","readFile","parseYaml","readFile","parseYaml","readFile","parseYaml","path","fileURLToPath","stat","path","stat","path","path","readdir","readFile","path","path","readFile","readdir","path","path","path","readdir","program","program","chalk","readFile","writeFile","parseYaml","path","readFile","readdir","stat","path","require","path","program","chalk","chalk","program","chalk","program","program","path","program","execSync","path","STRUCTURAL_RELATION_TYPES","EVENT_RELATION_TYPES","STRUCTURAL_RELATION_TYPES","EVENT_RELATION_TYPES","program","path","execSync","execSync","path","path","program","readFile","writeFile","mkdir","access","parseYaml","stringifyYaml","path","program","program","program"]}
|