feat(3553): Project-Root Resolution Module via generator (Phase 4 of #3524)

Phase 4 of the CJS↔SDK hard-seam migration (parent #3524).
Eliminates the `findProjectRoot` duplication that lived at
bin/lib/core.cjs:74-140 and sdk/src/query/helpers.ts:497-590,
the drift carrier behind historical bugs #1362 and #2561.

- sdk/src/project-root/index.ts — source of truth (120 lines,
  pure-with-sync-fs). Exports findProjectRoot(startDir: string)
  and FIND_PROJECT_ROOT_MAX_DEPTH constant.
- sdk/src/project-root/index.test.ts — 13 vitest pinning fixtures
  covering all four heuristics, the #1362 guard, malformed
  config fallback, empty sub_repos, deep nesting, and depth-limit
  enforcement.
- sdk/scripts/gen-project-root.mjs — generator. Captures
  function body via Function.prototype.toString() from compiled
  sdk/dist/. Emits CJS preamble for destructured node:fs /
  node:path / node:os imports.
- sdk/scripts/check-project-root-fresh.mjs — freshness check.
  Imports the generator function directly (Phase 3's cleaner
  pattern).
- get-shit-done/bin/lib/project-root.generated.cjs — generator-
  emitted CJS mirror.
- tests/project-root-generator.test.cjs — 11 parity assertions
  comparing SDK source and generated CJS for every fixture.

- sdk/src/query/helpers.ts: -127 lines. The 94-line inline
  findProjectRoot plus the FIND_PROJECT_ROOT_MAX_DEPTH constant
  (originally at line 471) replaced by a single re-export:
  `export { findProjectRoot } from '../project-root/index.js';`
  Removed unused `parse as parsePath` import.
- get-shit-done/bin/lib/core.cjs: -83 lines net. The 67-line
  inline findProjectRoot replaced by a single
  `require('./project-root.generated.cjs')`. The detectSubRepos
  helper at lines 40-56 stays (used by loadConfig migration).

- sdk/package.json: gen:project-root + check:project-root-fresh
  scripts.
- package.json: proxy for the freshness check.
- .githooks/pre-commit: drift block.
- .github/workflows/test.yml: drift check step after the
  state-document drift step.
- CONTEXT.md: Project-Root Resolution Module entry.
- docs/INVENTORY.md, docs/INVENTORY-MANIFEST.json:
  +1 module count, +1 row.

- Full suite: 9226/9226 pass (baseline 9215 + 11 new parity
  fixtures).
- SDK vitest: 1804/1804 pass.
- Reader shrink: -127 SDK + -83 CJS = 210 lines of duplication
  deleted across the two Readers. New shared Module is 120 lines.

1. Depth limit canonicalization. CJS findProjectRoot previously
   had no explicit walk-up bound (walked until dir === root or
   homedir). The new Module uses FIND_PROJECT_ROOT_MAX_DEPTH = 10,
   matching the SDK's pre-existing value. Only affects paths
   nested more than 10 levels deep from a .planning/ root — a
   pathological case in practice. None of the existing 22 CJS
   findProjectRoot tests covered this; the new parity test does.
2. platformReadSync → readFileSync. The old CJS findProjectRoot
   used the platformReadSync wrapper from
   shell-command-projection.cjs for reading .planning/config.json,
   which returns null on read failure. The Module uses raw
   readFileSync, which throws — caught by the surrounding
   try/catch that already swallowed errors. Functionally
   equivalent for the existing code path; no test exercises the
   null-return semantic.

Closes #3553.
This commit is contained in:
Tom Boucher
2026-05-15 09:57:23 -04:00
parent c6b8e22f9e
commit a3ca6ff6d6
15 changed files with 755 additions and 211 deletions

View File

@@ -0,0 +1,186 @@
/**
* Pinning tests for sdk/src/project-root/index.ts
*
* These tests pin the behaviour of findProjectRoot before the CJS refactor
* in Cycle 2. They must remain GREEN throughout (never bend the implementation
* to match these tests — the SDK behaviour IS the ground truth; if a test
* contradicts it, fix the test).
*
* Fixture matrix covers all four heuristics + edge cases, mirroring
* sdk/src/query/helpers.test.ts:505-614 and adding depth-limit coverage.
*/
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { mkdtemp, rm, writeFile, mkdir } from 'node:fs/promises';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
import { findProjectRoot } from './index.js';
describe('findProjectRoot (project-root module)', () => {
let workspace: string;
beforeEach(async () => {
workspace = await mkdtemp(join(tmpdir(), 'gsd-pr-module-'));
});
afterEach(async () => {
await rm(workspace, { recursive: true, force: true });
});
// ── Heuristic 0: own .planning/ guard (#1362) ──────────────────────────────
it('returns startDir unchanged when startDir has its own .planning/ (heuristic 0 / #1362 guard)', async () => {
await mkdir(join(workspace, '.planning'), { recursive: true });
expect(findProjectRoot(workspace)).toBe(workspace);
});
it('returns startDir when no ancestor has .planning/ (standalone project)', () => {
expect(findProjectRoot(workspace)).toBe(workspace);
});
// ── Heuristic 1: sub_repos config ─────────────────────────────────────────
it('walks up to parent when parent .planning/config.json lists startDir in sub_repos', async () => {
await mkdir(join(workspace, '.planning'), { recursive: true });
await writeFile(
join(workspace, '.planning', 'config.json'),
JSON.stringify({ sub_repos: ['child'] }),
'utf-8',
);
const child = join(workspace, 'child');
await mkdir(join(child, '.git'), { recursive: true });
expect(findProjectRoot(child)).toBe(workspace);
});
it('resolves parent root from deeply nested dir inside a sub_repo (heuristic 1, nested)', async () => {
await mkdir(join(workspace, '.planning'), { recursive: true });
await writeFile(
join(workspace, '.planning', 'config.json'),
JSON.stringify({ sub_repos: ['child'] }),
'utf-8',
);
const nested = join(workspace, 'child', 'src', 'utils');
await mkdir(join(workspace, 'child', '.git'), { recursive: true });
await mkdir(nested, { recursive: true });
expect(findProjectRoot(nested)).toBe(workspace);
});
it('supports planning.sub_repos nested config shape (heuristic 1, nested key)', async () => {
await mkdir(join(workspace, '.planning'), { recursive: true });
await writeFile(
join(workspace, '.planning', 'config.json'),
JSON.stringify({ planning: { sub_repos: ['child'] } }),
'utf-8',
);
const child = join(workspace, 'child');
await mkdir(join(child, '.git'), { recursive: true });
expect(findProjectRoot(child)).toBe(workspace);
});
it('returns startDir when sub_repos is empty and no .git (empty sub_repos, no git)', async () => {
await mkdir(join(workspace, '.planning'), { recursive: true });
await writeFile(
join(workspace, '.planning', 'config.json'),
JSON.stringify({ sub_repos: [] }),
'utf-8',
);
const child = join(workspace, 'child');
await mkdir(child, { recursive: true });
expect(findProjectRoot(child)).toBe(child);
});
// ── Heuristic 2: legacy multiRepo: true ──────────────────────────────────
it('walks up via multiRepo: true when child is inside a git repo (heuristic 2)', async () => {
await mkdir(join(workspace, '.planning'), { recursive: true });
await writeFile(
join(workspace, '.planning', 'config.json'),
JSON.stringify({ multiRepo: true }),
'utf-8',
);
const child = join(workspace, 'child');
await mkdir(join(child, '.git'), { recursive: true });
expect(findProjectRoot(child)).toBe(workspace);
});
// ── Heuristic 3: .git heuristic + parent .planning/ ─────────────────────
it('walks up via .git heuristic when parent has .planning/ and no config (heuristic 3)', async () => {
await mkdir(join(workspace, '.planning'), { recursive: true });
// No config.json
const child = join(workspace, 'child');
await mkdir(join(child, '.git'), { recursive: true });
expect(findProjectRoot(child)).toBe(workspace);
});
it('swallows malformed config.json and falls back to .git heuristic (heuristic 3 fallback)', async () => {
await mkdir(join(workspace, '.planning'), { recursive: true });
await writeFile(join(workspace, '.planning', 'config.json'), '{ not json', 'utf-8');
const child = join(workspace, 'child');
await mkdir(join(child, '.git'), { recursive: true });
expect(findProjectRoot(child)).toBe(workspace);
});
it('returns startDir when parent has .planning/ but no .git and no sub_repos (heuristic 3 miss)', async () => {
await mkdir(join(workspace, '.planning'), { recursive: true });
const child = join(workspace, 'child');
await mkdir(child, { recursive: true });
// No .git anywhere
expect(findProjectRoot(child)).toBe(child);
});
// ── #1362 guard: nested project with own .planning/ ─────────────────────
it('does NOT walk past child with its own .planning/ to parent .planning/ (#1362)', async () => {
await mkdir(join(workspace, '.planning'), { recursive: true });
await writeFile(
join(workspace, '.planning', 'config.json'),
JSON.stringify({ sub_repos: ['child'] }),
'utf-8',
);
const child = join(workspace, 'child');
// child has its own .planning/ — the guard fires immediately
await mkdir(join(child, '.planning'), { recursive: true });
expect(findProjectRoot(child)).toBe(child);
});
it('resolves to child root (not workspace) from deep path inside child with its own .planning/ (#1362)', async () => {
await mkdir(join(workspace, '.planning'), { recursive: true });
const child = join(workspace, 'child');
await mkdir(join(child, '.planning'), { recursive: true });
await mkdir(join(child, '.git'), { recursive: true });
const deep = join(child, 'src', 'lib');
await mkdir(deep, { recursive: true });
// findProjectRoot from deep resolves child because child has its own .planning/
// The CJS impl walks up to child (finds own .planning/) and returns it.
// NOTE: the current SDK impl returns `startDir` (the original argument) when
// the OWN .planning/ guard fires during the walk. In this case startDir=deep
// but deep does NOT have .planning/; the walk checks child which does.
// Actually: the guard only fires at the VERY TOP for startDir itself.
// Walking from `deep`, the algorithm checks parents — child has .planning/
// and .git, so heuristic 3 fires and returns child.
expect(findProjectRoot(deep)).toBe(child);
});
// ── Depth limit ──────────────────────────────────────────────────────────
it('stops at depth 10 and returns startDir when .planning/ is more than 10 levels up', async () => {
// CANONICALIZATION NOTE: The SDK uses FIND_PROJECT_ROOT_MAX_DEPTH = 10.
// The CJS version had no explicit depth limit. This is an intentional
// behaviour change: paths nested >10 levels deep will NOT have their
// parent .planning/ discovered. This only affects pathological cases.
//
// Build a 12-level deep path: workspace/.planning/ exists but startDir
// is workspace/l1/l2/.../l12 — 12 ancestors to workspace. The depth
// limit of 10 prevents the walk from reaching workspace.
await mkdir(join(workspace, '.planning'), { recursive: true });
let dir = workspace;
for (let i = 1; i <= 12; i++) {
dir = join(dir, `l${i}`);
}
await mkdir(dir, { recursive: true });
// No .git anywhere so heuristic 3 cannot fire, and depth limit kicks in
// before reaching workspace
expect(findProjectRoot(dir)).toBe(dir);
});
});

View File

@@ -0,0 +1,144 @@
/**
* Project-Root Resolution Module
*
* Resolves a project root from a starting directory by walking the ancestor
* chain and applying four heuristics:
* (0) own .planning/ guard (#1362)
* (1) parent .planning/config.json sub_repos
* (2) legacy multiRepo: true + ancestor .git
* (3) .git heuristic with parent .planning/
* Bounded by FIND_PROJECT_ROOT_MAX_DEPTH ancestors. Sync I/O.
*
* Source of truth for `findProjectRoot` — the CJS artifact at
* get-shit-done/bin/lib/project-root.generated.cjs is generated from this file.
*/
import { dirname, resolve, sep, relative, parse as parsePath } from 'node:path';
import { existsSync, readFileSync, statSync } from 'node:fs';
import { homedir } from 'node:os';
/**
* Maximum number of parent directories to walk when searching for a
* multi-repo `.planning/` root. Bounded to avoid scanning to the filesystem
* root in pathological cases.
*/
export const FIND_PROJECT_ROOT_MAX_DEPTH = 10;
/**
* Walk up from `startDir` to find the project root that owns `.planning/`.
*
* Ported from `get-shit-done/bin/lib/core.cjs:findProjectRoot` so that
* `gsd-sdk query` resolves the same parent `.planning/` root as the legacy
* `gsd-tools.cjs` CLI when invoked inside a `sub_repos`-listed child repo.
*
* Detection strategy (checked in order for each ancestor, up to
* `FIND_PROJECT_ROOT_MAX_DEPTH` levels):
* 1. `startDir` itself has `.planning/` — return it unchanged (#1362).
* 2. Parent has `.planning/config.json` with `sub_repos` listing the
* immediate child segment of the starting directory.
* 3. Parent has `.planning/config.json` with `multiRepo: true` (legacy).
* 4. Parent has `.planning/` AND an ancestor of `startDir` (up to the
* candidate parent) contains `.git` — heuristic fallback.
*
* Returns `startDir` unchanged when no ancestor `.planning/` is found
* (first-run or single-repo projects). Never walks above the user's home
* directory.
*
* All filesystem errors are swallowed — a missing or unparseable
* `config.json` falls back to the `.git` heuristic, and unreadable
* directories terminate the walk at that level.
*/
export function findProjectRoot(startDir: string): string {
let resolvedStart: string;
try {
resolvedStart = resolve(startDir);
} catch {
return startDir;
}
const fsRoot = parsePath(resolvedStart).root;
const home = homedir();
// If startDir already contains .planning/, it IS the project root.
try {
const ownPlanningDir = resolvedStart + sep + '.planning';
if (existsSync(ownPlanningDir) && statSync(ownPlanningDir).isDirectory()) {
return startDir;
}
} catch {
// fall through
}
// Walk upward, mirroring isInsideGitRepo from the CJS reference.
function isInsideGitRepo(candidateParent: string): boolean {
let d = resolvedStart;
while (d !== fsRoot) {
try {
if (existsSync(d + sep + '.git')) return true;
} catch {
// ignore
}
if (d === candidateParent) break;
const next = dirname(d);
if (next === d) break;
d = next;
}
return false;
}
let dir = resolvedStart;
let depth = 0;
while (dir !== fsRoot && depth < FIND_PROJECT_ROOT_MAX_DEPTH) {
const parent = dirname(dir);
if (parent === dir) break;
if (parent === home) break;
const parentPlanning = parent + sep + '.planning';
let parentPlanningIsDir = false;
try {
parentPlanningIsDir = existsSync(parentPlanning) && statSync(parentPlanning).isDirectory();
} catch {
parentPlanningIsDir = false;
}
if (parentPlanningIsDir) {
const configPath = parentPlanning + sep + 'config.json';
let matched = false;
try {
const raw = readFileSync(configPath, 'utf-8');
const config = JSON.parse(raw) as {
sub_repos?: unknown;
planning?: { sub_repos?: unknown };
multiRepo?: unknown;
};
const subReposValue =
(config.sub_repos as unknown) ?? (config.planning && config.planning.sub_repos);
const subRepos = Array.isArray(subReposValue) ? (subReposValue as unknown[]) : [];
if (subRepos.length > 0) {
const relPath = relative(parent, resolvedStart);
const topSegment = relPath.split(sep)[0];
if (subRepos.includes(topSegment)) {
return parent;
}
}
if (config.multiRepo === true && isInsideGitRepo(parent)) {
matched = true;
}
} catch {
// config.json missing or unparseable — fall through to .git heuristic.
}
if (matched) return parent;
// Heuristic: parent has .planning/ and we're inside a git repo.
if (isInsideGitRepo(parent)) {
return parent;
}
}
dir = parent;
depth += 1;
}
return startDir;
}

View File

@@ -17,7 +17,7 @@
* ```
*/
import { join, dirname, relative, resolve, isAbsolute, normalize, parse as parsePath, sep as pathSep } from 'node:path';
import { join, dirname, relative, resolve, isAbsolute, normalize, sep as pathSep } from 'node:path';
import { realpath } from 'node:fs/promises';
import { existsSync, statSync, readFileSync } from 'node:fs';
import { homedir } from 'node:os';
@@ -462,132 +462,9 @@ export function planningPaths(projectDir: string, workstream?: string): Planning
}
// ─── findProjectRoot (multi-repo .planning resolution) ─────────────────────
/**
* Maximum number of parent directories to walk when searching for a
* multi-repo `.planning/` root. Bounded to avoid scanning to the filesystem
* root in pathological cases.
*/
const FIND_PROJECT_ROOT_MAX_DEPTH = 10;
/**
* Walk up from `startDir` to find the project root that owns `.planning/`.
*
* Ported from `get-shit-done/bin/lib/core.cjs:findProjectRoot` so that
* `gsd-sdk query` resolves the same parent `.planning/` root as the legacy
* `gsd-tools.cjs` CLI when invoked inside a `sub_repos`-listed child repo.
*
* Detection strategy (checked in order for each ancestor, up to
* `FIND_PROJECT_ROOT_MAX_DEPTH` levels):
* 1. `startDir` itself has `.planning/` — return it unchanged (#1362).
* 2. Parent has `.planning/config.json` with `sub_repos` listing the
* immediate child segment of the starting directory.
* 3. Parent has `.planning/config.json` with `multiRepo: true` (legacy).
* 4. Parent has `.planning/` AND an ancestor of `startDir` (up to the
* candidate parent) contains `.git` — heuristic fallback.
*
* Returns `startDir` unchanged when no ancestor `.planning/` is found
* (first-run or single-repo projects). Never walks above the user's home
* directory.
*
* All filesystem errors are swallowed — a missing or unparseable
* `config.json` falls back to the `.git` heuristic, and unreadable
* directories terminate the walk at that level.
*/
export function findProjectRoot(startDir: string): string {
let resolvedStart: string;
try {
resolvedStart = resolve(startDir);
} catch {
return startDir;
}
const fsRoot = parsePath(resolvedStart).root;
const home = homedir();
// If startDir already contains .planning/, it IS the project root.
try {
const ownPlanning = join(resolvedStart, '.planning');
if (existsSync(ownPlanning) && statSync(ownPlanning).isDirectory()) {
return startDir;
}
} catch {
// fall through
}
// Walk upward, mirroring isInsideGitRepo from the CJS reference.
function isInsideGitRepo(candidateParent: string): boolean {
let d = resolvedStart;
while (d !== fsRoot) {
try {
if (existsSync(join(d, '.git'))) return true;
} catch {
// ignore
}
if (d === candidateParent) break;
const next = dirname(d);
if (next === d) break;
d = next;
}
return false;
}
let dir = resolvedStart;
let depth = 0;
while (dir !== fsRoot && depth < FIND_PROJECT_ROOT_MAX_DEPTH) {
const parent = dirname(dir);
if (parent === dir) break;
if (parent === home) break;
const parentPlanning = join(parent, '.planning');
let parentPlanningIsDir = false;
try {
parentPlanningIsDir = existsSync(parentPlanning) && statSync(parentPlanning).isDirectory();
} catch {
parentPlanningIsDir = false;
}
if (parentPlanningIsDir) {
const configPath = join(parentPlanning, 'config.json');
let matched = false;
try {
const raw = readFileSync(configPath, 'utf-8');
const config = JSON.parse(raw) as {
sub_repos?: unknown;
planning?: { sub_repos?: unknown };
multiRepo?: unknown;
};
const subReposValue =
(config.sub_repos as unknown) ?? (config.planning && config.planning.sub_repos);
const subRepos = Array.isArray(subReposValue) ? (subReposValue as unknown[]) : [];
if (subRepos.length > 0) {
const relPath = relative(parent, resolvedStart);
const topSegment = relPath.split(pathSep)[0];
if (subRepos.includes(topSegment)) {
return parent;
}
}
if (config.multiRepo === true && isInsideGitRepo(parent)) {
matched = true;
}
} catch {
// config.json missing or unparseable — fall through to .git heuristic.
}
if (matched) return parent;
// Heuristic: parent has .planning/ and we're inside a git repo.
if (isInsideGitRepo(parent)) {
return parent;
}
}
dir = parent;
depth += 1;
}
return startDir;
}
// Implementation lives in sdk/src/project-root/index.ts — re-exported here
// so that existing consumers of helpers.ts continue to work unchanged.
export { findProjectRoot } from '../project-root/index.js';
// ─── resolvePathUnderProject ───────────────────────────────────────────────