Merge pull request #3540 from gsd-build/feat/3536-configuration-module

feat(3536): Configuration Module via shared manifests + generator (Phase 2 of #3524)
This commit is contained in:
Tom Boucher
2026-05-15 09:33:22 -04:00
committed by GitHub
29 changed files with 2228 additions and 522 deletions

View File

@@ -367,7 +367,7 @@ async function main() {
// phase / roadmap / milestone / progress / etc.
const TOP_LEVEL_USAGE = 'Usage: gsd-tools <command> [args] [--raw] [--pick <field>] [--cwd <path>] [--ws <name>] [--json-errors]\n' +
'Commands: agent-skills, audit-open, audit-uat, check-commit, commit, commit-to-subrepo, ' +
'config-ensure-section, config-get, config-new-project, config-path, config-set, ' +
'config-ensure-section, config-get, config-new-project, config-path, config-set, migrate-config, ' +
'current-timestamp, detect-custom-files, docs-init, extract-messages, find-phase, ' +
'from-gsd2, frontmatter, gap-analysis, generate-claude-md, generate-claude-profile, ' +
'generate-dev-preferences, generate-slug, graphify, history-digest, init, intel, ' +
@@ -668,6 +668,13 @@ async function runCommand(command, args, cwd, raw, defaultValue, originalCommand
break;
}
case 'migrate-config': {
// Explicit on-disk migration of legacy config keys to canonical shape (#3536).
// Wraps Configuration Module migrateOnDisk(); idempotent. async — must await.
await config.cmdMigrateConfig(cwd, raw);
break;
}
case 'agent-skills': {
init.cmdAgentSkills(cwd, args[1], raw);
break;

View File

@@ -1,127 +1,23 @@
'use strict';
/**
* Single source of truth for valid config key paths.
* Thin adapter — sources schema data from the manifest via the generated
* Configuration Module. All inline literals have been removed; the manifest
* at sdk/shared/config-schema.manifest.json is the single source of truth.
*
* Imported by:
* - config.cjs (isValidConfigKey validator)
* - tests/config-schema-docs-parity.test.cjs (CI drift guard)
* - tests/config-schema-sdk-parity.test.cjs (CJS↔SDK parity guard)
*
* Adding a key here without documenting it in docs/CONFIGURATION.md will
* fail the parity test. Adding a key to docs/CONFIGURATION.md without
* adding it here will cause config-set to reject it at runtime.
* See Phase 2 Cycle 5 (#3536) — schema manifest migration.
*/
/** Exact-match config key paths accepted by config-set. */
const VALID_CONFIG_KEYS = new Set([
'mode', 'granularity', 'parallelization', 'commit_docs', 'model_profile',
'search_gitignored', 'brave_search', 'firecrawl', 'exa_search',
'workflow.research', 'workflow.plan_check', 'workflow.verifier',
'workflow.nyquist_validation', 'workflow.ai_integration_phase', 'workflow.ui_phase', 'workflow.ui_safety_gate',
'workflow.auto_advance', 'workflow.node_repair', 'workflow.node_repair_budget',
'workflow.tdd_mode',
'workflow.human_verify_mode',
'workflow.text_mode',
'workflow.research_before_questions',
'workflow.discuss_mode',
'workflow.skip_discuss',
'workflow.auto_prune_state',
'workflow.use_worktrees',
'workflow.worktree_skip_hooks',
'workflow.code_review',
'workflow.code_review_depth',
'workflow.code_review_command',
'workflow.pattern_mapper',
'workflow.plan_bounce',
'workflow.plan_bounce_script',
'workflow.plan_bounce_passes',
'workflow.plan_chunked',
'workflow.plan_review_convergence',
'workflow.post_planning_gaps',
'workflow.security_enforcement',
'workflow.security_asvs_level',
'workflow.security_block_on',
'workflow.drift_threshold',
'workflow.drift_action',
'code_quality.fallow.enabled',
'code_quality.fallow.scope',
'code_quality.fallow.profile',
'code_quality.fallow.mcp',
'ship.pr_body_sections',
'git.branching_strategy', 'git.base_branch', 'git.create_tag', 'git.phase_branch_template', 'git.milestone_branch_template', 'git.quick_branch_template',
'planning.commit_docs', 'planning.search_gitignored', 'planning.sub_repos',
'review.ollama_host', 'review.lm_studio_host', 'review.llama_cpp_host',
'review.default_reviewers',
'workflow.cross_ai_execution', 'workflow.cross_ai_command', 'workflow.cross_ai_timeout',
'workflow.subagent_timeout',
'executor.stall_detect_interval_minutes',
'executor.stall_threshold_minutes',
'workflow.inline_plan_threshold',
'hooks.context_warnings',
'hooks.workflow_guard',
'workflow.context_coverage_gate',
'statusline.show_last_command',
'statusline.context_position',
'workflow.ui_review',
'workflow.max_discuss_passes',
'features.thinking_partner',
'context',
'features.global_learnings',
'learnings.max_inject',
'project_code', 'phase_naming',
'manager.flags.discuss', 'manager.flags.plan', 'manager.flags.execute',
'response_language',
'context_window',
'intel.enabled',
'graphify.enabled',
'graphify.build_timeout',
'claude_md_path',
'claude_md_assembly.mode',
// #2517 — runtime-aware model profiles
'runtime',
// #3162 — documented top-level key: controls model ID resolution for non-Claude runtimes
'resolve_model_ids',
]);
/**
* Internal runtime-state keys — accepted by config-set (workflows write them) but not
* exposed as user-settable options. Excluded from VALID_CONFIG_KEYS so they stay out of
* the public docs-parity check and the "Valid keys:" error message.
* See: #3162 (workflow._auto_chain_active written by plan/execute/discuss workflows)
*/
const RUNTIME_STATE_KEYS = new Set([
'workflow._auto_chain_active',
]);
/**
* Dynamic-pattern validators — keys matching these regexes are also accepted.
* Each entry has a `test` function and a human-readable `description`.
*/
const DYNAMIC_KEY_PATTERNS = [
{ topLevel: 'agent_skills', test: (k) => /^agent_skills\.[a-zA-Z0-9_-]+$/.test(k), description: 'agent_skills.<agent-type>' },
{ topLevel: 'review', test: (k) => /^review\.models\.[a-zA-Z0-9_-]+$/.test(k), description: 'review.models.<cli-name>' },
{ topLevel: 'features', test: (k) => /^features\.[a-zA-Z0-9_]+$/.test(k), description: 'features.<feature_name>' },
{ topLevel: 'claude_md_assembly', test: (k) => /^claude_md_assembly\.blocks\.[a-zA-Z0-9_]+$/.test(k), description: 'claude_md_assembly.blocks.<section>' },
// #2517 — runtime-aware model profile overrides: model_profile_overrides.<runtime>.<tier>
// <runtime> is a free string (so users can map non-built-in runtimes); <tier> is enum-restricted.
{ topLevel: 'model_profile_overrides', test: (k) => /^model_profile_overrides\.[a-zA-Z0-9_-]+\.(opus|sonnet|haiku)$/.test(k),
description: 'model_profile_overrides.<runtime>.<opus|sonnet|haiku>' },
// #3023 — per-phase-type model map: models.<phase_type> = <tier>
// Six named slots (planning/discuss/research/execution/verification/completion);
// unknown phase-types are rejected. Per-agent model_overrides still take
// precedence over phase-type at resolve time.
{ topLevel: 'models', test: (k) => /^models\.(planning|discuss|research|execution|verification|completion)$/.test(k),
description: 'models.<planning|discuss|research|execution|verification|completion>' },
// #3024 — dynamic routing block. Three top-level scalar settings
// plus a tier_models sub-block keyed by light/standard/heavy.
{ topLevel: 'dynamic_routing',
test: (k) => /^dynamic_routing\.(enabled|escalate_on_failure|max_escalations|tier_models\.(light|standard|heavy))$/.test(k),
description: 'dynamic_routing.<enabled|escalate_on_failure|max_escalations|tier_models.<light|standard|heavy>>' },
// #3227 — per-agent model overrides: model_overrides.<agent-id>
// Full model IDs (e.g. "openai/o3") and tier aliases (opus/sonnet/haiku/inherit)
// are both accepted. Value validation is handled by the resolver at read time.
{ topLevel: 'model_overrides', test: (k) => /^model_overrides\.[a-zA-Z0-9_-]+$/.test(k), description: 'model_overrides.<agent-id>' },
];
const {
VALID_CONFIG_KEYS,
RUNTIME_STATE_KEYS,
DYNAMIC_KEY_PATTERNS,
} = require('./configuration.generated.cjs');
/**
* Returns true if keyPath is a valid config key (exact, dynamic pattern, or runtime state).

View File

@@ -648,6 +648,40 @@ function cmdConfigPath(cwd) {
output(configPath, true, configPath);
}
/**
* Explicit on-disk migration of legacy config keys to canonical nested shape.
*
* Wraps the Configuration Module's migrateOnDisk() for the CLI surface. This
* is the Phase 2 acceptance-criteria deliverable for opt-in migration (#3536):
* users can run `gsd-tools migrate-config` to apply all four legacy-key
* migrations to their .planning/config.json without having to load any config
* implicitly via another command.
*
* Output: JSON object with { migrated, normalizations, wrote } or a human-readable
* summary when --raw is set. Exits 0 in all cases (including no-op).
*/
async function cmdMigrateConfig(cwd, raw) {
const { migrateOnDisk } = require('./configuration.generated.cjs');
const ws = process.env.GSD_WORKSTREAM || null;
const report = await migrateOnDisk(cwd, ws || undefined);
if (raw) {
if (!report.migrated) {
const msg = 'No legacy keys found — config is already canonical.';
output(msg, true, msg);
} else {
const lines = [
`Migrated: ${report.wrote}`,
...report.normalizations.map(n => ` ${n.from} → ${n.to}`),
].join('\n');
output(lines, true, lines);
}
} else {
// output() JSON.stringify's its first arg when raw=false; pass the report object.
output(report, false, report);
}
}
module.exports = {
VALID_CONFIG_KEYS,
cmdConfigEnsureSection,
@@ -656,4 +690,5 @@ module.exports = {
cmdConfigSetModelProfile,
cmdConfigNewProject,
cmdConfigPath,
cmdMigrateConfig,
};

View File

@@ -0,0 +1,233 @@
'use strict';
/**
* GENERATED FILE — DO NOT EDIT.
*
* Source: sdk/src/configuration/index.ts
* Regenerate: cd sdk && npm run gen:configuration
*
* Configuration Module — single source of truth for config loading,
* legacy-key normalization, defaults merge, and explicit on-disk migration.
*/
const { readFileSync, writeFileSync, existsSync, readdirSync } = require('node:fs');
const { join } = require('node:path');
// ─── Manifest requires ───────────────────────────────────────────────────────
// Resolved relative to this file: get-shit-done/bin/lib/ → sdk/shared/
// This file lives at: get-shit-done/bin/lib/configuration.generated.cjs
// sdk/shared lives at: sdk/shared/ (3 dirs up from bin/lib, then into sdk/shared)
const CONFIG_DEFAULTS = require('../../../sdk/shared/config-defaults.manifest.json');
const SCHEMA_MANIFEST = require('../../../sdk/shared/config-schema.manifest.json');
const VALID_CONFIG_KEYS = new Set(SCHEMA_MANIFEST.validKeys);
const RUNTIME_STATE_KEYS = new Set(SCHEMA_MANIFEST.runtimeStateKeys);
const DYNAMIC_KEY_PATTERNS = SCHEMA_MANIFEST.dynamicKeyPatterns.map((p) => {
const pattern = new RegExp(p.source);
return {
...p,
test: (key) => {
pattern.lastIndex = 0;
return pattern.test(key);
},
};
});
// ─── Depth → Granularity mapping ─────────────────────────────────────────────
const DEPTH_TO_GRANULARITY = {
quick: 'coarse',
standard: 'standard',
comprehensive: 'fine',
};
// ─── Internal helpers ─────────────────────────────────────────────────────────
function planningDir(cwd, workstream) {
if (!workstream)
return join(cwd, '.planning');
return join(cwd, '.planning', 'workstreams', workstream);
}
function detectSubRepos(cwd) {
const results = [];
try {
const entries = readdirSync(cwd, { withFileTypes: true });
for (const entry of entries) {
if (!entry.isDirectory())
continue;
if (entry.name.startsWith('.') || entry.name === 'node_modules')
continue;
const gitPath = join(cwd, entry.name, '.git');
try {
if (existsSync(gitPath)) {
results.push(entry.name);
}
}
catch { /* ignore */ }
}
}
catch { /* ignore */ }
return results.sort();
}
function deepMergeConfig(base, overlay) {
const result = { ...base };
for (const key of Object.keys(overlay)) {
const ov = overlay[key];
if (ov !== null && ov !== undefined && typeof ov === 'object' && !Array.isArray(ov)) {
const bv = base[key];
if (bv !== null && bv !== undefined && typeof bv === 'object' && !Array.isArray(bv)) {
result[key] = deepMergeConfig(bv, ov);
}
else {
result[key] = deepMergeConfig({}, ov);
}
}
else {
result[key] = ov;
}
}
return result;
}
// ─── Exported functions ───────────────────────────────────────────────────────
function normalizeLegacyKeys(parsed) {
const result = { ...parsed };
const normalizations = [];
// 1. branching_strategy → git.branching_strategy
if (Object.prototype.hasOwnProperty.call(result, 'branching_strategy')) {
const value = result.branching_strategy;
const git = result.git ?? {};
if (git.branching_strategy === undefined) {
result.git = { ...git, branching_strategy: value };
}
else {
// canonical nested wins — just delete the stale top-level
result.git = { ...git };
}
delete result.branching_strategy;
normalizations.push({ from: 'branching_strategy', to: 'git.branching_strategy', value });
}
// 2. top-level sub_repos → planning.sub_repos
if (Object.prototype.hasOwnProperty.call(result, 'sub_repos')) {
const value = result.sub_repos;
const planning = result.planning ?? {};
if (planning.sub_repos === undefined) {
result.planning = { ...planning, sub_repos: value };
}
else {
// canonical nested wins — just drop the stale top-level
result.planning = { ...planning };
}
delete result.sub_repos;
normalizations.push({ from: 'sub_repos', to: 'planning.sub_repos', value });
}
// 3. multiRepo: true → marker (filesystem detection deferred to migrateOnDisk / caller)
if (result.multiRepo === true) {
delete result.multiRepo;
normalizations.push({ from: 'multiRepo', to: 'planning.sub_repos', value: true, requiresFilesystem: true });
}
// 4. top-level depth → granularity
if (Object.prototype.hasOwnProperty.call(result, 'depth') && !Object.prototype.hasOwnProperty.call(result, 'granularity')) {
const rawDepth = result.depth;
const mapped = DEPTH_TO_GRANULARITY[rawDepth] ?? rawDepth;
result.granularity = mapped;
delete result.depth;
normalizations.push({ from: 'depth', to: 'granularity', value: mapped });
}
return { parsed: result, normalizations };
}
function mergeDefaults(parsed) {
// Start with a deep clone of defaults, then overlay parsed
const defaults = JSON.parse(JSON.stringify(CONFIG_DEFAULTS));
return deepMergeConfig(defaults, parsed);
}
async function loadConfig(cwd, options) {
const configPath = join(planningDir(cwd, options?.workstream), 'config.json');
let raw;
try {
raw = readFileSync(configPath, 'utf-8');
}
catch {
// File missing — return defaults
return mergeDefaults({});
}
const trimmed = raw.trim();
if (trimmed === '') {
return mergeDefaults({});
}
let parsed;
try {
parsed = JSON.parse(trimmed);
}
catch (err) {
const msg = err instanceof Error ? err.message : String(err);
throw new Error(`Failed to parse config at ${configPath}: ${msg}`);
}
if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
throw new Error(`Config at ${configPath} must be a JSON object`);
}
const { parsed: normalized, normalizations } = normalizeLegacyKeys(parsed);
if (options?.onNormalizations && normalizations.length > 0) {
options.onNormalizations(normalizations);
}
return mergeDefaults(normalized);
}
async function migrateOnDisk(cwd, workstream) {
const configPath = join(planningDir(cwd, workstream), 'config.json');
let raw;
try {
raw = readFileSync(configPath, 'utf-8');
}
catch {
// File missing — nothing to migrate
return { migrated: false, normalizations: [], wrote: null };
}
const trimmed = raw.trim();
if (trimmed === '') {
return { migrated: false, normalizations: [], wrote: null };
}
let parsed;
try {
parsed = JSON.parse(trimmed);
}
catch {
// Malformed — can't migrate
return { migrated: false, normalizations: [], wrote: null };
}
const { parsed: normalized, normalizations } = normalizeLegacyKeys(parsed);
if (normalizations.length === 0) {
return { migrated: false, normalizations: [], wrote: null };
}
// Resolve multiRepo filesystem detection
const result = { ...normalized };
for (const norm of normalizations) {
if (norm.requiresFilesystem) {
const detected = detectSubRepos(cwd);
if (detected.length > 0) {
const planning = result.planning ?? {};
result.planning = { ...planning, sub_repos: detected, commit_docs: false };
}
}
}
try {
writeFileSync(configPath, JSON.stringify(result, null, 2));
}
catch (err) {
const msg = err instanceof Error ? err.message : String(err);
throw new Error(`Failed to write migrated config at ${configPath}: ${msg}`);
}
return { migrated: true, normalizations, wrote: configPath };
}
module.exports = {
loadConfig,
normalizeLegacyKeys,
mergeDefaults,
migrateOnDisk,
CONFIG_DEFAULTS,
VALID_CONFIG_KEYS,
RUNTIME_STATE_KEYS,
DYNAMIC_KEY_PATTERNS,
};

View File

@@ -25,6 +25,17 @@ const {
setActiveWorkstream,
} = require('./planning-workspace.cjs');
// ─── Configuration Module (generated CJS mirror) ────────────────────────────
// Cycle 4: import canonical defaults + normalization primitives from the
// generated module; core.cjs no longer carries its own inline literal or its
// own migration logic. The exported CONFIG_DEFAULTS remains a flat-key object
// (shape unchanged) so legacy consumers (config.cjs, verify.cjs, tests) require
// no changes. Values are sourced from the canonical nested manifest.
const {
CONFIG_DEFAULTS: CANONICAL_CONFIG_DEFAULTS,
normalizeLegacyKeys,
} = require('./configuration.generated.cjs');
// ─── Path helpers ────────────────────────────────────────────────────────────
/** Normalize a relative path to always use forward slashes (cross-platform). */
@@ -279,36 +290,49 @@ function error(message, reason = ERROR_REASON.UNKNOWN) {
// ─── File & Config utilities ──────────────────────────────────────────────────
/**
* Canonical config defaults. Single source of truth — imported by config.cjs and verify.cjs.
* Canonical config defaults — flat-key projection for CJS consumers.
*
* Cycle 4: Values are sourced from CANONICAL_CONFIG_DEFAULTS (the nested
* manifest loaded by configuration.generated.cjs). The flat shape is
* preserved here so legacy consumers (config.cjs, verify.cjs, tests that
* regex-parse this source) continue to work without changes. The key names
* and the `const CONFIG_DEFAULTS = {` pattern are intentionally kept.
*
* Mapping notes:
* - workflow.plan_check → plan_checker (CJS flat name; verify.cjs uses this)
* - git.* → flat git keys (branching_strategy, templates)
* - workflow.* → flat names (research, verifier, …)
* - planning.sub_repos → sub_repos
* - planning.commit_docs / search_gitignored → top-level flat keys
*/
const CONFIG_DEFAULTS = {
model_profile: 'balanced',
commit_docs: true,
search_gitignored: false,
branching_strategy: 'none',
phase_branch_template: 'gsd/phase-{phase}-{slug}',
milestone_branch_template: 'gsd/{milestone}-{slug}',
quick_branch_template: null,
research: true,
plan_checker: true,
verifier: true,
nyquist_validation: true,
ai_integration_phase: true,
parallelization: true,
brave_search: false,
firecrawl: false,
exa_search: false,
text_mode: false, // when true, use plain-text numbered lists instead of AskUserQuestion menus
sub_repos: [],
resolve_model_ids: false, // false: return alias as-is | true: map to full Claude model ID | "omit": return '' (runtime uses its default)
context_window: 200000, // default 200k; set to 1000000 for Opus/Sonnet 4.6 1M models
phase_naming: 'sequential', // 'sequential' (default, auto-increment) or 'custom' (arbitrary string IDs)
project_code: null, // optional short prefix for phase dirs (e.g., 'CK' → 'CK-01-foundation')
subagent_timeout: 300000, // 5 min default; increase for large codebases or slower models (ms)
security_enforcement: true, // workflow.security_enforcement — threat-model-anchored security verification via /gsd:secure-phase
security_asvs_level: 1, // workflow.security_asvs_level — OWASP ASVS verification level (1=opportunistic, 2=standard, 3=comprehensive)
security_block_on: 'high', // workflow.security_block_on — minimum severity that blocks phase advancement ('high' | 'medium' | 'low')
post_planning_gaps: true, // workflow.post_planning_gaps — unified post-planning gap report (#2493): scan REQUIREMENTS.md + CONTEXT.md decisions vs all PLAN.md files
model_profile: CANONICAL_CONFIG_DEFAULTS.model_profile,
commit_docs: CANONICAL_CONFIG_DEFAULTS.commit_docs,
search_gitignored: CANONICAL_CONFIG_DEFAULTS.search_gitignored,
branching_strategy: CANONICAL_CONFIG_DEFAULTS.git.branching_strategy,
phase_branch_template: CANONICAL_CONFIG_DEFAULTS.git.phase_branch_template,
milestone_branch_template: CANONICAL_CONFIG_DEFAULTS.git.milestone_branch_template,
quick_branch_template: CANONICAL_CONFIG_DEFAULTS.git.quick_branch_template,
research: CANONICAL_CONFIG_DEFAULTS.workflow.research,
plan_checker: CANONICAL_CONFIG_DEFAULTS.workflow.plan_check, // flat CJS name maps to workflow.plan_check
verifier: CANONICAL_CONFIG_DEFAULTS.workflow.verifier,
nyquist_validation: CANONICAL_CONFIG_DEFAULTS.workflow.nyquist_validation,
ai_integration_phase: CANONICAL_CONFIG_DEFAULTS.workflow.ai_integration_phase,
parallelization: CANONICAL_CONFIG_DEFAULTS.parallelization,
brave_search: CANONICAL_CONFIG_DEFAULTS.brave_search,
firecrawl: CANONICAL_CONFIG_DEFAULTS.firecrawl,
exa_search: CANONICAL_CONFIG_DEFAULTS.exa_search,
text_mode: CANONICAL_CONFIG_DEFAULTS.workflow.text_mode,
sub_repos: CANONICAL_CONFIG_DEFAULTS.planning.sub_repos,
resolve_model_ids: CANONICAL_CONFIG_DEFAULTS.resolve_model_ids,
context_window: CANONICAL_CONFIG_DEFAULTS.context_window,
phase_naming: CANONICAL_CONFIG_DEFAULTS.phase_naming,
project_code: CANONICAL_CONFIG_DEFAULTS.project_code,
subagent_timeout: CANONICAL_CONFIG_DEFAULTS.workflow.subagent_timeout,
security_enforcement: CANONICAL_CONFIG_DEFAULTS.workflow.security_enforcement,
security_asvs_level: CANONICAL_CONFIG_DEFAULTS.workflow.security_asvs_level,
security_block_on: CANONICAL_CONFIG_DEFAULTS.workflow.security_block_on,
post_planning_gaps: CANONICAL_CONFIG_DEFAULTS.workflow.post_planning_gaps,
};
/**
@@ -348,13 +372,26 @@ function loadConfig(cwd, options = {}) {
const raw = platformReadSync(rootConfigPath);
if (raw === null) throw new Error('missing');
rootParsed = JSON.parse(raw);
if (Object.prototype.hasOwnProperty.call(rootParsed, 'branching_strategy')) {
if (!rootParsed.git) rootParsed.git = {};
if (rootParsed.git.branching_strategy === undefined) {
rootParsed.git.branching_strategy = rootParsed.branching_strategy;
// Cycle 4: delegate all legacy-key normalization to the Configuration Module.
// normalizeLegacyKeys handles branching_strategy → git.branching_strategy,
// sub_repos → planning.sub_repos, multiRepo, and depth → granularity.
const { parsed: rootNormalized, normalizations: rootNorms } = normalizeLegacyKeys(rootParsed);
if (rootNorms.length > 0) {
// Resolve filesystem-dependent normalizations (multiRepo → planning.sub_repos)
for (const norm of rootNorms) {
if (norm.requiresFilesystem && !rootNormalized.planning?.sub_repos) {
const detected = detectSubRepos(cwd);
if (detected.length > 0) {
if (!rootNormalized.planning) rootNormalized.planning = {};
rootNormalized.planning.sub_repos = detected;
rootNormalized.planning.commit_docs = false;
}
}
}
delete rootParsed.branching_strategy;
rootParsed = rootNormalized;
try { platformWriteSync(rootConfigPath, JSON.stringify(rootParsed, null, 2)); } catch {}
} else {
rootParsed = rootNormalized;
}
} catch {
// Root config missing or unparseable — workstream config stands alone
@@ -371,57 +408,37 @@ function loadConfig(cwd, options = {}) {
// for migrations and writes so we never persist merged values back to disk.
const fileData = JSON.parse(raw);
// Migrate deprecated "depth" key to "granularity" with value mapping
if ('depth' in fileData && !('granularity' in fileData)) {
const depthToGranularity = { quick: 'coarse', standard: 'standard', comprehensive: 'fine' };
fileData.granularity = depthToGranularity[fileData.depth] || fileData.depth;
delete fileData.depth;
try { platformWriteSync(configPath, JSON.stringify(fileData, null, 2)); } catch { /* intentionally empty */ }
}
// Auto-detect and sync sub_repos: scan for child directories with .git
// Cycle 4: Single normalizeLegacyKeys call replaces all four inline migration
// blocks (depth→granularity, multiRepo→planning.sub_repos, sub_repos→planning.sub_repos,
// branching_strategy→git.branching_strategy). The Module is pure (no I/O); disk
// writeback is handled below with the existing platformWriteSync pattern.
// Note: migrateOnDisk from the Module is async; loadConfig is sync — so we
// call normalizeLegacyKeys inline and do the writeback at the call site.
// Per brief §4.3: "use normalizeLegacyKeys directly and do writeback inline."
let configDirty = false;
// Migrate legacy "multiRepo: true" boolean → planning.sub_repos array.
// Canonical location is planning.sub_repos (#2561); writing to top-level
// would be flagged as unknown by the validator below (#2638).
if (fileData.multiRepo === true && !fileData.sub_repos && !fileData.planning?.sub_repos) {
const detected = detectSubRepos(cwd);
if (detected.length > 0) {
if (!fileData.planning) fileData.planning = {};
fileData.planning.sub_repos = detected;
fileData.planning.commit_docs = false;
delete fileData.multiRepo;
{
const { parsed: normalized, normalizations } = normalizeLegacyKeys(fileData);
if (normalizations.length > 0) {
// Merge normalized values back into fileData (mutation-in-place for legacy code below)
Object.keys(fileData).forEach(k => delete fileData[k]);
Object.assign(fileData, normalized);
configDirty = true;
// Resolve filesystem-dependent normalizations (multiRepo → planning.sub_repos).
// Guard: only populate sub_repos from filesystem if not already set by normalization
// AND the original file didn't have sub_repos already (preserve existing intent).
for (const norm of normalizations) {
if (norm.requiresFilesystem && !fileData.planning?.sub_repos) {
const detected = detectSubRepos(cwd);
if (detected.length > 0) {
if (!fileData.planning) fileData.planning = {};
fileData.planning.sub_repos = detected;
fileData.planning.commit_docs = false;
}
}
}
}
}
// Self-heal legacy/buggy installs: strip any stale top-level sub_repos,
// preserving its value as the planning.sub_repos seed if that slot is empty.
if (Object.prototype.hasOwnProperty.call(fileData, 'sub_repos')) {
if (!fileData.planning) fileData.planning = {};
if (!fileData.planning.sub_repos) {
fileData.planning.sub_repos = fileData.sub_repos;
}
delete fileData.sub_repos;
configDirty = true;
}
// #3523 — Migrate legacy top-level branching_strategy → git.branching_strategy.
// Canonical location is git.branching_strategy (per config-schema.cjs); writing
// at the top level trips the unknown-key warning even though loadConfig:485 actively
// reads it via the nested fallback. This migration mirrors the multiRepo → sub_repos
// precedent: graft then delete so the warning never fires again on this project.
// The nested value wins if already set (matches SDK mergeDefaults precedence, PR #3116).
if (Object.prototype.hasOwnProperty.call(fileData, 'branching_strategy')) {
if (!fileData.git) fileData.git = {};
if (fileData.git.branching_strategy === undefined) {
fileData.git.branching_strategy = fileData.branching_strategy;
}
delete fileData.branching_strategy;
configDirty = true;
}
// Keep planning.sub_repos in sync with actual filesystem
const currentSubRepos = fileData.planning?.sub_repos || [];
if (Array.isArray(currentSubRepos) && currentSubRepos.length > 0) {