@polymorphism-tech/morph-spec 4.8.19 → 4.9.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 (137) hide show
  1. package/CLAUDE.md +21 -0
  2. package/README.md +2 -2
  3. package/bin/morph-spec.js +15 -56
  4. package/bin/task-manager.js +115 -14
  5. package/bin/validate.js +67 -33
  6. package/claude-plugin.json +1 -1
  7. package/docs/CHEATSHEET.md +201 -203
  8. package/docs/QUICKSTART.md +2 -2
  9. package/framework/CLAUDE.md +21 -0
  10. package/framework/agents.json +698 -176
  11. package/framework/hooks/claude-code/post-tool-use/context-refresh.js +1 -1
  12. package/framework/hooks/claude-code/post-tool-use/dispatch.js +2 -2
  13. package/framework/hooks/claude-code/post-tool-use/skill-reminder.js +155 -0
  14. package/framework/hooks/claude-code/pre-tool-use/protect-spec-files.js +1 -1
  15. package/framework/hooks/claude-code/session-start/inject-morph-context.js +71 -2
  16. package/framework/hooks/claude-code/statusline.py +76 -30
  17. package/framework/hooks/claude-code/user-prompt/set-terminal-title.js +14 -6
  18. package/framework/hooks/shared/activity-logger.js +0 -24
  19. package/framework/hooks/shared/phase-utils.js +3 -0
  20. package/framework/hooks/shared/skill-reminder-helpers.js +79 -0
  21. package/framework/hooks/shared/stale-task-reset.js +57 -0
  22. package/framework/hooks/shared/state-reader.js +2 -2
  23. package/framework/hooks/shared/worktree-helpers.js +53 -0
  24. package/framework/phases.json +40 -8
  25. package/framework/skills/level-0-meta/brainstorming/SKILL.md +1 -1
  26. package/framework/skills/level-0-meta/code-review/SKILL.md +1 -1
  27. package/framework/skills/level-0-meta/code-review-nextjs/SKILL.md +163 -163
  28. package/framework/skills/level-0-meta/frontend-review/SKILL.md +5 -5
  29. package/framework/skills/level-0-meta/morph-checklist/SKILL.md +2 -2
  30. package/framework/skills/level-0-meta/morph-init/SKILL.md +5 -5
  31. package/framework/skills/level-0-meta/morph-replicate/SKILL.md +4 -4
  32. package/framework/skills/level-0-meta/morph-replicate/references/blazor-html-mapping.md +1 -1
  33. package/framework/skills/level-0-meta/post-implementation/SKILL.md +59 -12
  34. package/framework/skills/level-0-meta/simulation-checklist/SKILL.md +1 -1
  35. package/framework/skills/level-0-meta/terminal-title/SKILL.md +1 -1
  36. package/framework/skills/level-0-meta/tool-usage-guide/SKILL.md +1 -1
  37. package/framework/skills/level-0-meta/tool-usage-guide/references/tools-per-phase.md +6 -5
  38. package/framework/skills/level-0-meta/verification-before-completion/SKILL.md +1 -1
  39. package/framework/skills/level-1-workflows/phase-clarify/SKILL.md +215 -189
  40. package/framework/skills/level-1-workflows/phase-codebase-analysis/SKILL.md +251 -251
  41. package/framework/skills/level-1-workflows/phase-design/SKILL.md +382 -365
  42. package/framework/skills/level-1-workflows/phase-implement/SKILL.md +492 -450
  43. package/framework/skills/level-1-workflows/phase-setup/SKILL.md +194 -190
  44. package/framework/skills/level-1-workflows/phase-tasks/SKILL.md +270 -270
  45. package/framework/skills/level-1-workflows/phase-uiux/SKILL.md +285 -285
  46. package/framework/standards/STANDARDS.json +640 -88
  47. package/framework/standards/infrastructure/vercel/vercel-database.md +106 -0
  48. package/framework/templates/REGISTRY.json +1825 -1909
  49. package/framework/templates/context/CONTEXT-FEATURE.md +276 -276
  50. package/framework/templates/docs/onboarding.md +1 -5
  51. package/package.json +2 -6
  52. package/src/commands/agents/dispatch-agents.js +55 -4
  53. package/src/commands/project/doctor.js +16 -47
  54. package/src/commands/project/init.js +1 -1
  55. package/src/commands/project/status.js +2 -2
  56. package/src/commands/project/update.js +381 -365
  57. package/src/commands/project/worktree.js +154 -0
  58. package/src/commands/state/advance-phase.js +120 -30
  59. package/src/commands/state/approve.js +2 -2
  60. package/src/commands/state/index.js +7 -8
  61. package/src/commands/state/phase-runner.js +1 -1
  62. package/src/commands/state/state.js +61 -6
  63. package/src/commands/tasks/task.js +78 -99
  64. package/src/commands/templates/template-render.js +93 -173
  65. package/src/commands/trust/trust.js +26 -21
  66. package/src/core/paths/output-schema.js +15 -0
  67. package/src/core/state/state-manager.js +28 -54
  68. package/src/core/workflows/workflow-detector.js +9 -87
  69. package/src/lib/phase-chain/phase-validator.js +330 -0
  70. package/src/lib/stack/stack-profile.js +88 -0
  71. package/src/lib/tasks/task-classifier.js +16 -0
  72. package/src/lib/tasks/test-runner.js +77 -0
  73. package/src/lib/trust/trust-manager.js +32 -144
  74. package/src/lib/validators/spec-validator.js +58 -4
  75. package/src/lib/validators/validation-runner.js +23 -11
  76. package/src/scripts/setup-infra.js +240 -224
  77. package/src/utils/agents-installer.js +2 -2
  78. package/src/utils/banner.js +1 -1
  79. package/src/utils/claude-settings-manager.js +1 -1
  80. package/src/utils/file-copier.js +1 -0
  81. package/src/utils/hooks-installer.js +258 -8
  82. package/framework/hooks/dev/check-sync-health.js +0 -117
  83. package/framework/hooks/dev/guard-version-numbers.js +0 -57
  84. package/framework/hooks/dev/sync-standards-registry.js +0 -60
  85. package/framework/hooks/dev/sync-template-registry.js +0 -60
  86. package/framework/hooks/dev/validate-skill-format.js +0 -70
  87. package/framework/hooks/dev/validate-standard-format.js +0 -73
  88. package/framework/templates/meta-prompts/hops/hop-retry.md +0 -78
  89. package/framework/templates/meta-prompts/hops/hop-validation.md +0 -97
  90. package/framework/templates/meta-prompts/hops/hop-wrapper.md +0 -36
  91. package/framework/workflows/configs/design-impl.json +0 -49
  92. package/framework/workflows/configs/express.json +0 -45
  93. package/framework/workflows/configs/fast-track.json +0 -42
  94. package/framework/workflows/configs/full-morph.json +0 -79
  95. package/framework/workflows/configs/fusion.json +0 -39
  96. package/framework/workflows/configs/long-running.json +0 -33
  97. package/framework/workflows/configs/spec-only.json +0 -43
  98. package/framework/workflows/configs/ui-refresh.json +0 -49
  99. package/framework/workflows/configs/zero-touch.json +0 -82
  100. package/src/commands/project/monitor.js +0 -295
  101. package/src/commands/project/tutorial.js +0 -115
  102. package/src/commands/state/validate-phase.js +0 -238
  103. package/src/commands/templates/generate-contracts.js +0 -445
  104. package/src/core/orchestrator.js +0 -171
  105. package/src/core/registry/command-registry.js +0 -28
  106. package/src/core/registry/index.js +0 -8
  107. package/src/core/registry/validator-registry.js +0 -204
  108. package/src/core/templates/template-validator.js +0 -296
  109. package/src/generator/config-generator.js +0 -206
  110. package/src/generator/templates/config.json.template +0 -40
  111. package/src/generator/templates/project.md.template +0 -67
  112. package/src/lib/agents/micro-agent-factory.js +0 -161
  113. package/src/lib/analysis/complexity-analyzer.js +0 -441
  114. package/src/lib/analysis/index.js +0 -7
  115. package/src/lib/analytics/analytics-engine.js +0 -345
  116. package/src/lib/checkpoints/checkpoint-hooks.js +0 -298
  117. package/src/lib/checkpoints/index.js +0 -7
  118. package/src/lib/context/context-bundler.js +0 -241
  119. package/src/lib/context/context-optimizer.js +0 -212
  120. package/src/lib/context/context-tracker.js +0 -273
  121. package/src/lib/context/core-four-tracker.js +0 -201
  122. package/src/lib/context/mcp-optimizer.js +0 -200
  123. package/src/lib/execution/fusion-executor.js +0 -304
  124. package/src/lib/execution/parallel-executor.js +0 -270
  125. package/src/lib/hooks/stop-hook-executor.js +0 -286
  126. package/src/lib/hops/hop-composer.js +0 -221
  127. package/src/lib/phase-chain/eligibility-checker.js +0 -243
  128. package/src/lib/threads/thread-coordinator.js +0 -238
  129. package/src/lib/threads/thread-manager.js +0 -317
  130. package/src/lib/tracking/artifact-trail.js +0 -202
  131. package/src/scanner/project-scanner.js +0 -242
  132. package/src/ui/diff-display.js +0 -91
  133. package/src/ui/interactive-wizard.js +0 -96
  134. package/src/ui/user-review.js +0 -211
  135. package/src/ui/wizard-questions.js +0 -188
  136. package/src/utils/color-utils.js +0 -70
  137. package/src/utils/process-handler.js +0 -97
