@chrisdudek/yg 0.3.2 → 1.0.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.
@@ -6,12 +6,10 @@ stack:
6
6
 
7
7
  standards: ""
8
8
 
9
- tags: []
10
-
11
9
  node_types:
12
- - module
13
- - service
14
- - library
10
+ - name: module
11
+ - name: service
12
+ - name: library
15
13
 
16
14
  artifacts:
17
15
  responsibility.md:
@@ -45,19 +43,10 @@ artifacts:
45
43
  required: never
46
44
  description: "Local design decisions and rationale — choices specific to this node, not system-wide"
47
45
 
48
- knowledge_categories:
49
- - name: decisions
50
- description: "Global semantic decisions and their rationale"
51
- - name: patterns
52
- description: "Implementation conventions with examples"
53
- - name: invariants
54
- description: "System truths that must never be violated"
55
-
56
46
  quality:
57
47
  min_artifact_length: 50
58
48
  max_direct_relations: 10
59
49
  context_budget:
60
50
  warning: 10000
61
51
  error: 20000
62
- knowledge_staleness_days: 90
63
52
  `;
@@ -1,241 +1,312 @@
1
1
  /**
2
2
  * Canonical agent rules content — hand-tuned, do not generate programmatically.
3
3
  *
4
- * Operating manual for agents: graph-first, exhaustive coverage, context is sufficient.
4
+ * Operating manual for agents working in a Yggdrasil-managed repository.
5
+ * Split into three cognitive sections optimized for LLM attention patterns:
6
+ * 1. CORE PROTOCOL — internalize before doing anything (primacy effect)
7
+ * 2. OPERATIONS — execute while working (working memory)
8
+ * 3. KNOWLEDGE BASE — look up when needed (recency effect)
5
9
  */
6
- export const AGENT_RULES_CONTENT = `# Yggdrasil - System Semantic Memory (Operating Manual)
7
10
 
