fix: remove duplicate stateExtractField, cross-platform code detection, STATE.md file locking

Code review fixes from codebase pattern analysis:

1. state.cjs: Remove duplicate stateExtractField() definition (lines 12 vs 184).
   The second definition shadowed the first with identical logic. Keeps the
   original that uses escapeRegex() from core.cjs.

2. init.cjs: Replace Unix-only 'find' pipe with cross-platform fs.readdirSync
   recursive walk for code file detection. The execSync('find ... | grep ...')
   command fails on Windows where these Unix utilities aren't available.
   Removes unused child_process import.

3. state.cjs: Add lockfile-based mutual exclusion to writeStateMd() to prevent
   parallel executor agents from overwriting each other's STATE.md changes.
   Uses O_EXCL atomic file creation for lock acquisition, stale lock detection
   (10s timeout), and spin-wait with jitter. Ensures data integrity during
   wave-based parallel execution where multiple agents update STATE.md
   concurrently.

All 755 existing tests pass.
This commit is contained in:
Tom Boucher
2026-03-16 20:37:58 -04:00
parent 3bfc0f6845
commit 60f38cdb9e
2 changed files with 63 additions and 21 deletions

View File

@@ -167,17 +167,26 @@ function cmdInitNewProject(cwd, raw) {
const braveKeyFile = path.join(homedir, '.gsd', 'brave_api_key');
const hasBraveSearch = !!(process.env.BRAVE_API_KEY || fs.existsSync(braveKeyFile));
// Detect existing code
// Detect existing code (cross-platform — no Unix `find` dependency)
let hasCode = false;
let hasPackageFile = false;
try {
const files = execSync('find . -maxdepth 3 \\( -name "*.ts" -o -name "*.js" -o -name "*.py" -o -name "*.go" -o -name "*.rs" -o -name "*.swift" -o -name "*.java" \\) 2>/dev/null | grep -v node_modules | grep -v .git | head -5', {
cwd,
encoding: 'utf-8',
stdio: ['pipe', 'pipe', 'pipe'],
});
hasCode = files.trim().length > 0;
} catch {}
const codeExtensions = new Set(['.ts', '.js', '.py', '.go', '.rs', '.swift', '.java']);
const skipDirs = new Set(['node_modules', '.git', '.planning', '.claude', '__pycache__', 'target', 'dist', 'build']);
function findCodeFiles(dir, depth) {
if (depth > 3) return false;
let entries;
try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return false; }
for (const entry of entries) {
if (entry.isFile() && codeExtensions.has(path.extname(entry.name))) return true;
if (entry.isDirectory() && !skipDirs.has(entry.name)) {
if (findCodeFiles(path.join(dir, entry.name), depth + 1)) return true;
}
}
return false;
}
hasCode = findCodeFiles(cwd, 0);
} catch { /* intentionally empty — best-effort detection */ }
hasPackageFile = pathExistsInternal(cwd, 'package.json') ||
pathExistsInternal(cwd, 'requirements.txt') ||