fix(workstream): normalize migration workstream names (#3269)

* fix(workstream): normalize migrate-name to valid slug

* docs(context): record workstream migrate-name slug invariant

* fix(catalog-cjs): balanced fallback for unknown profile (CR finding A)

profiles[profile] could return undefined for any profile key absent from
the catalog entry, causing downstream callers like formatAgentToModelMapAsTable
to crash on .length. Add ?? profiles.balanced fallback to match the SDK adapter.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* test(sdk): anchor path resolution on import.meta.url not cwd (CR finding B)

resolve(process.cwd(), '..') breaks when Vitest is invoked from the repo root
because cwd is already the repo root and '..' goes one level above. Replace
with a file-relative path using fileURLToPath(new URL('../../../', import.meta.url))
anchored at the test file's location (sdk/src/query/).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* test: derive Group B runtime list from catalog (CR finding C)

Hardcoded ['kilo', 'cline', ...] throws TypeError if a runtime name is
removed from the catalog. Derive group B dynamically via
Object.keys(catalog.runtimeTierDefaults).filter(r => !r.opus) so the
test never goes stale and auto-covers future Group B additions.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* docs(workflow): add hermes to Step B runtime options (CR finding D)

hermes appears in the Group A built-in defaults table but was missing from
the AskUserQuestion options in Step B, forcing users to manually type it via
'Other (Group B or custom)'. Add explicit hermes entry for UI consistency.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* docs(config): refresh dynamic_routing tier table; fix stale L671 (findings E+F)

Finding E: tier table was missing 6 heavy-tier agents and 15 standard/light
agents added by this PR. Updated all three rows to match catalog routingTier
assignments (33 agents total).

Finding F: removed stale '18 of 31' claim and agent enumeration; replaced
with accurate note that all 33 agents have explicit catalog entries. Updated
authoritative source pointers to model-catalog.cjs / model-catalog.ts.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* test(core): add profile-fallback unit tests for quality and budget (CR nitpick G)

The PR introduced quality→opus and budget→haiku unknown-agent fallbacks but
only balanced→sonnet and inherit→inherit were tested. Add two tests covering
the remaining two branches to complete coverage.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* adr: define planning workspace and worktree seam

* refactor(worktree): extract worktree safety policy module

* refactor(workstream): extract active workstream pointer store seam

* test(worktree): cover policy branch paths and persist seam guardrails

* refactor(worktree): centralize health inventory seam for W017

* fix(workspace): align SDK project path policy with CJS planningDir

* refactor(query): unify SDK planning path projection seam

* refactor(init): route workspace projection through planningPaths seam

* docs(adr): add SDK architecture and planning path ADRs

* refactor(worktree): deepen name, pointer, inventory, and config seams

* docs(config): harmonize claude-opus-4-6 to 4-7 in resolve_model_ids example (CR finding 2)

* fix(sdk): return undefined for model_profile='inherit' sentinel (CR finding 3)

* docs(adr): renumber conflicting 0003-sdk-package-seam-module to 0007, update seam-map reference (CR finding 4)

* fix(workstream): align CJS and SDK name validation to accept dots, guard path traversal via includes('..') (CR finding 5)

* fix(sdk): guard writeActiveWorkstream against non-existent workstream directory, k014/k031 parity (CR finding 6)

* chore(changeset): add #3269 changeset (CR finding 1 — proper changeset for this PR)

* docs(inventory): register 3 new CLI modules in INVENTORY.md/MANIFEST (active-workstream-store, workstream-name-policy, worktree-safety)

* fix(sdk): use relPlanningPath(workstream) in planningPaths, fix setActiveWorkstream/getActiveWorkstream name errors in workstream.ts

* fix(sdk): validate GSD_WORKSTREAM in planningPaths before use (#3269 regression)

planningPaths() called resolveWorkspaceContext() which returned GSD_WORKSTREAM
raw (no validation). An invalid value like '../evil' was used as effectiveWorkstream,
constructing a bad path; roadmapAnalyze() caught the ENOENT and returned a
no-phase_count error object instead of the root ROADMAP result.

Fix: validate envCtx.workstream with validateWorkstreamName() in planningPaths()
before accepting it as effectiveWorkstream. Invalid env → null → root .planning/
fallback, preserving the bug-2791 contract: invalid GSD_WORKSTREAM is silently
ignored and falls back to the root context (phase_count: 0 for empty root ROADMAP).

The bug-2791 regression test now passes. No other call sites read GSD_WORKSTREAM
without validation: query-runtime-context.ts already validates; cli.ts already
validates; context-engine.ts takes a caller-validated workstream parameter.

Closes #3268 (regression introduced by #3269 workstream-name-policy work).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
Tom Boucher
2026-05-09 00:15:04 -04:00
committed by GitHub
parent 65abc4fc90
commit 8bc255c266
37 changed files with 1267 additions and 263 deletions

View File

@@ -8,6 +8,13 @@ const path = require('path');
const { execSync, execFileSync, spawnSync } = require('child_process');
const { MODEL_PROFILES, AGENT_TO_PHASE_TYPE, VALID_PHASE_TYPES, AGENT_DEFAULT_TIERS, VALID_AGENT_TIERS, nextTier } = require('./model-profiles.cjs');
const { MODEL_ALIAS_MAP, RUNTIME_PROFILE_MAP, KNOWN_RUNTIMES, RUNTIMES_WITH_REASONING_EFFORT } = require('./model-catalog.cjs');
const {
resolveWorktreeContext,
parseWorktreePorcelain: parseWorktreePorcelainPolicy,
planWorktreePrune,
executeWorktreePrunePlan,
inspectWorktreeHealth,
} = require('./worktree-safety.cjs');
// Compatibility shim: new imports should use planning-workspace.cjs directly.
const {
planningDir,
@@ -332,11 +339,14 @@ function _deepMergeConfig(base, overlay) {
return result;
}
function loadConfig(cwd) {
function loadConfig(cwd, options = {}) {
const activeWorkstream = Object.prototype.hasOwnProperty.call(options, 'workstream')
? options.workstream
: (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 = process.env.GSD_WORKSTREAM || null;
const ws = activeWorkstream;
let rootParsed = null;
if (ws) {
const rootConfigPath = path.join(planningRoot(cwd), 'config.json');
@@ -348,7 +358,7 @@ function loadConfig(cwd) {
}
}
const configPath = path.join(planningDir(cwd), 'config.json');
const configPath = path.join(planningDir(cwd, ws), 'config.json');
const defaults = CONFIG_DEFAULTS;
try {
@@ -535,18 +545,11 @@ function loadConfig(cwd) {
// If .planning/ exists, the project is initialized — just missing config.json.
// When GSD_WORKSTREAM is set and root config was loaded, the workstream config
// doesn't exist — treat root config as the effective config for this workstream.
if (fs.existsSync(planningDir(cwd))) {
if (fs.existsSync(planningDir(cwd, ws))) {
if (rootParsed) {
// Workstream has no config.json: re-parse using root config as the sole source.
// Temporarily clear GSD_WORKSTREAM so planningDir() returns root .planning/,
// then reload. This is safe: rootParsed is already the root config object.
const savedWs = process.env.GSD_WORKSTREAM;
delete process.env.GSD_WORKSTREAM;
try {
return loadConfig(cwd);
} finally {
process.env.GSD_WORKSTREAM = savedWs;
}
// Keep env immutable by explicitly reloading with workstream context cleared.
return loadConfig(cwd, { workstream: null });
}
return defaults;
}
@@ -740,30 +743,11 @@ function execGit(cwd, args) {
* Returns the main worktree path, or cwd if not in a worktree.
*/
function resolveWorktreeRoot(cwd) {
// If the current directory already has its own .planning/, respect it.
// This handles linked worktrees with independent planning state (e.g., Conductor workspaces).
if (fs.existsSync(path.join(cwd, '.planning'))) {
return cwd;
}
// Check if we're in a linked worktree
const gitDir = execGit(cwd, ['rev-parse', '--git-dir']);
const commonDir = execGit(cwd, ['rev-parse', '--git-common-dir']);
if (gitDir.exitCode !== 0 || commonDir.exitCode !== 0) return cwd;
// In a linked worktree, .git is a file pointing to .git/worktrees/<name>
// and git-common-dir points to the main repo's .git directory
const gitDirResolved = path.resolve(cwd, gitDir.stdout);
const commonDirResolved = path.resolve(cwd, commonDir.stdout);
if (gitDirResolved !== commonDirResolved) {
// We're in a linked worktree — resolve main worktree root
// The common dir is the main repo's .git, so its parent is the main worktree root
return path.dirname(commonDirResolved);
}
return cwd;
const context = resolveWorktreeContext(cwd, {
execGit,
existsSync: fs.existsSync,
});
return context.effectiveRoot;
}
/**
@@ -775,21 +759,7 @@ function resolveWorktreeRoot(cwd) {
* @returns {{ path: string, branch: string }[]}
*/
function parseWorktreePorcelain(porcelain) {
const entries = [];
let current = null;
for (const line of porcelain.split('\n')) {
if (line.startsWith('worktree ')) {
current = { path: line.slice('worktree '.length).trim(), branch: null };
} else if (line.startsWith('branch refs/heads/') && current) {
current.branch = line.slice('branch refs/heads/'.length).trim();
} else if (line === '' && current) {
if (current.branch) entries.push(current);
current = null;
}
}
// flush last entry if file doesn't end with blank line
if (current && current.branch) entries.push(current);
return entries;
return parseWorktreePorcelainPolicy(porcelain);
}
/**
@@ -802,31 +772,15 @@ function parseWorktreePorcelain(porcelain) {
* @returns {string[]} list of worktree paths that were removed (always empty)
*/
function pruneOrphanedWorktrees(repoRoot) {
const pruned = [];
const cwd = process.cwd();
try {
// 1. Get all worktrees in porcelain format
const listResult = execGit(repoRoot, ['worktree', 'list', '--porcelain']);
if (listResult.exitCode !== 0) return pruned;
const worktrees = parseWorktreePorcelain(listResult.stdout);
if (worktrees.length === 0) {
execGit(repoRoot, ['worktree', 'prune']);
return pruned;
}
// Destructive removal of linked worktrees is intentionally disabled.
// Keep metadata cleanup only (git worktree prune), which clears stale refs
// for manually-deleted directories without removing active sibling worktrees.
void cwd;
void worktrees;
const plan = planWorktreePrune(
repoRoot,
{ allowDestructive: false },
{ execGit, parseWorktreePorcelain }
);
executeWorktreePrunePlan(plan, { execGit });
} catch { /* never crash the caller */ }
// Always run prune to clear stale references (e.g. manually-deleted dirs)
execGit(repoRoot, ['worktree', 'prune']);
return pruned;
return [];
}
// ─── Planning workspace (pathing + active workstream + lock) moved to planning-workspace.cjs ───
@@ -2047,4 +2001,5 @@ module.exports = {
atomicWriteFileSync,
timeAgo,
pruneOrphanedWorktrees,
inspectWorktreeHealth,
};