8
- You are working in a repository managed by Yggdrasil.
9
- Yggdrasil is a persistent, structured semantic memory graph stored in \`.yggdrasil/\`. It maps the repository, dictates system rules, and assembles implementation contexts.
11
+ // prettier-ignore
12
+ const CORE_PROTOCOL = `## CORE PROTOCOL
13
+
14
+ Yggdrasil is persistent semantic memory stored in \`.yggdrasil/\`. It maps the repository and provides deterministic implementation context for every node. This document is your complete operating manual. Follow it strictly.
15
+
16
+ ### Quick Start Protocol
17
+
18
+ \`\`\`
19
+ BEFORE reading, researching, planning, OR modifying ANY mapped file:
20
+ 1. yg owner --file <path>
21
+ 2. yg build-context --node <owner>
22
+ The context package is your primary source of understanding.
23
+ Raw file reads are for implementation details WITHIN a node you
24
+ already understand from its context package.
25
+ If the context package seems insufficient — enrich the graph.
26
+ Do not bypass it.
27
+
28
+ AFTER modifying:
29
+ 3. Update graph artifacts to reflect changes
30
+ 4. yg validate — fix all errors
31
+ 5. yg drift-sync --node <owner>
10
32
 
11
- **Why:** AI agents degrade with project size — too little context breaks contracts, too much context drowns in noise. The graph is persistent semantic memory: agents need exactly the right tokens for the task, not the whole repo. Small, precise context beats massive noisy. A repository with Yggdrasil is self-aware.
33
+ EVERY conversation start:
34
+ yg preflight → act on findings (see Operations)
12
35
 
13
- THIS PROMPT IS YOUR ENTIRE OPERATING MANUAL. Read it carefully. Follow it strictly.
36
+ NEVER: modify code without graph coverage.
37
+ NEVER: read mapped source files to understand a component without
38
+ running yg build-context first — the graph captures intent,
39
+ constraints, and relations that source files cannot.
40
+ NEVER: invent rationale, business rules, or decisions.
41
+ NEVER: auto-resolve drift without asking the user.
42
+ WHEN UNSURE: ask the user. Never guess. Never assume.
43
+ \`\`\`
14
44
 
15
- ---
45
+ ### Five Core Rules
16
46
 
17
- ## 0. ATOMIC INVARIANTOVERRIDES EVERYTHING
47
+ 1. **Graph first.** Before reading, researching, planning, or modifying mapped files, run \`yg owner\` and \`yg build-context\`. Always. The context package not raw source — is your primary source of understanding.
48
+ 2. **Code and graph are one.** Code changed → graph updated in the same response. Graph changed → source verified in the same response. No exceptions.
49
+ 3. **Never invent why.** The graph captures human intent. If you don't know why something was decided, ask. Never hallucinate rationale.
50
+ 4. **Always capture why.** When the user explains a reason, record it in the graph immediately. Conversation evaporates; graph persists.
51
+ 5. **Ask before resolving ambiguity.** When multiple valid interpretations exist, stop, list options, ask the user. Never silently choose.
18
52
 
19
- **CODE GRAPH ARE ONE.**
20
- - Code changed → graph artifacts MUST be updated IN THE SAME RESPONSE. No exceptions.
21
- - Graph changed → source files MUST be verified/updated IN THE SAME RESPONSE. No exceptions.
22
- - There is NO "code-only" response. There is NO "graph-only" response (unless explicitly a dry-run plan).
23
- - If you complete a response and one side is changed but the other is not, you have VIOLATED the core contract of Yggdrasil.
53
+ ### Failure States
24
54
 
25
- ---
55
+ You have broken Yggdrasil if you do any of the following:
26
56
 
27
- ## 1. CORE PRINCIPLES (NON-NEGOTIABLE)
57
+ - Modified source code without running \`yg owner --file <path>\` first.
58
+ - ❌ Modified source code without updating graph artifacts in the same response.
59
+ - ❌ Modified graph files without verifying source code alignment in the same response.
60
+ - ❌ Resolved a code-graph inconsistency without asking the user first.
61
+ - ❌ Created or edited a graph element without reading its schema in \`schemas/\` first.
62
+ - ❌ Ran \`yg drift-sync\` before updating graph artifacts.
63
+ - ❌ Wrote a flow description that describes code sequences instead of a business process.
64
+ - ❌ Used an aspect identifier that has no corresponding \`aspects/\` directory.
65
+ - ❌ Placed a cross-cutting requirement in a local node artifact instead of an aspect.
66
+ - ❌ Invented a rationale, business rule, or architectural decision.
67
+ - ❌ Used blackbox coverage for greenfield (new) code.
68
+ - ❌ Answered a question about a mapped file without running \`yg build-context\` first.
69
+ - ❌ Read mapped source files to plan or research changes without running \`yg build-context\` first.
70
+ - ❌ Deferred \`yg drift-sync\` to the end of a multi-step task instead of running it incrementally after each logical group of changes.
28
71
 
29
- 1. **Graph First, Always:** Before answering a question, modifying code, or planning a feature, you MUST consult the graph.
30
- 2. **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.
31
- 3. **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.
32
- 4. **Exhaustive Coverage:** Every source file MUST belong to exactly one graph node. No orphaned files.
33
- 5. **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.
34
- 6. **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.
35
- 7. **Never Touch Operational Metadata:** NEVER manually edit \`.yggdrasil/.drift-state\` or \`.yggdrasil/.journal.yaml\`.
36
- 8. **Ask, Never Infer:** If graph and code diverge in a way with multiple valid resolutions, or if a required decision is ambiguous — STOP. State the ambiguity. List interpretations. Ask the user to decide. Never silently choose. Never patch without confirmation. When you stop, always explain the context and available options clearly so the user can make an informed choice.
72
+ ### Escape Hatch
37
73
 
38
- ---
74
+ If the user explicitly requests a code-only change, comply but:
39
75
 
40
- ## 1.5 FAILURE STATES
76
+ - Warn: "This creates drift. Run \`yg drift\` next session to reconcile."
77
+ - Do NOT run \`yg drift-sync\` — leave the drift visible.
41
78
 
42
- You have fundamentally broken Yggdrasil if you do any of the following:
43
- - ❌ You modified source code without having run \`yg owner --file <path>\` for each modified file in the SAME response.
44
- - ❌ You modified source code without updating graph artifacts in the SAME response.
45
- - ❌ You modified graph files without verifying/updating source code alignment in the SAME response.
46
- - ❌ You resolved a code↔graph inconsistency without asking the user first.
47
- - ❌ You created or edited a graph element without reading its schema in \`.yggdrasil/templates/\`.
48
- - ❌ You ran \`yg drift-sync\` before updating graph artifacts.
49
- - ❌ You ran \`yg drift-sync\` after a graph-only change without verifying source files.
50
- - ❌ You used Blackbox coverage for greenfield/new code.
51
- - ❌ You answered a question about a mapped file/area without running \`yg build-context\` when the path was known.
79
+ ### Environment Check
52
80
 
53
- ---
81
+ Before preflight:
54
82
 
55
- ## 2. CONVERSATION LIFECYCLE (YOUR HABITS)
83
+ - Verify \`yg\` CLI is available. If not found, inform user and stop.
84
+ - If \`yg preflight\` shows 0 nodes → enter BOOTSTRAP MODE (see Operations).
85
+ - If drift report shows >10 drifted nodes → report scope to user, ask which area to prioritize. Do not resolve all at once.`;
56
86
 
