@chrisdudek/yg 3.0.0 → 4.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.
@@ -1,695 +0,0 @@
1
- /**
2
- * Canonical agent rules content — hand-tuned, do not generate programmatically.
3
- *
4
- * Operating manual for agents working in a Yggdrasil-managed repository.
5
- * Split into three cognitive sections optimized for LLM attention patterns:
6
- * 1. PROTOCOL — the rule and the procedure (primacy zone — internalize)
7
- * 2. REFERENCE — lookup material (middle zone — consult when needed)
8
- * 3. GUARD RAILS — what goes wrong and how to catch it (recency zone — fresh in memory during work)
9
- */
10
-
11
- // prettier-ignore
12
- const PROTOCOL = `## PROTOCOL
13
-
14
- <EXTREMELY-IMPORTANT>
15
- This is your operating manual for working in a Yggdrasil-managed repository.
16
-
17
- <critical_protocol>
18
- BEFORE starting any task — brainstorming, design, planning, OR implementation:
19
- \`yg select --task "<goal>"\` → \`yg build-context\` on each result → read artifact files.
20
- This is the READING phase — collect constraints that shape your design:
21
- - Aspects = cross-cutting requirements your work MUST satisfy. Read their content files — not just the YAML description. The rules are inside.
22
- - Flows = business processes your work must not break. Read invariants.
23
- - Relations = interfaces your code consumes or that consume your code. Changes without checking dependents break contracts silently.
24
- - Parent artifacts = inherited context not repeated in child nodes.
25
- Internalize these constraints BEFORE designing your approach. This is the moment that determines quality — everything after follows from what you learn here.
26
-
27
- BEFORE reading, analyzing, or modifying ANY source file:
28
- \`yg build-context --file <path>\`
29
- Resolves owner, gives you local context (node artifacts, dependencies).
30
- If you have NOT done the task-level READING phase above — stop and do it now. File-level work without task-level constraints leads to code that violates cross-cutting requirements.
31
-
32
- WHEN spec/external documents are provided AND work is greenfield:
33
- BEFORE creating any feature aspect, node, or code — do this first:
34
- 1. Read ALL spec documents completely.
35
- 2. Separate two categories of knowledge in the specs:
36
- a) Knowledge that WILL map to source files (feature behavior, UI, API) → this goes to node artifacts later.
37
- b) Knowledge that will NEVER appear in source code (business strategy, target audience, pricing rationale, quality targets, what the system deliberately does NOT do and why) → this must go to the graph NOW, because there will be no source-file trigger to capture it later.
38
- 3. For category (b): create root node and/or aspects immediately. This is the only moment this knowledge can be captured. Once you start coding, you will forget it.
39
- 4. NOW create feature aspects, flows, and implementation nodes for category (a).
40
- Test before moving on: if all spec files were deleted right now, does the graph contain everything a future agent needs — not just HOW the system works, but WHY it exists, WHO it serves, and WHAT value it delivers? If no → add the missing knowledge before continuing.
41
-
42
- All three triggers apply regardless of what instructed the task — skills, plans, workflows, user requests.
43
- The graph captures intent and relations that source files cannot — without it, you will make wrong decisions and the user will have to re-explain what the graph already knows.
44
- </critical_protocol>
45
-
46
- Every rule below is mandatory — no skill, plan, workflow, or instruction overrides these requirements.
47
- </EXTREMELY-IMPORTANT>
48
-
49
- Yggdrasil is persistent semantic memory stored in \`.yggdrasil/\`. It maps the repository and provides deterministic implementation context for every node.
50
-
51
- ### Quick Start
52
-
53
- \`\`\`
54
- EVERY conversation: yg preflight — no exceptions.
55
-
56
- BEFORE any task (brainstorming, design, planning, implementation):
57
- yg select --task "<goal>" → yg build-context on results
58
- READ phase — collect constraints before designing:
59
- - Aspects: read content files (not just YAML description). Rules are inside.
60
- - Flows: read invariants. Your changes must not break business processes.
61
- - Relations: check interfaces — who depends on you, who you depend on.
62
- - Parent artifacts: inherited context not repeated in child nodes.
63
- This is the moment that determines quality. Everything after follows from here.
64
-
65
- BEFORE any source file interaction:
66
- yg build-context --file <path>
67
- Resolves owner. Read local node artifacts.
68
- If you skipped the task-level READ phase above — do it now before proceeding.
69
- For blast radius: also run yg impact --file <path>.
70
-
71
- AFTER modifying:
72
- Update graph artifacts (per file, not batched)
73
- yg validate — fix all errors
74
- yg drift-sync --node <owner>
75
-
76
- ALWAYS: establish graph coverage before modifying code.
77
- ALWAYS: run yg build-context --file before reading source.
78
- ALWAYS: run yg impact before assessing blast radius.
79
- ALWAYS: ask the user for rationale — record it, do not invent it.
80
- ALWAYS: ask before resolving drift or ambiguity.
81
- WHEN UNSURE: ask the user. Do not guess. Do not assume.
82
- \`\`\`
83
-
84
- ### Modify Source Code
85
-
86
- You are not allowed to edit or create source code without establishing graph coverage first.
87
-
88
- **Step 1** — Get context: \`yg build-context --file <path>\` (resolves owner automatically)
89
-
90
- **Step 2a** — Owner found: execute checklist:
91
-
92
- - [ ] 1. Read local node artifacts (responsibility, interface, internals) and dependency interfaces from the context package. Cross-cutting constraints (aspects, flows) should already be internalized from the task-level READ phase — if not, stop and do it now.
93
- - [ ] 2. Assess blast radius: \`yg impact --node <node_path>\` — review dependents, descendants, and co-aspect nodes before changing interfaces or shared behavior
94
- - [ ] 3. Modify source code. When implementing logic subject to an aspect (e.g., writing a save function on a node with the autosave aspect), re-read that aspect's content file NOW — don't rely on memory from the task-level READ phase. Aspect rules are specific (exact timings, error handling patterns, UI details) and fade from working memory. Read them at the moment you need them.
95
- - [ ] 4. Sync graph artifacts — edit artifact files to reflect the changes (after each file, not batched — context is freshest immediately after the change). If the node's purpose changed, update \`description\` in \`yg-node.yaml\`.
96
- - [ ] 4b. If you split, merged, or renamed a node: run \`yg flows\` and update any flow \`nodes\` lists that referenced the old node path to point to the correct child/new nodes.
97
- - [ ] 5. Run \`yg validate\` — fix all errors (if unfixable after 3 attempts → stop, report to user)
98
- - [ ] 6. Run \`yg drift-sync --node <node_path>\` — only after graph and code are both current
99
-
100
- **Step 2b** — Owner not found: establish coverage first. Present options to the user:
101
-
102
- *Partially mapped* (file unmapped but inside a mapped module): ask whether to add to existing node or create new one.
103
-
104
- *Existing code:*
105
-
106
- - Option A — Full node: create node(s), map files, write artifacts from code analysis
107
- - Option B — Blackbox: create a blackbox node at agreed granularity
108
- - Option C — Abort
109
-
110
- *Greenfield (new code):* Only Option A. Blackbox is forbidden for new code. Follow the graph-first workflow:
111
-
112
- 0. **If spec/external documents exist:** route ALL knowledge from specs to the graph per the Information Routing table BEFORE any feature work. Use the appropriate location for each piece of knowledge — root node, aspects, flows, or node artifacts depending on its nature.
113
- 1. Create aspects first (cross-cutting requirements the new code must satisfy)
114
- 2. Create flows if the code participates in a business process
115
- 3. Create nodes with full artifacts — description in \`yg-node.yaml\`, responsibility, interface, internals
116
- 4. Review the context package (\`yg build-context\`) — it is now the behavioral specification
117
- 5. Implement code that satisfies the specification. Every source file must be mapped — including shared utilities, types, and helpers.
118
- 6. After implementing each node, write \`internals.md\` with a ## Decisions section. Record every design choice: "Chose X over Y because Z." This is required in greenfield — not optional. Every node has design decisions (data model shape, algorithm, library, UI pattern). If you made a choice between alternatives, document it now — you will not remember later.
119
- 7. The graph specifies WHAT and WHY; the code implements HOW (framework APIs, library choices)
120
-
121
- **Node sizing rule:** One node per cohesive feature area, NOT per directory. If a node would map >10 source files or cover >3 distinct user workflows, split it into child nodes. Example: an admin panel should be \`admin/blog\`, \`admin/gallery\`, \`admin/clients\`, \`admin/orders\` — not one \`admin-pages\` node. The CLI enforces this with W017, but plan granularity upfront rather than splitting after the fact.
122
-
123
- After the user chooses, return to Step 1 and follow Step 2a.
124
-
125
- ### Working from External Specifications
126
-
127
- When the user provides external documents (specs, PRDs, design docs, reference docs) as input for implementation:
128
-
129
- 1. **Read ALL spec documents BEFORE writing any code.** Understand the full scope — business context, feature specs, quality requirements, UX rules, deployment config.
130
- 2. **Extract and route knowledge to the graph FIRST**, using the Information Routing table:
131
- - Business rules, personas, pricing strategy, acquisition channels → aspects or root node artifacts
132
- - Feature specifications (UI behavior, validation, workflows) → node responsibility/interface/internals artifacts
133
- - Cross-cutting UX/quality requirements → aspects
134
- - Business processes → flows
135
- 3. **The graph is the specification; external docs are INPUT to the graph, not a parallel source of truth.** After the graph is populated, external docs become redundant — the graph is what future agents will read.
136
- 4. **Spec knowledge is not code knowledge.** Specs contain business context (WHY the system exists, WHO it serves, WHAT it should do) that will never appear in source code. If you only document what you built, you lose what motivated building it.
137
- 5. **Completeness test:** "If the external docs disappeared today, does the graph contain everything a future agent needs to understand the system — not just HOW it works, but WHY it exists and WHAT business value it delivers?"
138
-
139
- **Common failure mode:** Agent reads spec → implements code → documents code in graph → spec knowledge (personas, pricing, UX rationale, quality targets) is lost because it was treated as "input I consumed" rather than "knowledge I must persist." The graph must absorb the spec, not just the code.
140
-
141
- ### Example: Correct vs Wrong
142
-
143
- <example_correct>
144
-
145
- User: "Fix the bug in payment.service.ts"
146
-
147
- 1. yg build-context --file src/payment.service.ts → payment/payment-service
148
- 2. Read YAML map — glossary, then artifact files
149
- 3. Read source file, understand bug in graph context
150
- 4. Fix bug
151
- 5. Update payment-service artifacts (responsibility.md, interface.md if API changed)
152
- 6. yg validate
153
- 7. yg drift-sync --node payment/payment-service
154
-
155
- </example_correct>
156
-
157
- <example_wrong>
158
-
159
- User: "Fix the bug in payment.service.ts"
160
-
161
- 1. Read src/payment.service.ts ← WRONG: no graph context loaded
162
- 2. Fix bug
163
- 3. "I'll update the graph later" ← WRONG: deferred = forgotten
164
-
165
- Result: graph is stale, next agent asks user the same questions
166
-
167
- </example_wrong>
168
-
169
- <example_correct>
170
-
171
- User: "Here are the spec docs. Implement the admin blog editor."
172
-
173
- 1. Read ALL spec docs (blog-editor.md, autosave.md, user-persona.md, version-history.md)
174
- 2. Route all knowledge from spec docs to the graph per Information Routing table — business context to root node artifacts, cross-cutting requirements to aspects, business processes to flows, feature specs to node artifacts
175
- 3. Extract cross-cutting patterns → create aspects (admin-ux-rules, autosave, version-history) if they don't exist
176
- 4. Create flow if the blog participates in a business process
177
- 5. Create node admin/blog with artifacts populated from spec (responsibility, interface, internals)
178
- 6. Run yg build-context → the context package is now the behavioral specification
179
- 7. Implement code that satisfies the specification
180
- 8. Update artifacts with any implementation details that emerged during coding
181
- 9. yg validate, yg drift-sync
182
- Test: if spec files disappeared today, does the graph contain everything a future agent needs to understand the system?
183
-
184
- </example_correct>
185
-
186
- <example_wrong>
187
-
188
- User: "Here are the spec docs. Implement the admin blog editor."
189
-
190
- 1. Read spec docs
191
- 2. Create aspects and flow for the blog feature ← INCOMPLETE: knowledge from spec docs not routed to graph per Information Routing table
192
- 3. Create node admin/blog, implement code
193
- 4. Write responsibility.md summarizing what the code does ← WRONG: describes code, not spec intent
194
- 5. Knowledge from spec docs lost ← WRONG: spec treated as consumed input, not persisted to graph
195
-
196
- Result: graph mirrors code structure but misses everything spec docs contained that has no corresponding source file. Future agent must re-read spec files or ask the user.
197
-
198
- </example_wrong>
199
-
200
- <example_correct>
201
-
202
- User: "Let's design a soft delete feature for blog posts"
203
-
204
- 1. yg select --task "blog soft delete" → find relevant nodes
205
- 2. yg build-context on each result → read ALL artifacts (aspects, flows, conventions)
206
- 3. Now read source files WITH graph context
207
- 4. Propose design informed by admin-ux-rules, existing flows, database conventions
208
-
209
- </example_correct>
210
-
211
- <example_wrong>
212
-
213
- User: "Let's design a soft delete feature for blog posts"
214
-
215
- 1. Read BlogEditor.tsx to understand current behavior ← WRONG: no graph context
216
- 2. Read database schema ← WRONG: graph has conventions, aspects, flows
217
- 3. Propose design based on raw code ← WRONG: missed admin-ux-rules aspect, existing flows
218
-
219
- Result: design misses cross-cutting requirements the graph already captured.
220
-
221
- </example_wrong>
222
-
223
- ### Conversation Lifecycle
224
-
225
- \`\`\`
226
- PREFLIGHT (every conversation, before any work):
227
- - [ ] 1. yg preflight → read unified report
228
- - [ ] 2. If drift: resolve per Drift Resolution, then yg drift-sync per node
229
- - [ ] 3. If validation errors: fix, re-run yg validate
230
- No exceptions. You cannot know if a file is mapped without running yg.
231
-
232
- UNDERSTANDING any source file (questions, research, OR planning):
233
- - [ ] 1. yg build-context --file <path>
234
- Mapped → read the YAML map (glossary first, then artifact files).
235
- Unmapped → use file analysis, state it is not graph-backed.
236
- Never use grep or raw file reads as primary understanding when graph coverage exists.
237
- Raw reads supplement the context package — they do not replace it.
238
-
239
- BEFORE reasoning about source code, state which graph context you loaded:
240
- "graph: <node_path>" if mapped, "graph: unmapped" if not.
241
- This is a required output step, not optional reflection.
242
-
243
- WRAP-UP (user signals "done", "wrap up", "that's enough"):
244
- - [ ] 1. yg drift --drifted-only → resolve
245
- - [ ] 2. yg validate → fix errors
246
- - [ ] 3. Report: which nodes and files were changed
247
-
248
- \`\`\`
249
-
250
- ### Modify Graph
251
-
252
- - [ ] 1. Read the relevant schema from \`schemas/\` before touching any YAML
253
- - [ ] 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
254
- - [ ] 3. Make changes
255
- - [ ] 4. Run \`yg validate\` immediately — fix all errors
256
- - [ ] 5. Verify affected source files are consistent — update if needed
257
- - [ ] 6. Run \`yg drift-sync\` for affected nodes
258
-
259
- ### Delegating to Subagents
260
-
261
- When you delegate work to a subagent (any subprocess, tool agent, or spawned assistant), the subagent does NOT inherit your Yggdrasil knowledge. Before any other instruction, the subagent MUST:
262
-
263
- 1. Read \`.yggdrasil/agent-rules.md\` — this is the complete operating manual
264
- 2. Follow the Quick Start Protocol from that file before touching any mapped code
265
-
266
- Include this as the FIRST instruction in every subagent prompt:
267
-
268
- \`\`\`
269
- BEFORE doing anything else: read .yggdrasil/agent-rules.md and follow its protocol.
270
- DELIVERABLES — all required, incomplete work will be rejected:
271
- 1. Working source code
272
- 2. Graph nodes with artifacts for every new/modified source file
273
- 3. \`yg validate\` passing
274
- \`\`\`
275
-
276
- A subagent that delivers code without corresponding graph updates has not completed its task. Before accepting subagent output, verify: are there new or modified source files without corresponding graph coverage? If yes, the work is incomplete.`;
277
-
278
- // prettier-ignore
279
- const REFERENCE = `## REFERENCE
280
-
281
- ### Graph Structure
282
-
283
- \`\`\`
284
- .yggdrasil/
285
- yg-config.yaml ← version, vocabulary, node types, required aspects
286
- model/ ← what exists: nodes, hierarchy, relations, file mappings
287
- aspects/ ← what must: cross-cutting requirements with rationale and guidance
288
- flows/ ← why and in what process: business processes with node participation
289
- schemas/ ← YAML schemas — read before creating any graph element
290
- .drift-state/ ← generated by CLI; never edit manually
291
- \`\`\`
292
-
293
- Key facts:
294
-
295
- - **Hierarchy:** nodes nest in \`model/\`. Children inherit parent context. Do not repeat parent content in children.
296
- - **Aspect id = directory path** under \`aspects/\`. Each aspect has \`yg-aspect.yaml\` + content \`.md\` files. No automatic parent-child — use \`implies\` explicitly.
297
- - **Flows = business processes.** A flow describes what happens in the world, not code sequences. Flow aspects propagate to all participants.
298
-
299
- **Node type guidance:** Each type in \`yg-config.yaml node_types\` has a \`description\` that tells you when to use it. Check the project's config for the full list and descriptions. Common types: \`module\` (business logic), \`service\` (providing functionality), \`library\` (shared utilities), \`infrastructure\` (guards, middleware, interceptors — invisible in call graphs but affect blast radius).
300
-
301
- ### Artifact Structure
302
-
303
- Three artifacts capture node knowledge at three levels:
304
-
305
- - **responsibility.md** (always required) — WHAT: identity, boundaries, what the node is NOT responsible for.
306
- - **interface.md** (required when node has consumers) — HOW TO USE: public methods, parameters, return types, contracts, failure modes, exposed data structures. Everything another node needs to interact with this one.
307
- - **internals.md** (optional, highest value for cross-module nodes) — HOW IT WORKS + WHY: algorithms, control flow, business rules, invariants, state machines, lifecycle, and design decisions with rejected alternatives. Use sections within the file: ## Logic, ## Constraints, ## State, ## Decisions (with "Chose X over Y because Z" format).
308
-
309
- **Enrichment priority (when adding incrementally):** \`interface.md\` first (highest cross-module ROI — contracts enable other nodes to reason about interactions), then \`responsibility.md\` (identity and boundaries), then \`internals.md\` (depth for complex nodes). A node with only \`interface.md\` provides more cross-module value than one with only \`internals.md\`.
310
-
311
- These three artifacts are built into the CLI and are not configurable. \`responsibility.md\` is always required, \`interface.md\` is required when the node has incoming relations, and \`internals.md\` is always optional.
312
-
313
- ### Context Assembly
314
-
315
- **Reading context:** \`yg build-context --node <path>\` returns a YAML map structured as follows:
316
-
317
- - **\`glossary\`** (top) — definitions for every aspect and flow referenced in the map, each with \`files\` listing their artifact paths. Read this first to understand IDs used throughout.
318
- - **\`node\`** — the target node with inline \`files\` (its artifact paths). No \`yg-node.yaml\` in file lists.
319
- - **\`hierarchy\`** — ancestor and sibling nodes, each with inline \`files\`.
320
- - **\`dependencies\`** — dependency nodes, each with inline \`files\`.
321
- - **\`meta\`** (bottom) — context assembly metadata.
322
- - YAML comments before each section guide reading order.
323
-
324
- All artifact paths are relative to \`.yggdrasil/\` — construct full path as \`.yggdrasil/<path>\`.
325
-
326
- **Default mode (paths-only):** Use for all graph operations. Read the YAML map, then read artifact files with purpose:
327
-
328
- 1. **Glossary first** — defines aspects and flows. Aspects are constraints your implementation must satisfy (not background reading). Flows are business processes whose invariants you must not break.
329
- 2. **Node section** — your target's own artifacts. Read before modifying.
330
- 3. **Hierarchy** — parent artifacts contain inherited requirements not repeated in child nodes.
331
- 4. **Dependencies** — interfaces you consume or that consume you. Read before changing contracts.
332
-
333
- A typical context package is ~8K tokens (less than a single source file). Read ALL artifact files listed — the cost is low, the risk of skipping is high (violating constraints you didn't know about).
334
-
335
- **Full mode (\`--full\`):** Use only when you cannot read files individually — e.g., when pasting context into a prompt, sharing with a user, or when you have no Read tool available.
336
-
337
- Artifact paths are stable identifiers within a session. When building context for multiple nodes, skip reading files you have already read — same path means same content.
338
-
339
- ### Information Routing
340
-
341
- When you encounter information, route it to the correct location:
342
-
343
- - **Specific to this node** → local node artifact (\`responsibility.md\`, \`interface.md\`, or \`internals.md\` depending on the knowledge type)
344
- - **Rule for many nodes** → aspect (\`aspects/<id>/\` with \`yg-aspect.yaml\` + content \`.md\` files). If applies to ALL nodes of a type → \`node_types.<type>.required_aspects\` in \`yg-config.yaml\`
345
- - **Business process** → flow (\`flows/<name>/\` with \`yg-flow.yaml\` + \`description.md\`). Ask user if process unclear.
346
- - **Shared across a domain** → parent node artifact. Children receive it through hierarchy.
347
- - **Technology stack or standard** → node artifact at the appropriate hierarchy level (e.g., root node's \`responsibility.md\` for single-stack repos, or deployment unit node for monorepos)
348
- - **Decision (why + why NOT):** one node → Decisions section of \`internals.md\` with format "Chose X over Y because Z"; category of nodes → aspect content files; tech choice → node artifact at the level where the technology applies. Always include rejected alternatives — they are the highest-value graph content. If the rationale is unknown: record the decision with "rationale: unknown" and note what CAN be observed from the code. Never invent a plausible-sounding rationale.
349
- - **Business strategy** (personas, pricing, acquisition channels, brand positioning) → root node artifact or dedicated business-context aspect. This knowledge has NO source file — it exists only in specs and conversations.
350
- - **Quality targets** (performance budgets, accessibility level, Lighthouse scores, test coverage goals) → aspect per quality dimension (e.g., \`performance-targets\`, \`accessibility\`). These are measurable cross-cutting constraints.
351
- - **UX patterns** (autosave, version history, empty states, confirmation modals) → aspect when the pattern applies to 3+ screens. UX patterns are cross-cutting even if they aren't architectural.
352
- - **Infrastructure/deployment** (domains, DNS, env vars, CI/CD, cron scheduling, hosting config) → infrastructure node or root node artifacts. Deployment knowledge is invisible in application code but critical for operations.
353
-
354
- ### Creating Aspects
355
-
356
- - [ ] 1. Read \`schemas/yg-aspect.yaml\`
357
- - [ ] 2. Create \`aspects/<id>/\` directory
358
- - [ ] 3. Write \`yg-aspect.yaml\` — name, optional description, optional implies
359
- - [ ] 4. Write content \`.md\` files: WHAT must be satisfied + WHY (user's words, do not invent)
360
- - [ ] 5. \`yg validate\`
361
-
362
- Test: "Does this requirement apply to more than one node?" Yes → aspect. No → local artifact.
363
-
364
- **Aspect identification heuristic:** If the same pattern, constraint, or rule appears in 3+ places, it is a candidate aspect. Aspects fall into natural categories:
365
-
366
- - **Domain-specific:** Business rules that cross module boundaries (e.g., timezone handling, booking periods, currency rounding)
367
- - **Architectural:** Structural patterns with rationale (e.g., dual-rollback on provider failure, idempotency via key generation, fire-and-forget dispatch)
368
- - **Concurrency:** Shared concurrency strategies (e.g., pessimistic locking, retry-on-deadlock, optimistic versioning)
369
-
370
- When a node follows an aspect's pattern with exceptions, record them in the \`exceptions\` field of the aspect entry in \`yg-node.yaml\`. Example: aspect says "fire-and-forget" but this node awaits the publish call — add \`exceptions: ["awaits publish call instead of fire-and-forget because..."]\`. Exceptions appear in the context package next to the aspect content, preventing abstractions from masking implementation details.
371
-
372
- **Aspect lifecycle warning.** Aspects decay CATASTROPHICALLY — a pattern either exists or it doesn't. When a pattern changes, ALL aspect claims become wrong at once. This differs from other artifacts: \`interface.md\` and \`responsibility.md\` are most stable (~9-year half-life); \`internals.md\` has moderate stability (~2.5-year half-life); aspects are least stable (~2.4-year half-life, binary decay). After any significant feature addition, review ALL aspects touching the affected area. Don't wait for drift — aspects can be 100% wrong without any mapped file changing.
373
-
374
- **Aspect stability tiers.** If an aspect has a \`stability\` field in \`yg-aspect.yaml\`, use it to calibrate review urgency:
375
-
376
- - \`schema\` — enforced by data model; review only when data model changes (most stable)
377
- - \`protocol\` — contractual pattern; review when contracts or interfaces change
378
- - \`implementation\` — specific mechanism; review after ANY significant code change (least stable)
379
-
380
- When code anchors (\`anchors\` in an aspect entry in \`yg-node.yaml\`) are present, they list code patterns (function names, constants, SQL fragments) evidencing the aspect's implementation in this node. \`yg validate\` checks that each anchor exists in the node's mapped source files — a missing anchor (W014) signals the aspect may be stale for this node.
381
-
382
- ### Creating Flows
383
-
384
- - [ ] 1. Read \`schemas/yg-flow.yaml\`
385
- - [ ] 2. Create \`flows/<name>/\` directory
386
- - [ ] 3. Write \`yg-flow.yaml\` — name, description, nodes (participant list), and flow-level aspects
387
- - [ ] 4. Write \`description.md\` with required sections: Business context, Trigger, Goal, Participants, Paths (at least Happy path), Invariants across all paths
388
- - [ ] 5. \`yg validate\`
389
-
390
- Test: "Does this describe what happens in the world, or only in the software?" If only software — rewrite.
391
-
392
- **Warning:** Flow descriptions must describe business processes, not code sequences. "The OrderService calls PaymentGateway.charge()" is WRONG. "The system charges the customer's payment method" is CORRECT.
393
-
394
- **Flow identification heuristic:** If a spec, conversation, or code reveals a sequence of steps toward a business goal — it IS a flow, and you MUST create one. This applies to multi-actor processes (user submits form → system notifies → admin responds) AND single-actor workflows (admin creates post → edits → publishes → system revalidates). A user performing actions on the system toward a goal is a business process, not "just CRUD." This applies equally when working from specs and when working from code. Examples: "user submits contact form → system sends notification → user receives response" (ContactInquiry), "user creates gallery → sends link → recipient views photos → user sees stats" (GalleryDelivery), "user writes blog post → publishes → system revalidates → readers see content" (BlogPublishing). Test: "Does this describe a goal-directed sequence of steps that a future agent needs to understand as a whole?" Yes → create the flow before or during implementation, never after.
395
-
396
- **Flow verification from specs:** When working from external specifications, for EACH business process described in the specs, verify a corresponding flow exists. If it doesn't, create one. Specs are the primary source of flow discovery — they describe what happens in the world, which is exactly what flows capture. Do not wait until implementation is complete to create flows.
397
-
398
- **Flow participant maintenance:** When splitting a node that participates in a flow (e.g., splitting \`admin-pages\` into \`admin-pages/blog\`, \`admin-pages/gallery\`, etc.), update the flow's \`nodes\` list to reference the specific child nodes that actually participate, not the parent. A flow participant must be the most specific node that performs the action. After any node restructuring (split, merge, rename), run \`yg flows\` and verify all participant references are still valid.
399
-
400
- ### Operational Rules
401
-
402
- - **English only** for all files in \`.yggdrasil/\`. Conversation can be any language.
403
- - **Read schemas before creating** any \`yg-node.yaml\`, \`yg-aspect.yaml\`, or \`yg-flow.yaml\`.
404
- - **Tools read, you write.** The \`yg\` CLI only reads, validates, and manages metadata. You create and edit files manually.
405
- - **Incremental sync.** Run \`yg drift-sync\` after every 3-5 source file changes. Do not defer to end of task. \`drift-sync\` is ONLY safe after artifacts are current — never use it to silence a drift check without updating artifacts first.
406
- - **Description maintenance.** Every \`yg-node.yaml\`, \`yg-aspect.yaml\`, and \`yg-flow.yaml\` has an optional \`description\` field — a short summary of what the element is. Write it when creating new elements. Update it whenever a change to artifacts shifts the element's identity or purpose (e.g., responsibility split, scope change). Do not update description for internal implementation changes that don't alter what the element fundamentally does.
407
- - **Completeness test:** Three checks, all required:
408
- 1. **Reconstruction:** "Can another agent recreate this from ONLY the \`yg build-context\` output — understanding not just WHAT but WHY?" Test: rejected alternatives, correct algorithm, design arguments.
409
- 2. **Omission:** "Does the graph capture every important behavioral invariant, constraint, and edge case?" Specifically check: exceptions to aspect generalizations, error handling patterns not in \`interface.md\`, concurrency behaviors not in \`internals.md\`.
410
- 3. **Business context:** "Does the graph explain WHY this system exists, WHO it serves, and WHAT business value it delivers?" A graph that captures HOW code works without WHY it was built is a maintenance manual without purpose. Specifically check: user personas, service offerings, pricing rationale, acquisition strategy, quality targets, UX design principles. Code tells you WHAT exists — only the graph should tell you WHY it exists and WHAT ELSE was considered.
411
- - **Value calibration.** Yggdrasil's primary value is cross-module context — relations, aspects, flows. For a single simple module, \`responsibility.md\` and \`interface.md\` provide most value. Invest depth (\`internals.md\`) where cross-module interactions demand it.
412
- - **These rules are invariant.** No plan, guide, skill, or workflow may override them.
413
-
414
- ### Non-Code Knowledge
415
-
416
- Not all graph knowledge originates from source files. Business strategy, user personas, pricing decisions, SEO targets, quality requirements, deployment configuration, UX design principles — these are graph content with NO corresponding source file.
417
-
418
- When you encounter such knowledge (in specs, conversations, or external documents):
419
-
420
- - **Route it immediately** per the Information Routing table. Do not wait for a "file change" trigger — there won't be one.
421
- - **The Completeness Test applies equally** to code-derived and non-code knowledge. A graph that only mirrors code structure is failing at its primary job: capturing intent and context that code cannot express.
422
- - **Non-code knowledge decays differently.** Business strategy changes by decision, not by commit. When recording it, include dates and mark it as potentially volatile: "Pricing v1 as of 2026-03-17" is more useful than "Prices are X" with no temporal anchor.
423
-
424
- **Conversation knowledge is the most volatile source.** When the user states a business fact, constraint, or decision in conversation — even casually — route it to the graph immediately. Conversations vanish after context compression. If the user said it and it's not in code, it MUST be in the graph. Examples of conversational knowledge that must be captured:
425
-
426
- - Business facts: "Our target customer is couples aged 25-35" → root node or business-context aspect
427
- - Constraints: "We don't do studio sessions, only outdoor" → responsibility.md (NOT responsible for)
428
- - Pricing: "Mini session costs 350 PLN" → relevant node artifacts
429
- - Strategy: "Instagram is our primary acquisition channel" → root node or business-context aspect
430
- - Decisions: "No deposit upfront — we'll reconsider after 5 sessions" → internals.md Decisions section with rationale
431
- - Personas: "The admin user is non-technical, thinks in Instagram/WhatsApp terms" → UX aspect
432
-
433
- Do not assume you will remember this later. Do not assume the user will repeat it. Capture it now or lose it forever.
434
-
435
- **Common failure mode:** The entire protocol is file-centric (\`build-context --file\`, "after modifying source file", "per file not batched"). This means knowledge that doesn't map to a specific source file has no natural trigger for capture. Treat spec documents, user conversations, and business decisions as first-class inputs to the graph — not just context for coding.
436
-
437
- ### Aspect Discovery During Implementation
438
-
439
- Aspects emerge from patterns across features. During greenfield implementation of multiple features:
440
-
441
- - **After implementing 3+ features in the same area, pause and review:** Are there repeated patterns (autosave, version history, confirmation modals, empty states)? Are there shared UX rules from a persona doc? Are there quality requirements from specs? Extract them to aspects NOW.
442
- - **Do NOT wait until all features are done.** Aspect extraction after 3 features captures the pattern while context is fresh. After 30 features, the rationale is forgotten and the aspect becomes a mechanical extraction without WHY.
443
- - **Watch for "invisible" aspects:** UX patterns (autosave everywhere), quality constraints (WCAG level, Lighthouse targets), and business rules (Polish locale, price-in-grosz) are cross-cutting but don't feel "architectural." They are still aspects.
444
- - **Trigger:** If you notice yourself implementing the same pattern for the third time, stop coding and create the aspect first. Then continue with the aspect applied to the current and previous nodes.
445
-
446
- ### CLI Reference
447
-
448
- \`\`\`
449
- yg preflight [--quick] Unified diagnostic: drift + status + validate.
450
- yg owner --file <path> Find the node that owns this file (quick check).
451
- yg build-context --file <path> Resolve owner + assemble context in one step.
452
- yg build-context --node <path> Assemble context map for a known node.
453
- yg build-context --node <path> --full Same map + file contents appended below separator.
454
- yg build-context --file <path> --self Own artifacts only (no hierarchy/deps/aspects/flows).
455
- yg tree [--root <path>] [--depth N] Print graph structure.
456
- yg aspects List aspects with metadata (YAML output).
457
- yg flows List flows with metadata (YAML output).
458
- yg select --task <description> [--limit <n>]
459
- Find graph nodes relevant to a task description.
460
- yg deps --node <path> [--depth N] [--type structural|event|all]
461
- Show dependencies.
462
- yg impact --file <path> Resolve owner + show blast radius in one step.
463
- yg impact --node <path> --simulate Simulate blast radius (works with --file too).
464
- yg impact --node <path> --method <name> Filter to dependents consuming a method (works with --file too).
465
- yg impact --aspect <id> Show all nodes where aspect is effective.
466
- yg impact --flow <name> Show flow participants and descendants.
467
- yg status Graph health: nodes, coverage, drift summary.
468
- yg validate [--scope <path>|all] Check structural integrity and completeness.
469
- yg drift [--scope <path>|all] [--drifted-only] [--limit <n>]
470
- Detect source and graph drift (bidirectional).
471
- yg drift-sync --node <path> [--recursive] | --all
472
- Record file hashes as new baseline.
473
- \`\`\`
474
-
475
- ### Quick Routing Table
476
-
477
- | What you have | Where it goes |
478
- |---|---|
479
- | Information specific to this node | Local node artifact (\`responsibility.md\`, \`interface.md\`, or \`internals.md\`) |
480
- | Rule that applies to many nodes | Aspect (content \`.md\` files in \`aspects/<id>/\`) |
481
- | Architectural invariant for a node type | Required aspect in \`yg-config.yaml node_types\` |
482
- | Business process participation | Flow (\`yg-flow.yaml nodes\`) |
483
- | Process-level requirement | Flow \`aspects\` + aspect directory |
484
- | Context shared across a domain | Parent node artifact |
485
- | Technology stack | Node artifact at appropriate hierarchy level |
486
- | Coding standards | Node artifact at appropriate hierarchy level |
487
- | Business strategy (personas, pricing, channels) | Root node artifact or dedicated business-context aspect |
488
- | Quality targets (perf budgets, a11y, test goals) | Aspect per quality dimension |
489
- | UX patterns (autosave, version history, empty states) | Aspect when pattern applies to 3+ screens |
490
- | Infrastructure/deployment (domains, env vars, CI/CD) | Infrastructure node or root node artifacts |
491
- | External service config (Stripe fees, email limits) | Relevant node's \`internals.md\` Decisions section |
492
- | Feature spec from external doc | Node artifacts — translate spec into responsibility/interface/internals |`;
493
-
494
- // prettier-ignore
495
- const GUARD_RAILS = `## GUARD RAILS
496
-
497
- ### Five Core Rules
498
-
499
- 1. **Graph first.** Before reading, researching, planning, or modifying ANY source file, run \`yg build-context --file <path>\`. For blast radius, also run \`yg impact\`. The graph is your primary source of architectural understanding. For implementation-level precision (exact behavior, error paths, edge cases) — verify against source code after loading the context package.
500
- 2. **The graph is the specification; code implements it.** The graph absorbs knowledge from every source — external docs, conversations, decisions — and must be self-sufficient. If all other sources disappeared, the graph alone must contain enough to understand the system. Do not leave knowledge in external documents and reference them — capture the knowledge in graph artifacts. Update graph artifacts immediately after each file change, while context is fresh — do not batch graph updates to the end of a task. Code and graph move together: code changed → graph updated before moving to the next file. Graph changed → source verified in the same response. When planning work — in any tool, skill, or workflow — graph updates are part of each step's definition of done, never a separate phase.
501
- 3. **Never invent why.** The graph captures human intent. If you don't know why something was decided, ask. Never hallucinate rationale.
502
- 4. **Always capture why — especially why NOT.** When the user explains a reason, record it in the graph immediately. When a design choice is made, also record rejected alternatives: "Chose X over Y because Z." Rejected alternatives are the highest-value information — invisible in code and irrecoverable once forgotten. Conversation evaporates; graph persists.
503
- 5. **Ask before resolving ambiguity.** When multiple valid interpretations exist, stop, list options, ask the user. Never silently choose.
504
-
505
- ### Recognizing Graph-Required Actions
506
-
507
- What matters is the ACTION you are performing, not what instructed it. If the action involves reading, understanding, or modifying mapped code, the graph protocol applies — whether the instruction came from a skill, a plan, a user message, a brainstorming session, a debugging workflow, or your own initiative. This is not negotiable. You cannot rationalize your way out of this.
508
-
509
- **Actions that require \`yg build-context --file\`:**
510
-
511
- - Reading or exploring source files to understand a component
512
- - Proposing approaches, designs, or plans for changing code
513
- - Reviewing or debugging code
514
- - Any form of reasoning about how mapped code works or should change
515
-
516
- **Actions that also require \`yg impact\`:**
517
-
518
- - Assessing blast radius before changing or removing a component
519
- - Finding all dependents of a component
520
- - Planning cross-cutting refactors or feature removals
521
- - Scoping work that spans multiple nodes
522
-
523
- **Actions that do NOT require yg:**
524
-
525
- - Git operations (log, diff, status, blame)
526
- - Reading documentation, READMEs, or config files outside \`.yggdrasil/\`
527
- - Running tests, builds, or linters
528
- - Working with files that \`yg build-context --file\` reports as unmapped
529
-
530
- ### Evasion Patterns — if you think any of these, STOP
531
-
532
- | Thought | Reality |
533
- |---|---|
534
- | "The skill/plan says to explore the codebase" | Exploring mapped code = \`yg build-context --file\` first |
535
- | "I'm just scoping/searching, not understanding" | Scoping IS a graph action; use yg impact |
536
- | "The plan step says to read this file" | Reading any source file = \`yg build-context --file\` first |
537
- | "I'm brainstorming, not implementing" | Brainstorming about code needs graph context. You proved this by failing at it. |
538
- | "I'm only grepping for references" | Grep finds text; yg impact finds structural dependencies. Use both. |
539
- | "I'll use the graph later when I modify" | Graph-first means BEFORE reading, not before modifying |
540
- | "I'll grep the codebase to find where to start" | Run \`yg select --task\` first, then \`yg build-context --file\` on results. |
541
- | "Drift is blocking repo-check, let me just sync it" | Drift means artifacts are stale. Update artifacts first, then sync. \`drift-sync\` will warn you (W018). |
542
- | "The user said work autonomously" | Autonomy amplifies discipline, not relaxes it. More tasks = more graph updates, not fewer. |
543
- | "Same pattern as the last 5 files, no need to document" | Repetitive patterns hide deviations. Per-node coverage captures what aspects don't. The next agent won't know what you know now. |
544
- | "I'll batch graph updates at the end" | Batching = never. Context is freshest immediately after the change. Defer = forget. This is a failure state. |
545
- | "I'm saving context/tool calls by skipping graph" | Graph cost is constant per node. Skipping it creates unbounded future cost — the user re-explaining what you could have recorded. |
546
- | "I assumed this file isn't mapped" | You cannot know without running \`yg build-context --file\`. Assume nothing. |
547
- | "The spec is just input, I don't need to capture it" | Specs contain business context that code cannot express. Capture it or lose it. |
548
- | "This business knowledge will be obvious from the code" | Pricing strategy, personas, UX rationale, and quality targets are NEVER obvious from code. |
549
- | "I'll extract aspects after I finish all the features" | After 30 features the rationale is gone. Extract after 3. |
550
- | "This is a UX detail, not architecture" | UX patterns that apply to 3+ screens ARE cross-cutting requirements. Create an aspect. |
551
- | "The user just mentioned it casually, it's not a formal decision" | Casual statements ARE decisions. "We don't do studio" is a business constraint. Capture it now or lose it after context compression. |
552
- | "I'll remember this from the conversation" | No you won't. Context gets compressed. The user won't repeat it. Write it to the graph now. |
553
- | "Flows can wait until I understand the full system" | Flows capture business processes from specs. Create them BEFORE implementing — they are part of the specification, not an afterthought. |
554
- | "I split the node but the flow still works" | Flow participants reference specific node paths. After a split, old paths are stale. Run \`yg flows\` and update. |
555
- | "This is just CRUD, not a business process" | A user performing a sequence of steps toward a goal IS a business process — even single-actor workflows (publish blog, manage portfolio, fulfill order). Create a flow. |
556
- | "The context package is too large to read" | A typical context package is ~8K tokens — less than one source file. Read ALL of it. |
557
- | "I have a plan, I don't need graph context" | A plan is not a substitute for graph context. Plans capture task steps; the graph captures cross-cutting aspects, flows, and conventions that plans may not repeat. Always run \`build-context\`. |
558
- | "The user told me what to do, that's my plan" | A verbal instruction is not a written plan. And even a written plan does not exempt you from the graph protocol. |
559
-
560
- ### Failure States
561
-
562
- You have broken Yggdrasil if you do any of the following:
563
-
564
- - ❌ Started brainstorming, design, or planning without running \`yg select --task\` and reading graph context first. The graph contains aspects, flows, and conventions that MUST inform design decisions.
565
- - ❌ Worked on a source file without running \`yg build-context --file\` first — regardless of what instructed the action (skill, plan, user request, workflow step).
566
- - ❌ Modified source code without updating graph artifacts before moving to the next file, or vice versa.
567
- - ❌ Batched graph updates to "do later" — deferred = forgotten. Update after EACH file.
568
- - ❌ Resolved a code-graph inconsistency or ambiguity without asking the user first.
569
- - ❌ Created or edited a graph element without reading its schema in \`schemas/\` first.
570
- - ❌ Ran \`yg drift-sync\` before both graph artifacts and source code are current. (CLI will warn you: W018.)
571
- - ❌ Placed a cross-cutting requirement in a local artifact instead of an aspect, or used an aspect id with no \`aspects/\` directory.
572
- - ❌ Invented a rationale, business rule, or decision — or recorded a decision without documenting rejected alternatives and rationale (use "rationale: unknown" if unknown).
573
- - ❌ Used blackbox coverage for greenfield (new) code.
574
- - ❌ Deleted or shortened graph artifact content to reduce context package size instead of splitting the node.
575
- - ❌ Created one wide node for many files instead of granular nodes with focused responsibilities. (CLI will warn you: W017.)
576
- - ❌ Implemented features from a spec without first transferring spec knowledge (business context, UX rules, quality targets) into the graph. Code without captured intent is a maintenance trap.
577
- - ❌ Implemented 3+ features sharing a pattern (autosave, version history, empty states) without extracting it to an aspect. Deferred aspect discovery = lost rationale.
578
- - ❌ Left business strategy, personas, or quality targets only in external documents instead of routing them to graph artifacts. External docs are input; the graph is the persistent store.
579
- - ❌ Heard the user state a business fact, constraint, or decision in conversation and did not record it in the graph. Conversations are the most volatile knowledge source — they vanish after context compression and the user will not repeat them.
580
- - ❌ Split or renamed a node that participates in a flow without updating the flow's \`nodes\` list. Stale flow participants are invisible broken references.
581
- - ❌ Implemented a spec that describes a goal-directed workflow (publishing content, managing portfolio, fulfilling orders, processing payments) without creating a corresponding flow. Any sequence of steps toward a business goal IS a flow — single-actor workflows included.
582
- - ❌ Created flows only after all implementation was complete. Flows are part of the specification phase — they describe WHAT happens in the world, which informs HOW to implement it.
583
-
584
- ### Reverse Engineering
585
-
586
- **Order:** aspects (cross-cutting patterns) → flows (business processes) → model nodes. Never create nodes before aspects and flows are understood.
587
-
588
- Per area checklist:
589
-
590
- - [ ] 1. \`yg build-context --file <path>\` — confirm no coverage
591
- - [ ] 2. Determine node granularity — propose to user if unclear
592
- - [ ] 3. Create node directory, read \`schemas/yg-node.yaml\`, create \`yg-node.yaml\`
593
- - [ ] 3b. Write \`description\` in \`yg-node.yaml\` — a short summary of what the node does
594
- - [ ] 4. Analyze source — write \`responsibility.md\`, \`interface.md\`, and \`internals.md\` from code analysis, do not invent
595
- - [ ] 5. Identify relations — add to \`yg-node.yaml\`
596
- - [ ] 6. Identify cross-cutting requirements — add matching aspects, create if needed
597
- - [ ] 6b. For each aspect on the node: identify 2-5 code anchors (function names, constants) that evidence the pattern → add as \`anchors\` in the aspect entry in \`yg-node.yaml\`
598
- - [ ] 7. Identify business process participation — add to flow, ask user if process unclear
599
- - [ ] 8. \`yg validate\` — fix errors
600
- - [ ] 9. \`yg drift-sync --node <path>\`
601
-
602
- **When to ask:**
603
-
604
- - Business process unclear: "This code appears to be part of a larger process. Can you describe what it means from a business perspective?"
605
- - Constraint without rationale: "I see [constraint X]. Do you know why this exists? I want to record the reason, not just the rule."
606
- - Unexplained architectural choice: "I see [approach X]. What was the reason for this choice?"
607
- - Decision without alternatives: "You chose [X]. What alternatives did you consider, and why did you reject them?" Record the answer in the Decisions section of \`internals.md\`.
608
- - Decision without known rationale: Record the decision in \`internals.md\` with "rationale: unknown — inferred from code, not confirmed by developer." A recorded decision with unknown rationale is infinitely more valuable than no record at all, and safer than an invented rationale.
609
-
610
- ### Bootstrap Mode
611
-
612
- Trigger: \`yg preflight\` shows 0 nodes, or no nodes cover the active work area.
613
-
614
- - [ ] 1. Identify the active work area (files the user wants to modify)
615
- - [ ] 2. Scan for cross-cutting patterns → create aspects
616
- - [ ] 3. Ask user about business processes → create flows if applicable
617
- - [ ] 4. Propose node structure for the area
618
- - [ ] 5. Create node(s) with initial artifacts, map files
619
- - [ ] 6. \`yg validate\`, \`yg drift-sync\`
620
- - [ ] 7. Proceed with user's original request
621
-
622
- Constraint: Do NOT map the entire repository. Focus on the active area. Expand incrementally.
623
-
624
- ### Drift Resolution
625
-
626
- Always ask the user before resolving drift. Never auto-resolve.
627
-
628
- - **Source drift** (source files changed) → update graph artifacts to match source, then \`yg drift-sync\`
629
- - **Graph drift** (graph artifacts changed) → review affected source, update if needed, then \`yg drift-sync\`
630
- - **Full drift** (both changed) → present both sides to user, ask which direction wins
631
- - **Missing** → ask: re-materialize or remove mapping?
632
- - **Unmaterialized** → ask user how to proceed
633
-
634
- Threshold: >10 drifted nodes → ask user which area to prioritize. Do not resolve all at once.
635
-
636
- **Drift triage:** Prioritize aspects and \`internals.md\` (highest decay rate), then \`responsibility.md\` and \`interface.md\` (most stable).
637
-
638
- ### Graph Audit
639
-
640
- When reviewing graph quality (triggered by user or quality improvement):
641
-
642
- **Step 1 — Consistency** (catches WRONG information):
643
-
644
- - [ ] 1. \`yg build-context --node <path>\`
645
- - [ ] 2. Read mapped source files
646
- - [ ] 3. For each claim in graph: verify against source code
647
- - [ ] 4. For each aspect: verify the pattern holds in THIS node. If it deviates, add \`exceptions\` to the aspect entry in \`yg-node.yaml\`
648
- - [ ] 5. Report inconsistencies
649
-
650
- **Step 2 — Completeness** (catches MISSING information):
651
-
652
- - [ ] 1. For each public method: is it in \`interface.md\`?
653
- - [ ] 2. For each error path: is it in \`interface.md\` (Failure Modes section)?
654
- - [ ] 3. For each behavioral invariant: is it in the graph?
655
- - [ ] 4. Report omissions separately from inconsistencies
656
-
657
- **Step 3 — Non-Derivable Knowledge** (catches knowledge that exists ONLY in external docs or conversations, not in code):
658
-
659
- - [ ] 1. For each business rule embedded in code: is the WHY recorded in the graph, or only the WHAT visible in code?
660
- - [ ] 2. For each design decision: is the rationale AND rejected alternatives recorded?
661
- - [ ] 3. For each external constraint (brand guidelines, legal, UX persona, quality targets): is it in the graph?
662
- - [ ] 4. For each cross-cutting pattern implemented in 3+ places: does an aspect exist?
663
- - [ ] 5. Report non-derivable knowledge gaps separately — these are the highest-value omissions because they cannot be recovered by reading code.
664
-
665
- ### Error Recovery
666
-
667
- - **\`yg\` not found** → inform user: "yg CLI is not installed or not in PATH." Stop.
668
- - **Unfixable validate errors** → if not resolved after 3 attempts, stop and report to user. Do not loop.
669
- - **Budget warning (W005/W006)** → informational. \`yg validate\` shows a breakdown (own/hierarchy/aspects/flows/dependencies). Large inherited context means the system is complex — this is not a problem to fix, it is reality to acknowledge. Do not delete knowledge from artifacts. Do not attempt to "reduce" inherited context.
670
- - **Own budget warning (W015)** → own artifacts are large. Consider splitting this node's responsibilities into child nodes. Redistribute knowledge across children so total knowledge is preserved or increased, never reduced.
671
- - **Corrupted \`.yggdrasil/\` files** → report to user. Do not attempt repair.
672
- - **Incremental sync** → run \`yg drift-sync\` every 3-5 source files during multi-file tasks. Do not defer to end. But NEVER run \`yg drift-sync\` to silence a failing drift check — drift is a signal that artifacts need updating. First update artifacts, then sync.
673
-
674
- ### Escape Hatch
675
-
676
- If the user explicitly requests a code-only change, comply but:
677
-
678
- - Warn: "This creates drift. Run \`yg drift\` next session to reconcile."
679
- - Do NOT run \`yg drift-sync\` — leave the drift visible.
680
-
681
- ### Environment Check
682
-
683
- Before preflight:
684
-
685
- - Verify \`yg\` CLI is available. If not found, inform user and stop.
686
- - If \`yg preflight\` shows 0 nodes → enter BOOTSTRAP MODE (see above).
687
- - If drift report shows >10 drifted nodes → report scope to user, ask which area to prioritize. Do not resolve all at once.
688
-
689
- <critical_protocol>
690
- BEFORE reading, analyzing, or modifying ANY source file:
691
- \`yg build-context --file <path>\`
692
- One command. No exceptions. No "I'll do it later." No "this is just analysis."
693
- </critical_protocol>`;
694
-
695
- export const AGENT_RULES_CONTENT = [PROTOCOL, REFERENCE, GUARD_RAILS].join('\n\n---\n\n') + '\n';