@nathapp/nax 0.37.0 → 0.38.1

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 (72) hide show
  1. package/dist/nax.js +3258 -2894
  2. package/package.json +4 -1
  3. package/src/agents/claude-complete.ts +72 -0
  4. package/src/agents/claude-execution.ts +189 -0
  5. package/src/agents/claude-interactive.ts +77 -0
  6. package/src/agents/claude-plan.ts +23 -8
  7. package/src/agents/claude.ts +64 -349
  8. package/src/analyze/classifier.ts +2 -1
  9. package/src/cli/config-descriptions.ts +206 -0
  10. package/src/cli/config-diff.ts +103 -0
  11. package/src/cli/config-display.ts +285 -0
  12. package/src/cli/config-get.ts +55 -0
  13. package/src/cli/config.ts +7 -618
  14. package/src/cli/prompts-export.ts +58 -0
  15. package/src/cli/prompts-init.ts +200 -0
  16. package/src/cli/prompts-main.ts +237 -0
  17. package/src/cli/prompts-tdd.ts +78 -0
  18. package/src/cli/prompts.ts +10 -541
  19. package/src/commands/logs-formatter.ts +201 -0
  20. package/src/commands/logs-reader.ts +171 -0
  21. package/src/commands/logs.ts +11 -362
  22. package/src/config/loader.ts +4 -15
  23. package/src/config/runtime-types.ts +448 -0
  24. package/src/config/schema-types.ts +53 -0
  25. package/src/config/types.ts +49 -486
  26. package/src/context/auto-detect.ts +2 -1
  27. package/src/context/builder.ts +3 -2
  28. package/src/execution/crash-heartbeat.ts +77 -0
  29. package/src/execution/crash-recovery.ts +23 -365
  30. package/src/execution/crash-signals.ts +149 -0
  31. package/src/execution/crash-writer.ts +154 -0
  32. package/src/execution/parallel-coordinator.ts +278 -0
  33. package/src/execution/parallel-executor-rectification-pass.ts +117 -0
  34. package/src/execution/parallel-executor-rectify.ts +135 -0
  35. package/src/execution/parallel-executor.ts +19 -211
  36. package/src/execution/parallel-worker.ts +148 -0
  37. package/src/execution/parallel.ts +5 -404
  38. package/src/execution/pid-registry.ts +3 -8
  39. package/src/execution/runner-completion.ts +160 -0
  40. package/src/execution/runner-execution.ts +221 -0
  41. package/src/execution/runner-setup.ts +82 -0
  42. package/src/execution/runner.ts +53 -202
  43. package/src/execution/timeout-handler.ts +100 -0
  44. package/src/hooks/runner.ts +11 -21
  45. package/src/metrics/tracker.ts +7 -30
  46. package/src/pipeline/runner.ts +2 -1
  47. package/src/pipeline/stages/completion.ts +0 -1
  48. package/src/pipeline/stages/context.ts +2 -1
  49. package/src/plugins/extensions.ts +225 -0
  50. package/src/plugins/loader.ts +2 -1
  51. package/src/plugins/types.ts +16 -221
  52. package/src/prd/index.ts +2 -1
  53. package/src/prd/validate.ts +41 -0
  54. package/src/precheck/checks-blockers.ts +15 -419
  55. package/src/precheck/checks-cli.ts +68 -0
  56. package/src/precheck/checks-config.ts +102 -0
  57. package/src/precheck/checks-git.ts +87 -0
  58. package/src/precheck/checks-system.ts +163 -0
  59. package/src/review/orchestrator.ts +19 -6
  60. package/src/review/runner.ts +17 -5
  61. package/src/routing/chain.ts +2 -1
  62. package/src/routing/loader.ts +2 -5
  63. package/src/tdd/orchestrator.ts +2 -1
  64. package/src/tdd/verdict-reader.ts +266 -0
  65. package/src/tdd/verdict.ts +6 -271
  66. package/src/utils/errors.ts +12 -0
  67. package/src/utils/git.ts +12 -5
  68. package/src/utils/json-file.ts +72 -0
  69. package/src/verification/executor.ts +2 -1
  70. package/src/verification/smart-runner.ts +23 -3
  71. package/src/worktree/manager.ts +9 -3
  72. package/src/worktree/merge.ts +3 -2
package/src/cli/config.ts CHANGED
@@ -1,625 +1,14 @@
1
1
  /**
2
2
  * Config Command
3
3
  *
4
- * Displays effective merged configuration with inline explanations.
4
+ * Re-exports config display and loading utilities.
5
5
  */