57
- You do not need explicit "session" commands. Follow these conversational triggers:
87
+ // prettier-ignore
88
+ const OPERATIONS = `## OPERATIONS
58
89
 
59
- ### A. Preflight (First message of the conversation)
60
- Always execute these commands before doing anything else. *(Exception: If the user's request is clearly read-only, run ONLY step 1).* **Read-only** means the user asks only for explanation, clarification, analysis, or evaluation — no code or graph modification will occur. Examples: "explain this", "evaluate X", "what does Y do?", "analyze Z". If unsure, run full preflight.
61
- 1. \`yg journal-read\` -> If entries exist, consolidate them into the graph, then \`yg journal-archive\`.
62
- 2. \`yg drift\` -> If **drift** (code changed, graph baseline stale): run \`yg drift-sync\` for each affected node. Do NOT ask the user — they do not need to know this step. If **missing** or **unmaterialized**: report and ask the user how to proceed.
63
- 3. \`yg status\` -> Report graph health.
64
- 4. \`yg validate\` -> If W008 stale-knowledge appears, update the knowledge artifacts to reflect current node state.
90
+ ### Conversation Lifecycle
65
91
 
66
- ### B. Answering Questions (When a specific file or area is known)
67
- When the user asks a question and you know (or can infer) which file or area of the codebase it concerns:
68
- 1. Run \`yg owner --file <path>\` for the relevant file(s).
69
- 2. **If owner FOUND:** Run \`yg build-context --node <node_path>\` and base your answer on that context. Do NOT answer from grep/search alone — the graph provides intent, constraints, and relations that yield better answers.
70
- 3. **If owner NOT FOUND:** The file is outside the graph (e.g. third-party code, user's theme/plugin, unmapped area). You may answer from grep/search, but state that the answer is not graph-based.
92
+ \`\`\`
93
+ PREFLIGHT (every conversation, before any work):
94
+ - [ ] 1. yg preflight read unified report
95
+ - [ ] 2. If journal entries: consolidate to graph, then yg journal-archive
96
+ - [ ] 3. If drift: resolve per Drift Resolution, then yg drift-sync per node
97
+ - [ ] 4. If validation errors: fix, re-run yg validate
98
+ Exception: read-only requests (explain, analyze) — skip preflight.
71
99
 
72
- This applies even when you are **not modifying files** — e.g. when providing code snippets to paste elsewhere, explaining behavior, or suggesting hooks. If the question touches mapped code, build-context first.
100
+ UNDERSTANDING mapped code (questions, research, OR planning):
101
+ - [ ] 1. yg owner --file <path>
102
+ - [ ] 2. Owner found → yg build-context --node <path>. Use context package as primary source.
103
+ - [ ] 3. Owner not found → use file analysis, state it is not graph-backed.
104
+ Never use grep or raw file reads as primary understanding when graph coverage exists.
105
+ Raw reads supplement the context package — they do not replace it.
73
106
 
74
- ### C. Session Verification (Wrap-up)
75
- Triggered by phrases like: "we're done", "wrap up", "that's enough", "done", "ok".
76
- **Note: The graph should ALREADY be up to date. If the graph requires massive updates at this stage, YOU HAVE FAILED.**
77
- 1. If iterative journal mode was used: consolidate notes to the graph, then \`yg journal-archive\`.
78
- 2. \`yg drift\` -> If drift detected, run \`yg drift-sync\` for each affected node. Do NOT ask absorb automatically.
79
- 3. \`yg validate\` -> Fix any structural errors.
80
- 4. Report exactly what nodes and files were changed.
107
+ WRAP-UP (user signals "done", "wrap up", "that's enough"):
108
+ - [ ] 1. Consolidate journal if used yg journal-archive
109
+ - [ ] 2. yg drift --drifted-only resolve
110
+ - [ ] 3. yg validate fix errors
111
+ - [ ] 4. Report: which nodes and files were changed
112
+ \`\`\`
81
113
 
82
- ---
114
+ ### Modify Source Code
83
115
 
84
- ## 3. WORKFLOW: MODIFYING OR CREATING FILES (Code-First)
116
+ You are not allowed to edit or create source code without establishing graph coverage first.
85
117
 
86
- You are NOT ALLOWED to edit or create source code without establishing graph coverage first.
118
+ **Step 1** Check coverage: \`yg owner --file <path>\`
87
119
 
88
- **Gate:** Before using any tool that modifies files, you MUST have run \`yg owner --file <path>\` for each file you intend to modify. If you have not run it first, then proceed. No exceptions. Gate applies to **source files** (files outside \`.yggdrasil/\`). For graph files (\`.yggdrasil/model/\`, \`.yggdrasil/aspects/\`, etc.), follow the Graph Modification Checklist in section 4 instead.
120
+ **Step 2a**Owner found: execute checklist:
89
121
 
90
- **Step 1: Check coverage** -> Run \`yg owner --file <path>\`
122
+ - [ ] 1. Read specification: \`yg build-context --node <node_path>\`
123
+ - [ ] 2. Assess blast radius: \`yg impact --node <node_path>\` — review dependents, descendants, and co-aspect nodes before changing interfaces or shared behavior
124
+ - [ ] 3. Modify source code
125
+ - [ ] 4. Sync graph artifacts — edit artifact files to reflect the changes
126
+ - [ ] 5. Run \`yg validate\` — fix all errors (if unfixable after 3 attempts → stop, report to user)
127
+ - [ ] 6. Run \`yg drift-sync --node <node_path>\` — only after graph and code are both current
91
128
 
92
- **Step 2: If Owner FOUND (The Execution Checklist)**
93
- Whenever 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:
129
+ **Step 2b** Owner not found: establish coverage first. Present options to the user:
94
130
 
95
- - [ ] 1. Read Specification (ran \`yg build-context\`)
96
- - [ ] 2. Modify Source Code
97
- - [ ] 3. Sync Graph Artifacts (manually edit the node's artifact files IMMEDIATELY to match new code behavior)
98
- - [ ] 4. Baseline Hash (ran \`yg drift-sync\` ONLY AFTER updating the graph)
131
+ *Partially mapped* (file unmapped but inside a mapped module): ask whether to add to existing node or create new one.
99
132
 
100
- **Step 3: If Owner NOT FOUND (Uncovered Area)**
101
- STOP. Do not modify the code. First determine: **Is this greenfield or existing code?**
133
+ *Existing code:*
102
134
 
103
- * **If GREENFIELD (empty directory, new project):** Do NOT offer blackbox. Create proper nodes (reverse engineering or upfront design) before implementing.
104
- * **If PARTIALLY MAPPED (file is unmapped, but lives inside a mapped module):** Stop and ask the user if this file should be added to the existing node or if a new node is required.
105
- * **If EXISTING CODE (legacy, third-party):** Present the user with 3 options and wait:
106
- * **Option 1: Reverse Engineering:** Create/extend standard nodes to map the area fully before modifying.
107
- * **Option 2: Blackbox Coverage:** Create a \`blackbox: true\` node to establish ownership without deep semantic exploration.
108
- * **Option 3: Abort/Change Plan:** Do not touch the file.
135
+ - Option A Full node: create node(s), map files, write artifacts from code analysis
136
+ - Option B Blackbox: create a blackbox node at agreed granularity
137
+ - Option C Abort
109
138
 
110
- ---
139
+ *Greenfield (new code):* Only Option A. Blackbox is forbidden for new code. Create nodes with full artifacts, then materialize.
111
140
 
112
- ## 4. WORKFLOW: MODIFYING THE GRAPH & BLAST RADIUS (Graph-First)
141
+ After the user chooses, return to Step 1 and follow Step 2a.
113
142
 
114
- When adding features, changing architecture, or doing graph-first design:
143
+ ### Modify Graph
115
144
 
116
- 1. **Check Blast Radius:** Before modifying a node that others depend on, run \`yg impact --node <node_path> --simulate\`. Report the impact to the user.
117
- 2. **Read Config & Templates:**
118
- * Check \`.yggdrasil/config.yaml\` for allowed \`node_types\` and \`tags\`.
119
- * **CRITICAL:** ALWAYS read the schema in \`.yggdrasil/templates/\` for the element type (node.yaml, aspect.yaml, flow.yaml, knowledge.yaml) before creating or editing it.
120
- 3. **Validate & Fix:** Run \`yg validate\`. You must fix all E-codes (Errors).
121
- 4. **Token Economy & W-codes:**
122
- * W005/W006: Context package too large. Consider splitting the node.
123
- * W008: Stale semantic memory. Update knowledge artifacts.
145
+ - [ ] 1. Read the relevant schema from \`schemas/\` before touching any YAML
146
+ - [ ] 2. Before changing an aspect or flow, check scope: \`yg impact --aspect <id>\` or \`yg impact --flow <name>\` — understand which nodes are affected before modifying shared rules or processes
147
+ - [ ] 3. Make changes
148
+ - [ ] 4. Run \`yg validate\` immediately fix all errors
149
+ - [ ] 5. Verify affected source files are consistent update if needed
150
+ - [ ] 6. Run \`yg drift-sync\` for affected nodes
124
151
 
125
- **Graph Modification Checklist**
126
- Whenever you change the graph structure or semantics, you MUST output and execute this exact checklist:
152
+ ### Reverse Engineering
127
153
 
128
- - [ ] 1. Read schema from \`.yggdrasil/templates/\` (node.yaml, aspect.yaml, flow.yaml, or knowledge.yaml for the element type)
129
- - [ ] 2. Edit graph files (\`node.yaml\`, artifacts)
130
- - [ ] 3. Verify corresponding source files exist and their behavior matches updated artifacts
131
- - [ ] 4. Validate (ran \`yg validate\` — fix all Errors)
132
- - [ ] 5. Baseline Hash (ran \`yg drift-sync\` ONLY AFTER steps 2-3 are confirmed)
154
+ **Order:** aspects (cross-cutting patterns) flows (business processes) model nodes. Never create nodes before aspects and flows are understood.
133
155
 
134
- **Journaling (Iterative Mode Scope):**
135
- * **Default:** Write changes directly to graph files immediately. Do not defer.
136
- * **Opt-in:** ONLY if the user says "use iterative mode" or "use journal". Once activated, it remains active for the ENTIRE conversation until wrap-up. Use \`yg journal-add --note "..."\` to buffer intent.
156
+ Per area checklist:
137
157
 
138
- ---
158
+ - [ ] 1. \`yg owner --file <path>\` — confirm no coverage
159
+ - [ ] 2. Determine node granularity — propose to user if unclear
160
+ - [ ] 3. Create node directory, read \`schemas/node.yaml\`, create \`node.yaml\`
161
+ - [ ] 4. Analyze source — for each artifact type in \`config.artifacts\`: extract content, do not invent
162
+ - [ ] 5. Identify relations — add to \`node.yaml\`
163
+ - [ ] 6. Identify cross-cutting requirements — add matching aspects, create if needed
164
+ - [ ] 7. Identify business process participation — add to flow, ask user if process unclear
165
+ - [ ] 8. \`yg validate\` — fix errors
166
+ - [ ] 9. \`yg drift-sync --node <path>\`
139
167
 
140
- ## 5. PATH CONVENTIONS (CRITICAL)
168
+ **When to ask:**
141
169
 
142
- To avoid broken references (\`E004\`, \`E005\`), use correct relative paths:
143
- * **Node paths** (used in CLI, relations, flow nodes): Relative to \`.yggdrasil/model/\` (e.g., \`orders/order-service\`).
144
- * **File paths** (used in mapping, \`yg owner\`): Relative to the repository root (e.g., \`src/modules/orders/order.service.ts\`).
145
- * **Knowledge paths** (used in node explicit refs): Relative to \`.yggdrasil/knowledge/\` (e.g., \`decisions/001-event-sourcing\`).
170
+ - Business process unclear: "This code appears to be part of a larger process. Can you describe what it means from a business perspective?"
171
+ - Constraint without rationale: "I see [constraint X]. Do you know why this exists? I want to record the reason, not just the rule."
172
+ - Unexplained architectural choice: "I see [approach X]. What was the reason for this choice?"
146
173
 
147
- ---
174
+ ### Bootstrap Mode
148
175
 
149
- ## 6. GRAPH STRUCTURE, CONFIG & TEMPLATES CHEAT SHEET
176
+ Trigger: \`yg preflight\` shows 0 nodes, or no nodes cover the active work area.
150
177
 
151
- The 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.
178
+ - [ ] 1. Identify the active work area (files the user wants to modify)
179
+ - [ ] 2. Scan for cross-cutting patterns → create aspects
180
+ - [ ] 3. Ask user about business processes → create flows if applicable
181
+ - [ ] 4. Propose node structure for the area
182
+ - [ ] 5. Create node(s) with initial artifacts, map files
183
+ - [ ] 6. \`yg validate\`, \`yg drift-sync\`
184
+ - [ ] 7. Proceed with user's original request
152
185
 
153
- * **\`.yggdrasil/config.yaml\`**: Defines \`node_types\`, \`tags\`, \`artifacts\`, \`knowledge_categories\`.
154
- * **\`.yggdrasil/templates/\`**: Schemas for each graph layer — \`node.yaml\`, \`aspect.yaml\`, \`flow.yaml\`, \`knowledge.yaml\`.
155
- * **\`.yggdrasil/model/\`**: Node tree. Each node is a directory with \`node.yaml\` and artifact files.
156
- * **\`.yggdrasil/aspects/\`**: Cross-cutting rules. Directory contains \`aspect.yaml\` and \`.md\` content.
157
- * **\`.yggdrasil/flows/\`**: End-to-end processes. Directory contains \`flow.yaml\` and \`.md\` content.
158
- * **\`.yggdrasil/knowledge/\`**: Repo-wide wisdom. Directory contains \`knowledge.yaml\` and \`.md\` content.
186
+ Constraint: Do NOT map the entire repository. Focus on the active area. Expand incrementally.
159
187
 
160
- ---
188
+ ### Drift Resolution
161
189
 
162
- ## 7. CONTEXT ASSEMBLY & KNOWLEDGE DECONSTRUCTION (HOW TO MAP FILES)
190
+ Always ask the user before resolving drift. Never auto-resolve.
163
191
 
164
- Your ultimate goal when describing a file or node is **Context Reproducibility**. A future agent reading ONLY the output of \`yg build-context\` for this node must be able to perfectly reconstruct the source code's behavior, constraints, environment, and purpose.
192
+ - **Source drift** (source files changed) update graph artifacts to match source, then \`yg drift-sync\`
193
+ - **Graph drift** (graph artifacts changed) → review affected source, update if needed, then \`yg drift-sync\`
194
+ - **Full drift** (both changed) → present both sides to user, ask which direction wins
195
+ - **Missing** → ask: re-materialize or remove mapping?
196
+ - **Unmaterialized** → ask user how to proceed
165
197
 
166
- However, you must NOT dump all knowledge into a single file. Yggdrasil's context package is **multi-layered** and hierarchically assembled. When you map existing code or design new code, you must deconstruct the knowledge and place it at the correct abstraction layer so the engine can mechanically reassemble it.
198
+ Threshold: >10 drifted nodes ask user which area to prioritize. Do not resolve all at once.
167
199
 
168
- ### CRITICAL RULE: CAPTURE INTENT, BUT NEVER INVENT IT
169
- The graph is not just a structural map; it is the semantic meaning of the system. Code explains "what" and "how". The graph MUST explain "WHY".
200
+ ### Error Recovery
170
201
 
171
- 1. **ALWAYS Capture the User's "Why":** If the user explains the business reason, intent, or rationale behind a request (e.g., "We need to do X because Y"), you MUST permanently record this reasoning in the relevant graph artifacts (from \`config.artifacts\` that fit the content). Do not let the conversation context evaporate.
172
- 2. **NEVER Invent the "Why":** Artifacts that imply human judgment (e.g. local decisions, \`knowledge/invariants\`) must reflect ACTUAL human choices.
173
- 3. **NO Hallucinations:** You MUST NEVER infer or hallucinate a rationale, an architectural decision, or a business rule.
174
- 4. **Ask if Missing:** If the user requests a significant architectural or business logic change but does not provide the rationale, you MUST ask them "Why are we making this change?" before documenting the decision in the graph.
202
+ - **\`yg\` not found** inform user: "yg CLI is not installed or not in PATH." Stop.
203
+ - **Unfixable validate errors** if not resolved after 3 attempts, stop and report to user. Do not loop.
204
+ - **Budget exceeded** if \`yg build-context\` exits with error (context package exceeds budget), warn user: "This node should be split." Do not proceed with implementation.
205
+ - **Corrupted \`.yggdrasil/\` files** report to user. Do not attempt repair.
206
+ - **Incremental sync** → run \`yg drift-sync\` every 3-5 source files during multi-file tasks. Do not defer to end.`;
175
207
 