@@ -1,286 +0,0 @@
1
- /**
2
- * Stop Hook Executor — L-Thread validation loops
3
- *
4
- * Manages stop hooks for Long-Running threads.
5
- * Executes hook scripts, captures output, provides structured feedback.
6
- *
7
- * On failure: writes feedback to .morph/stop-hook-feedback/{threadId}.json
8
- * Agent reads feedback before retrying.
9
- *
10
- * Max retries: 5. Interval: configurable (default: 30 min).
11
- */
12
-
13
- import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'fs';
14
- import { join } from 'path';
15
- import { execSync } from 'child_process';
16
- import { recordEvent } from '../analytics/analytics-engine.js';
17
-
18
- const FEEDBACK_DIR = join(process.cwd(), '.morph/stop-hook-feedback');
19
- const MAX_RETRIES = 5;
20
- const DEFAULT_INTERVAL_MINUTES = 30;
21
-
22
- // Hook registry — hooks registered for each thread
23
- const hookRegistry = new Map(); // threadId → [{ hookPath, config }]
24
-
25
- // ============================================================================
26
- // Hook Registration
27
- // ============================================================================
28
-
29
- /**
30
- * Register a stop hook for a thread
31
- * @param {string} threadId - Thread ID
32
- * @param {string} hookPath - Path to hook script
33
- * @param {Object} [config]
34
- * @param {string[]} [config.triggers] - When to run: ['interval', 'on-stop', 'on-error']
35
- * @param {number} [config.intervalMinutes] - Interval for periodic execution
36
- * @param {boolean} [config.blocking] - Whether failure blocks thread progress
37
- */
38
- export function registerStopHook(threadId, hookPath, config = {}) {
39
- if (!hookRegistry.has(threadId)) {
40
- hookRegistry.set(threadId, []);
41
- }
42
-
43
- hookRegistry.get(threadId).push({
44
- hookPath,
45
- config: {
46
- triggers: config.triggers || ['on-stop'],
47
- intervalMinutes: config.intervalMinutes || DEFAULT_INTERVAL_MINUTES,
48
- blocking: config.blocking !== false,
49
- ...config
50
- }
51
- });
52
- }
53
-
54
- /**
55
- * Get registered hooks for a thread
56
- * @param {string} threadId
57
- * @returns {Array}
58
- */
59
- export function getThreadHooks(threadId) {
60
- return hookRegistry.get(threadId) || [];
61
- }
62
-
63
- // ============================================================================
64
- // Hook Execution
65
- // ============================================================================
66
-
67
- /**
68
- * Execute all stop hooks for a thread
69
- * @param {string} threadId - Thread ID
70
- * @param {string} hookType - Trigger type ('interval' | 'on-stop' | 'on-error')
71
- * @param {Object} [context] - Additional context passed to hooks
72
- * @returns {Promise<Object>} { passed, feedback, results }
73
- */
74
- export async function executeStopHooks(threadId, hookType = 'on-stop', context = {}) {
75
- const hooks = hookRegistry.get(threadId) || loadDefaultHooks(threadId);
76
- const results = [];
77
- let allPassed = true;
78
-
79
- for (const hook of hooks) {
80
- if (!hook.config.triggers.includes(hookType) && !hook.config.triggers.includes('all')) {
81
- continue;
82
- }
83
-
84
- const result = await executeHook(hook.hookPath, { threadId, hookType, ...context });
85
- results.push(result);
86
-
87
- if (!result.passed && hook.config.blocking) {
88
- allPassed = false;
89
- }
90
- }
91
-
92
- const passed = allPassed;
93
- const feedback = buildFeedback(results, passed);
94
-
95
- if (!passed) {
96
- saveFeedback(threadId, feedback);
97
- }
98
-
99
- recordEvent({
100
- type: passed ? 'stop_hook_passed' : 'stop_hook_failed',
101
- data: { threadId, hookType, resultsCount: results.length, passed }
102
- });
103
-
104
- return { passed, feedback, results };
105
- }
106
-
107
- /**
108
- * Execute a single hook script
109
- * @param {string} hookPath - Path to hook script
110
- * @param {Object} context - Context passed as environment variables
111
- * @returns {Promise<Object>} { hookPath, passed, output, error }
112
- */
113
- async function executeHook(hookPath, context) {
114
- const fullPath = existsSync(hookPath) ? hookPath : join(process.cwd(), hookPath);
115
-
116
- if (!existsSync(fullPath)) {
117
- return {
118
- hookPath,
119
- passed: true, // Missing hooks don't block
120
- output: null,
121
- error: `Hook not found: ${hookPath} (skipped)`,
122
- skipped: true
123
- };
124
- }
125
-
126
- try {
127
- const env = {
128
- ...process.env,
129
- MORPH_THREAD_ID: context.threadId || '',
130
- MORPH_HOOK_TYPE: context.hookType || '',
131
- MORPH_FEATURE: context.feature || ''
132
- };
133
-
134
- const output = execSync(`node "${fullPath}"`, {
135
- encoding: 'utf8',
136
- stdio: 'pipe',
137
- timeout: 120000, // 2 minute timeout per hook
138
- env
139
- });
140
-
141
- // Parse JSON output from hook
142
- let parsed;
143
- try {
144
- parsed = JSON.parse(output);
145
- } catch {
146
- // Non-JSON output means pass (for legacy hooks)
147
- parsed = { passed: true, output };
148
- }
149
-
150
- return {
151
- hookPath,
152
- passed: parsed.passed !== false,
153
- output: parsed,
154
- error: parsed.error || null
155
- };
156
- } catch (err) {
157
- return {
158
- hookPath,
159
- passed: false,
160
- output: null,
161
- error: err.message || 'Hook execution failed'
162
- };
163
- }
164
- }
165
-
166
- // ============================================================================
167
- // Feedback Management
168
- // ============================================================================
169
-
170
- /**
171
- * Build structured feedback from hook results
172
- * @param {Array} results - Hook execution results
173
- * @param {boolean} passed - Overall pass/fail
174
- * @returns {Object} Structured feedback
175
- */
176
- function buildFeedback(results, passed) {
177
- const failures = results.filter(r => !r.passed && !r.skipped);
178
- const issues = failures.flatMap(r => {
179
- const output = r.output;
180
- if (output?.issues) return output.issues;
181
- if (output?.errors) return output.errors;
182
- if (r.error) return [{ message: r.error, severity: 'error' }];
183
- return [];
184
- });
185
-
186
- return {
187
- passed,
188
- timestamp: new Date().toISOString(),
189
- hooksRun: results.length,
190
- hooksFailed: failures.length,
191
- issues,
192
- suggestions: failures.flatMap(r => r.output?.suggestions || []),
193
- nextAction: passed
194
- ? 'continue'
195
- : failures.length > 0 ? 'fix-and-retry' : 'investigate'
196
- };
197
- }
198
-
199
- /**
200
- * Save feedback to file for agent to read
201
- * @param {string} threadId - Thread ID
202
- * @param {Object} feedback - Feedback object
203
- * @returns {string} Path to feedback file
204
- */
205
- export function saveFeedback(threadId, feedback) {
206
- if (!existsSync(FEEDBACK_DIR)) {
207
- mkdirSync(FEEDBACK_DIR, { recursive: true });
208
- }
209
-
210
- const filePath = join(FEEDBACK_DIR, `${threadId}.json`);
211
- writeFileSync(filePath, JSON.stringify(feedback, null, 2), 'utf8');
212
- return filePath;
213
- }
214
-
215
- /**
216
- * Load feedback for a thread (agent reads this after failure)
217
- * @param {string} threadId - Thread ID
218
- * @returns {Object|null} Feedback object or null
219
- */
220
- export function loadFeedback(threadId) {
221
- const filePath = join(FEEDBACK_DIR, `${threadId}.json`);
222
- if (!existsSync(filePath)) return null;
223
- try {
224
- return JSON.parse(readFileSync(filePath, 'utf8'));
225
- } catch {
226
- return null;
227
- }
228
- }
229
-
230
- /**
231
- * Track retry count for a thread
232
- * @param {string} threadId
233
- * @returns {number} Current retry count
234
- */
235
- export function getRetryCount(threadId) {
236
- const feedback = loadFeedback(threadId);
237
- return feedback?.retryCount || 0;
238
- }
239
-
240
- /**
241
- * Increment retry count
242
- * @param {string} threadId
243
- * @returns {number} New retry count
244
- */
245
- export function incrementRetryCount(threadId) {
246
- const feedback = loadFeedback(threadId) || {};
247
- feedback.retryCount = (feedback.retryCount || 0) + 1;
248
- saveFeedback(threadId, feedback);
249
- return feedback.retryCount;
250
- }
251
-
252
- /**
253
- * Check if max retries exceeded
254
- * @param {string} threadId
255
- * @param {number} [maxRetries=5]
256
- * @returns {boolean}
257
- */
258
- export function isMaxRetriesExceeded(threadId, maxRetries = MAX_RETRIES) {
259
- return getRetryCount(threadId) >= maxRetries;
260
- }
261
-
262
- // ============================================================================
263
- // Helpers
264
- // ============================================================================
265
-
266
- function loadDefaultHooks(threadId) {
267
- // Load hooks from llm-interaction.json if no hooks registered
268
- const configPath = join(process.cwd(), '.morph/config/llm-interaction.json');
269
- if (!existsSync(configPath)) return [];
270
-
271
- try {
272
- const config = JSON.parse(readFileSync(configPath, 'utf8'));
273
- const hookNames = config.stopHooks?.hooks || [];
274
-
275
- return hookNames.map(name => ({
276
- hookPath: `framework/hooks/agent-stop/${name}.js`,
277
- config: {
278
- triggers: ['on-stop', 'interval'],
279
- intervalMinutes: config.stopHooks?.interval || DEFAULT_INTERVAL_MINUTES,
280
- blocking: true
281
- }
282
- }));
283
- } catch {
284
- return [];
285
- }
286
- }
@@ -1,221 +0,0 @@
1
- /**
2
- * HOP Composer — Higher-Order Prompt rendering and nesting
3
- *
4
- * Compiles Handlebars templates for agent prompts (HOPs).
5
- * Supports:
6
- * - renderHOP(templatePath, variables) → compiled prompt string
7
- * - composeHOPs(hopChain[], variables) → nested HOPs (outer wraps inner)
8
- * - listAvailableHOPs() → scan meta-prompts/ and return HOPDescriptor[]
9
- *
10
- * Standard HOP variables auto-injected:
11
- * FEATURE_NAME, AGENT_ID, MISSION, SPEC_SUMMARY, STANDARDS, TASKS,
12
- * DELIVERABLES, CONSTRAINTS, DATE, TIMESTAMP
13
- */
14
-
15
- import { readFileSync, existsSync, readdirSync, statSync } from 'fs';
16
- import { join, relative, extname, basename } from 'path';
17
-
18
- const META_PROMPTS_DIR = join(process.cwd(), 'framework/templates/meta-prompts');
19
- const REGISTRY_PATH = join(process.cwd(), 'framework/templates/REGISTRY.json');
20
-
21
- // ============================================================================
22
- // Handlebars-Compatible Mini-Compiler
23
- // ============================================================================
24
-
25
- /**
26
- * Compile a Handlebars template with variables (subset of Handlebars features)
27
- * Supports: {{variable}}, {{#if condition}}...{{/if}}, {{#each array}}...{{/each}}
28
- * Also supports built-in helpers: {{pascalCase}}, {{camelCase}}, {{snakeCase}}
29
- *
30
- * @param {string} template - Handlebars template string
31
- * @param {Object} variables - Variables to inject
32
- * @returns {string} Compiled template
33
- */
34
- export function compileTemplate(template, variables) {
35
- const vars = {
36
- DATE: new Date().toISOString().split('T')[0],
37
- TIMESTAMP: new Date().toISOString(),
38
- ...injectCasedHelpers(variables),
39
- ...variables
40
- };
41
-
42
- let result = template;
43
-
44
- // 1. Process {{#if VAR}}...{{/if}} blocks
45
- result = result.replace(/\{\{#if\s+(\w+)\}\}([\s\S]*?)\{\{\/if\}\}/g, (_, key, content) => {
46
- return vars[key] ? content : '';
47
- });
48
-
49
- // 2. Process {{#each ARRAY}}...{{/each}} blocks
50
- result = result.replace(/\{\{#each\s+(\w+)\}\}([\s\S]*?)\{\{\/each\}\}/g, (_, key, content) => {
51
- const arr = vars[key];
52
- if (!Array.isArray(arr)) return '';
53
- return arr.map(item => {
54
- const itemVars = typeof item === 'object' ? { ...vars, ...item, this: item } : { ...vars, this: item };
55
- return compileTemplate(content, itemVars);
56
- }).join('');
57
- });
58
-
59
- // 3. Process helper calls: {{pascalCase VARIABLE}}, {{camelCase VARIABLE}}, etc.
60
- result = result.replace(/\{\{(pascalCase|camelCase|snakeCase|titleCase|pluralize)\s+(\w+)\}\}/g, (_, helper, key) => {
61
- const value = String(vars[key] || '');
62
- return applyHelper(helper, value);
63
- });
64
-
65
- // 4. Process simple {{VARIABLE}} substitutions
66
- result = result.replace(/\{\{(\w+)\}\}/g, (_, key) => {
67
- return vars[key] !== undefined ? String(vars[key]) : `{{${key}}}`;
68
- });
69
-
70
- return result;
71
- }
72
-
73
- function injectCasedHelpers(variables) {
74
- const extras = {};
75
- for (const [key, value] of Object.entries(variables)) {
76
- if (typeof value === 'string') {
77
- extras[`${key}_PASCAL`] = applyHelper('pascalCase', value);
78
- extras[`${key}_CAMEL`] = applyHelper('camelCase', value);
79
- extras[`${key}_SNAKE`] = applyHelper('snakeCase', value);
80
- }
81
- }
82
- return extras;
83
- }
84
-
85
- function applyHelper(helper, value) {
86
- const words = value.replace(/[-_\s]+/g, ' ').trim().split(' ');
87
- switch (helper) {
88
- case 'pascalCase':
89
- return words.map(w => w.charAt(0).toUpperCase() + w.slice(1).toLowerCase()).join('');
90
- case 'camelCase':
91
- return words[0].toLowerCase() + words.slice(1).map(w => w.charAt(0).toUpperCase() + w.slice(1).toLowerCase()).join('');
92
- case 'snakeCase':
93
- return value.replace(/[-\s]+/g, '_').replace(/([a-z])([A-Z])/g, '$1_$2').toLowerCase();
94
- case 'titleCase':
95
- return words.map(w => w.charAt(0).toUpperCase() + w.slice(1).toLowerCase()).join(' ');
96
- case 'pluralize':
97
- const last = value.slice(-1);
98
- if (last === 'y') return value.slice(0, -1) + 'ies';
99
- if (last === 's') return value;
100
- return value + 's';
101
- default:
102
- return value;
103
- }
104
- }
105
-
106
- // ============================================================================
107
- // HOP Rendering
108
- // ============================================================================
109
-
110
- /**
111
- * Render a HOP template with variables
112
- * @param {string} templatePath - Path to template (relative to meta-prompts/ or absolute)
113
- * @param {Object} variables - Variables to inject
114
- * @returns {string} Rendered prompt string
115
- */
116
- export function renderHOP(templatePath, variables = {}) {
117
- // Resolve template path
118
- const paths = [
119
- templatePath,
120
- join(META_PROMPTS_DIR, templatePath),
121
- join(META_PROMPTS_DIR, templatePath + '.md'),
122
- join(process.cwd(), templatePath)
123
- ];
124
-
125
- let resolved = null;
126
- for (const p of paths) {
127
- if (existsSync(p)) {
128
- resolved = p;
129
- break;
130
- }
131
- }
132
-
133
- if (!resolved) {
134
- throw new Error(`HOP template not found: ${templatePath}\nSearched: ${paths.join(', ')}`);
135
- }
136
-
137
- const template = readFileSync(resolved, 'utf8');
138
- return compileTemplate(template, variables);
139
- }
140
-
141
- /**
142
- * Compose nested HOPs (outer wraps inner, variables bubble down)
143
- * @param {Array} hopChain - Array of { templatePath, variables } objects (outer first)
144
- * @param {Object} [sharedVariables] - Variables shared across all HOPs
145
- * @returns {string} Composed prompt string
146
- */
147
- export function composeHOPs(hopChain, sharedVariables = {}) {
148
- if (!hopChain || hopChain.length === 0) {
149
- throw new Error('hopChain must be a non-empty array');
150
- }
151
-
152
- if (hopChain.length === 1) {
153
- return renderHOP(hopChain[0].templatePath, { ...sharedVariables, ...hopChain[0].variables });
154
- }
155
-
156
- // Render inner HOPs first, then wrap with outer
157
- let innerContent = '';
158
- for (let i = hopChain.length - 1; i >= 1; i--) {
159
- const hop = hopChain[i];
160
- const vars = { ...sharedVariables, ...hop.variables, INNER_PROMPT: innerContent };
161
- innerContent = renderHOP(hop.templatePath, vars);
162
- }
163
-
164
- // Render outermost HOP with inner content
165
- const outerHop = hopChain[0];
166
- return renderHOP(outerHop.templatePath, {
167
- ...sharedVariables,
168
- ...outerHop.variables,
169
- INNER_PROMPT: innerContent
170
- });
171
- }
172
-
173
- // ============================================================================
174
- // HOP Discovery
175
- // ============================================================================
176
-
177
- /**
178
- * List all available HOPs from the meta-prompts directory
179
- * @returns {Array} Array of HOPDescriptor objects
180
- */
181
- export function listAvailableHOPs() {
182
- if (!existsSync(META_PROMPTS_DIR)) return [];
183
-
184
- const hops = [];
185
- scanDir(META_PROMPTS_DIR, META_PROMPTS_DIR, hops);
186
- return hops;
187
- }
188
-
189
- function scanDir(dir, baseDir, hops) {
190
- if (!existsSync(dir)) return;
191
-
192
- for (const entry of readdirSync(dir, { withFileTypes: true })) {
193
- const fullPath = join(dir, entry.name);
194
- if (entry.isDirectory()) {
195
- scanDir(fullPath, baseDir, hops);
196
- } else if (entry.name.endsWith('.md') || entry.name.endsWith('.hbs')) {
197
- const relPath = relative(baseDir, fullPath);
198
- const content = readFileSync(fullPath, 'utf8');
199
- const firstLine = content.split('\n')[0] || '';
200
- const description = firstLine.startsWith('#')
201
- ? firstLine.replace(/^#+\s*/, '')
202
- : 'Higher-Order Prompt template';
203
-
204
- // Extract variables from template
205
- const variables = [...new Set(
206
- (content.match(/\{\{(\w+)\}\}/g) || [])
207
- .map(m => m.replace(/\{\{|\}\}/g, ''))
208
- .filter(v => !['if', 'each', 'this', 'else', 'pascalCase', 'camelCase', 'snakeCase', 'titleCase', 'pluralize'].includes(v))
209
- )];
210
-
211
- hops.push({
212
- id: relPath.replace(/\\/g, '/').replace(/\.(md|hbs)$/, ''),
213
- path: fullPath,
214
- relativePath: relPath.replace(/\\/g, '/'),
215
- description,
216
- variables,
217
- category: relPath.split(/[\\/]/)[0]
218
- });
219
- }
220
- }
221
- }