6
6
 
7
- import { existsSync } from "node:fs";
8
- import { join } from "node:path";
9
- import { DEFAULT_CONFIG } from "../config/defaults";
10
- import { findProjectDir, globalConfigPath } from "../config/loader";
11
- import { deepMergeConfig } from "../config/merger";
12
- import type { NaxConfig } from "../config/schema";
7
+ // Display exports
8
+ export { configCommand, FIELD_DESCRIPTIONS, type ConfigCommandOptions } from "./config-display";
13
9
 
14
- /** Field descriptions for human-readable output */
15
- const FIELD_DESCRIPTIONS: Record<string, string> = {
16
- // Top-level
17
- version: "Configuration schema version",
10
+ // Loading exports
11
+ export { loadConfigFile, loadGlobalConfig, loadProjectConfig } from "./config-get";
18
12
 
19
- // Models
20
- models: "Model tier definitions (fast/balanced/powerful)",
21
- "models.fast": "Fast model for lightweight tasks (e.g., haiku)",
22
- "models.balanced": "Balanced model for general coding (e.g., sonnet)",
23
- "models.powerful": "Powerful model for complex tasks (e.g., opus)",
24
-
25
- // Auto mode
26
- autoMode:
27
- "Auto mode configuration for agent orchestration. Enables multi-agent routing with model tier selection per task complexity and escalation on failures.",
28
- "autoMode.enabled": "Enable automatic agent selection and escalation",
29
- "autoMode.defaultAgent":
30
- "Default agent to use when no specific agent is requested. Examples: 'claude' (Claude Code), 'codex' (GitHub Copilot), 'opencode' (OpenCode). The agent handles the main coding tasks.",
31
- "autoMode.fallbackOrder":
32
- 'Fallback order for agent selection when the primary agent is rate-limited, unavailable, or fails. Tries each agent in sequence until one succeeds. Example: ["claude", "codex", "opencode"] means try Claude first, then Copilot, then OpenCode.',
33
- "autoMode.complexityRouting":
34
- "Model tier routing rules mapped to story complexity levels. Determines which model (fast/balanced/powerful) to use based on task complexity: simple → fast, medium → balanced, complex → powerful, expert → powerful.",
35
- "autoMode.complexityRouting.simple": "Model tier for simple tasks (low complexity, straightforward changes)",
36
- "autoMode.complexityRouting.medium": "Model tier for medium tasks (moderate complexity, multi-file changes)",
37
- "autoMode.complexityRouting.complex": "Model tier for complex tasks (high complexity, architectural decisions)",
38
- "autoMode.complexityRouting.expert":
39
- "Model tier for expert tasks (highest complexity, novel problems, design patterns)",
40
- "autoMode.escalation":
41
- "Escalation settings for failed stories. When a story fails after max attempts at current tier, escalate to the next tier in tierOrder. Enables progressive use of more powerful models.",
42
- "autoMode.escalation.enabled": "Enable tier escalation on failure",
43
- "autoMode.escalation.tierOrder":
44
- 'Ordered tier escalation chain with per-tier attempt budgets. Format: [{"tier": "fast", "attempts": 2}, {"tier": "balanced", "attempts": 2}, {"tier": "powerful", "attempts": 1}]. Allows each tier to attempt fixes before escalating to the next.',
45
- "autoMode.escalation.escalateEntireBatch":
46
- "When enabled, escalate all stories in a batch if one fails. When disabled, only the failing story escalates (allows parallel attempts at different tiers).",
47
-
48
- // Routing
49
- routing: "Model routing strategy configuration",
50
- "routing.strategy": "Routing strategy: keyword | llm | manual | adaptive | custom",
51
- "routing.customStrategyPath": "Path to custom routing strategy (if strategy=custom)",
52
- "routing.adaptive": "Adaptive routing settings",
53
- "routing.adaptive.minSamples": "Minimum samples before adaptive routing activates",
54
- "routing.adaptive.costThreshold": "Cost threshold for strategy switching (0-1)",
55
- "routing.adaptive.fallbackStrategy": "Fallback strategy if adaptive fails",
56
- "routing.llm": "LLM-based routing settings",
57
- "routing.llm.model": "Model tier for routing decisions",
58
- "routing.llm.fallbackToKeywords": "Fall back to keyword routing on LLM failure",
59
- "routing.llm.cacheDecisions": "Cache routing decisions per story ID",
60
- "routing.llm.mode": "Routing mode: one-shot | per-story | hybrid",
61
- "routing.llm.timeoutMs": "Timeout for LLM routing call in milliseconds",
62
-
63
- // Execution
64
- execution: "Execution limits and timeouts",
65
- "execution.maxIterations": "Max iterations per feature run (auto-calculated if not set)",
66
- "execution.iterationDelayMs": "Delay between iterations in milliseconds",
67
- "execution.costLimit": "Max cost in USD before pausing execution",
68
- "execution.sessionTimeoutSeconds": "Timeout per agent coding session in seconds",
69
- "execution.verificationTimeoutSeconds": "Verification subprocess timeout in seconds",
70
- "execution.maxStoriesPerFeature": "Max stories per feature (prevents memory exhaustion)",
71
- "execution.contextProviderTokenBudget": "Token budget for plugin context providers",
72
- "execution.lintCommand": "Lint command override (null=disabled, undefined=auto-detect)",
73
- "execution.typecheckCommand": "Typecheck command override (null=disabled, undefined=auto-detect)",
74
- "execution.dangerouslySkipPermissions": "Skip permissions for agent (use with caution)",
75
- "execution.rectification": "Rectification loop settings (retry failed tests)",
76
- "execution.rectification.enabled": "Enable rectification loop",
77
- "execution.rectification.maxRetries": "Max retry attempts per story",
78
- "execution.rectification.fullSuiteTimeoutSeconds": "Timeout for full test suite run in seconds",
79
- "execution.rectification.maxFailureSummaryChars": "Max characters in failure summary",
80
- "execution.rectification.abortOnIncreasingFailures": "Abort if failure count increases",
81
- "execution.regressionGate": "Regression gate settings (full suite after scoped tests)",
82
- "execution.regressionGate.enabled": "Enable full-suite regression gate",
83
- "execution.regressionGate.timeoutSeconds": "Timeout for regression run in seconds",
84
-
85
- // Quality
86
- quality: "Quality gate configuration",
87
- "quality.requireTypecheck": "Require typecheck to pass",
88
- "quality.requireLint": "Require lint to pass",
89
- "quality.requireTests": "Require tests to pass",
90
- "quality.commands": "Custom quality commands",
91
- "quality.commands.typecheck": "Custom typecheck command",
92
- "quality.commands.lint": "Custom lint command",
93
- "quality.commands.test": "Custom test command",
94
- "quality.forceExit": "Append --forceExit to test command (prevents hangs)",
95
- "quality.detectOpenHandles": "Append --detectOpenHandles on timeout",
96
- "quality.detectOpenHandlesRetries": "Max retries with --detectOpenHandles",
97
- "quality.gracePeriodMs": "Grace period in ms after SIGTERM before SIGKILL",
98
- "quality.drainTimeoutMs": "Deadline in ms to drain stdout/stderr after kill",
99
- "quality.shell": "Shell to use for verification commands",
100
- "quality.stripEnvVars": "Environment variables to strip during verification",
101
- "quality.environmentalEscalationDivisor": "Divisor for environmental failure early escalation",
102
-
103
- // TDD
104
- tdd: "Test-driven development configuration",
105
- "tdd.maxRetries": "Max retries per TDD session before escalating",
106
- "tdd.autoVerifyIsolation": "Auto-verify test isolation between sessions",
107
- "tdd.strategy": "TDD strategy: auto | strict | lite | off",
108
- "tdd.autoApproveVerifier": "Auto-approve legitimate fixes in verifier session",
109
- "tdd.sessionTiers": "Per-session model tier overrides",
110
- "tdd.sessionTiers.testWriter": "Model tier for test-writer session",
111
- "tdd.sessionTiers.implementer": "Model tier for implementer session",
112
- "tdd.sessionTiers.verifier": "Model tier for verifier session",
113
- "tdd.testWriterAllowedPaths": "Glob patterns for files test-writer can modify",
114
- "tdd.rollbackOnFailure": "Rollback git changes when TDD fails",
115
- "tdd.greenfieldDetection": "Force test-after on projects with no test files",
116
-
117
- // Constitution
118
- constitution: "Constitution settings (core rules and constraints)",
119
- "constitution.enabled": "Enable constitution loading and injection",
120
- "constitution.path": "Path to constitution file (relative to nax/ directory)",
121
- "constitution.maxTokens": "Maximum tokens allowed for constitution content",
122
- "constitution.skipGlobal": "Skip loading global constitution",
123
-
124
- // Analyze
125
- analyze: "Feature analysis settings",
126
- "analyze.llmEnhanced": "Enable LLM-enhanced analysis",
127
- "analyze.model": "Model tier for decompose and classify",
128
- "analyze.fallbackToKeywords": "Fall back to keyword matching on LLM failure",
129
- "analyze.maxCodebaseSummaryTokens": "Max tokens for codebase summary",
130
-
131
- // Review
132
- review: "Review phase configuration",
133
- "review.enabled": "Enable review phase",
134
- "review.checks": "List of checks to run (typecheck, lint, test)",
135
- "review.commands": "Custom commands per check",
136
- "review.commands.typecheck": "Custom typecheck command for review",
137
- "review.commands.lint": "Custom lint command for review",
138
- "review.commands.test": "Custom test command for review",
139
-
140
- // Plan
141
- plan: "Planning phase configuration",
142
- "plan.model": "Model tier for planning",
143
- "plan.outputPath": "Output path for generated spec (relative to nax/)",
144
-
145
- // Acceptance
146
- acceptance: "Acceptance test configuration",
147
- "acceptance.enabled": "Enable acceptance test generation and validation",
148
- "acceptance.maxRetries": "Max retry loops for fix stories",
149
- "acceptance.generateTests": "Generate acceptance tests during analyze",
150
- "acceptance.testPath": "Path to acceptance test file (relative to feature dir)",
151
-
152
- // Context
153
- context: "Context injection configuration",
154
- "context.fileInjection":
155
- "Mode: 'disabled' (default, MCP-aware agents pull context on-demand) | 'keyword' (legacy git-grep injection for non-MCP agents). Set context.fileInjection in config.",
156
- "context.testCoverage": "Test coverage context settings",
157
- "context.testCoverage.enabled": "Enable test coverage context injection",
158
- "context.testCoverage.detail": "Detail level: names-only | names-and-counts | describe-blocks",
159
- "context.testCoverage.maxTokens": "Max tokens for test summary",
160
- "context.testCoverage.testDir": "Test directory relative to workdir",
161
- "context.testCoverage.testPattern": "Glob pattern for test files",
162
- "context.testCoverage.scopeToStory": "Scope test coverage to story-relevant files only",
163
- "context.autoDetect": "Auto-detect relevant files settings",
164
- "context.autoDetect.enabled": "Enable auto-detection of relevant files",
165
- "context.autoDetect.maxFiles": "Max files to auto-detect",
166
- "context.autoDetect.traceImports": "Trace imports to find related files",
167
-
168
- // Optimizer
169
- optimizer: "Prompt optimizer configuration",
170
- "optimizer.enabled": "Enable prompt optimizer",
171
- "optimizer.strategy": "Optimization strategy: rule-based | llm | noop",
172
-
173
- // Plugins
174
- plugins: "Plugin configurations",
175
-
176
- // Hooks
177
- hooks: "Hooks configuration",
178
- "hooks.skipGlobal": "Skip loading global hooks",
179
-
180
- // Interaction
181
- interaction: "Interaction plugin configuration",
182
- "interaction.plugin": "Plugin to use for interactions (default: cli)",
183
- "interaction.config": "Plugin-specific configuration",
184
- "interaction.defaults": "Default interaction settings",
185
- "interaction.defaults.timeout": "Default timeout in milliseconds",
186
- "interaction.defaults.fallback": "Default fallback behavior: continue | skip | escalate | abort",
187
- "interaction.triggers": "Enable/disable built-in triggers",
188
-
189
- // Precheck
190
- precheck: "Precheck configuration (run before analysis)",
191
- "precheck.storySizeGate": "Story size gate settings",
192
- "precheck.storySizeGate.enabled": "Enable story size gate",
193
- "precheck.storySizeGate.maxAcCount": "Max acceptance criteria count before flagging",
194
- "precheck.storySizeGate.maxDescriptionLength": "Max description character length before flagging",
195
- "precheck.storySizeGate.maxBulletPoints": "Max bullet point count before flagging",
196
-
197
- // Prompts
198
- prompts: "Prompt template overrides (PB-003: PromptBuilder)",
199
- "prompts.overrides": "Custom prompt template files for specific roles",
200
- "prompts.overrides.test-writer": 'Path to custom test-writer prompt (e.g., ".nax/prompts/test-writer.md")',
201
- "prompts.overrides.implementer": 'Path to custom implementer prompt (e.g., ".nax/prompts/implementer.md")',
202
- "prompts.overrides.verifier": 'Path to custom verifier prompt (e.g., ".nax/prompts/verifier.md")',
203
- "prompts.overrides.single-session": 'Path to custom single-session prompt (e.g., ".nax/prompts/single-session.md")',
204
-
205
- // Decompose
206
- decompose: "Story decomposition configuration (SD-003)",
207
- "decompose.trigger": "Decomposition trigger mode: auto | confirm | disabled",
208
- "decompose.maxAcceptanceCriteria": "Max acceptance criteria before flagging as oversized (default: 6)",
209
- "decompose.maxSubstories": "Max number of substories to generate (default: 5)",
210
- "decompose.maxSubstoryComplexity": "Max complexity for any generated substory (default: 'medium')",
211
- "decompose.maxRetries": "Max retries on decomposition validation failure (default: 2)",
212
- "decompose.model": "Model tier for decomposition LLM calls (default: 'balanced')",
213
- };
214
-
215
- /** Options for config command */
216
- export interface ConfigCommandOptions {
217
- /** Show field explanations */
218
- explain?: boolean;
219
- /** Show only fields where project overrides global */
220
- diff?: boolean;
221
- }
222
-
223
- /**
224
- * Load and parse a JSON config file.
225
- *
226
- * @param path - Path to config file
227
- * @returns Parsed config object or null if file doesn't exist
228
- */
229
- async function loadConfigFile(path: string): Promise<Record<string, unknown> | null> {
230
- if (!existsSync(path)) return null;
231
- try {
232
- return await Bun.file(path).json();
233
- } catch {
234
- return null;
235
- }
236
- }
237
-
238
- /**
239
- * Load global config merged with defaults.
240
- *
241
- * @returns Global config object (defaults + global overrides)
242
- */
243
- async function loadGlobalConfig(): Promise<Record<string, unknown>> {
244
- const globalPath = globalConfigPath();
245
- const globalConf = await loadConfigFile(globalPath);
246
-
247
- if (!globalConf) {
248
- return structuredClone(DEFAULT_CONFIG as unknown as Record<string, unknown>);
249
- }
250
-
251
- return deepMergeConfig(structuredClone(DEFAULT_CONFIG as unknown as Record<string, unknown>), globalConf);
252
- }
253
-
254
- /**
255
- * Load project config (raw, without defaults or global).
256
- *
257
- * @returns Project config object or null if not found
258
- */
259
- async function loadProjectConfig(): Promise<Record<string, unknown> | null> {
260
- const projectDir = findProjectDir();
261
- if (!projectDir) return null;
262
-
263
- const projectPath = join(projectDir, "config.json");
264
- return await loadConfigFile(projectPath);
265
- }
266
-
267
- /**
268
- * Represents a single config field difference.
269
- */
270
- interface ConfigDiff {
271
- /** Dot-separated field path (e.g., "execution.maxIterations") */
272
- path: string;
273
- /** Value from global config */
274
- globalValue: unknown;
275
- /** Value from project config */
276
- projectValue: unknown;
277
- }
278
-
279
- /**
280
- * Deep diff two config objects, returning only fields that differ.
281
- *
282
- * @param global - Global config (defaults + global overrides)
283
- * @param project - Project config (raw overrides only)
284
- * @param currentPath - Current path in object tree (for recursion)
285
- * @returns Array of differences
286
- */
287
- function deepDiffConfigs(
288
- global: Record<string, unknown>,
289
- project: Record<string, unknown>,
290
- currentPath: string[] = [],
291
- ): ConfigDiff[] {
292
- const diffs: ConfigDiff[] = [];
293
-
294
- // Iterate over project config keys (we only care about what project overrides)
295
- for (const key of Object.keys(project)) {
296
- const projectValue = project[key];
297
- const globalValue = global[key];
298
- const path = [...currentPath, key];
299
- const pathStr = path.join(".");
300
-
301
- // Handle nested objects
302
- if (
303
- projectValue !== null &&
304
- typeof projectValue === "object" &&
305
- !Array.isArray(projectValue) &&
306
- globalValue !== null &&
307
- typeof globalValue === "object" &&
308
- !Array.isArray(globalValue)
309
- ) {
310
- // Recurse into nested object
311
- const nestedDiffs = deepDiffConfigs(
312
- globalValue as Record<string, unknown>,
313
- projectValue as Record<string, unknown>,
314
- path,
315
- );
316
- diffs.push(...nestedDiffs);
317
- } else {
318
- // Compare primitive values or arrays
319
- if (!deepEqual(projectValue, globalValue)) {
320
- diffs.push({
321
- path: pathStr,
322
- globalValue,
323
- projectValue,
324
- });
325
- }
326
- }
327
- }
328
-
329
- return diffs;
330
- }
331
-
332
- /**
333
- * Deep equality check for two values.
334
- *
335
- * @param a - First value
336
- * @param b - Second value
337
- * @returns True if values are deeply equal
338
- */
339
- function deepEqual(a: unknown, b: unknown): boolean {
340
- if (a === b) return true;
341
- if (a === null || b === null) return false;
342
- if (a === undefined || b === undefined) return false;
343
-
344
- // Handle arrays
345
- if (Array.isArray(a) && Array.isArray(b)) {
346
- if (a.length !== b.length) return false;
347
- return a.every((val, idx) => deepEqual(val, b[idx]));
348
- }
349
-
350
- // Handle objects
351
- if (typeof a === "object" && typeof b === "object") {
352
- const aObj = a as Record<string, unknown>;
353
- const bObj = b as Record<string, unknown>;
354
- const aKeys = Object.keys(aObj);
355
- const bKeys = Object.keys(bObj);
356
-
357
- if (aKeys.length !== bKeys.length) return false;
358
-
359
- return aKeys.every((key) => deepEqual(aObj[key], bObj[key]));
360
- }
361
-
362
- return false;
363
- }
364
-
365
- /**
366
- * Display effective configuration with optional explanations.
367
- *
368
- * @param config - Loaded configuration
369
- * @param options - Command options
370
- */
371
- export async function configCommand(config: NaxConfig, options: ConfigCommandOptions = {}): Promise<void> {
372
- const { explain = false, diff = false } = options;
373
-
374
- // Validate mutually exclusive flags
375
- if (explain && diff) {
376
- console.error("Error: --explain and --diff are mutually exclusive");
377
- process.exit(1);
378
- }
379
-
380
- // Determine sources
381
- const sources = determineConfigSources();
382
-
383
- if (diff) {
384
- // Diff mode: show only fields where project overrides global
385
- const projectConf = await loadProjectConfig();
386
-
387
- if (!projectConf) {
388
- console.log("No project config found — using global defaults");
389
- return;
390
- }
391
-
392
- const globalConf = await loadGlobalConfig();
393
- const diffs = deepDiffConfigs(globalConf, projectConf);
394
-
395
- if (diffs.length === 0) {
396
- console.log("No differences between project and global config");
397
- return;
398
- }
399
-
400
- console.log("# Config Differences (Project overrides Global)");
401
- console.log();
402
- console.log("─".repeat(80));
403
- console.log(`${"Field".padEnd(40)}${"Project Value".padEnd(20)}Global Value`);
404
- console.log("─".repeat(80));
405
-
406
- for (const diff of diffs) {
407
- const path = diff.path.padEnd(40);
408
- const projectVal = formatValueForTable(diff.projectValue);
409
- const globalVal = formatValueForTable(diff.globalValue);
410
-
411
- console.log(`${path}${projectVal.padEnd(20)}${globalVal}`);
412
-
413
- // Show description if available
414
- const description = FIELD_DESCRIPTIONS[diff.path];
415
- if (description) {
416
- console.log(`${"".padEnd(40)}↳ ${description}`);
417
- }
418
- }
419
-
420
- console.log("─".repeat(80));
421
- } else if (explain) {
422
- console.log("# nax Configuration");
423
- console.log("#");
424
- console.log("# Resolution order: defaults → global → project → CLI overrides");
425
- console.log(`# Global config: ${sources.global ? sources.global : "(not found)"}`);
426
- console.log(`# Project config: ${sources.project ? sources.project : "(not found)"}`);
427
- console.log();
428
-
429
- // Recursively display config with descriptions
430
- displayConfigWithDescriptions(config, [], sources);
431
- } else {
432
- // Default view: JSON with header showing config sources
433
- console.log("// nax Configuration");
434
- console.log("// Resolution order: defaults → global → project → CLI overrides");
435
- console.log(`// Global config: ${sources.global ? sources.global : "(not found)"}`);
436
- console.log(`// Project config: ${sources.project ? sources.project : "(not found)"}`);
437
- console.log();
438
- console.log(JSON.stringify(config, null, 2));
439
- }
440
- }
441
-
442
- /**
443
- * Determine which config files are present.
444
- *
445
- * @returns Paths to global and project config files (null if not found)
446
- */
447
- function determineConfigSources(): { global: string | null; project: string | null } {
448
- const globalPath = globalConfigPath();
449
- const projectDir = findProjectDir();
450
- const projectPath = projectDir ? join(projectDir, "config.json") : null;
451
-
452
- return {
453
- global: fileExists(globalPath) ? globalPath : null,
454
- project: projectPath && fileExists(projectPath) ? projectPath : null,
455
- };
456
- }
457
-
458
- /**
459
- * Check if a file exists.
460
- *
461
- * @param path - File path to check
462
- * @returns True if file exists, false otherwise
463
- */
464
- function fileExists(path: string): boolean {
465
- return existsSync(path);
466
- }
467
-
468
- /**
469
- * Display configuration with descriptions and source annotations.
470
- *
471
- * @param obj - Configuration object or value
472
- * @param path - Current path in config tree
473
- * @param sources - Config source paths
474
- * @param indent - Current indentation level
475
- */
476
- function displayConfigWithDescriptions(
477
- obj: unknown,
478
- path: string[],
479
- sources: { global: string | null; project: string | null },
480
- indent = 0,
481
- ): void {
482
- const indentStr = " ".repeat(indent);
483
- const pathStr = path.join(".");
484
-
485
- // Handle primitives and arrays
486
- if (obj === null || obj === undefined || typeof obj !== "object" || Array.isArray(obj)) {
487
- const description = FIELD_DESCRIPTIONS[pathStr];
488
- const value = formatValue(obj);
489
-
490
- if (description) {
491
- console.log(`${indentStr}# ${description}`);
492
- }
493
-
494
- const key = path[path.length - 1] || "";
495
- console.log(`${indentStr}${key}: ${value}`);
496
- console.log();
497
- return;
498
- }
499
-
500
- // Handle objects
501
- const entries = Object.entries(obj as Record<string, unknown>);
502
-
503
- // Special handling for prompts section: always show overrides documentation
504
- const objAsRecord = obj as Record<string, unknown>;
505
- const isPromptsSection = path.join(".") === "prompts";
506
- if (isPromptsSection && !objAsRecord.overrides) {
507
- // Add prompts.overrides documentation even if not in config
508
- const description = FIELD_DESCRIPTIONS["prompts.overrides"];
509
- if (description) {
510
- console.log(`${indentStr}# prompts.overrides: ${description}`);
511
- }
512
-
513
- // Show role examples
514
- const roles = ["test-writer", "implementer", "verifier", "single-session"];
515
- console.log(`${indentStr}overrides:`);
516
- for (const role of roles) {
517
- const roleDesc = FIELD_DESCRIPTIONS[`prompts.overrides.${role}`];
518
- if (roleDesc) {
519
- console.log(`${indentStr} # ${roleDesc}`);
520
- // Extract the example path from description
521
- const match = roleDesc.match(/e\.g\., "([^"]+)"/);
522
- if (match) {
523
- console.log(`${indentStr} # ${role}: "${match[1]}"`);
524
- }
525
- }
526
- }
527
- console.log();
528
- return;
529
- }
530
-
531
- for (let i = 0; i < entries.length; i++) {
532
- const [key, value] = entries[i];
533
- const currentPath = [...path, key];
534
- const currentPathStr = currentPath.join(".");
535
- const description = FIELD_DESCRIPTIONS[currentPathStr];
536
-
537
- // Display description comment if available
538
- if (description) {
539
- // Include path for direct subsections of key configuration sections
540
- // (to improve clarity of important configs like multi-agent setup)
541
- const pathParts = currentPathStr.split(".");
542
- // Only show path for 2-level paths (e.g., "autoMode.enabled", "models.fast")
543
- // to keep deeply nested descriptions concise
544
- const isDirectSubsection = pathParts.length === 2;
545
- const isKeySection = ["prompts", "autoMode", "models", "routing"].includes(pathParts[0]);
546
- const shouldIncludePath = isKeySection && isDirectSubsection;
547
- const comment = shouldIncludePath ? `${currentPathStr}: ${description}` : description;
548
- console.log(`${indentStr}# ${comment}`);
549
- }
550
-
551
- // Handle nested objects
552
- if (value !== null && typeof value === "object" && !Array.isArray(value)) {
553
- console.log(`${indentStr}${key}:`);
554
- displayConfigWithDescriptions(value, currentPath, sources, indent + 1);
555
- } else {
556
- // Display value
557
- const formattedValue = formatValue(value);
558
- console.log(`${indentStr}${key}: ${formattedValue}`);
559
-
560
- // Add blank line after each top-level section
561
- if (indent === 0 && i < entries.length - 1) {
562
- console.log();
563
- }
564
- }
565
- }
566
- }
567
-
568
- /**
569
- * Format a config value for display.
570
- *
571
- * @param value - Value to format
572
- * @returns Formatted string
573
- */
574
- function formatValue(value: unknown): string {
575
- if (value === null) return "null";
576
- if (value === undefined) return "undefined";
577
- if (typeof value === "string") return `"${value}"`;
578
- if (typeof value === "boolean") return String(value);
579
- if (typeof value === "number") return String(value);
580
- if (Array.isArray(value)) {
581
- if (value.length === 0) return "[]";
582
- if (value.length <= 3) {
583
- return `[${value.map((v) => formatValue(v)).join(", ")}]`;
584
- }
585
- return `[${value
586
- .slice(0, 3)
587
- .map((v) => formatValue(v))
588
- .join(", ")}, ... (${value.length} items)]`;
589
- }
590
- if (typeof value === "object") {
591
- return JSON.stringify(value);
592
- }
593
- return String(value);
594
- }
595
-
596
- /**
597
- * Format a config value for table display (shorter format).
598
- *
599
- * @param value - Value to format
600
- * @returns Formatted string (max ~18 chars)
601
- */
602
- function formatValueForTable(value: unknown): string {
603
- if (value === null) return "null";
604
- if (value === undefined) return "undefined";
605
- if (typeof value === "string") {
606
- if (value.length > 15) {
607
- return `"${value.slice(0, 12)}..."`;
608
- }
609
- return `"${value}"`;
610
- }
611
- if (typeof value === "boolean") return String(value);
612
- if (typeof value === "number") return String(value);
613
- if (Array.isArray(value)) {
614
- if (value.length === 0) return "[]";
615
- return `[...${value.length}]`;
616
- }
617
- if (typeof value === "object") {
618
- const str = JSON.stringify(value);
619
- if (str.length > 15) {
620
- return "{...}";
621
- }
622
- return str;
623
- }
624
- return String(value);
625
- }
13
+ // Diff exports
14
+ export { deepDiffConfigs, deepEqual, type ConfigDiff } from "./config-diff";
@@ -0,0 +1,58 @@
1
+ /**
2
+ * Prompts Export Command
3
+ *
4
+ * Export default prompts for a given role.
5
+ */
6
+
7
+ import type { UserStory } from "../prd";
8
+ import { PromptBuilder } from "../prompts";
9
+
10
+ const VALID_EXPORT_ROLES = ["test-writer", "implementer", "verifier", "single-session", "tdd-simple"] as const;
11
+
12
+ export interface ExportPromptCommandOptions {
13
+ /** Role to export prompt for */
14
+ role: string;
15
+ /** Optional output file path (stdout if not provided) */
16
+ out?: string;
17
+ }
18
+
19
+ /**
20
+ * Execute the `nax prompts --export <role>` command.
21
+ *
22
+ * Builds the full default prompt for the given role using a stub story
23
+ * and empty context, then writes it to stdout or a file.
24
+ *
25
+ * @param options - Command options
26
+ */
27
+ export async function exportPromptCommand(options: ExportPromptCommandOptions): Promise<void> {
28
+ const { role, out } = options;
29
+
30
+ if (!VALID_EXPORT_ROLES.includes(role as (typeof VALID_EXPORT_ROLES)[number])) {
31
+ console.error(`[ERROR] Invalid role: "${role}". Valid roles: ${VALID_EXPORT_ROLES.join(", ")}`);
32
+ process.exit(1);
33
+ }
34
+
35
+ const stubStory: UserStory = {
36
+ id: "EXAMPLE",
37
+ title: "Example story",
38
+ description: "Story ID: EXAMPLE. This is a placeholder story used to demonstrate the default prompt.",
39
+ acceptanceCriteria: ["AC-1: Example criterion"],
40
+ tags: [],
41
+ dependencies: [],
42
+ status: "pending",
43
+ passes: false,
44
+ escalations: [],
45
+ attempts: 0,
46
+ };
47
+
48
+ const prompt = await PromptBuilder.for(role as (typeof VALID_EXPORT_ROLES)[number])
49
+ .story(stubStory)
50
+ .build();
51
+
52
+ if (out) {
53
+ await Bun.write(out, prompt);
54
+ console.log(`[OK] Exported prompt for "${role}" to ${out}`);
55
+ } else {
56
+ console.log(prompt);
57
+ }
58
+ }