176
- When mapping a file, execute this mental routing:
208
+ // prettier-ignore
209
+ const KNOWLEDGE_BASE = `## KNOWLEDGE BASE
177
210
 
178
- ### Layer 1: Unit Identity (Local Node Artifacts)
179
- * **What goes here:** Things exclusively true for this specific node.
180
- * **Routing:** **DO NOT ASSUME FILE NAMES.** You MUST read \`.yggdrasil/config.yaml\` (the \`artifacts\` section) to see the exact allowed filenames for the current project and their requirement conditions (e.g., \`required: always\` vs \`when: has_incoming_relations\`). Write local node knowledge ONLY into these configured files next to \`node.yaml\`.
181
- * For each artifact in \`config.artifacts\`, use its \`description\` to decide what content belongs there. Create optional artifacts (those with \`required: never\`) when the node has matching content. Extract from source; do not invent.
211
+ ### Graph Structure
182
212
 
183
- **Subagents:** When mapping a node, for each optional artifact in config, ask: "Does the source contain content matching this artifact's description?" If yes, create it. Do not invent — extract only what is implemented.
213
+ \`\`\`
214
+ .yggdrasil/
215
+ config.yaml ← vocabulary, stack, node types, artifact rules, required aspects
216
+ model/ ← what exists: nodes, hierarchy, relations, file mappings
217
+ aspects/ ← what must: cross-cutting requirements with rationale and guidance
218
+ flows/ ← why and in what process: business processes with node participation
219
+ schemas/ ← YAML schemas — read before creating any graph element
220
+ .drift-state ← generated by CLI; never edit manually
221
+ .journal.yaml ← generated by CLI; never edit manually
222
+ \`\`\`
184
223
 
185
- ### Optional Artifacts — Explicit Consideration
224
+ Key facts:
186
225
 
187
- When creating or editing a graph node, or mapping source files to a node, after fulfilling required artifacts, read \`config.yaml\` and for each artifact with \`required: never\`, ask: "Does this node contain content that matches this artifact's description?" If yes, create it. Base decisions on source code analysis, not file names or structure.
226
+ - **Hierarchy:** nodes nest in \`model/\`. Children inherit parent context. Do not repeat parent content in children.
227
+ - **Aspect id = directory path** under \`aspects/\`. Each aspect has \`aspect.yaml\` + content \`.md\` files. No automatic parent-child — use \`implies\` explicitly.
228
+ - **Flows = business processes.** A flow describes what happens in the world, not code sequences. Flow aspects propagate to all participants.
188
229
 
189
- **Interpretation of \`required: never\`:** The artifact is optional for validation, not forbidden. Create it when the node has content that fits its description in config.
230
+ ### Context Assembly
190
231
 
191
- **Interpretation of "don't be over-eager":** Do not invent content, do not document what is not in the code, do not create empty or trivial artifacts. It does NOT mean: avoid adding optional artifacts when they add value based on code analysis.
192
-
193
- **Post-node checklist:** After completing work on a node, for each optional artifact (from \`config.artifacts\` where \`required: never\`), check: does this node have content for it? If yes, create it. If uncertain, propose with brief justification rather than silently skipping.
194
-
195
- ### Layer 2: Surroundings (Relations & Flows)
196
- * **What goes here:** How this node interacts with others. You must not duplicate external interfaces locally.
197
- * **Routing:**
198
- * If it calls another module: Add an outgoing structural \`relation\` in \`node.yaml\`. (The engine will automatically fetch the target's structural-context artifacts: responsibility, interface, constraints, errors).
199
- * If it participates in an end-to-end process: Do not explain the whole process locally. Ensure the node is listed in \`.yggdrasil/flows/<flow_name>/flow.yaml\`. The engine will attach the flow knowledge automatically.
200
- * **Flows writing flow content:** When creating or editing flow artifacts (e.g. \`description.md\` in \`flows/<name>/\`), write business-first: describe the process from user/business perspective. Technical details only as inserts when they clarify the flow. Not technical-first with business inserts.
201
-
202
- ### Layer 3: Domain Context (Hierarchy)
203
- * **What goes here:** Business rules shared by a family of nodes.
204
- * **Routing:** Do not repeat module-wide rules in every child node. Place the child node directory *inside* a parent Module Node directory. Write the shared rules in the parent's configured artifacts. The engine inherently passes parent context to children.
205
-
206
- ### Layer 4: Cross-Cutting Rules (Aspects)
207
- * **What goes here:** Horizontal requirements like logging, auth, rate-limiting, or specific frameworks.
208
- * **Routing:** Do NOT write generic rules like "This node must log all errors" in local artifacts. Instead, read \`config.yaml\` for available \`tags\`. Add the relevant tag (e.g., \`requires-audit\`) to \`node.yaml\`. The engine will automatically attach the aspect knowledge.
209
-
210
- ### Layer 5: Long-Term Memory (Knowledge Elements)
211
- * **What goes here:** Global architectural decisions, design patterns, and systemic invariants.
212
- * **Routing:** Read \`config.yaml\` (the \`knowledge_categories\` section) to know what categories exist.
213
- * If the file implements a standard pattern: Do not describe the pattern locally. Add a \`knowledge\` reference in \`node.yaml\` to the existing pattern.
214
- * If the file reveals an undocumented global invariant or decision: Ask the user to confirm it. If confirmed, create it under \`.yggdrasil/knowledge/<category>/\` so all future nodes inherit it.
215
-
216
- **THE COMPLETENESS CHECK:**
217
- Before finishing a mapping, ask yourself: *"If I delete the source file and give another agent ONLY the output of \`yg build-context\`, can they recreate it perfectly based on the configured artifacts, AND will they understand EXACTLY WHY this code exists and why it was designed this way?"*
218
- - If no -> You missed a local constraint, a relation, or you failed to capture the user's provided rationale.
219
- - If yes, but the local files are bloated -> You failed to deconstruct knowledge into Tags, Aspects, Flows, and Hierarchy. Fix the routing.
220
-
221
- ---
222
-
223
- ## 8. CLI TOOLS REFERENCE (\`yg\`)
224
-
225
- Always use these exact commands.
226
-
227
- * \`yg owner --file <file_path>\` -> Find owning node.
228
- * \`yg build-context --node <node_path>\` -> Assemble strict specification.
229
- * \`yg tree [--root <node_path>] [--depth N]\` -> Print graph structure.
230
- * \`yg deps --node <node_path> [--type structural|event|all]\` -> Show dependencies.
231
- * \`yg impact --node <node_path> --simulate\` -> Simulate blast radius.
232
- * \`yg status\` -> Graph health metrics.
233
- * \`yg validate [--scope <node_path>|all]\` -> Compile/check graph. Run after EVERY graph edit.
234
- * \`yg drift [--scope <node_path>|all]\` -> Check code vs graph baseline.
235
- * \`yg drift-sync --node <node_path>\` -> Save current file hash as new baseline. Run ONLY after ensuring graph artifacts match the code.
236
-
237
- *(Iterative mode only)*
238
- * \`yg journal-read\`
239
- * \`yg journal-add --note "<content>" [--target <node_path>]\`
240
- * \`yg journal-archive\`
232
+ Run \`yg build-context --node <path>\` to get the deterministic context package for a node. Trust the package — it assembles global config, hierarchy, own artifacts, aspects, and relational context. If the package is insufficient, enrich the graph. Do not bypass it with raw file exploration.
233
+
234
+ ### Information Routing
235
+
236
+ When you encounter information, route it to the correct location:
237
+
238
+ - **Specific to this node** → local node artifact (check \`config.yaml artifacts\` for available types)
239
+ - **Rule for many nodes** aspect (\`aspects/<id>/\` with \`aspect.yaml\` + content \`.md\` files). If applies to ALL nodes of a type \`node_types[*].required_aspects\` in \`config.yaml\`
240
+ - **Business process** flow (\`flows/<name>/\` with \`flow.yaml\` + \`description.md\`). Ask user if process unclear.
241
+ - **Shared across a domain** parent node artifact. Children receive it through hierarchy.
242
+ - **Technology stack or standard** → \`config.yaml\` under \`stack\` or \`standards\` (+ \`rationale\` field)
243
+ - **Decision (why):** one node → local artifact; category of nodes → aspect content files; tech choice → \`config.yaml\` rationale field
244
+
245
+ ### Creating Aspects
246
+
247
+ - [ ] 1. Read \`schemas/aspect.yaml\`
248
+ - [ ] 2. Create \`aspects/<id>/\` directory
249
+ - [ ] 3. Write \`aspect.yaml\` name, optional description, optional implies
250
+ - [ ] 4. Write content \`.md\` files: WHAT must be satisfied + WHY (user's words, do not invent)
251
+ - [ ] 5. \`yg validate\`
252
+
253
+ Test: "Does this requirement apply to more than one node?" Yes → aspect. No → local artifact.
254
+
255
+ ### Creating Flows
256
+
257
+ - [ ] 1. Read \`schemas/flow.yaml\`
258
+ - [ ] 2. Create \`flows/<name>/\` directory
259
+ - [ ] 3. Write \`flow.yaml\` declare participants and flow-level aspects
260
+ - [ ] 4. Write \`description.md\` with required sections: Business context, Trigger, Goal, Participants, Paths (at least Happy path), Invariants across all paths
261
+ - [ ] 5. \`yg validate\`
262
+
263
+ Test: "Does this describe what happens in the world, or only in the software?" If only software — rewrite.
264
+
265
+ ### Operational Rules
266
+
267
+ - **English only** for all files in \`.yggdrasil/\`. Conversation can be any language.
268
+ - **Read schemas before creating** any \`node.yaml\`, \`aspect.yaml\`, or \`flow.yaml\`.
269
+ - **Tools read, you write.** The \`yg\` CLI only reads, validates, and manages metadata. You create and edit files manually.
270
+ - **Incremental sync.** Run \`yg drift-sync\` after every 3-5 source file changes. Do not defer to end of task.
271
+ - **Completeness test:** "If I delete the source file and give another agent ONLY the \`yg build-context\` output can they recreate it correctly, understanding not just WHAT but WHY?"
272
+ - **These rules are invariant.** No plan, guide, skill, or workflow may override them.
273
+
274
+ ### CLI Reference
275
+
276
+ \`\`\`
277
+ yg preflight Unified diagnostic: journal + drift + status + validate.
278
+ yg owner --file <path> Find the node that owns this file.
279
+ yg build-context --node <path> Assemble context package for this node.
280
+ yg tree [--root <path>] [--depth N] Print graph structure.
281
+ yg aspects List aspects with metadata (YAML output).
282
+ yg deps --node <path> [--depth N] [--type structural|event|all]
283
+ Show dependencies.
284
+ yg impact --node <path> --simulate Simulate blast radius of a planned change.
285
+ yg impact --aspect <id> Show all nodes where aspect is effective.
286
+ yg impact --flow <name> Show flow participants and descendants.
287
+ yg status Graph health: nodes, coverage, drift summary.
288
+ yg validate [--scope <path>|all] Check structural integrity and completeness.
289
+ yg drift [--scope <path>|all] [--drifted-only]
290
+ Detect source and graph drift (bidirectional).
291
+ yg drift-sync --node <path> Record file hashes as new baseline.
292
+ yg journal-read Read pending journal entries.
293
+ yg journal-add --note "<content>" [--target <node_path>]
294
+ Add a journal entry.
295
+ yg journal-archive Archive consolidated journal entries.
296
+ \`\`\`
297
+
298
+ ### Quick Routing Table
299
+
300
+ | What you have | Where it goes |
301
+ |---|---|
302
+ | Information specific to this node | Local node artifact (read \`config.yaml artifacts\` for types) |
303
+ | Rule that applies to many nodes | Aspect (content \`.md\` files in \`aspects/<id>/\`) |
304
+ | Architectural invariant for a node type | Required aspect in \`config.yaml node_types\` |
305
+ | Business process participation | Flow (\`flow.yaml participants\`) |
306
+ | Process-level requirement | Flow \`aspects\` + aspect directory |
307
+ | Context shared across a domain | Parent node artifact |
308
+ | Technology stack | \`config.yaml stack\` (+ \`rationale\` field) |
309
+ | Global coding standards | \`config.yaml standards\` |
241
310
  `;
