guild-agents 0.3.1 → 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.
Files changed (38) hide show
  1. package/README.md +5 -1
  2. package/bin/guild.js +74 -1
  3. package/package.json +12 -5
  4. package/src/commands/doctor.js +70 -1
  5. package/src/commands/logs.js +63 -0
  6. package/src/commands/reset-learnings.js +44 -0
  7. package/src/commands/run.js +62 -0
  8. package/src/templates/agents/advisor.md +1 -0
  9. package/src/templates/agents/bugfix.md +1 -0
  10. package/src/templates/agents/code-reviewer.md +1 -0
  11. package/src/templates/agents/db-migration.md +1 -0
  12. package/src/templates/agents/developer.md +1 -0
  13. package/src/templates/agents/learnings-extractor.md +49 -0
  14. package/src/templates/agents/platform-expert.md +1 -0
  15. package/src/templates/agents/product-owner.md +1 -0
  16. package/src/templates/agents/qa.md +1 -0
  17. package/src/templates/agents/tech-lead.md +1 -0
  18. package/src/templates/skills/build-feature/SKILL.md +130 -26
  19. package/src/templates/skills/council/SKILL.md +51 -4
  20. package/src/templates/skills/create-pr/SKILL.md +32 -0
  21. package/src/templates/skills/dev-flow/SKILL.md +14 -0
  22. package/src/templates/skills/guild-specialize/SKILL.md +45 -3
  23. package/src/templates/skills/new-feature/SKILL.md +33 -0
  24. package/src/templates/skills/qa-cycle/SKILL.md +48 -5
  25. package/src/templates/skills/review/SKILL.md +22 -1
  26. package/src/templates/skills/session-end/SKILL.md +27 -0
  27. package/src/templates/skills/session-start/SKILL.md +32 -0
  28. package/src/templates/skills/status/SKILL.md +19 -0
  29. package/src/utils/dispatch-protocol.js +74 -0
  30. package/src/utils/dispatch.js +172 -0
  31. package/src/utils/learnings-io.js +76 -0
  32. package/src/utils/learnings.js +204 -0
  33. package/src/utils/orchestrator-io.js +356 -0
  34. package/src/utils/orchestrator.js +590 -0
  35. package/src/utils/skill-loader.js +83 -0
  36. package/src/utils/trace.js +400 -0
  37. package/src/utils/version.js +90 -0
  38. package/src/utils/workflow-parser.js +225 -0
@@ -2,6 +2,38 @@
2
2
  name: session-start
3
3
  description: "Loads context and resumes work from SESSION.md"
4
4
  user-invocable: true
5
+ workflow:
6
+ version: 1
7
+ steps:
8
+ - id: load-context
9
+ role: system
10
+ intent: "Read CLAUDE.md, SESSION.md, and PROJECT.md to load project context."
11
+ commands: [cat CLAUDE.md, cat SESSION.md, cat PROJECT.md]
12
+ produces: [claude-md, session-md, project-md]
13
+ - id: detect-resumable
14
+ role: system
15
+ intent: "Check for wip: checkpoint commits on feature and fix branches."
16
+ commands: [git branch --list "feature/*" --list "fix/*", git log --oneline -1]
17
+ requires: [session-md]
18
+ produces: [resumable-branches, last-phase]
19
+ - id: present-state
20
+ role: system
21
+ intent: "Display previous session summary: date, task, state, decisions, next steps, resumable pipelines."
22
+ requires: [session-md, resumable-branches]
23
+ produces: [state-display]
24
+ gate: true
25
+ - id: suggest-continuation
26
+ role: system
27
+ intent: "Suggest appropriate skill to continue based on current state."
28
+ requires: [state-display]
29
+ produces: [suggested-action]
30
+ gate: true
31
+ - id: update-session
32
+ role: system
33
+ intent: "Update SESSION.md with current date to record session start."
34
+ requires: [session-md]
35
+ produces: [session-updated]
36
+ gate: true
5
37
  ---
