Implements ADR-1411 P2 / #1415, closing #1366. Part 1 — config-loader.cts: - Adds `loadConfigResolved(cwd, options) → ConfigResolution { config, source, degraded }` with six tagged branch return paths: A1 ws+wsconfig → source:'workstream', degraded:false A2 no-ws+config → source:'root', degraded:false B ws requested, wsconfig absent → source:'root', degraded:true (intercepts recursive call) C .planning/ exists, no config → source:'builtin-defaults', degraded:false D no .planning/, global defaults readable → source:'global-defaults', degraded:false E no .planning/, no global → source:'builtin-defaults', degraded:false - `loadConfigResolved` calls `findProjectRoot` at entry to anchor resolution to the nearest .planning/ ancestor (cwd-drift fix, heuristic 4 from P1) - `loadConfig` becomes a one-line delegation: `return loadConfigResolved(cwd, options).config` - Exports `loadConfigResolved` in the `export =` block Part 2 — init.cts cmdAgentSkills: - Imports `findProjectRoot` from `./project-root.cjs` - Anchors to project root before loading config (fixes #1366 cwd-drift) - Uses `loadConfigResolved` for provenance; passes projectRoot to buildAgentSkillsBlock - Computes `configured` + `reason` (AgentSkillsReason enum): 'resolved' | 'not_configured' | 'configured_empty' | 'configured_unresolved' - configured_empty and configured_unresolved emit stderr WARNING; not_configured is silent - --json IR gains: configured, reason, source, degraded (in addition to existing agent_type, block, skills_count, warnings) Tests (TDD): - tests/config-loader.test.cjs: 8 new provenance tests (RED before impl, GREEN after) - tests/agent-skills.test.cjs: 7 new diagnostic tests (RED before impl, GREEN after) - All 306 tests across 4 suites pass (config-loader:33, agent-skills:72, init:105, workstream:96) Docs: - CONTEXT.md: Config Loader Module entry updated with loadConfigResolved interface; Resolution Provenance entry notes P2 is now implemented - docs/CLI-TOOLS.md: --json field reference table added for agent-skills Closes #1366 Part of #1411 Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
5
.changeset/fix-1415-loadconfig-provenance.md
Normal file
5
.changeset/fix-1415-loadconfig-provenance.md
Normal file
@@ -0,0 +1,5 @@
|
||||
---
|
||||
type: Fixed
|
||||
pr: 1424
|
||||
---
|
||||
**`gsd-tools query agent-skills` no longer silently drops a configured agent's skills under cwd or workstream drift** — `cmdAgentSkills` now anchors to the project root via `findProjectRoot` before loading config, so invoking it from a descendant subdirectory or with a `GSD_WORKSTREAM` that has no scoped config correctly resolves the configured `agent_skills` block. A new `loadConfigResolved(cwd, options) → { config, source, degraded }` function reports provenance alongside the config object: `source` distinguishes `'root' | 'workstream' | 'builtin-defaults' | 'global-defaults'`; `degraded:true` signals a workstream was requested but its config.json was absent. The `--json` IR of `agent-skills` gains four new fields — `configured` (bool), `reason` (`'resolved' | 'not_configured' | 'configured_empty' | 'configured_unresolved'`), `source`, and `degraded` — making silent failures visible and testable. A `configured_empty` or `configured_unresolved` agent emits a `stderr WARNING`; an unconfigured agent stays silent. (Closes #1366. Part of #1411, P2 / #1415.)
|
||||
@@ -95,7 +95,7 @@ Module owning project-root resolution from any starting directory. Walks the anc
|
||||
Module owning projection from project/workstream context to concrete `.planning` paths. Policy precedence is `explicit workstream > env workstream > env project > root`. Invalid workspace context is a validation error at this seam rather than a silent fallback.
|
||||
|
||||
### Resolution Provenance
|
||||
Cross-seam principle (ADR-1411, epic #1411): context resolution — config loading, project-root anchoring, workstream resolution — must report its provenance, not fall open silently to defaults. A resolver anchors deterministically to the project root (one walk-up module, no dependence on an arbitrary descendant cwd), returns *what* it resolved **and** *where it came from* (`source`/`degraded`), and surfaces a diagnostic when a *configured* input resolves empty (`not configured` and `configured-but-empty` are distinguishable). The resolution-side analog of ADR-227 (input-validation shape). Target seams: Config Loader Module (`loadConfig` → `ConfigResolution { config, source, degraded }`), Project-Root Resolution Module (single nearest-`.planning/` walk-up, retiring ad-hoc resolvers like `resolvePlanningCwd`), I/O Module (`Resolution<T> { value, configured, reason, warnings }` output envelope). A configured input resolving empty without a reason is a CI-guarded regression.
|
||||
Cross-seam principle (ADR-1411, epic #1411): context resolution — config loading, project-root anchoring, workstream resolution — must report its provenance, not fall open silently to defaults. A resolver anchors deterministically to the project root (one walk-up module, no dependence on an arbitrary descendant cwd), returns *what* it resolved **and** *where it came from* (`source`/`degraded`), and surfaces a diagnostic when a *configured* input resolves empty (`not configured` and `configured-but-empty` are distinguishable). The resolution-side analog of ADR-227 (input-validation shape). Target seams: Config Loader Module (`loadConfig` → `ConfigResolution { config, source, degraded }`), Project-Root Resolution Module (single nearest-`.planning/` walk-up, retiring ad-hoc resolvers like `resolvePlanningCwd`), I/O Module (`Resolution<T> { value, configured, reason, warnings }` output envelope). A configured input resolving empty without a reason is a CI-guarded regression. **P1 (nearest-.planning/ heuristic) shipped in #1413; P2 (loadConfigResolved + agent-skills diagnostic) shipped in #1415 / closes #1366**: `loadConfigResolved` now implements the Config Loader seam target; `cmdAgentSkills` uses `findProjectRoot` + `loadConfigResolved` and emits `configured`/`reason`/`source`/`degraded` in its `--json` IR.
|
||||
|
||||
### Worktree Safety Policy Module
|
||||
CJS Module owning worktree lifecycle safety policy for the GSD orchestration layer. Interface: `resolveWorktreeContext(cwd, deps) → WorktreeContext` (linked-worktree root mapping), `parseWorktreePorcelain(output) → WorktreeEntry[]` (porcelain parser, skips detached HEAD), `planWorktreePrune(repoRoot, opts, deps) → PrunePlan` (metadata-prune plan, never destructive by default), `executeWorktreePrunePlan(plan, deps) → PruneResult` (executes prune; degrades gracefully on git timeout), `listLinkedWorktreePaths(repoRoot, deps) → LinkedPathsResult`, `inspectWorktreeHealth(repoRoot, opts, deps) → HealthResult` (orphan + stale detection), `snapshotWorktreeInventory(repoRoot, opts, deps) → InventoryResult`, `planWorktreeWaveCleanup(repoRoot, manifest) → CleanupPlan` (manifest-scoped, fail-closed), `executeWorktreeWaveCleanupPlan(plan, deps) → CleanupResult`. Source of truth: `gsd-core/bin/lib/worktree-safety.cjs`. Timeout path: all git subprocess calls are bounded; callers receive `ok:false, reason:'git_timed_out'` rather than a thrown exception. Test anchor: `tests/worktree-safety.test.cjs`. The `core.cjs` re-export spine was retired in epic #1267: this module absorbed the two thin compositional wrappers that squatted in Core — `resolveWorktreeRoot(cwd, deps)` (a projection over `resolveWorktreeContext`) and `pruneOrphanedWorktrees(...)` (sequences `planWorktreePrune` + `executeWorktreePrunePlan` with a timeout warning) — so callers reach this single worktree-lifecycle seam directly. `gitWorktreeInfoInternal` did NOT move here — worktree-info detection belongs to the Git Query Module.
|
||||
@@ -134,7 +134,7 @@ Module owning the shared low-level utility primitives extracted from Core: POSIX
|
||||
Module owning agent-presence resolution and verification, extracted from the Core module as the cleanup step that retired the `core.cjs` re-export spine (the final ADR-857 decomposition, epic #1267). Interface: `getAgentsDir(runtime?, env?)` — env-var-aware, runtime-aware agents-directory resolution (the `claude` runtime resolves `__dirname`-relative); `checkAgentsInstalled(...)` — multi-runtime agent-presence check that validates `gsd-file-manifest.json` completeness and confirms the declared agents exist on disk. Pure read/verify — no install-write side effects (writes remain the Installer Module's). Consumed by the Init Command Module, the verify workflow, and the docs workflow. Source of truth: `gsd-core/bin/lib/agent-install-check.cjs` (generated from `src/agent-install-check.cts`); replaced the two functions that squatted in `core.cts`. See Installer Module and ADR-857.
|
||||
|
||||
### Config Loader Module
|
||||
Module owning project configuration loading: reads `.planning/config.json`, merges built-in defaults (`CONFIG_DEFAULTS`/`CANONICAL_CONFIG_DEFAULTS`), normalizes legacy keys, applies the active-workstream overlay, validates against the config schema, and warns on unknown keys/profile overrides (`loadConfig` plus its `_deepMergeConfig`/`isGitIgnored`/`_warnUnknownProfileOverrides` helpers). Depends only on leaf modules (`configuration`, `config-schema`, `planning-workspace`, `shell-command-projection`, `core-utils`, `model-catalog`) — no other core dependency. Extracted from the Core module per ADR-857 rollout phase 2e (#885) as the prerequisite for the model-resolver extraction (the resolvers call `loadConfig`); the `core.cjs` re-export spine was retired in epic #1267, so callers import this leaf directly. Source of truth: `gsd-core/bin/lib/config-loader.cjs` (generated from `src/config-loader.cts`).
|
||||
Module owning project configuration loading: reads `.planning/config.json`, merges built-in defaults (`CONFIG_DEFAULTS`/`CANONICAL_CONFIG_DEFAULTS`), normalizes legacy keys, applies the active-workstream overlay, validates against the config schema, and warns on unknown keys/profile overrides. Primary interface: `loadConfigResolved(cwd, options) → ConfigResolution { config, source, degraded }` (provenance-aware, ADR-1411 P2 / #1415) — `source` ∈ `'workstream' | 'root' | 'builtin-defaults' | 'global-defaults'`; `degraded:true` when a workstream was requested but its config.json was absent (fell back to root config). `loadConfig(cwd, options) → Record<string,unknown>` is the back-compat thin wrapper over `loadConfigResolved` (byte-identical result). Resolution is **caller-anchored, not loader-anchored**: `loadConfigResolved` resolves `cwd` as-is (no walk-up), so `loadConfig` stays byte-identical for its callers; callers that need cwd-drift tolerance (e.g. `cmdAgentSkills`) anchor to the project root via `findProjectRoot` (Project-Root Resolution Module) *before* calling `loadConfigResolved`. Helper exports: `_deepMergeConfig`, `isGitIgnored`, `_warnUnknownProfileOverrides`. Depends only on leaf modules (`configuration`, `config-schema`, `planning-workspace`, `shell-command-projection`, `core-utils`, `model-catalog`) — no other core dependency. Extracted from the Core module per ADR-857 rollout phase 2e (#885) as the prerequisite for the model-resolver extraction (the resolvers call `loadConfig`); the `core.cjs` re-export spine was retired in epic #1267, so callers import this leaf directly. Source of truth: `gsd-core/bin/lib/config-loader.cjs` (generated from `src/config-loader.cts`).
|
||||
|
||||
### Model Resolver Module
|
||||
Module owning model and effort resolution policy: resolves the model, runtime tier, planning granularity, reasoning effort, and fast-mode for a given agent by reading project config and resolving against the model profiles and catalog (`resolveModelInternal`, `resolveModelPolicy`, `resolveTierEntry`, `resolveModelForTier`, `resolveGranularityInternal`, `resolveEffortInternal`, `resolveFastModeInternal`, `resolveEffortForTier`, `nextEffort`, `assertValidGranularityOverride`). Depends only on leaf modules (`config-loader` for `loadConfig`, `configuration` for defaults, `model-profiles` and `model-catalog` for the static tables) — no other core dependency. Extracted from the Core module per ADR-857 rollout phase 2f (#888) — the final core.cts decomposition step; the `core.cjs` re-export spine was retired in epic #1267, so callers import this leaf directly. Source of truth: `gsd-core/bin/lib/model-resolver.cjs` (generated from `src/model-resolver.cts`).
|
||||
|
||||
@@ -425,11 +425,26 @@ Emit the skill block for a given agent type.
|
||||
# Emit raw XML skill block (default — safe for shell expansion)
|
||||
node gsd-tools.cjs agent-skills <agent-type>
|
||||
|
||||
# Emit typed JSON surface (#455) — { agent_type, block, skills_count, warnings }
|
||||
# Emit typed JSON surface (#455) — { agent_type, block, skills_count, warnings, configured, reason, source, degraded }
|
||||
node gsd-tools.cjs agent-skills <agent-type> --json
|
||||
```
|
||||
|
||||
The `--json` flag returns a typed IR object suitable for structured consumption and test assertions, while the default (no flag) preserves the raw XML output that workflow shell expansions rely on. The IR also includes a `warnings` array naming any configured skill paths that were skipped (for example a missing `SKILL.md`); it is empty when every configured skill resolved.
|
||||
The `--json` flag returns a typed IR object suitable for structured consumption and test assertions, while the default (no flag) preserves the raw XML output that workflow shell expansions rely on.
|
||||
|
||||
**`--json` field reference** (as of #1415, Resolution Provenance P2):
|
||||
|
||||
| Field | Type | Description |
|
||||
|---|---|---|
|
||||
| `agent_type` | `string` | The agent type that was queried. |
|
||||
| `block` | `string` | The `<agent_skills>` XML block, or `""` when empty. |
|
||||
| `skills_count` | `number` | Number of skill paths configured for this agent type. |
|
||||
| `warnings` | `string[]` | Per-path warnings for skills that were skipped (missing `SKILL.md`, unsafe path, etc.). Empty when all configured paths resolved. |
|
||||
| `configured` | `boolean` | `true` when the agent type appears in `agent_skills` in the config; `false` when the key is absent entirely. |
|
||||
| `reason` | `string` | Resolution reason: `"resolved"` (block non-empty), `"not_configured"` (agent not in `agent_skills` — silent), `"configured_empty"` (configured but paths list is empty — emits stderr WARNING), `"configured_unresolved"` (configured with paths but all failed to resolve — emits stderr WARNING). |
|
||||
| `source` | `string` | Config provenance: `"root"` (`.planning/config.json`), `"workstream"` (workstream-scoped config), `"global-defaults"` (`~/.gsd/defaults.json`), `"builtin-defaults"` (no project config). |
|
||||
| `degraded` | `boolean` | `true` when a workstream was requested but its config.json was absent and the command fell back to root config; `false` otherwise. |
|
||||
|
||||
The command anchors to the project root via `findProjectRoot` before loading config, so invoking it from a descendant subdirectory resolves the same config as the project root.
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -368,25 +368,57 @@ function _applyFederatedOverlay(
|
||||
return cloned;
|
||||
}
|
||||
|
||||
function loadConfig(cwd: string, options: Record<string, unknown> = {}): Record<string, unknown> {
|
||||
// ─── Resolution Provenance (ADR-1411, #1415) ─────────────────────────────────
|
||||
|
||||
/** Source of a resolved config: which layer actually supplied the config. */
|
||||
type ConfigSource = 'workstream' | 'root' | 'builtin-defaults' | 'global-defaults';
|
||||
|
||||
/**
|
||||
* Result of loadConfigResolved — wraps the config object with provenance metadata.
|
||||
* - source: which layer supplied the config
|
||||
* - degraded: true when a workstream was requested but its config.json was absent
|
||||
* (fell back to root config); false otherwise
|
||||
*/
|
||||
interface ConfigResolution {
|
||||
config: Record<string, unknown>;
|
||||
source: ConfigSource;
|
||||
degraded: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* loadConfigResolved — provenance-aware config loading (#1415, ADR-1411 P2).
|
||||
*
|
||||
* Identical to loadConfig in every observable way except it returns
|
||||
* { config, source, degraded } instead of just the config object.
|
||||
* loadConfig now delegates to this function (byte-identical back-compat).
|
||||
*
|
||||
* Branch → source/degraded mapping:
|
||||
* A1: ws set + ws config.json found → source:'workstream', degraded:false
|
||||
* A2: ws null + config.json found → source:'root', degraded:false
|
||||
* B: catch + .planning/ + rootParsed set (ws fallback) → source:'root', degraded:true
|
||||
* C: catch + .planning/ + rootParsed null (federated defaults) → source:'builtin-defaults', degraded:false
|
||||
* D: catch + no .planning/ + ~/.gsd/defaults.json readable → source:'global-defaults', degraded:false
|
||||
* E: catch + no .planning/ + no global → source:'builtin-defaults', degraded:false
|
||||
*/
|
||||
function loadConfigResolved(cwd: string, options: Record<string, unknown> = {}): ConfigResolution {
|
||||
// NOTE: loadConfigResolved resolves from cwd AS-IS (no walk-up).
|
||||
// Callers that need ancestor-anchoring (e.g. cmdAgentSkills) must do so
|
||||
// themselves via findProjectRoot() before calling this function.
|
||||
// This preserves back-compat for the ~30 other loadConfig callers (#1415).
|
||||
|
||||
const activeWorkstream = Object.prototype.hasOwnProperty.call(options, 'workstream')
|
||||
? options['workstream']
|
||||
: (options['workstreamContext'] && Object.prototype.hasOwnProperty.call(options['workstreamContext'], 'ws'))
|
||||
? (options['workstreamContext'] as Record<string, unknown>)['ws']
|
||||
: (process.env['GSD_WORKSTREAM'] || null);
|
||||
// When GSD_WORKSTREAM is set, load root config first so workstream config
|
||||
// can inherit from it. This prevents users from duplicating model_overrides,
|
||||
// workflow.*, etc. across every workstream config (#2714).
|
||||
const ws = typeof activeWorkstream === 'string' ? activeWorkstream : (activeWorkstream === null ? null : null);
|
||||
// #315 — per-call lazy memo: all three detection sites inside this loadConfig
|
||||
// call operate on the same cwd and the subrepo set cannot change mid-call, so
|
||||
// a single scan is sufficient. The memo is scoped to THIS call (not module-level)
|
||||
// so separate loadConfig invocations each get a fresh scan.
|
||||
// wsRequested: true when caller explicitly requested a non-empty workstream.
|
||||
// Used for source labeling (Fix 4) and early absent-dir intercept (Fix 2).
|
||||
const wsRequested = ws != null && ws !== '';
|
||||
|
||||
let cachedSubRepos: string[] | undefined;
|
||||
const getDetectedSubRepos = (): string[] => {
|
||||
if (cachedSubRepos === undefined) cachedSubRepos = detectSubRepos(cwd);
|
||||
// Return a copy: original detectSubRepos returned a fresh array per call,
|
||||
// so each site must keep an independent array (avoid cross-site aliasing).
|
||||
return cachedSubRepos.slice();
|
||||
};
|
||||
let rootParsed: ParsedConfig | null = null;
|
||||
@@ -396,10 +428,8 @@ function loadConfig(cwd: string, options: Record<string, unknown> = {}): Record<
|
||||
const raw = platformReadSync(rootConfigPath);
|
||||
if (raw === null) throw new Error('missing');
|
||||
rootParsed = JSON.parse(raw) as ParsedConfig;
|
||||
// Cycle 4: delegate all legacy-key normalization to the Configuration Module.
|
||||
const { parsed: rootNormalized, normalizations: rootNorms } = normalizeLegacyKeys(rootParsed);
|
||||
if (rootNorms.length > 0) {
|
||||
// Resolve filesystem-dependent normalizations (multiRepo → planning.sub_repos)
|
||||
for (const norm of rootNorms as unknown as NormalizationEntry[]) {
|
||||
if (norm.requiresFilesystem && !(rootNormalized as ParsedConfig).planning?.['sub_repos']) {
|
||||
const detected = getDetectedSubRepos();
|
||||
@@ -426,23 +456,15 @@ function loadConfig(cwd: string, options: Record<string, unknown> = {}): Record<
|
||||
try {
|
||||
const raw = platformReadSync(configPath);
|
||||
if (raw === null) throw new Error('missing');
|
||||
// `fileData` is the parsed content of the config.json file on disk — used
|
||||
// for migrations and writes so we never persist merged values back to disk.
|
||||
const fileData: ParsedConfig = JSON.parse(raw) as ParsedConfig;
|
||||
|
||||
// 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.
|
||||
let configDirty = false;
|
||||
{
|
||||
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 as Record<string, unknown>)[k]);
|
||||
Object.assign(fileData, normalized);
|
||||
configDirty = true;
|
||||
// Resolve filesystem-dependent normalizations (multiRepo → planning.sub_repos).
|
||||
for (const norm of normalizations as unknown as NormalizationEntry[]) {
|
||||
if (norm.requiresFilesystem && !fileData.planning?.['sub_repos']) {
|
||||
const detected = getDetectedSubRepos();
|
||||
@@ -456,7 +478,6 @@ function loadConfig(cwd: string, options: Record<string, unknown> = {}): Record<
|
||||
}
|
||||
}
|
||||
|
||||
// Keep planning.sub_repos in sync with actual filesystem
|
||||
const currentSubRepos = (fileData.planning?.['sub_repos'] as string[] | undefined) || [];
|
||||
if (Array.isArray(currentSubRepos) && currentSubRepos.length > 0) {
|
||||
const detected = getDetectedSubRepos();
|
||||
@@ -470,33 +491,21 @@ function loadConfig(cwd: string, options: Record<string, unknown> = {}): Record<
|
||||
}
|
||||
}
|
||||
|
||||
// Persist sub_repos changes (migration or sync) — write only the on-disk
|
||||
// file contents, never the merged result, to avoid polluting workstream configs.
|
||||
if (configDirty) {
|
||||
try { platformWriteSync(configPath, JSON.stringify(fileData, null, 2)); } catch { /* ignore */ }
|
||||
}
|
||||
|
||||
// Now apply root→workstream inheritance. `parsed` is the effective config
|
||||
// used for value extraction below; fileData is kept for disk writes only.
|
||||
const parsed: ParsedConfig = rootParsed
|
||||
? (_deepMergeConfig(rootParsed, fileData) as ParsedConfig ?? fileData)
|
||||
: fileData;
|
||||
|
||||
// Warn about unrecognized top-level keys so users don't silently lose config.
|
||||
const KNOWN_TOP_LEVEL = new Set([
|
||||
// Extract top-level key names from dot-notation paths (e.g., 'workflow.research' → 'workflow')
|
||||
...[...VALID_CONFIG_KEYS].map((k: string) => k.split('.')[0]),
|
||||
// Dynamic-pattern top-level containers (e.g. review, model_profile_overrides)
|
||||
...(DYNAMIC_KEY_PATTERNS as unknown as Array<{ topLevel: string }>).map(p => p.topLevel),
|
||||
// Internal keys loadConfig reads but config-set doesn't expose
|
||||
'model_overrides', 'context_window', 'resolve_model_ids', 'claude_md_path', 'effort', 'fast_mode',
|
||||
// Deprecated keys (still accepted for migration, not in config-set)
|
||||
'depth', 'multiRepo', 'branching_strategy', 'research',
|
||||
]);
|
||||
|
||||
// FIX 3: Compute federated overlay BEFORE the unknown-key warning, so that
|
||||
// federated top-level keys are added to KNOWN_TOP_LEVEL before the check runs.
|
||||
// This is hoisted out of the try-catch below so validKeys are available here.
|
||||
let _preWarningFedValidKeys: string[] = [];
|
||||
try {
|
||||
const _fedRegistrySchemaEarly = _capabilityRegistry.configSchema;
|
||||
@@ -515,7 +524,7 @@ function loadConfig(cwd: string, options: Record<string, unknown> = {}): Record<
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Defensive: if registry access fails here, proceed without pre-warning keys
|
||||
// Defensive
|
||||
}
|
||||
|
||||
const unknownKeys = Object.keys(parsed).filter(k => !KNOWN_TOP_LEVEL.has(k));
|
||||
@@ -529,7 +538,6 @@ function loadConfig(cwd: string, options: Record<string, unknown> = {}): Record<
|
||||
}
|
||||
}
|
||||
|
||||
// #2517 — Validate runtime/tier values
|
||||
_warnUnknownProfileOverrides(parsed, '.planning/config.json');
|
||||
|
||||
const get = (key: string, nested?: { section: string; field: string }): unknown => {
|
||||
@@ -554,10 +562,7 @@ function loadConfig(cwd: string, options: Record<string, unknown> = {}): Record<
|
||||
model_profile: get('model_profile') ?? defaults.model_profile,
|
||||
commit_docs: (() => {
|
||||
const explicit = get('commit_docs', { section: 'planning', field: 'commit_docs' });
|
||||
// If explicitly set in config, respect the user's choice
|
||||
if (explicit !== undefined) return explicit;
|
||||
// Auto-detection: when no explicit value and .planning/ is gitignored,
|
||||
// default to false instead of true
|
||||
if (isGitIgnored(cwd, '.planning/')) return false;
|
||||
return defaults.commit_docs;
|
||||
})(),
|
||||
@@ -587,22 +592,14 @@ function loadConfig(cwd: string, options: Record<string, unknown> = {}): Record<
|
||||
project_code: get('project_code') ?? defaults.project_code,
|
||||
subagent_timeout: get('subagent_timeout', { section: 'workflow', field: 'subagent_timeout' }) ?? defaults.subagent_timeout,
|
||||
model_overrides: (parsed['model_overrides']) || null,
|
||||
// #3023 — per-phase-type model map.
|
||||
models: (parsed['models']) || null,
|
||||
// #68 — top-level granularity
|
||||
granularity: parsed['granularity'] !== undefined ? parsed['granularity'] : null,
|
||||
// #68 — per-phase-type granularity map.
|
||||
granularities: (parsed['granularities']) || null,
|
||||
// #68 — planning sub-object
|
||||
planning: (parsed['planning']) || null,
|
||||
// #3024 — dynamic routing block.
|
||||
dynamic_routing: (parsed['dynamic_routing']) || null,
|
||||
// #2517 — runtime-aware profiles.
|
||||
runtime: (parsed['runtime']) || null,
|
||||
model_profile_overrides: (parsed['model_profile_overrides']) || null,
|
||||
// #49 — provider-neutral model policy presets.
|
||||
model_policy: (parsed['model_policy']) || null,
|
||||
// #443 — effort/fast_mode
|
||||
effort: (parsed['effort']) || null,
|
||||
fast_mode: (parsed['fast_mode']) || null,
|
||||
agent_skills: (parsed['agent_skills']) || {},
|
||||
@@ -613,18 +610,9 @@ function loadConfig(cwd: string, options: Record<string, unknown> = {}): Record<
|
||||
claude_md_assembly: (parsed['claude_md_assembly']) || null,
|
||||
};
|
||||
|
||||
// ─── ADR-857 phase 3b: federated config overlay ───────────────────────────
|
||||
// FIX 2: Use the pre-computed _preWarningFedValidKeys (from the FIX 3 block above)
|
||||
// plus a fresh overlay call to get values. The KNOWN_TOP_LEVEL was already updated.
|
||||
// TODAY: every UI key is still in the central config-schema, so isCentralKey()
|
||||
// returns true for all of them → validKeys is empty → _baseConfig is returned UNCHANGED
|
||||
// (true no-op: no clone, no reorder, byte-identical output).
|
||||
// This becomes a live channel once a key is atomically removed from the central schema.
|
||||
// ADR-857 phase 3b: federated config overlay
|
||||
try {
|
||||
if (_preWarningFedValidKeys.length > 0) {
|
||||
// There are actual federated values — re-use the already-computed overlay
|
||||
// (we run mergeFederatedConfig again here to get the values map; the validKeys
|
||||
// are guaranteed identical since it's the same inputs).
|
||||
const _fedRegistrySchema = _capabilityRegistry.configSchema;
|
||||
if (_fedRegistrySchema && typeof _fedRegistrySchema === 'object') {
|
||||
const _fedOverlay = mergeFederatedConfig({
|
||||
@@ -632,35 +620,43 @@ function loadConfig(cwd: string, options: Record<string, unknown> = {}): Record<
|
||||
isCentralKey: (key: string) => _isCentralConfigKeyFn(key),
|
||||
userConfig: parsed,
|
||||
});
|
||||
// Apply dotted-path values (e.g. "workflow.ui_phase" → _baseConfig.workflow.ui_phase)
|
||||
// WITHOUT clobbering existing keys. N-level nesting supported.
|
||||
_applyFederatedValues(_baseConfig, _fedOverlay.values, _fedOverlay.validKeys);
|
||||
}
|
||||
}
|
||||
// Pending-migration warnings are suppressed at load time to avoid noisy output on
|
||||
// every loadConfig call. They are surfaced at registry-generation time (--check/--write).
|
||||
} catch {
|
||||
// Defensive: if the federated overlay throws for any reason, return the base config unchanged.
|
||||
// This keeps loadConfig's no-throw contract intact regardless of capability registry state.
|
||||
// Defensive: keep no-throw contract
|
||||
}
|
||||
return _baseConfig;
|
||||
|
||||
// A1 vs A2: disambiguate by whether a real workstream was requested.
|
||||
// Fix 4: empty-string ws ('') resolves the root path → source:'root'.
|
||||
const source: ConfigSource = wsRequested ? 'workstream' : 'root';
|
||||
return { config: _baseConfig, source, degraded: false };
|
||||
|
||||
} catch {
|
||||
// Fall back to ~/.gsd/defaults.json only for truly pre-project contexts (#1683)
|
||||
// Fix 2: Early intercept — workstream requested but ws config.json absent (or dir absent)
|
||||
// AND root config was loaded. Covers BOTH "dir exists, no config.json" AND "dir absent".
|
||||
// This delivers the #1366 acceptance criterion: nonexistent GSD_WORKSTREAM yields root, degraded.
|
||||
if (wsRequested && rootParsed) {
|
||||
const fb = loadConfigResolved(cwd, { workstream: null });
|
||||
return { config: fb.config, source: 'root', degraded: true };
|
||||
}
|
||||
|
||||
// Branch B, C, D, E
|
||||
if (fs.existsSync(planningDir(cwd, ws))) {
|
||||
if (rootParsed) {
|
||||
// Workstream has no config.json: re-parse using root config as the sole source.
|
||||
// (FIX 2: overlay is applied recursively in the re-entrant loadConfig call)
|
||||
return loadConfig(cwd, { workstream: null });
|
||||
// Branch B: workstream requested but ws config.json absent; root config present.
|
||||
// (Only reached when wsRequested is false — e.g. ws='' with .planning/workstreams//config.json)
|
||||
const fb = loadConfigResolved(cwd, { workstream: null });
|
||||
return { config: fb.config, source: 'root', degraded: true };
|
||||
}
|
||||
// FIX 2: Apply the federated overlay on the no-config path.
|
||||
// Migrated Capability keys are surfaced from the generated registry even
|
||||
// when the project has no config.json, so schema defaults still apply.
|
||||
// Branch C: .planning/ exists but no config.json and no root config — federated/builtin defaults
|
||||
try {
|
||||
return _applyFederatedOverlay(defaults, {});
|
||||
return { config: _applyFederatedOverlay(defaults, {}), source: 'builtin-defaults', degraded: false };
|
||||
} catch {
|
||||
return defaults;
|
||||
return { config: defaults, source: 'builtin-defaults', degraded: false };
|
||||
}
|
||||
}
|
||||
// Branch D or E: no .planning/
|
||||
try {
|
||||
const home = process.env['GSD_HOME'] || os.homedir();
|
||||
const globalDefaultsPath = path.join(home, '.gsd', 'defaults.json');
|
||||
@@ -694,27 +690,34 @@ function loadConfig(cwd: string, options: Record<string, unknown> = {}): Record<
|
||||
agent_skills: (globalDefaults['agent_skills']) || {},
|
||||
response_language: (globalDefaults['response_language']) || null,
|
||||
};
|
||||
// FIX 2: Apply federated overlay on global-defaults path.
|
||||
// With the current registry this is a true no-op (returns _globalBaseCfg unchanged).
|
||||
// Branch D: global-defaults
|
||||
try {
|
||||
return _applyFederatedOverlay(_globalBaseCfg, globalDefaults);
|
||||
return { config: _applyFederatedOverlay(_globalBaseCfg, globalDefaults), source: 'global-defaults', degraded: false };
|
||||
} catch {
|
||||
return _globalBaseCfg;
|
||||
return { config: _globalBaseCfg, source: 'global-defaults', degraded: false };
|
||||
}
|
||||
} catch {
|
||||
// FIX 2: Apply federated overlay on the final fallback path.
|
||||
// With the current registry this is a true no-op (returns `defaults` unchanged).
|
||||
// Branch E: no global defaults
|
||||
try {
|
||||
return _applyFederatedOverlay(defaults, {});
|
||||
return { config: _applyFederatedOverlay(defaults, {}), source: 'builtin-defaults', degraded: false };
|
||||
} catch {
|
||||
return defaults;
|
||||
return { config: defaults, source: 'builtin-defaults', degraded: false };
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* loadConfig — backwards-compatible config loading, now a thin wrapper over loadConfigResolved.
|
||||
* Returns the config object only; for provenance metadata use loadConfigResolved.
|
||||
*/
|
||||
function loadConfig(cwd: string, options: Record<string, unknown> = {}): Record<string, unknown> {
|
||||
return loadConfigResolved(cwd, options).config;
|
||||
}
|
||||
|
||||
export = {
|
||||
loadConfig,
|
||||
loadConfigResolved,
|
||||
isGitIgnored,
|
||||
CONFIG_DEFAULTS,
|
||||
_getConfigDefault,
|
||||
|
||||
69
src/init.cts
69
src/init.cts
@@ -14,6 +14,7 @@ import { execGit, platformWriteSync, platformReadSync } from './shell-command-pr
|
||||
import io = require('./io.cjs');
|
||||
// eslint-disable-next-line @typescript-eslint/no-require-imports -- config-loader.cjs is an export= CommonJS module
|
||||
import configLoader = require('./config-loader.cjs');
|
||||
import { findProjectRoot } from './project-root.cjs';
|
||||
// eslint-disable-next-line @typescript-eslint/no-require-imports -- model-resolver.cjs is an export= CommonJS module
|
||||
import modelResolver = require('./model-resolver.cjs');
|
||||
// eslint-disable-next-line @typescript-eslint/no-require-imports -- phase-locator.cjs is an export= CommonJS module
|
||||
@@ -47,7 +48,7 @@ import gitBaseBranch = require('./git-base-branch.cjs');
|
||||
const { gitWorktreeInfoInternal } = gitBaseBranch;
|
||||
|
||||
const { output, error } = io;
|
||||
const { loadConfig } = configLoader;
|
||||
const { loadConfig, loadConfigResolved } = configLoader;
|
||||
const { resolveModelInternal, resolveGranularityInternal, assertValidGranularityOverride } = modelResolver;
|
||||
const { findPhaseInternal } = phaseLocator;
|
||||
const {
|
||||
@@ -2015,6 +2016,9 @@ function buildAgentSkillsBlock(
|
||||
return `<agent_skills>\nRead these user-configured skills:\n${lines}\n</agent_skills>`;
|
||||
}
|
||||
|
||||
/** Reason enum for agent-skills diagnostic (#1415, ADR-1411 P2). */
|
||||
type AgentSkillsReason = 'resolved' | 'not_configured' | 'configured_empty' | 'configured_unresolved';
|
||||
|
||||
function cmdAgentSkills(
|
||||
cwd: string,
|
||||
agentType: string | undefined,
|
||||
@@ -2026,24 +2030,67 @@ function cmdAgentSkills(
|
||||
return;
|
||||
}
|
||||
|
||||
const config = loadConfig(cwd);
|
||||
// Anchor to project root before loading config (#1415/#1366 cwd-drift fix).
|
||||
const projectRoot = findProjectRoot(cwd);
|
||||
const { config, source, degraded } = loadConfigResolved(projectRoot);
|
||||
const diagnostics = { warnings: [] as string[] };
|
||||
const block = buildAgentSkillsBlock(
|
||||
config,
|
||||
agentType,
|
||||
cwd,
|
||||
projectRoot,
|
||||
diagnostics,
|
||||
);
|
||||
|
||||
// Compute configured + reason for diagnostic output.
|
||||
const agentSkillsMap = (config && config['agent_skills'] && typeof config['agent_skills'] === 'object')
|
||||
? config['agent_skills'] as Record<string, unknown>
|
||||
: {};
|
||||
const configured = Object.prototype.hasOwnProperty.call(agentSkillsMap, agentType);
|
||||
|
||||
let reason: AgentSkillsReason;
|
||||
let skillPaths: unknown = configured ? agentSkillsMap[agentType] : [];
|
||||
if (!configured) {
|
||||
reason = 'not_configured';
|
||||
skillPaths = [];
|
||||
} else {
|
||||
// Normalize paths to array
|
||||
if (typeof skillPaths === 'string') skillPaths = [skillPaths];
|
||||
if (!Array.isArray(skillPaths)) skillPaths = [];
|
||||
const pathsArr = skillPaths as unknown[];
|
||||
// Fix 3: treat "" (empty string) as configured_empty — all-blank entries = no meaningful paths.
|
||||
// An array of all empty/blank strings has length > 0 but zero meaningful paths.
|
||||
const nonBlankPaths = pathsArr.filter(p => typeof p === 'string' && p.trim().length > 0);
|
||||
if (pathsArr.length === 0 || nonBlankPaths.length === 0) {
|
||||
// configured with empty array / "" / all-blank entries
|
||||
reason = 'configured_empty';
|
||||
// Reflect zero meaningful paths in the normalized array used for skills_count
|
||||
skillPaths = [];
|
||||
try {
|
||||
process.stderr.write(
|
||||
`[agent-skills] WARNING: Agent "${agentType}" is configured in agent_skills but has no skill paths — skills_count will be 0\n`
|
||||
);
|
||||
} catch { /* stderr might be closed */ }
|
||||
} else if (!block) {
|
||||
// configured with paths but all failed to resolve (warnings already emitted by buildAgentSkillsBlock)
|
||||
reason = 'configured_unresolved';
|
||||
} else {
|
||||
reason = 'resolved';
|
||||
}
|
||||
}
|
||||
|
||||
const normalizedPaths = Array.isArray(skillPaths) ? skillPaths : [];
|
||||
|
||||
if (jsonMode) {
|
||||
const skillPaths =
|
||||
(config && config.agent_skills && (config.agent_skills as Record<string, unknown>)[agentType]) || [];
|
||||
const normalizedPaths = Array.isArray(skillPaths)
|
||||
? skillPaths
|
||||
: skillPaths
|
||||
? [skillPaths]
|
||||
: [];
|
||||
output({ agent_type: agentType, block: block || '', skills_count: normalizedPaths.length, warnings: diagnostics.warnings }, raw);
|
||||
output({
|
||||
agent_type: agentType,
|
||||
block: block || '',
|
||||
skills_count: normalizedPaths.length,
|
||||
warnings: diagnostics.warnings,
|
||||
configured,
|
||||
reason,
|
||||
source,
|
||||
degraded,
|
||||
}, raw);
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -1423,3 +1423,151 @@ describe('bug #1243: plugin-namespaced agent skills', () => {
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Resolution Provenance diagnostics (#1415 / #1366) ────────────────────────
|
||||
//
|
||||
// Verifies that cmdAgentSkills uses findProjectRoot (cwd-drift anchor) and
|
||||
// loadConfigResolved (provenance-aware config loading), and that the --json IR
|
||||
// includes the new fields: configured, reason, source, degraded.
|
||||
|
||||
describe('agent-skills — Resolution Provenance (#1415)', () => {
|
||||
let tmpDir;
|
||||
|
||||
beforeEach(() => {
|
||||
tmpDir = createTempProject();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanup(tmpDir);
|
||||
});
|
||||
|
||||
test('--json IR includes configured, reason, source, degraded fields', () => {
|
||||
// Minimal smoke: just the field presence
|
||||
const r = runAgentSkillsJson(['agent-skills', 'gsd-executor'], tmpDir);
|
||||
assert.ok(r.success, `Command failed: ${r.error}`);
|
||||
assert.ok('configured' in r.ir, 'IR must include "configured" field');
|
||||
assert.ok('reason' in r.ir, 'IR must include "reason" field');
|
||||
assert.ok('source' in r.ir, 'IR must include "source" field');
|
||||
assert.ok('degraded' in r.ir, 'IR must include "degraded" field');
|
||||
});
|
||||
|
||||
test('not_configured: agent not in map → configured:false, reason:not_configured, no stderr warning', () => {
|
||||
writeConfig(tmpDir, {
|
||||
agent_skills: { 'gsd-executor': ['skills/foo'] },
|
||||
});
|
||||
const r = runGsdToolsWithStderr(['agent-skills', '--json', 'gsd-planner'], tmpDir, {
|
||||
HOME: tmpDir,
|
||||
USERPROFILE: tmpDir,
|
||||
});
|
||||
assert.ok(r.success, `Command failed: ${r.stderr}`);
|
||||
const ir = JSON.parse(r.stdout);
|
||||
assert.strictEqual(ir.configured, false);
|
||||
assert.strictEqual(ir.reason, 'not_configured');
|
||||
// No warning on stderr for not_configured
|
||||
assert.ok(
|
||||
!r.stderr.includes('WARNING'),
|
||||
`Should NOT emit WARNING for not_configured agent, got stderr: ${r.stderr}`,
|
||||
);
|
||||
});
|
||||
|
||||
test('configured_empty: agent_skills[X]=[] → configured:true, reason:configured_empty, stderr WARNING, skills_count:0', () => {
|
||||
writeConfig(tmpDir, {
|
||||
agent_skills: { 'gsd-executor': [] },
|
||||
});
|
||||
const r = runGsdToolsWithStderr(['agent-skills', '--json', 'gsd-executor'], tmpDir, {
|
||||
HOME: tmpDir,
|
||||
USERPROFILE: tmpDir,
|
||||
});
|
||||
assert.ok(r.success, `Command failed: ${r.stderr}`);
|
||||
const ir = JSON.parse(r.stdout);
|
||||
assert.strictEqual(ir.configured, true);
|
||||
assert.strictEqual(ir.reason, 'configured_empty');
|
||||
assert.strictEqual(ir.skills_count, 0);
|
||||
assert.strictEqual(ir.block, '');
|
||||
assert.ok(
|
||||
r.stderr.includes('WARNING') || r.stderr.toLowerCase().includes('warning'),
|
||||
`Should emit WARNING for configured_empty, got stderr: ${r.stderr}`,
|
||||
);
|
||||
});
|
||||
|
||||
test('configured_unresolved: configured path that does not exist → reason:configured_unresolved, stderr WARNING', () => {
|
||||
writeConfig(tmpDir, {
|
||||
agent_skills: { 'gsd-executor': ['skills/nonexistent-1415'] },
|
||||
});
|
||||
const r = runGsdToolsWithStderr(['agent-skills', '--json', 'gsd-executor'], tmpDir, {
|
||||
HOME: tmpDir,
|
||||
USERPROFILE: tmpDir,
|
||||
});
|
||||
assert.ok(r.success, `Command failed: ${r.stderr}`);
|
||||
const ir = JSON.parse(r.stdout);
|
||||
assert.strictEqual(ir.configured, true);
|
||||
assert.strictEqual(ir.reason, 'configured_unresolved');
|
||||
assert.strictEqual(ir.block, '');
|
||||
assert.ok(
|
||||
r.stderr.includes('WARNING') || r.stderr.toLowerCase().includes('warning'),
|
||||
`Should emit WARNING for configured_unresolved, got stderr: ${r.stderr}`,
|
||||
);
|
||||
});
|
||||
|
||||
test('resolved: valid configured path → configured:true, reason:resolved, block non-empty', () => {
|
||||
const skillDir = path.join(tmpDir, 'skills', 'my-skill-1415');
|
||||
fs.mkdirSync(skillDir, { recursive: true });
|
||||
fs.writeFileSync(path.join(skillDir, 'SKILL.md'), '# My Skill\n');
|
||||
writeConfig(tmpDir, {
|
||||
agent_skills: { 'gsd-executor': ['skills/my-skill-1415'] },
|
||||
});
|
||||
const r = runAgentSkillsJson(['agent-skills', 'gsd-executor'], tmpDir);
|
||||
assert.ok(r.success, `Command failed: ${r.error}`);
|
||||
assert.strictEqual(r.ir.configured, true);
|
||||
assert.strictEqual(r.ir.reason, 'resolved');
|
||||
assert.ok(r.ir.block.includes('<agent_skills>'), 'block must be non-empty for resolved');
|
||||
});
|
||||
|
||||
test('cwd-drift: invoking from descendant subdir resolves config from project root', () => {
|
||||
const skillDir = path.join(tmpDir, 'skills', 'drift-skill');
|
||||
fs.mkdirSync(skillDir, { recursive: true });
|
||||
fs.writeFileSync(path.join(skillDir, 'SKILL.md'), '# Drift Skill\n');
|
||||
writeConfig(tmpDir, {
|
||||
agent_skills: { 'gsd-executor': ['skills/drift-skill'] },
|
||||
});
|
||||
// Invoke from a descendant subdirectory
|
||||
const deepDir = path.join(tmpDir, 'src', 'feature');
|
||||
fs.mkdirSync(deepDir, { recursive: true });
|
||||
const r = runAgentSkillsJson(['agent-skills', 'gsd-executor'], deepDir);
|
||||
assert.ok(r.success, `Command failed: ${r.error}`);
|
||||
assert.strictEqual(r.ir.configured, true);
|
||||
assert.strictEqual(r.ir.reason, 'resolved');
|
||||
assert.ok(r.ir.block.includes('<agent_skills>'), `block must be non-empty for drift test, got: ${r.ir.block}`);
|
||||
});
|
||||
|
||||
test('source field matches config provenance (root when config.json present)', () => {
|
||||
writeConfig(tmpDir, {
|
||||
agent_skills: { 'gsd-executor': [] },
|
||||
});
|
||||
const r = runAgentSkillsJson(['agent-skills', 'gsd-executor'], tmpDir);
|
||||
assert.ok(r.success, `Command failed: ${r.error}`);
|
||||
assert.strictEqual(r.ir.source, 'root');
|
||||
assert.strictEqual(r.ir.degraded, false);
|
||||
});
|
||||
|
||||
test('Fix 3: agent_skills[X]="" (empty string) → configured_empty, skills_count:0, stderr WARNING', () => {
|
||||
writeConfig(tmpDir, {
|
||||
agent_skills: { 'gsd-executor': '' },
|
||||
});
|
||||
const r = runGsdToolsWithStderr(['agent-skills', '--json', 'gsd-executor'], tmpDir, {
|
||||
HOME: tmpDir,
|
||||
USERPROFILE: tmpDir,
|
||||
});
|
||||
assert.ok(r.success, `Command failed: ${r.stderr}`);
|
||||
const ir = JSON.parse(r.stdout);
|
||||
assert.strictEqual(ir.configured, true, 'should be configured');
|
||||
assert.strictEqual(ir.reason, 'configured_empty',
|
||||
`empty string must yield configured_empty, got: ${ir.reason}`);
|
||||
assert.strictEqual(ir.skills_count, 0, 'skills_count must be 0 for empty string');
|
||||
assert.strictEqual(ir.block, '', 'block must be empty');
|
||||
assert.ok(
|
||||
r.stderr.includes('WARNING') || r.stderr.toLowerCase().includes('warning'),
|
||||
`Should emit WARNING for empty-string configured_empty, got stderr: ${r.stderr}`,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -28,7 +28,7 @@ const { cleanup } = require('./helpers.cjs');
|
||||
|
||||
const configLoader = require('../gsd-core/bin/lib/config-loader.cjs');
|
||||
|
||||
const { loadConfig, _resetRuntimeWarningCacheForTests } = configLoader;
|
||||
const { loadConfig, loadConfigResolved, _resetRuntimeWarningCacheForTests } = configLoader;
|
||||
|
||||
// ─── helpers ──────────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -333,3 +333,162 @@ describe('loadConfig — adversarial fixtures', () => {
|
||||
assert.equal(config.model_profile, 'balanced');
|
||||
});
|
||||
});
|
||||
|
||||
// ─── loadConfigResolved — provenance ──────────────────────────────────────────
|
||||
|
||||
describe('loadConfigResolved — provenance', () => {
|
||||
let tmpDir;
|
||||
|
||||
beforeEach(() => { tmpDir = makeTempProject(); });
|
||||
afterEach(() => { if (tmpDir) cleanup(tmpDir); tmpDir = null; });
|
||||
|
||||
test('source is "root" when config.json exists and no workstream requested', () => {
|
||||
writeConfig(tmpDir, { model_profile: 'quality' });
|
||||
const result = loadConfigResolved(tmpDir);
|
||||
assert.equal(result.source, 'root');
|
||||
assert.equal(result.degraded, false);
|
||||
assert.ok(typeof result.config === 'object', 'config must be an object');
|
||||
assert.equal(result.config.model_profile, 'quality');
|
||||
});
|
||||
|
||||
test('source is "workstream", degraded:false when workstream config.json present', () => {
|
||||
writeConfig(tmpDir, { model_profile: 'balanced' });
|
||||
writeWorkstreamConfig(tmpDir, 'ws-a', { model_profile: 'quality' });
|
||||
const result = loadConfigResolved(tmpDir, { workstream: 'ws-a' });
|
||||
assert.equal(result.source, 'workstream');
|
||||
assert.equal(result.degraded, false);
|
||||
assert.equal(result.config.model_profile, 'quality');
|
||||
});
|
||||
|
||||
test('source is "root", degraded:true when workstream requested but ws config.json absent', () => {
|
||||
writeConfig(tmpDir, { model_profile: 'budget' });
|
||||
// Create ws directory without config.json
|
||||
const wsDir = path.join(tmpDir, '.planning', 'workstreams', 'ws-no-config');
|
||||
fs.mkdirSync(path.join(wsDir, 'phases'), { recursive: true });
|
||||
const result = loadConfigResolved(tmpDir, { workstream: 'ws-no-config' });
|
||||
assert.equal(result.source, 'root');
|
||||
assert.equal(result.degraded, true);
|
||||
assert.equal(result.config.model_profile, 'budget');
|
||||
});
|
||||
|
||||
test('source is "builtin-defaults" when .planning exists but config.json is absent', () => {
|
||||
// tmpDir already has .planning/ but no config.json
|
||||
const result = loadConfigResolved(tmpDir);
|
||||
assert.equal(result.source, 'builtin-defaults');
|
||||
assert.equal(result.degraded, false);
|
||||
assert.ok('model_profile' in result.config);
|
||||
});
|
||||
|
||||
test('source is "global-defaults" when no .planning exists but ~/.gsd/defaults.json readable', () => {
|
||||
const homeTmp = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-home-test-'));
|
||||
const origGsdHome = process.env['GSD_HOME'];
|
||||
try {
|
||||
const gsdDir = path.join(homeTmp, '.gsd');
|
||||
fs.mkdirSync(gsdDir, { recursive: true });
|
||||
fs.writeFileSync(path.join(gsdDir, 'defaults.json'), JSON.stringify({ model_profile: 'home-defaults' }), 'utf-8');
|
||||
process.env['GSD_HOME'] = homeTmp;
|
||||
const noPlanning = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-noplanning-'));
|
||||
try {
|
||||
const result = loadConfigResolved(noPlanning);
|
||||
assert.equal(result.source, 'global-defaults');
|
||||
assert.equal(result.degraded, false);
|
||||
assert.equal(result.config.model_profile, 'home-defaults');
|
||||
} finally {
|
||||
cleanup(noPlanning);
|
||||
}
|
||||
} finally {
|
||||
if (origGsdHome === undefined) delete process.env['GSD_HOME'];
|
||||
else process.env['GSD_HOME'] = origGsdHome;
|
||||
cleanup(homeTmp);
|
||||
}
|
||||
});
|
||||
|
||||
test('source is "builtin-defaults" when no .planning and no global defaults', () => {
|
||||
const noPlanning = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-noplanning2-'));
|
||||
const homeTmp = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-nohome-'));
|
||||
const origGsdHome = process.env['GSD_HOME'];
|
||||
try {
|
||||
// Point GSD_HOME to a directory with no .gsd/defaults.json
|
||||
process.env['GSD_HOME'] = homeTmp;
|
||||
const result = loadConfigResolved(noPlanning);
|
||||
assert.equal(result.source, 'builtin-defaults');
|
||||
assert.equal(result.degraded, false);
|
||||
assert.ok('model_profile' in result.config);
|
||||
} finally {
|
||||
if (origGsdHome === undefined) delete process.env['GSD_HOME'];
|
||||
else process.env['GSD_HOME'] = origGsdHome;
|
||||
cleanup(noPlanning);
|
||||
cleanup(homeTmp);
|
||||
}
|
||||
});
|
||||
|
||||
test('back-compat: loadConfig(tmp) deepEquals loadConfigResolved(tmp).config', () => {
|
||||
writeConfig(tmpDir, { model_profile: 'quality', research: 'minimal' });
|
||||
const fromLoadConfig = loadConfig(tmpDir);
|
||||
const { config: fromResolved } = loadConfigResolved(tmpDir);
|
||||
assert.deepEqual(fromLoadConfig, fromResolved);
|
||||
});
|
||||
|
||||
test('back-compat: loadConfigResolved(descendant) does NOT walk up — returns defaults, not ancestor config', () => {
|
||||
// Fix 1: loadConfigResolved must NOT call findProjectRoot internally.
|
||||
// Calling from a descendant that has no .planning/ of its own must return
|
||||
// defaults (builtin-defaults source), NOT the ancestor's config value.
|
||||
writeConfig(tmpDir, { model_profile: 'ancestor-config-should-not-appear' });
|
||||
const deepDir = path.join(tmpDir, 'src', 'deep');
|
||||
fs.mkdirSync(deepDir, { recursive: true });
|
||||
const result = loadConfigResolved(deepDir);
|
||||
// No .planning/ in deepDir → must fall back to defaults, NOT walk up to tmpDir.
|
||||
assert.notEqual(result.config.model_profile, 'ancestor-config-should-not-appear',
|
||||
'loadConfigResolved must NOT walk up to find ancestor config');
|
||||
// The source must be a defaults source (builtin-defaults or global-defaults),
|
||||
// NOT "root" (which would imply a config.json was found).
|
||||
assert.ok(
|
||||
result.source === 'builtin-defaults' || result.source === 'global-defaults',
|
||||
`Expected a defaults source, got: ${result.source}`,
|
||||
);
|
||||
});
|
||||
|
||||
test('Fix 4: loadConfigResolved(tmp, { workstream: "" }) → source:"root"', () => {
|
||||
writeConfig(tmpDir, { model_profile: 'quality' });
|
||||
// empty-string ws resolves the root path → source must be "root"
|
||||
const result = loadConfigResolved(tmpDir, { workstream: '' });
|
||||
assert.equal(result.source, 'root', 'empty-string workstream should yield source:"root"');
|
||||
assert.equal(result.degraded, false);
|
||||
});
|
||||
|
||||
test('Fix 2a: GSD_WORKSTREAM set to nonexistent workstream (dir absent) → source:"root", degraded:true', () => {
|
||||
writeConfig(tmpDir, { model_profile: 'root-value' });
|
||||
const origWs = process.env['GSD_WORKSTREAM'];
|
||||
try {
|
||||
process.env['GSD_WORKSTREAM'] = 'nonexistent-ws';
|
||||
// Do NOT create the workstream directory
|
||||
const result = loadConfigResolved(tmpDir);
|
||||
assert.equal(result.source, 'root', 'nonexistent workstream should fall back to source:"root"');
|
||||
assert.equal(result.degraded, true, 'should be degraded when workstream dir is absent');
|
||||
assert.equal(result.config.model_profile, 'root-value', 'config should equal root config');
|
||||
} finally {
|
||||
if (origWs === undefined) delete process.env['GSD_WORKSTREAM'];
|
||||
else process.env['GSD_WORKSTREAM'] = origWs;
|
||||
}
|
||||
});
|
||||
|
||||
test('Fix 2b: options.workstream missing dir → source:"root", degraded:true', () => {
|
||||
writeConfig(tmpDir, { model_profile: 'root-val' });
|
||||
// workstream dir NOT created
|
||||
const result = loadConfigResolved(tmpDir, { workstream: 'missing-ws' });
|
||||
assert.equal(result.source, 'root');
|
||||
assert.equal(result.degraded, true);
|
||||
assert.equal(result.config.model_profile, 'root-val');
|
||||
});
|
||||
|
||||
test('Fix 2c: workstream dir exists but no config.json → source:"root", degraded:true (existing case still works)', () => {
|
||||
writeConfig(tmpDir, { model_profile: 'root-val-c' });
|
||||
// Create ws dir but no config.json
|
||||
const wsDir = path.join(tmpDir, '.planning', 'workstreams', 'ws-no-cfg');
|
||||
fs.mkdirSync(path.join(wsDir, 'phases'), { recursive: true });
|
||||
const result = loadConfigResolved(tmpDir, { workstream: 'ws-no-cfg' });
|
||||
assert.equal(result.source, 'root');
|
||||
assert.equal(result.degraded, true);
|
||||
assert.equal(result.config.model_profile, 'root-val-c');
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user