@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
@@ -0,0 +1,206 @@
1
+ /**
2
+ * Configuration Field Descriptions
3
+ *
4
+ * Human-readable descriptions for all configuration fields.
5
+ * Extracted from config-display.ts for better maintainability.
6
+ */
7
+
8
+ export const FIELD_DESCRIPTIONS: Record<string, string> = {
9
+ // Top-level
10
+ version: "Configuration schema version",
11
+
12
+ // Models
13
+ models: "Model tier definitions (fast/balanced/powerful)",
14
+ "models.fast": "Fast model for lightweight tasks (e.g., haiku)",
15
+ "models.balanced": "Balanced model for general coding (e.g., sonnet)",
16
+ "models.powerful": "Powerful model for complex tasks (e.g., opus)",
17
+
18
+ // Auto mode
19
+ autoMode:
20
+ "Auto mode configuration for agent orchestration. Enables multi-agent routing with model tier selection per task complexity and escalation on failures.",
21
+ "autoMode.enabled": "Enable automatic agent selection and escalation",
22
+ "autoMode.defaultAgent":
23
+ "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.",
24
+ "autoMode.fallbackOrder":
25
+ '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.',
26
+ "autoMode.complexityRouting":
27
+ "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.",
28
+ "autoMode.complexityRouting.simple": "Model tier for simple tasks (low complexity, straightforward changes)",
29
+ "autoMode.complexityRouting.medium": "Model tier for medium tasks (moderate complexity, multi-file changes)",
30
+ "autoMode.complexityRouting.complex": "Model tier for complex tasks (high complexity, architectural decisions)",
31
+ "autoMode.complexityRouting.expert":
32
+ "Model tier for expert tasks (highest complexity, novel problems, design patterns)",
33
+ "autoMode.escalation":
34
+ "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.",
35
+ "autoMode.escalation.enabled": "Enable tier escalation on failure",
36
+ "autoMode.escalation.tierOrder":
37
+ '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.',
38
+ "autoMode.escalation.escalateEntireBatch":
39
+ "When enabled, escalate all stories in a batch if one fails. When disabled, only the failing story escalates (allows parallel attempts at different tiers).",
40
+
41
+ // Routing
42
+ routing: "Model routing strategy configuration",
43
+ "routing.strategy": "Routing strategy: keyword | llm | manual | adaptive | custom",
44
+ "routing.customStrategyPath": "Path to custom routing strategy (if strategy=custom)",
45
+ "routing.adaptive": "Adaptive routing settings",
46
+ "routing.adaptive.minSamples": "Minimum samples before adaptive routing activates",
47
+ "routing.adaptive.costThreshold": "Cost threshold for strategy switching (0-1)",
48
+ "routing.adaptive.fallbackStrategy": "Fallback strategy if adaptive fails",
49
+ "routing.llm": "LLM-based routing settings",
50
+ "routing.llm.model": "Model tier for routing decisions",
51
+ "routing.llm.fallbackToKeywords": "Fall back to keyword routing on LLM failure",
52
+ "routing.llm.cacheDecisions": "Cache routing decisions per story ID",
53
+ "routing.llm.mode": "Routing mode: one-shot | per-story | hybrid",
54
+ "routing.llm.timeoutMs": "Timeout for LLM routing call in milliseconds",
55
+
56
+ // Execution
57
+ execution: "Execution limits and timeouts",
58
+ "execution.maxIterations": "Max iterations per feature run (auto-calculated if not set)",
59
+ "execution.iterationDelayMs": "Delay between iterations in milliseconds",
60
+ "execution.costLimit": "Max cost in USD before pausing execution",
61
+ "execution.sessionTimeoutSeconds": "Timeout per agent coding session in seconds",
62
+ "execution.verificationTimeoutSeconds": "Verification subprocess timeout in seconds",
63
+ "execution.maxStoriesPerFeature": "Max stories per feature (prevents memory exhaustion)",
64
+ "execution.contextProviderTokenBudget": "Token budget for plugin context providers",
65
+ "execution.lintCommand": "Lint command override (null=disabled, undefined=auto-detect)",
66
+ "execution.typecheckCommand": "Typecheck command override (null=disabled, undefined=auto-detect)",
67
+ "execution.dangerouslySkipPermissions": "Skip permissions for agent (use with caution)",
68
+ "execution.rectification": "Rectification loop settings (retry failed tests)",
69
+ "execution.rectification.enabled": "Enable rectification loop",
70
+ "execution.rectification.maxRetries": "Max retry attempts per story",
71
+ "execution.rectification.fullSuiteTimeoutSeconds": "Timeout for full test suite run in seconds",
72
+ "execution.rectification.maxFailureSummaryChars": "Max characters in failure summary",
73
+ "execution.rectification.abortOnIncreasingFailures": "Abort if failure count increases",
74
+ "execution.regressionGate": "Regression gate settings (full suite after scoped tests)",
75
+ "execution.regressionGate.enabled": "Enable full-suite regression gate",
76
+ "execution.regressionGate.timeoutSeconds": "Timeout for regression run in seconds",
77
+
78
+ // Quality
79
+ quality: "Quality gate configuration",
80
+ "quality.requireTypecheck": "Require typecheck to pass",
81
+ "quality.requireLint": "Require lint to pass",
82
+ "quality.requireTests": "Require tests to pass",
83
+ "quality.commands": "Custom quality commands",
84
+ "quality.commands.typecheck": "Custom typecheck command",
85
+ "quality.commands.lint": "Custom lint command",
86
+ "quality.commands.test": "Custom test command",
87
+ "quality.forceExit": "Append --forceExit to test command (prevents hangs)",
88
+ "quality.detectOpenHandles": "Append --detectOpenHandles on timeout",
89
+ "quality.detectOpenHandlesRetries": "Max retries with --detectOpenHandles",
90
+ "quality.gracePeriodMs": "Grace period in ms after SIGTERM before SIGKILL",
91
+ "quality.drainTimeoutMs": "Deadline in ms to drain stdout/stderr after kill",
92
+ "quality.shell": "Shell to use for verification commands",
93
+ "quality.stripEnvVars": "Environment variables to strip during verification",
94
+ "quality.environmentalEscalationDivisor": "Divisor for environmental failure early escalation",
95
+
96
+ // TDD
97
+ tdd: "Test-driven development configuration",
98
+ "tdd.maxRetries": "Max retries per TDD session before escalating",
99
+ "tdd.autoVerifyIsolation": "Auto-verify test isolation between sessions",
100
+ "tdd.strategy": "TDD strategy: auto | strict | lite | off",
101
+ "tdd.autoApproveVerifier": "Auto-approve legitimate fixes in verifier session",
102
+ "tdd.sessionTiers": "Per-session model tier overrides",
103
+ "tdd.sessionTiers.testWriter": "Model tier for test-writer session",
104
+ "tdd.sessionTiers.implementer": "Model tier for implementer session",
105
+ "tdd.sessionTiers.verifier": "Model tier for verifier session",
106
+ "tdd.testWriterAllowedPaths": "Glob patterns for files test-writer can modify",
107
+ "tdd.rollbackOnFailure": "Rollback git changes when TDD fails",
108
+ "tdd.greenfieldDetection": "Force test-after on projects with no test files",
109
+
110
+ // Constitution
111
+ constitution: "Constitution settings (core rules and constraints)",
112
+ "constitution.enabled": "Enable constitution loading and injection",
113
+ "constitution.path": "Path to constitution file (relative to nax/ directory)",
114
+ "constitution.maxTokens": "Maximum tokens allowed for constitution content",
115
+ "constitution.skipGlobal": "Skip loading global constitution",
116
+
117
+ // Analyze
118
+ analyze: "Feature analysis settings",
119
+ "analyze.llmEnhanced": "Enable LLM-enhanced analysis",
120
+ "analyze.model": "Model tier for decompose and classify",
121
+ "analyze.fallbackToKeywords": "Fall back to keyword matching on LLM failure",
122
+ "analyze.maxCodebaseSummaryTokens": "Max tokens for codebase summary",
123
+
124
+ // Review
125
+ review: "Review phase configuration",
126
+ "review.enabled": "Enable review phase",
127
+ "review.checks": "List of checks to run (typecheck, lint, test)",
128
+ "review.commands": "Custom commands per check",
129
+ "review.commands.typecheck": "Custom typecheck command for review",
130
+ "review.commands.lint": "Custom lint command for review",
131
+ "review.commands.test": "Custom test command for review",
132
+
133
+ // Plan
134
+ plan: "Planning phase configuration",
135
+ "plan.model": "Model tier for planning",
136
+ "plan.outputPath": "Output path for generated spec (relative to nax/)",
137
+
138
+ // Acceptance
139
+ acceptance: "Acceptance test configuration",
140
+ "acceptance.enabled": "Enable acceptance test generation and validation",
141
+ "acceptance.maxRetries": "Max retry loops for fix stories",
142
+ "acceptance.generateTests": "Generate acceptance tests during analyze",
143
+ "acceptance.testPath": "Path to acceptance test file (relative to feature dir)",
144
+
145
+ // Context
146
+ context: "Context injection configuration",
147
+ "context.fileInjection":
148
+ "Mode: 'disabled' (default, MCP-aware agents pull context on-demand) | 'keyword' (legacy git-grep injection for non-MCP agents). Set context.fileInjection in config.",
149
+ "context.testCoverage": "Test coverage context settings",
150
+ "context.testCoverage.enabled": "Enable test coverage context injection",
151
+ "context.testCoverage.detail": "Detail level: names-only | names-and-counts | describe-blocks",
152
+ "context.testCoverage.maxTokens": "Max tokens for test summary",
153
+ "context.testCoverage.testDir": "Test directory relative to workdir",
154
+ "context.testCoverage.testPattern": "Glob pattern for test files",
155
+ "context.testCoverage.scopeToStory": "Scope test coverage to story-relevant files only",
156
+ "context.autoDetect": "Auto-detect relevant files settings",
157
+ "context.autoDetect.enabled": "Enable auto-detection of relevant files",
158
+ "context.autoDetect.maxFiles": "Max files to auto-detect",
159
+ "context.autoDetect.traceImports": "Trace imports to find related files",
160
+
161
+ // Optimizer
162
+ optimizer: "Prompt optimizer configuration",
163
+ "optimizer.enabled": "Enable prompt optimizer",
164
+ "optimizer.strategy": "Optimization strategy: rule-based | llm | noop",
165
+
166
+ // Plugins
167
+ plugins: "Plugin configurations",
168
+
169
+ // Hooks
170
+ hooks: "Hooks configuration",
171
+ "hooks.skipGlobal": "Skip loading global hooks",
172
+
173
+ // Interaction
174
+ interaction: "Interaction plugin configuration",
175
+ "interaction.plugin": "Plugin to use for interactions (default: cli)",
176
+ "interaction.config": "Plugin-specific configuration",
177
+ "interaction.defaults": "Default interaction settings",
178
+ "interaction.defaults.timeout": "Default timeout in milliseconds",
179
+ "interaction.defaults.fallback": "Default fallback behavior: continue | skip | escalate | abort",
180
+ "interaction.triggers": "Enable/disable built-in triggers",
181
+
182
+ // Precheck
183
+ precheck: "Precheck configuration (run before analysis)",
184
+ "precheck.storySizeGate": "Story size gate settings",
185
+ "precheck.storySizeGate.enabled": "Enable story size gate",
186
+ "precheck.storySizeGate.maxAcCount": "Max acceptance criteria count before flagging",
187
+ "precheck.storySizeGate.maxDescriptionLength": "Max description character length before flagging",
188
+ "precheck.storySizeGate.maxBulletPoints": "Max bullet point count before flagging",
189
+
190
+ // Prompts
191
+ prompts: "Prompt template overrides (PB-003: PromptBuilder)",
192
+ "prompts.overrides": "Custom prompt template files for specific roles",
193
+ "prompts.overrides.test-writer": 'Path to custom test-writer prompt (e.g., ".nax/prompts/test-writer.md")',
194
+ "prompts.overrides.implementer": 'Path to custom implementer prompt (e.g., ".nax/prompts/implementer.md")',
195
+ "prompts.overrides.verifier": 'Path to custom verifier prompt (e.g., ".nax/prompts/verifier.md")',
196
+ "prompts.overrides.single-session": 'Path to custom single-session prompt (e.g., ".nax/prompts/single-session.md")',
197
+
198
+ // Decompose
199
+ decompose: "Story decomposition configuration (SD-003)",
200
+ "decompose.trigger": "Decomposition trigger mode: auto | confirm | disabled",
201
+ "decompose.maxAcceptanceCriteria": "Max acceptance criteria before flagging as oversized (default: 6)",
202
+ "decompose.maxSubstories": "Max number of substories to generate (default: 5)",
203
+ "decompose.maxSubstoryComplexity": "Max complexity for any generated substory (default: 'medium')",
204
+ "decompose.maxRetries": "Max retries on decomposition validation failure (default: 2)",
205
+ "decompose.model": "Model tier for decomposition LLM calls (default: 'balanced')",
206
+ };
@@ -0,0 +1,103 @@
1
+ /**
2
+ * Config Diffing
3
+ *
4
+ * Compare global and project configurations.
5
+ */
6
+
7
+ /**
8
+ * Represents a single config field difference.
9
+ */
10
+ export interface ConfigDiff {
11
+ /** Dot-separated field path (e.g., "execution.maxIterations") */
12
+ path: string;
13
+ /** Value from global config */
14
+ globalValue: unknown;
15
+ /** Value from project config */
16
+ projectValue: unknown;
17
+ }
18
+
19
+ /**
20
+ * Deep diff two config objects, returning only fields that differ.
21
+ *
22
+ * @param global - Global config (defaults + global overrides)
23
+ * @param project - Project config (raw overrides only)
24
+ * @param currentPath - Current path in object tree (for recursion)
25
+ * @returns Array of differences
26
+ */
27
+ export function deepDiffConfigs(
28
+ global: Record<string, unknown>,
29
+ project: Record<string, unknown>,
30
+ currentPath: string[] = [],
31
+ ): ConfigDiff[] {
32
+ const diffs: ConfigDiff[] = [];
33
+
34
+ // Iterate over project config keys (we only care about what project overrides)
35
+ for (const key of Object.keys(project)) {
36
+ const projectValue = project[key];
37
+ const globalValue = global[key];
38
+ const path = [...currentPath, key];
39
+ const pathStr = path.join(".");
40
+
41
+ // Handle nested objects
42
+ if (
43
+ projectValue !== null &&
44
+ typeof projectValue === "object" &&
45
+ !Array.isArray(projectValue) &&
46
+ globalValue !== null &&
47
+ typeof globalValue === "object" &&
48
+ !Array.isArray(globalValue)
49
+ ) {
50
+ // Recurse into nested object
51
+ const nestedDiffs = deepDiffConfigs(
52
+ globalValue as Record<string, unknown>,
53
+ projectValue as Record<string, unknown>,
54
+ path,
55
+ );
56
+ diffs.push(...nestedDiffs);
57
+ } else {
58
+ // Compare primitive values or arrays
59
+ if (!deepEqual(projectValue, globalValue)) {
60
+ diffs.push({
61
+ path: pathStr,
62
+ globalValue,
63
+ projectValue,
64
+ });
65
+ }
66
+ }
67
+ }
68
+
69
+ return diffs;
70
+ }
71
+
72
+ /**
73
+ * Deep equality check for two values.
74
+ *
75
+ * @param a - First value
76
+ * @param b - Second value
77
+ * @returns True if values are deeply equal
78
+ */
79
+ export function deepEqual(a: unknown, b: unknown): boolean {
80
+ if (a === b) return true;
81
+ if (a === null || b === null) return false;
82
+ if (a === undefined || b === undefined) return false;
83
+
84
+ // Handle arrays
85
+ if (Array.isArray(a) && Array.isArray(b)) {
86
+ if (a.length !== b.length) return false;
87
+ return a.every((val, idx) => deepEqual(val, b[idx]));
88
+ }
89
+
90
+ // Handle objects
91
+ if (typeof a === "object" && typeof b === "object") {
92
+ const aObj = a as Record<string, unknown>;
93
+ const bObj = b as Record<string, unknown>;
94
+ const aKeys = Object.keys(aObj);
95
+ const bKeys = Object.keys(bObj);
96
+
97
+ if (aKeys.length !== bKeys.length) return false;
98
+
99
+ return aKeys.every((key) => deepEqual(aObj[key], bObj[key]));
100
+ }
101
+
102
+ return false;
103
+ }
@@ -0,0 +1,285 @@
1
+ /**
2
+ * Config Display
3
+ *
4
+ * Format and display configuration with descriptions and explanations.
5
+ */
6
+
7
+ import { existsSync } from "node:fs";
8
+ import { join } from "node:path";
9
+ import { findProjectDir, globalConfigPath } from "../config/loader";
10
+ import type { NaxConfig } from "../config/schema";
11
+ import { FIELD_DESCRIPTIONS } from "./config-descriptions";
12
+ import { deepDiffConfigs } from "./config-diff";
13
+ import { loadGlobalConfig, loadProjectConfig } from "./config-get";
14
+
15
+ export { FIELD_DESCRIPTIONS };
16
+
17
+ /** Options for config command */
18
+ export interface ConfigCommandOptions {
19
+ /** Show field explanations */
20
+ explain?: boolean;
21
+ /** Show only fields where project overrides global */
22
+ diff?: boolean;
23
+ }
24
+
25
+ /**
26
+ * Display effective configuration with optional explanations.
27
+ *
28
+ * @param config - Loaded configuration
29
+ * @param options - Command options
30
+ */
31
+ export async function configCommand(config: NaxConfig, options: ConfigCommandOptions = {}): Promise<void> {
32
+ const { explain = false, diff = false } = options;
33
+
34
+ // Validate mutually exclusive flags
35
+ if (explain && diff) {
36
+ console.error("Error: --explain and --diff are mutually exclusive");
37
+ process.exit(1);
38
+ }
39
+
40
+ // Determine sources
41
+ const sources = determineConfigSources();
42
+
43
+ if (diff) {
44
+ // Diff mode: show only fields where project overrides global
45
+ const projectConf = await loadProjectConfig();
46
+
47
+ if (!projectConf) {
48
+ console.log("No project config found — using global defaults");
49
+ return;
50
+ }
51
+
52
+ const globalConf = await loadGlobalConfig();
53
+ const diffs = deepDiffConfigs(globalConf, projectConf);
54
+
55
+ if (diffs.length === 0) {
56
+ console.log("No differences between project and global config");
57
+ return;
58
+ }
59
+
60
+ console.log("# Config Differences (Project overrides Global)");
61
+ console.log();
62
+ console.log("─".repeat(80));
63
+ console.log(`${"Field".padEnd(40)}${"Project Value".padEnd(20)}Global Value`);
64
+ console.log("─".repeat(80));
65
+
66
+ for (const diff of diffs) {
67
+ const path = diff.path.padEnd(40);
68
+ const projectVal = formatValueForTable(diff.projectValue);
69
+ const globalVal = formatValueForTable(diff.globalValue);
70
+
71
+ console.log(`${path}${projectVal.padEnd(20)}${globalVal}`);
72
+
73
+ // Show description if available
74
+ const description = FIELD_DESCRIPTIONS[diff.path];
75
+ if (description) {
76
+ console.log(`${"".padEnd(40)}↳ ${description}`);
77
+ }
78
+ }
79
+
80
+ console.log("─".repeat(80));
81
+ } else if (explain) {
82
+ console.log("# nax Configuration");
83
+ console.log("#");
84
+ console.log("# Resolution order: defaults → global → project → CLI overrides");
85
+ console.log(`# Global config: ${sources.global ? sources.global : "(not found)"}`);
86
+ console.log(`# Project config: ${sources.project ? sources.project : "(not found)"}`);
87
+ console.log();
88
+
89
+ // Recursively display config with descriptions
90
+ displayConfigWithDescriptions(config, [], sources);
91
+ } else {
92
+ // Default view: JSON with header showing config sources
93
+ console.log("// nax Configuration");
94
+ console.log("// Resolution order: defaults → global → project → CLI overrides");
95
+ console.log(`// Global config: ${sources.global ? sources.global : "(not found)"}`);
96
+ console.log(`// Project config: ${sources.project ? sources.project : "(not found)"}`);
97
+ console.log();
98
+ console.log(JSON.stringify(config, null, 2));
99
+ }
100
+ }
101
+
102
+ /**
103
+ * Determine which config files are present.
104
+ *
105
+ * @returns Paths to global and project config files (null if not found)
106
+ */
107
+ function determineConfigSources(): { global: string | null; project: string | null } {
108
+ const globalPath = globalConfigPath();
109
+ const projectDir = findProjectDir();
110
+ const projectPath = projectDir ? join(projectDir, "config.json") : null;
111
+
112
+ return {
113
+ global: fileExists(globalPath) ? globalPath : null,
114
+ project: projectPath && fileExists(projectPath) ? projectPath : null,
115
+ };
116
+ }
117
+
118
+ /**
119
+ * Check if a file exists.
120
+ *
121
+ * @param path - File path to check
122
+ * @returns True if file exists, false otherwise
123
+ */
124
+ function fileExists(path: string): boolean {
125
+ return existsSync(path);
126
+ }
127
+
128
+ /**
129
+ * Display configuration with descriptions and source annotations.
130
+ *
131
+ * @param obj - Configuration object or value
132
+ * @param path - Current path in config tree
133
+ * @param sources - Config source paths
134
+ * @param indent - Current indentation level
135
+ */
136
+ function displayConfigWithDescriptions(
137
+ obj: unknown,
138
+ path: string[],
139
+ sources: { global: string | null; project: string | null },
140
+ indent = 0,
141
+ ): void {
142
+ const indentStr = " ".repeat(indent);
143
+ const pathStr = path.join(".");
144
+
145
+ // Handle primitives and arrays
146
+ if (obj === null || obj === undefined || typeof obj !== "object" || Array.isArray(obj)) {
147
+ const description = FIELD_DESCRIPTIONS[pathStr];
148
+ const value = formatValue(obj);
149
+
150
+ if (description) {
151
+ console.log(`${indentStr}# ${description}`);
152
+ }
153
+
154
+ const key = path[path.length - 1] || "";
155
+ console.log(`${indentStr}${key}: ${value}`);
156
+ console.log();
157
+ return;
158
+ }
159
+
160
+ // Handle objects
161
+ const entries = Object.entries(obj as Record<string, unknown>);
162
+
163
+ // Special handling for prompts section: always show overrides documentation
164
+ const objAsRecord = obj as Record<string, unknown>;
165
+ const isPromptsSection = path.join(".") === "prompts";
166
+ if (isPromptsSection && !objAsRecord.overrides) {
167
+ // Add prompts.overrides documentation even if not in config
168
+ const description = FIELD_DESCRIPTIONS["prompts.overrides"];
169
+ if (description) {
170
+ console.log(`${indentStr}# prompts.overrides: ${description}`);
171
+ }
172
+
173
+ // Show role examples
174
+ const roles = ["test-writer", "implementer", "verifier", "single-session"];
175
+ console.log(`${indentStr}overrides:`);
176
+ for (const role of roles) {
177
+ const roleDesc = FIELD_DESCRIPTIONS[`prompts.overrides.${role}`];
178
+ if (roleDesc) {
179
+ console.log(`${indentStr} # ${roleDesc}`);
180
+ // Extract the example path from description
181
+ const match = roleDesc.match(/e\.g\., "([^"]+)"/);
182
+ if (match) {
183
+ console.log(`${indentStr} # ${role}: "${match[1]}"`);
184
+ }
185
+ }
186
+ }
187
+ console.log();
188
+ return;
189
+ }
190
+
191
+ for (let i = 0; i < entries.length; i++) {
192
+ const [key, value] = entries[i];
193
+ const currentPath = [...path, key];
194
+ const currentPathStr = currentPath.join(".");
195
+ const description = FIELD_DESCRIPTIONS[currentPathStr];
196
+
197
+ // Display description comment if available
198
+ if (description) {
199
+ // Include path for direct subsections of key configuration sections
200
+ // (to improve clarity of important configs like multi-agent setup)
201
+ const pathParts = currentPathStr.split(".");
202
+ // Only show path for 2-level paths (e.g., "autoMode.enabled", "models.fast")
203
+ // to keep deeply nested descriptions concise
204
+ const isDirectSubsection = pathParts.length === 2;
205
+ const isKeySection = ["prompts", "autoMode", "models", "routing"].includes(pathParts[0]);
206
+ const shouldIncludePath = isKeySection && isDirectSubsection;
207
+ const comment = shouldIncludePath ? `${currentPathStr}: ${description}` : description;
208
+ console.log(`${indentStr}# ${comment}`);
209
+ }
210
+
211
+ // Handle nested objects
212
+ if (value !== null && typeof value === "object" && !Array.isArray(value)) {
213
+ console.log(`${indentStr}${key}:`);
214
+ displayConfigWithDescriptions(value, currentPath, sources, indent + 1);
215
+ } else {
216
+ // Display value
217
+ const formattedValue = formatValue(value);
218
+ console.log(`${indentStr}${key}: ${formattedValue}`);
219
+
220
+ // Add blank line after each top-level section
221
+ if (indent === 0 && i < entries.length - 1) {
222
+ console.log();
223
+ }
224
+ }
225
+ }
226
+ }
227
+
228
+ /**
229
+ * Format a config value for display.
230
+ *
231
+ * @param value - Value to format
232
+ * @returns Formatted string
233
+ */
234
+ function formatValue(value: unknown): string {
235
+ if (value === null) return "null";
236
+ if (value === undefined) return "undefined";
237
+ if (typeof value === "string") return `"${value}"`;
238
+ if (typeof value === "boolean") return String(value);
239
+ if (typeof value === "number") return String(value);
240
+ if (Array.isArray(value)) {
241
+ if (value.length === 0) return "[]";
242
+ if (value.length <= 3) {
243
+ return `[${value.map((v) => formatValue(v)).join(", ")}]`;
244
+ }
245
+ return `[${value
246
+ .slice(0, 3)
247
+ .map((v) => formatValue(v))
248
+ .join(", ")}, ... (${value.length} items)]`;
249
+ }
250
+ if (typeof value === "object") {
251
+ return JSON.stringify(value);
252
+ }
253
+ return String(value);
254
+ }
255
+
256
+ /**
257
+ * Format a config value for table display (shorter format).
258
+ *
259
+ * @param value - Value to format
260
+ * @returns Formatted string (max ~18 chars)
261
+ */
262
+ function formatValueForTable(value: unknown): string {
263
+ if (value === null) return "null";
264
+ if (value === undefined) return "undefined";
265
+ if (typeof value === "string") {
266
+ if (value.length > 15) {
267
+ return `"${value.slice(0, 12)}..."`;
268
+ }
269
+ return `"${value}"`;
270
+ }
271
+ if (typeof value === "boolean") return String(value);
272
+ if (typeof value === "number") return String(value);
273
+ if (Array.isArray(value)) {
274
+ if (value.length === 0) return "[]";
275
+ return `[...${value.length}]`;
276
+ }
277
+ if (typeof value === "object") {
278
+ const str = JSON.stringify(value);
279
+ if (str.length > 15) {
280
+ return "{...}";
281
+ }
282
+ return str;
283
+ }
284
+ return String(value);
285
+ }
@@ -0,0 +1,55 @@
1
+ /**
2
+ * Config Loading
3
+ *
4
+ * Load global and project configuration files.
5
+ */
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
+
13
+ /**
14
+ * Load and parse a JSON config file.
15
+ *
16
+ * @param path - Path to config file
17
+ * @returns Parsed config object or null if file doesn't exist
18
+ */
19
+ export async function loadConfigFile(path: string): Promise<Record<string, unknown> | null> {
20
+ if (!existsSync(path)) return null;
21
+ try {
22
+ return await Bun.file(path).json();
23
+ } catch {
24
+ return null;
25
+ }
26
+ }
27
+
28
+ /**
29
+ * Load global config merged with defaults.
30
+ *
31
+ * @returns Global config object (defaults + global overrides)
32
+ */
33
+ export async function loadGlobalConfig(): Promise<Record<string, unknown>> {
34
+ const globalPath = globalConfigPath();
35
+ const globalConf = await loadConfigFile(globalPath);
36
+
37
+ if (!globalConf) {
38
+ return structuredClone(DEFAULT_CONFIG as unknown as Record<string, unknown>);
39
+ }
40
+
41
+ return deepMergeConfig(structuredClone(DEFAULT_CONFIG as unknown as Record<string, unknown>), globalConf);
42
+ }
43
+
44
+ /**
45
+ * Load project config (raw, without defaults or global).
46
+ *
47
+ * @returns Project config object or null if not found
48
+ */
49
+ export async function loadProjectConfig(): Promise<Record<string, unknown> | null> {
50
+ const projectDir = findProjectDir();
51
+ if (!projectDir) return null;
52
+
53
+ const projectPath = join(projectDir, "config.json");
54
+ return await loadConfigFile(projectPath);
55
+ }