* test(3739): add RED tests for padded-prefix CONTEXT.md gap-checker miss Covers bare and padded (01-CONTEXT.md, 02.1-CONTEXT.md) forms, an uncovered-decision counter-test, and unit tests for the upcoming findContextMdIn() helper. All 6 new tests fail before the fix. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * fix(3739): extract findContextMdIn() helper; fix gap-checker bare lookup gap-checker.cjs:136 used a bare path.join(absPhaseDir, 'CONTEXT.md') that silently returned '' for any phase using the padded-prefix convention (01-CONTEXT.md, 02.1-CONTEXT.md, etc.). Extract findContextMdIn(absDir) to planning-workspace.cjs — the module already imported by gap-checker, init, roadmap, and core — and wire gap-checker.cjs to call it instead of the bare lookup. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * refactor(3739): replace inline dual-form predicate with findContextMdIn() at all 4 remaining sites The dual-form predicate `f.endsWith('-CONTEXT.md') || f === 'CONTEXT.md'` existed verbatim at 5 sites across init.cjs (×3), roadmap.cjs, and core.cjs — Rule of Three mandates extraction at ≥3 sites. All 4 remaining call sites now delegate to findContextMdIn() from planning-workspace.cjs. No behaviour change; all existing tests pass. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * chore(3739): update changeset to reference PR #3764 * fix(3739): findContextMdIn prefers bare CONTEXT.md over padded form (deterministic precedence) `.find()` with `f.endsWith('-CONTEXT.md') || f === 'CONTEXT.md'` returned the first match in `readdirSync` order — undefined on most filesystems. When both `CONTEXT.md` and `01-CONTEXT.md` exist the winner was arbitrary. The old gap-checker.cjs:136 code always used bare `CONTEXT.md` first (existsSync on the bare path). Restore that invariant: check `files.includes('CONTEXT.md')` before falling through to the padded scan. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * test(3739): dual-file precedence test — bare CONTEXT.md wins over padded form Adds two test cases for the scenario where both CONTEXT.md and 01-CONTEXT.md exist in the same phase directory: 1. Helper level: findContextMdIn() must return 'CONTEXT.md' (not the padded filename) when both files are present on disk. 2. Integration level: gap-analysis must resolve decisions from the bare form only; D-PADDED (from 01-CONTEXT.md) must not appear when the bare form shadows it. Without these tests a future change to findContextMdIn could silently regress the precedence guarantee. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * fix(3739): bug-2798 tests skip cleanly when sdk/dist is absent (was hard-fail) The 3 tests in bug-2798-context-window-config-key.test.cjs invoke the built SDK CLI (sdk/dist/cli.js) and require sdk/dist/query/config-schema.js. When dist is absent, they threw hard errors rather than observable skips. Apply the same `if (!existsSync(...)) { t.skip(...); return; }` guard used in bug-2767-gsd-sdk-commit-files-flag.test.cjs (c2812313). Tests 1 & 2 guard on sdk/dist/cli.js; test 3 guards on sdk/dist/query/config-schema.js. When dist is present all 3 run; when absent all 3 emit actionable skip lines. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * fix(3739): eliminate double readdirSync in findContextMdIn callers findContextMdIn now accepts either a directory path or an already-read files array, allowing callers that already hold a directory listing (core.cjs:getPhaseFileStats, roadmap.cjs:countPhasePlansAndSummaries, gap-checker.cjs:runGapAnalysis) to skip redundant readdirSync calls. Test coverage added for the array-argument overload. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * test: redesign flaky concurrent add-blocker test with deterministic barrier Previous design relied on OS scheduler to interleave two subprocess writes, producing a flake under CI load. Redesigned using a file-barrier (Option A) that forces both subprocesses to reach a ready-gate before either proceeds, guaranteeing true concurrent lock contention and eliminating timing dependency. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
416 lines
12 KiB
JavaScript
416 lines
12 KiB
JavaScript
/**
|
|
* Planning Workspace — .planning path resolution + active workstream routing.
|
|
*
|
|
* This module owns the planning workspace seam:
|
|
* - planningDir/planningRoot/planningPaths
|
|
* - active workstream pointer policy (session-scoped > shared)
|
|
* - pointer storage adapters (session/shared/memory)
|
|
*/
|
|
|
|
const fs = require('fs');
|
|
const os = require('os');
|
|
const path = require('path');
|
|
const crypto = require('crypto');
|
|
const { probeTty, platformWriteSync, platformReadSync, platformEnsureDir } = require('./shell-command-projection.cjs');
|
|
const { isValidActiveWorkstreamName } = require('./workstream-name-policy.cjs');
|
|
|
|
const WORKSTREAM_SESSION_ENV_KEYS = [
|
|
'GSD_SESSION_KEY',
|
|
'CODEX_THREAD_ID',
|
|
'CLAUDE_SESSION_ID',
|
|
'CLAUDE_CODE_SSE_PORT',
|
|
'OPENCODE_SESSION_ID',
|
|
'GEMINI_SESSION_ID',
|
|
'CURSOR_SESSION_ID',
|
|
'WINDSURF_SESSION_ID',
|
|
'TERM_SESSION_ID',
|
|
'WT_SESSION',
|
|
'TMUX_PANE',
|
|
'ZELLIJ_SESSION_NAME',
|
|
];
|
|
|
|
let cachedControllingTtyToken = null;
|
|
let didProbeControllingTtyToken = false;
|
|
|
|
// Track .planning/.lock files held by this process so they can be removed on exit.
|
|
const _heldPlanningLocks = new Set();
|
|
process.on('exit', () => {
|
|
for (const lockPath of _heldPlanningLocks) {
|
|
try { fs.unlinkSync(lockPath); } catch { /* already gone */ }
|
|
}
|
|
});
|
|
|
|
// Transient errno codes that indicate a temporary filesystem condition under
|
|
// concurrent O_EXCL races — Docker overlay-fs (ENOENT/EINVAL/EIO), NFS
|
|
// (ESTALE), and OS-level interrupt/retry signals (EAGAIN/EINTR). These are
|
|
// recoverable; withPlanningLock retries instead of propagating them.
|
|
// Truly fatal codes (EMFILE, ENOSPC, EROFS, EACCES) are NOT in this set and
|
|
// will still throw immediately.
|
|
const PLANNING_LOCK_RETRY_ERRNOS = new Set([
|
|
'EPERM', // Windows / macOS AV scanner holds the file open during delete
|
|
'EBUSY', // Windows: file in use by another process
|
|
'EAGAIN', // POSIX: resource temporarily unavailable
|
|
'EINTR', // POSIX: syscall interrupted by signal
|
|
'EINVAL', // Docker overlay-fs: transient during concurrent O_EXCL creation
|
|
'EIO', // Docker overlay-fs / NFS: transient I/O error
|
|
'ENOENT', // Docker overlay-fs: parent dir transiently missing during race
|
|
'ESTALE', // NFS: stale file handle (self-resolves on retry)
|
|
]);
|
|
|
|
function planningDir(cwd, ws, project) {
|
|
if (project === undefined) project = process.env.GSD_PROJECT || null;
|
|
if (ws === undefined) ws = process.env.GSD_WORKSTREAM || null;
|
|
|
|
// Reject path separators and traversal components in project/workstream names
|
|
const BAD_SEGMENT = /[/\\]|\.\./;
|
|
if (project && BAD_SEGMENT.test(project)) {
|
|
throw new Error(`GSD_PROJECT contains invalid path characters: ${project}`);
|
|
}
|
|
if (ws && BAD_SEGMENT.test(ws)) {
|
|
throw new Error(`GSD_WORKSTREAM contains invalid path characters: ${ws}`);
|
|
}
|
|
|
|
let base = path.join(cwd, '.planning');
|
|
if (project) base = path.join(base, project);
|
|
if (ws) base = path.join(base, 'workstreams', ws);
|
|
return base;
|
|
}
|
|
|
|
function planningRoot(cwd) {
|
|
return path.join(cwd, '.planning');
|
|
}
|
|
|
|
function planningPaths(cwd, ws) {
|
|
const base = planningDir(cwd, ws);
|
|
return {
|
|
planning: base,
|
|
state: path.join(base, 'STATE.md'),
|
|
roadmap: path.join(base, 'ROADMAP.md'),
|
|
project: path.join(base, 'PROJECT.md'),
|
|
config: path.join(base, 'config.json'),
|
|
phases: path.join(base, 'phases'),
|
|
requirements: path.join(base, 'REQUIREMENTS.md'),
|
|
};
|
|
}
|
|
|
|
function sanitizeWorkstreamSessionToken(value) {
|
|
if (value === null || value === undefined) return null;
|
|
const token = String(value).trim().replace(/[^a-zA-Z0-9._-]+/g, '_').replace(/^_+|_+$/g, '');
|
|
return token ? token.slice(0, 160) : null;
|
|
}
|
|
|
|
function probeControllingTtyToken() {
|
|
if (didProbeControllingTtyToken) return cachedControllingTtyToken;
|
|
didProbeControllingTtyToken = true;
|
|
|
|
// `tty` reads stdin. When stdin is already non-interactive, spawning it only
|
|
// adds avoidable failures on the routing hot path and cannot reveal a stable token.
|
|
if (!(process.stdin && process.stdin.isTTY)) {
|
|
return cachedControllingTtyToken;
|
|
}
|
|
|
|
const ttyPath = probeTty();
|
|
if (ttyPath) {
|
|
const token = sanitizeWorkstreamSessionToken(ttyPath.replace(/^\/dev\//, ''));
|
|
if (token) cachedControllingTtyToken = `tty-${token}`;
|
|
}
|
|
|
|
return cachedControllingTtyToken;
|
|
}
|
|
|
|
function getControllingTtyToken() {
|
|
for (const envKey of ['TTY', 'SSH_TTY']) {
|
|
const token = sanitizeWorkstreamSessionToken(process.env[envKey]);
|
|
if (token) return `tty-${token.replace(/^dev_/, '')}`;
|
|
}
|
|
|
|
return probeControllingTtyToken();
|
|
}
|
|
|
|
function getWorkstreamSessionKey() {
|
|
for (const envKey of WORKSTREAM_SESSION_ENV_KEYS) {
|
|
const raw = process.env[envKey];
|
|
const token = sanitizeWorkstreamSessionToken(raw);
|
|
if (token) return `${envKey.toLowerCase().replace(/[^a-z0-9]+/g, '-')}-${token}`;
|
|
}
|
|
|
|
return getControllingTtyToken();
|
|
}
|
|
|
|
function getSessionScopedWorkstreamFile(cwd, fixedSessionKey) {
|
|
const sessionKey = fixedSessionKey || getWorkstreamSessionKey();
|
|
if (!sessionKey) return null;
|
|
|
|
// Use realpathSync.native so the hash is derived from the canonical filesystem
|
|
// path. On Windows, path.resolve returns whatever case the caller supplied,
|
|
// while realpathSync.native returns the case the OS recorded — they differ on
|
|
// case-insensitive NTFS, producing different hashes and different tmpdir slots.
|
|
// Fall back to path.resolve when the directory does not yet exist.
|
|
let planningAbs;
|
|
try {
|
|
planningAbs = fs.realpathSync.native(planningRoot(cwd));
|
|
} catch {
|
|
planningAbs = path.resolve(planningRoot(cwd));
|
|
}
|
|
const projectId = crypto
|
|
.createHash('sha1')
|
|
.update(planningAbs)
|
|
.digest('hex')
|
|
.slice(0, 16);
|
|
|
|
const dirPath = path.join(os.tmpdir(), 'gsd-workstream-sessions', projectId);
|
|
return {
|
|
sessionKey,
|
|
dirPath,
|
|
filePath: path.join(dirPath, sessionKey),
|
|
};
|
|
}
|
|
|
|
function createSharedPointerAdapter(cwd) {
|
|
const filePath = path.join(planningRoot(cwd), 'active-workstream');
|
|
return {
|
|
read() {
|
|
const raw = platformReadSync(filePath);
|
|
return raw ? raw.trim() || null : null;
|
|
},
|
|
write(name) {
|
|
platformWriteSync(filePath, name + '\n');
|
|
},
|
|
clear() {
|
|
try { fs.unlinkSync(filePath); } catch {}
|
|
},
|
|
};
|
|
}
|
|
|
|
function createSessionScopedPointerAdapter(cwd, fixedSessionKey) {
|
|
const scoped = getSessionScopedWorkstreamFile(cwd, fixedSessionKey);
|
|
if (!scoped) return null;
|
|
|
|
return {
|
|
read() {
|
|
const raw = platformReadSync(scoped.filePath);
|
|
return raw ? raw.trim() || null : null;
|
|
},
|
|
write(name) {
|
|
platformEnsureDir(scoped.dirPath);
|
|
platformWriteSync(scoped.filePath, name + '\n');
|
|
},
|
|
clear() {
|
|
try { fs.unlinkSync(scoped.filePath); } catch {}
|
|
try {
|
|
const remaining = fs.readdirSync(scoped.dirPath);
|
|
if (remaining.length === 0) {
|
|
fs.rmdirSync(scoped.dirPath);
|
|
}
|
|
} catch {}
|
|
},
|
|
};
|
|
}
|
|
|
|
function createMemoryPointerAdapter(initialName = null) {
|
|
let value = initialName;
|
|
return {
|
|
read() {
|
|
return value;
|
|
},
|
|
write(name) {
|
|
value = name;
|
|
},
|
|
clear() {
|
|
value = null;
|
|
},
|
|
};
|
|
}
|
|
|
|
function pickActiveWorkstreamAdapter(cwd, opts = {}) {
|
|
if (opts.activeWorkstreamAdapter) {
|
|
return opts.activeWorkstreamAdapter;
|
|
}
|
|
|
|
const sessionKey = getWorkstreamSessionKey();
|
|
if (sessionKey) {
|
|
if (opts.activeWorkstreamAdapters && opts.activeWorkstreamAdapters.session) {
|
|
return opts.activeWorkstreamAdapters.session;
|
|
}
|
|
return createSessionScopedPointerAdapter(cwd, sessionKey);
|
|
}
|
|
|
|
if (opts.activeWorkstreamAdapters && opts.activeWorkstreamAdapters.shared) {
|
|
return opts.activeWorkstreamAdapters.shared;
|
|
}
|
|
return createSharedPointerAdapter(cwd);
|
|
}
|
|
|
|
function validateWorkstreamName(name) {
|
|
return isValidActiveWorkstreamName(name);
|
|
}
|
|
|
|
function withPlanningLock(cwd, fn) {
|
|
const lockPath = path.join(planningDir(cwd), '.lock');
|
|
const lockTimeout = 10000; // 10 seconds
|
|
const start = Date.now();
|
|
|
|
// Ensure .planning/ exists
|
|
try { platformEnsureDir(planningDir(cwd)); } catch { /* ok */ }
|
|
|
|
function runWithHeldLock() {
|
|
// Atomic create — fails if file exists
|
|
fs.writeFileSync(lockPath, JSON.stringify({
|
|
pid: process.pid,
|
|
cwd,
|
|
acquired: new Date().toISOString(),
|
|
}), { flag: 'wx' });
|
|
|
|
_heldPlanningLocks.add(lockPath);
|
|
|
|
// Lock acquired — run the function
|
|
try {
|
|
return fn();
|
|
} finally {
|
|
_heldPlanningLocks.delete(lockPath);
|
|
try { fs.unlinkSync(lockPath); } catch { /* already released */ }
|
|
}
|
|
}
|
|
|
|
while (Date.now() - start < lockTimeout) {
|
|
try {
|
|
return runWithHeldLock();
|
|
} catch (err) {
|
|
// Transient filesystem errors (Docker overlay-fs, NFS, OS signals, AV scanners)
|
|
// are recoverable — wait and retry rather than propagating.
|
|
// See PLANNING_LOCK_RETRY_ERRNOS for the full list and rationale.
|
|
if (PLANNING_LOCK_RETRY_ERRNOS.has(err.code)) {
|
|
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 100);
|
|
continue;
|
|
}
|
|
if (err.code === 'EEXIST') {
|
|
// Lock exists — check if stale (>30s old)
|
|
try {
|
|
const stat = fs.statSync(lockPath);
|
|
if (Date.now() - stat.mtimeMs > 30000) {
|
|
fs.unlinkSync(lockPath);
|
|
continue; // retry
|
|
}
|
|
} catch { continue; }
|
|
|
|
// Wait and retry (cross-platform, no shell dependency)
|
|
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 100);
|
|
continue;
|
|
}
|
|
throw err;
|
|
}
|
|
}
|
|
|
|
// Timeout — stale-lock recovery, then re-acquire atomically before entering critical section.
|
|
try { fs.unlinkSync(lockPath); } catch { /* ok */ }
|
|
return runWithHeldLock();
|
|
}
|
|
|
|
function createPlanningWorkspace(cwd, opts = {}) {
|
|
return {
|
|
paths: {
|
|
dir(ws, project) {
|
|
return planningDir(cwd, ws, project);
|
|
},
|
|
root() {
|
|
return planningRoot(cwd);
|
|
},
|
|
all(ws) {
|
|
return planningPaths(cwd, ws);
|
|
},
|
|
},
|
|
activeWorkstream: {
|
|
get() {
|
|
const adapter = pickActiveWorkstreamAdapter(cwd, opts);
|
|
if (!adapter) return null;
|
|
|
|
const name = adapter.read();
|
|
if (!name || !validateWorkstreamName(name)) {
|
|
adapter.clear();
|
|
return null;
|
|
}
|
|
|
|
const wsDir = path.join(planningRoot(cwd), 'workstreams', name);
|
|
if (!fs.existsSync(wsDir)) {
|
|
adapter.clear();
|
|
return null;
|
|
}
|
|
|
|
return name;
|
|
},
|
|
set(name) {
|
|
const adapter = pickActiveWorkstreamAdapter(cwd, opts);
|
|
if (!adapter) return;
|
|
|
|
if (!name) {
|
|
adapter.clear();
|
|
return;
|
|
}
|
|
if (!validateWorkstreamName(name)) {
|
|
throw new Error('Invalid workstream name: must be alphanumeric, hyphens, underscores, or dots');
|
|
}
|
|
|
|
const wsDir = path.join(planningRoot(cwd), 'workstreams', name);
|
|
platformEnsureDir(wsDir);
|
|
adapter.write(name);
|
|
},
|
|
clear() {
|
|
const adapter = pickActiveWorkstreamAdapter(cwd, opts);
|
|
if (!adapter) return;
|
|
adapter.clear();
|
|
},
|
|
},
|
|
};
|
|
}
|
|
|
|
function getActiveWorkstream(cwd) {
|
|
return createPlanningWorkspace(cwd).activeWorkstream.get();
|
|
}
|
|
|
|
function setActiveWorkstream(cwd, name) {
|
|
createPlanningWorkspace(cwd).activeWorkstream.set(name);
|
|
}
|
|
|
|
/**
|
|
* Locate the CONTEXT.md file in a phase directory, handling both the bare
|
|
* form (`CONTEXT.md`) and the padded-prefix convention (`NN-CONTEXT.md`,
|
|
* `NN.N-CONTEXT.md`, etc.) used by gsd-discuss-phase output.
|
|
*
|
|
* Returns the filename (not the full path) of the first match, or null if
|
|
* no CONTEXT.md exists in the directory.
|
|
*
|
|
* Canonical dual-form predicate extracted here to eliminate the 5-site
|
|
* duplication that previously existed across init.cjs, roadmap.cjs,
|
|
* core.cjs, gap-checker.cjs (#3739).
|
|
*
|
|
* @param {string|string[]} absDirOrFiles - Absolute path to the phase directory,
|
|
* OR an already-read files array (avoids a redundant readdirSync at call sites
|
|
* that already hold a directory listing).
|
|
* @returns {string|null}
|
|
*/
|
|
function findContextMdIn(absDirOrFiles) {
|
|
try {
|
|
const files = Array.isArray(absDirOrFiles)
|
|
? absDirOrFiles
|
|
: fs.readdirSync(absDirOrFiles);
|
|
if (files.includes('CONTEXT.md')) return 'CONTEXT.md';
|
|
return files.find(f => f.endsWith('-CONTEXT.md')) ?? null;
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
module.exports = {
|
|
createPlanningWorkspace,
|
|
createSharedPointerAdapter,
|
|
createSessionScopedPointerAdapter,
|
|
createMemoryPointerAdapter,
|
|
planningDir,
|
|
planningRoot,
|
|
planningPaths,
|
|
withPlanningLock,
|
|
getActiveWorkstream,
|
|
setActiveWorkstream,
|
|
findContextMdIn,
|
|
};
|