6
38
 
7
39
  # Session Start
@@ -2,6 +2,25 @@
2
2
  name: status
3
3
  description: "Shows current project and session state"
4
4
  user-invocable: true
5
+ workflow:
6
+ version: 1
7
+ steps:
8
+ - id: read-state
9
+ role: system
10
+ intent: "Read CLAUDE.md, PROJECT.md, and SESSION.md for project state."
11
+ commands: [cat CLAUDE.md, cat PROJECT.md, cat SESSION.md]
12
+ produces: [claude-md, project-md, session-md]
13
+ - id: scan-resources
14
+ role: system
15
+ intent: "List available agents and skills from .claude/ directories."
16
+ commands: [ls .claude/agents/, ls .claude/skills/]
17
+ produces: [agent-list, skill-list]
18
+ - id: present-status
19
+ role: system
20
+ intent: "Display project summary: name, stack, session state, agents, skills, and suggested next steps."
21
+ requires: [project-md, session-md, agent-list, skill-list]
22
+ produces: [status-display]
23
+ gate: true
5
24
  ---
6
25
 
7
26
  # Status
@@ -0,0 +1,74 @@
1
+ /**
2
+ * dispatch-protocol.js — Constants and type definitions for the Guild dispatch protocol.
3
+ *
4
+ * Defines the vocabulary shared by dispatch utilities, workflow parser,
5
+ * model routing, and trace modules. Zero dependencies.
6
+ */
7
+
8
+ /**
9
+ * Valid model tier values. Each tier maps to a class of model capability.
10
+ * @type {readonly ['reasoning', 'execution', 'routine']}
11
+ */
12
+ export const MODEL_TIERS = ['reasoning', 'execution', 'routine'];
13
+
14
+ /**
15
+ * Valid failure strategy base values for workflow steps.
16
+ * - abort: halt the workflow on failure (default)
17
+ * - continue: skip this step and proceed
18
+ * Additionally, `goto:<step-id>` is valid for redirecting to another step.
19
+ * @type {readonly ['abort', 'continue']}
20
+ */
21
+ export const FAILURE_STRATEGIES = ['abort', 'continue'];
22
+
23
+ /**
24
+ * Default failure strategy when none is specified.
25
+ * @type {string}
26
+ */
27
+ export const DEFAULT_FAILURE_STRATEGY = 'abort';
28
+
29
+ /**
30
+ * Default tier assignment for each Guild agent role.
31
+ * Used as fallback when neither the workflow step nor the agent frontmatter
32
+ * specifies a tier.
33
+ * @type {Record<string, string>}
34
+ */
35
+ export const DEFAULT_AGENT_TIERS = {
36
+ 'advisor': 'reasoning',
37
+ 'product-owner': 'reasoning',
38
+ 'tech-lead': 'reasoning',
39
+ 'code-reviewer': 'reasoning',
40
+ 'developer': 'execution',
41
+ 'bugfix': 'execution',
42
+ 'db-migration': 'execution',
43
+ 'qa': 'execution',
44
+ 'platform-expert': 'execution',
45
+ 'learnings-extractor': 'routine',
46
+ };
47
+
48
+ /**
49
+ * Built-in model profiles mapping tiers to concrete model IDs.
50
+ * @type {Record<string, Record<string, string>>}
51
+ */
52
+ export const DEFAULT_MODEL_PROFILES = {
53
+ max: {
54
+ reasoning: 'claude-opus-4-6',
55
+ execution: 'claude-sonnet-4-6',
56
+ routine: 'claude-haiku-4-5',
57
+ },
58
+ pro: {
59
+ reasoning: 'claude-sonnet-4-6',
60
+ execution: 'claude-sonnet-4-6',
61
+ routine: 'claude-haiku-4-5',
62
+ },
63
+ };
64
+
65
+ /**
66
+ * Fallback chain for tier resolution. When a tier's model is unavailable,
67
+ * fall back to the next tier. `null` means no further fallback.
68
+ * @type {Record<string, string|null>}
69
+ */
70
+ export const FALLBACK_CHAIN = {
71
+ reasoning: 'execution',
72
+ execution: 'routine',
73
+ routine: null,
74
+ };
@@ -0,0 +1,172 @@
1
+ /**
2
+ * dispatch.js — Validation and resolution utilities for the Guild dispatch protocol.
3
+ *
4
+ * Provides functions to validate workflow step configurations, resolve agent
5
+ * metadata from frontmatter, determine effective model tiers, and resolve
6
+ * tiers to concrete model IDs.
7
+ */
8
+
9
+ import { existsSync, readFileSync } from 'fs';
10
+ import { join } from 'path';
11
+ import { parseFrontmatter } from './files.js';
12
+ import { parseSkill } from './workflow-parser.js';
13
+ import {
14
+ MODEL_TIERS,
15
+ FAILURE_STRATEGIES,
16
+ DEFAULT_AGENT_TIERS,
17
+ DEFAULT_MODEL_PROFILES,
18
+ FALLBACK_CHAIN,
19
+ } from './dispatch-protocol.js';
20
+
21
+ /**
22
+ * Validates a workflow step configuration object.
23
+ * @param {object} config - Step config with role, intent, model-tier, etc.
24
+ * @returns {string[]} Array of error messages (empty means valid)
25
+ */
26
+ export function validateStepConfig(config) {
27
+ const errors = [];
28
+
29
+ if (!config.role) {
30
+ errors.push('Missing required field: role');
31
+ }
32
+
33
+ if (!config.intent) {
34
+ errors.push('Missing required field: intent');
35
+ }
36
+
37
+ if (config['model-tier'] && !MODEL_TIERS.includes(config['model-tier'])) {
38
+ errors.push(`Invalid model-tier: "${config['model-tier']}". Must be one of: ${MODEL_TIERS.join(', ')}`);
39
+ }
40
+
41
+ if (config['on-failure']) {
42
+ const isGoto = config['on-failure'].startsWith('goto:');
43
+ if (!FAILURE_STRATEGIES.includes(config['on-failure']) && !isGoto) {
44
+ errors.push(`Invalid on-failure: "${config['on-failure']}". Must be one of: ${FAILURE_STRATEGIES.join(', ')}, or goto:<step-id>`);
45
+ }
46
+ }
47
+
48
+ if (config['max-retries'] !== undefined) {
49
+ const val = config['max-retries'];
50
+ if (!Number.isInteger(val) || val < 1) {
51
+ errors.push(`Invalid max-retries: ${val}. Must be a positive integer`);
52
+ }
53
+ }
54
+
55
+ return errors;
56
+ }
57
+
58
+ /**
59
+ * Reads agent metadata from the agent's markdown frontmatter.
60
+ * @param {string} role - Agent role name (e.g., 'tech-lead')
61
+ * @param {string} [projectRoot=process.cwd()] - Project root directory
62
+ * @returns {{ name: string, role: string, defaultTier: string|undefined, [key: string]: unknown } | null}
63
+ */
64
+ export function resolveAgentMetadata(role, projectRoot = process.cwd()) {
65
+ const agentPath = join(projectRoot, '.claude', 'agents', `${role}.md`);
66
+
67
+ if (!existsSync(agentPath)) {
68
+ return null;
69
+ }
70
+
71
+ const content = readFileSync(agentPath, 'utf8');
72
+ const frontmatter = parseFrontmatter(content);
73
+
74
+ return {
75
+ ...frontmatter,
76
+ role,
77
+ defaultTier: frontmatter['default-tier'] || undefined,
78
+ };
79
+ }
80
+
81
+ /**
82
+ * Resolves the effective model tier for a workflow step using the precedence chain:
83
+ * 1. stepConfig['model-tier'] (explicit in workflow step)
84
+ * 2. agentMetadata.defaultTier (from agent frontmatter)
85
+ * 3. DEFAULT_AGENT_TIERS[role] (hardcoded defaults)
86
+ * 4. 'execution' (ultimate fallback)
87
+ *
88
+ * @param {object} stepConfig - Workflow step with role and optional model-tier
89
+ * @param {object|null} [agentMetadata=null] - Agent metadata from resolveAgentMetadata
90
+ * @returns {string} One of MODEL_TIERS values
91
+ */
92
+ export function resolveEffectiveTier(stepConfig, agentMetadata = null) {
93
+ if (stepConfig['model-tier'] && MODEL_TIERS.includes(stepConfig['model-tier'])) {
94
+ return stepConfig['model-tier'];
95
+ }
96
+
97
+ if (agentMetadata?.defaultTier && MODEL_TIERS.includes(agentMetadata.defaultTier)) {
98
+ return agentMetadata.defaultTier;
99
+ }
100
+
101
+ const defaultTier = DEFAULT_AGENT_TIERS[stepConfig.role];
102
+ if (defaultTier) {
103
+ return defaultTier;
104
+ }
105
+
106
+ return 'execution';
107
+ }
108
+
109
+ /**
110
+ * Resolves a model tier to a concrete model ID using a profile.
111
+ * Applies the fallback chain if the tier is not found in the profile.
112
+ *
113
+ * @param {string} tier - One of MODEL_TIERS
114
+ * @param {string|Record<string, string>} profile - Profile name ('max', 'pro') or custom mapping
115
+ * @returns {string} Concrete model ID (e.g., 'claude-opus-4-6')
116
+ * @throws {Error} If no model can be resolved after exhausting the fallback chain
117
+ */
118
+ export function resolveModel(tier, profile) {
119
+ const profileMap = typeof profile === 'string'
120
+ ? DEFAULT_MODEL_PROFILES[profile]
121
+ : profile;
122
+
123
+ if (!profileMap) {
124
+ throw new Error(`Unknown profile: "${profile}". Available: ${Object.keys(DEFAULT_MODEL_PROFILES).join(', ')}`);
125
+ }
126
+
127
+ let currentTier = tier;
128
+ const visited = new Set();
129
+
130
+ while (currentTier) {
131
+ if (visited.has(currentTier)) {
132
+ break;
133
+ }
134
+ visited.add(currentTier);
135
+
136
+ if (profileMap[currentTier]) {
137
+ return profileMap[currentTier];
138
+ }
139
+
140
+ currentTier = FALLBACK_CHAIN[currentTier];
141
+ }
142
+
143
+ throw new Error(`Cannot resolve model for tier "${tier}": no model available in profile after fallback chain`);
144
+ }
145
+
146
+ /**
147
+ * Extracts dispatch configuration from skill markdown content.
148
+ * Precedence: workflow steps (frontmatter) > null (legacy prose).
149
+ *
150
+ * Dependency direction: dispatch.js imports from workflow-parser.js.
151
+ * Do not reverse this — workflow-parser.js must not import from dispatch.js.
152
+ *
153
+ * @param {string} skillMarkdown - Raw SKILL.md content
154
+ * @returns {{ source: 'workflow', steps: Array<object> } | { source: null }}
155
+ * @throws {Error} If YAML frontmatter is malformed (propagated from parseSkill)
156
+ */
157
+ export function extractDispatchConfigs(skillMarkdown) {
158
+ if (!skillMarkdown) {
159
+ return { source: null };
160
+ }
161
+
162
+ const skill = parseSkill(skillMarkdown);
163
+
164
+ if (skill.workflow && Array.isArray(skill.workflow.steps) && skill.workflow.steps.length > 0) {
165
+ return {
166
+ source: 'workflow',
167
+ steps: skill.workflow.steps,
168
+ };
169
+ }
170
+
171
+ return { source: null };
172
+ }
@@ -0,0 +1,76 @@
1
+ /**
2
+ * learnings-io.js — File I/O operations for compound learnings.
3
+ *
4
+ * Read, write, init, exists, and delete operations for .claude/guild/learnings.md.
5
+ * Separated from the pure functions in learnings.js following the trace.js pattern.
6
+ *
7
+ * NOTE: File locking for concurrent access is intentionally omitted.
8
+ * Concurrent workflow execution is a v2 concern — current Guild workflows
9
+ * are single-session and sequential.
10
+ */
11
+
12
+ import { readFileSync, writeFileSync, existsSync, unlinkSync, mkdirSync } from 'fs';
13
+ import { dirname } from 'path';
14
+ import { GUILD_LEARNINGS_PATH, renderEmptyLearnings } from './learnings.js';
15
+
16
+ /**
17
+ * Reads the learnings file from disk.
18
+ * Returns the raw content as a string, or null if the file does not exist.
19
+ * @param {string} [filePath] - Override path (default: GUILD_LEARNINGS_PATH)
20
+ * @returns {string | null}
21
+ */
22
+ export function readLearnings(filePath) {
23
+ const target = filePath || GUILD_LEARNINGS_PATH;
24
+ if (!existsSync(target)) return null;
25
+ return readFileSync(target, 'utf8');
26
+ }
27
+
28
+ /**
29
+ * Writes content to the learnings file.
30
+ * Creates parent directories if needed.
31
+ * @param {string} content - Markdown content to write
32
+ * @param {string} [filePath] - Override path (default: GUILD_LEARNINGS_PATH)
33
+ */
34
+ export function writeLearnings(content, filePath) {
35
+ const target = filePath || GUILD_LEARNINGS_PATH;
36
+ mkdirSync(dirname(target), { recursive: true });
37
+ writeFileSync(target, content, 'utf8');
38
+ }
39
+
40
+ /**
41
+ * Checks whether the learnings file exists on disk.
42
+ * @param {string} [filePath] - Override path (default: GUILD_LEARNINGS_PATH)
43
+ * @returns {boolean}
44
+ */
45
+ export function learningsExist(filePath) {
46
+ const target = filePath || GUILD_LEARNINGS_PATH;
47
+ return existsSync(target);
48
+ }
49
+
50
+ /**
51
+ * Initializes the learnings file with empty scaffold content.
52
+ * No-ops if the file already exists.
53
+ * @param {string} [projectName='Project'] - Project name for the header
54
+ * @param {string} [filePath] - Override path (default: GUILD_LEARNINGS_PATH)
55
+ * @returns {{ created: boolean }}
56
+ */
57
+ export function initLearnings(projectName = 'Project', filePath) {
58
+ const target = filePath || GUILD_LEARNINGS_PATH;
59
+ if (existsSync(target)) return { created: false };
60
+ mkdirSync(dirname(target), { recursive: true });
61
+ writeFileSync(target, renderEmptyLearnings(projectName), 'utf8');
62
+ return { created: true };
63
+ }
64
+
65
+ /**
66
+ * Deletes the learnings file from disk.
67
+ * Returns { deleted: false } if the file does not exist (no throw).
68
+ * @param {string} [filePath] - Override path (default: GUILD_LEARNINGS_PATH)
69
+ * @returns {{ deleted: boolean }}
70
+ */
71
+ export function deleteLearnings(filePath) {
72
+ const target = filePath || GUILD_LEARNINGS_PATH;
73
+ if (!existsSync(target)) return { deleted: false };
74
+ unlinkSync(target);
75
+ return { deleted: true };
76
+ }
@@ -0,0 +1,204 @@
1
+ /**
2
+ * learnings.js — Pure functions for compound learning.
3
+ *
4
+ * Constants, parsing, rendering, token estimation, and context injection.
5
+ * Zero I/O, zero external dependencies — leaf module.
6
+ */
7
+
8
+ /** Fixed section names for the learnings file (spec section 3.3). */
9
+ export const LEARNINGS_SECTIONS = [
10
+ 'Project Patterns',
11
+ 'Architecture Decisions',
12
+ 'Past Issues & Resolutions',
13
+ 'User Preferences',
14
+ 'Agent Notes',
15
+ ];
16
+
17
+ /** Maximum token budget for the learnings file. */
18
+ export const TOKEN_BUDGET = 2000;
19
+
20
+ /** Default path to the learnings file, relative to project root. */
21
+ export const GUILD_LEARNINGS_PATH = '.claude/guild/learnings.md';
22
+
23
+ /**
24
+ * Estimates token count from text using a word-count heuristic.
25
+ * Approximation: tokens ≈ ceil(words × 1.35).
26
+ * @param {string | null | undefined} text
27
+ * @returns {number}
28
+ */
29
+ export function estimateTokens(text) {
30
+ if (!text || !text.trim()) return 0;
31
+ const words = text.trim().split(/\s+/).length;
32
+ return Math.ceil(words * 1.35);
33
+ }
34
+
35
+ /**
36
+ * Returns true if the estimated token count is within the budget.
37
+ * @param {string | null | undefined} text
38
+ * @param {number} [budget=TOKEN_BUDGET]
39
+ * @returns {boolean}
40
+ */
41
+ export function isWithinBudget(text, budget = TOKEN_BUDGET) {
42
+ return estimateTokens(text) <= budget;
43
+ }
44
+
45
+ /**
46
+ * Renders the initial/empty learnings file content.
47
+ * @param {string} [projectName='Project']
48
+ * @returns {string}
49
+ */
50
+ export function renderEmptyLearnings(projectName = 'Project') {
51
+ const lines = [];
52
+ lines.push(`# Guild Learnings — ${projectName}`);
53
+ lines.push('');
54
+ lines.push(`> Auto-generated by Guild. Last updated: ${new Date().toISOString()}`);
55
+ lines.push('> Total executions: 0');
56
+ lines.push('> Token budget: this file should stay under 2000 tokens');
57
+ lines.push('');
58
+
59
+ for (const section of LEARNINGS_SECTIONS) {
60
+ lines.push(`## ${section}`);
61
+ lines.push('');
62
+ lines.push('_No learnings yet._');
63
+ lines.push('');
64
+ }
65
+
66
+ return lines.join('\n');
67
+ }
68
+
69
+ const PLACEHOLDER_RE = /^_No learnings yet\._$/;
70
+ const ENTRY_RE = /^- (.+)$/;
71
+ const DISCOVERED_RE = /\(discovered: ([^)]+)\)/;
72
+
73
+ /**
74
+ * Parses a learnings.md file into a structured object.
75
+ * @param {string | null | undefined} content
76
+ * @returns {{ header: { project: string, lastUpdated: string, totalExecutions: number }, sections: Record<string, Array<{ text: string, discovered: string }>> }}
77
+ */
78
+ export function parseLearnings(content) {
79
+ const empty = {
80
+ header: { project: '', lastUpdated: '', totalExecutions: 0 },
81
+ sections: {},
82
+ };
83
+ for (const s of LEARNINGS_SECTIONS) empty.sections[s] = [];
84
+
85
+ if (!content || !content.trim()) return empty;
86
+
87
+ const lines = content.split('\n');
88
+ const result = { header: { project: '', lastUpdated: '', totalExecutions: 0 }, sections: {} };
89
+ for (const s of LEARNINGS_SECTIONS) result.sections[s] = [];
90
+
91
+ let currentSection = null;
92
+
93
+ for (const line of lines) {
94
+ // Parse H1 header
95
+ const h1Match = line.match(/^# Guild Learnings — (.+)$/);
96
+ if (h1Match) {
97
+ result.header.project = h1Match[1].trim();
98
+ continue;
99
+ }
100
+
101
+ // Parse header metadata
102
+ const updatedMatch = line.match(/^> Auto-generated by Guild\. Last updated: (.+)$/);
103
+ if (updatedMatch) {
104
+ result.header.lastUpdated = updatedMatch[1].trim();
105
+ continue;
106
+ }
107
+ const execMatch = line.match(/^> Total executions: (\d+)$/);
108
+ if (execMatch) {
109
+ result.header.totalExecutions = parseInt(execMatch[1], 10);
110
+ continue;
111
+ }
112
+
113
+ // Parse section headers
114
+ const h2Match = line.match(/^## (.+)$/);
115
+ if (h2Match) {
116
+ const sectionName = h2Match[1].trim();
117
+ if (LEARNINGS_SECTIONS.includes(sectionName)) {
118
+ currentSection = sectionName;
119
+ } else {
120
+ currentSection = null;
121
+ }
122
+ continue;
123
+ }
124
+
125
+ // Skip placeholders and blank lines
126
+ if (!currentSection) continue;
127
+ if (PLACEHOLDER_RE.test(line.trim())) continue;
128
+ if (!line.trim()) continue;
129
+
130
+ // Parse entries (lines starting with "- ")
131
+ const entryMatch = line.match(ENTRY_RE);
132
+ if (entryMatch) {
133
+ const text = entryMatch[1].trim();
134
+ const discoveredMatch = text.match(DISCOVERED_RE);
135
+ result.sections[currentSection].push({
136
+ text,
137
+ discovered: discoveredMatch ? discoveredMatch[1] : '',
138
+ });
139
+ }
140
+ }
141
+
142
+ return result;
143
+ }
144
+
145
+ /**
146
+ * Renders a parsed learnings structure back to markdown.
147
+ * @param {{ header: { project: string, lastUpdated: string, totalExecutions: number }, sections: Record<string, Array<{ text: string, discovered: string }>> }} parsed
148
+ * @returns {string}
149
+ */
150
+ export function renderLearnings(parsed) {
151
+ const lines = [];
152
+ const project = parsed.header.project || 'Project';
153
+ const lastUpdated = parsed.header.lastUpdated || new Date().toISOString();
154
+ const totalExecutions = parsed.header.totalExecutions || 0;
155
+
156
+ lines.push(`# Guild Learnings — ${project}`);
157
+ lines.push('');
158
+ lines.push(`> Auto-generated by Guild. Last updated: ${lastUpdated}`);
159
+ lines.push(`> Total executions: ${totalExecutions}`);
160
+ lines.push('> Token budget: this file should stay under 2000 tokens');
161
+ lines.push('');
162
+
163
+ for (const section of LEARNINGS_SECTIONS) {
164
+ lines.push(`## ${section}`);
165
+ lines.push('');
166
+ const entries = parsed.sections[section] || [];
167
+ if (entries.length === 0) {
168
+ lines.push('_No learnings yet._');
169
+ } else {
170
+ for (const entry of entries) {
171
+ lines.push(`- ${entry.text}`);
172
+ }
173
+ }
174
+ lines.push('');
175
+ }
176
+
177
+ return lines.join('\n');
178
+ }
179
+
180
+ /**
181
+ * Builds a context injection string from raw learnings content.
182
+ * Wraps in <guild-learnings> tags per spec section 4.2.
183
+ * Returns empty string for null/empty input.
184
+ * @param {string | null | undefined} content
185
+ * @returns {string}
186
+ */
187
+ export function buildContextInjection(content) {
188
+ if (!content || !content.trim()) return '';
189
+
190
+ const parsed = parseLearnings(content);
191
+ const hasEntries = LEARNINGS_SECTIONS.some(s => (parsed.sections[s] || []).length > 0);
192
+ if (!hasEntries) return '';
193
+
194
+ const lines = [];
195
+ lines.push('<guild-learnings>');
196
+ lines.push(content.trim());
197
+ lines.push('</guild-learnings>');
198
+ lines.push('');
199
+ lines.push('These are accumulated learnings from previous Guild executions on this project.');
200
+ lines.push('Use them to inform your work. Do not contradict established patterns unless');
201
+ lines.push('explicitly asked to change them.');
202
+
203
+ return lines.join('\n');
204
+ }