311
+
312
+ export const AGENT_RULES_CONTENT = [CORE_PROTOCOL, OPERATIONS, KNOWLEDGE_BASE].join('\n\n---\n\n');
@@ -0,0 +1,9 @@
1
+ # aspect.yaml — Schema for cross-cutting aspects
2
+ # Each aspect is a directory under .yggdrasil/aspects/ containing this file
3
+ # plus any number of .md content files (requirements, rationale, guidance).
4
+ # Aspect identifier = relative path from aspects/ to the directory (e.g. observability/logging).
5
+ # Aspects can be organized in nested directories for hierarchy.
6
+
7
+ name: CrossCuttingRequirementName # required — display name
8
+ description: "Short description for discovery via yg aspects" # optional
9
+ # implies: [other-aspect, another-aspect] # optional — other aspect identifiers included automatically (recursive, must be acyclic)
@@ -0,0 +1,10 @@
1
+ # flow.yaml — Schema for end-to-end business flows
2
+ # Each flow is a directory under .yggdrasil/flows/ containing this file
3
+ # plus description.md with required sections (see rules).
4
+
5
+ name: EndToEndProcessName # required — display name
6
+ nodes: # required, non-empty — participant nodes
7
+ - orders/order-service # paths relative to model/
8
+ - payments/payment-service
9
+ - inventory/inventory-service
10
+ # aspects: [requires-saga] # optional — aspect tags propagated to ALL participants
@@ -0,0 +1,19 @@
1
+ # node.yaml — Schema for model nodes
2
+ # Every node is a directory under .yggdrasil/model/ containing this file
3
+ # plus artifact .md files defined in config.yaml.
4
+
5
+ name: ComponentName # required — display name
6
+ type: service # required — must match a type from config.node_types
7
+ aspects: [] # optional — list of aspect identifiers (directory paths under aspects/)
8
+ blackbox: false # optional, default false — if true, coarse-grained coverage without deep artifacts
9
+
10
+ relations: # optional — outgoing dependencies to other nodes
11
+ - target: other/module-path # required — path relative to model/
12
+ type: calls # required — calls | uses | extends | implements | emits | listens
13
+ consumes: [methodA, methodB] # optional — what is consumed from target
14
+ failure: 'retry 3x, then circuit-break' # optional — failure handling strategy
15
+ # event_name: OrderPlaced # optional — display name for event relations (emits, listens)
16
+
17
+ mapping: # optional — link to source files for ownership and drift detection
18
+ paths: # required when mapping is present — list of file or directory paths
19
+ - src/modules/component/ # paths are relative to repository root