feat(#2873): detect cross-scope shadowing and reach the local spec tree

4a - the detection floor. A shadowed install now reports which triggers are
shadowed and which scope wins, at install time and through a new W028
/gsd-health diagnostic. Exit codes are untouched: a shadowed install is a
warning, not a failure. Only triggers whose stem exists at BOTH scopes are
reported, so a global full profile beside a local core profile no longer
names local artifacts the user does not have.

4b - spec-root reachability, claude runtime and global scope only. The
winning global skill stops carrying a static workflow @-include and instead
resolves its spec at runtime: prefer the project-local copy, fall back to
the global one, stop if neither exists. Every other @-include stays static,
and the local emission is byte-identical. It runs after the staged-skills
rewrite pass, whose claude branch would otherwise mangle the literal tilde
path into an undocumented $HOME form.

Also fixed inline: readInstallManifest classified a top-level JSON array as
an installed v1 manifest, because typeof [] is object.

Refs #2873
This commit is contained in:
sim
2026-08-14 22:47:17 -04:00
parent 52f4ea17cc
commit 2641e6cb67
14 changed files with 1765 additions and 176 deletions

View File

@@ -19,13 +19,21 @@
process.env.GSD_TEST_MODE = '1';
const { test, describe } = require('node:test');
const { test, describe, before, after } = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const crypto = require('node:crypto');
const os = require('node:os');
const { createTempDir, cleanup } = require('./helpers.cjs');
const { runNode } = require('./helpers/process-seam.cjs');
const { INSTALL_TIMEOUT_MS } = require('./helpers/timeouts.cjs');
const {
INSTALL_SCRIPT,
MANIFEST_NAME,
installerEnv,
} = require('./helpers/install-shared.cjs');
const {
installRuntimeArtifacts,
@@ -6253,3 +6261,183 @@ describe('Gap 2: installer ships the capability registry generator scripts (#192
});
});
}
// ─── #2218 cross-scope shadowing — coexistence gate (C1) + 4b guard pair
// (E13/E14, #2873, epic #2866 Phase 4a) ────────────────────────────────────
//
// Moved here from the now-deleted tests/install-cross-scope-shadowing.test.cjs:
// `scripts/lint-test-file-count.allowlist.json` grandfathers the `install`
// prefix at 8 files, and that suite's own `_doc` says adding a 9th file to a
// capped module is a novel offender, not a fix — this gate is folded into
// the emitted-artifact suite instead, which is already allowlisted and,
// per #2873's acceptance criteria, is the correct home ("written against the
// existing `runMinimalInstall` harness").
//
// Implements the coexistence gate (`C1`) and the 4b behavioral pair
// (`E13`/`E14`) from
// `.gsd/phase/feat-2873-cross-scope-shadowing/50-test-matrix.md`. Per that
// matrix's "Red-first order": C1 must go RED against `next` (no
// `install-shadow-report.cjs` report exists today), E14 must go RED today
// (the global skill's spec-root include points at the global tree even when
// a coexisting local install has its own project-local copy of that
// workflow file), and E13 must stay GREEN both before and after — it is the
// guard that phase 4b does not break today's global-only case.
//
// This section does NOT implement the 4b spec-root emission transform
// (E1-E12, a separate matrix section) — that transform
// (`resolveSpecRootReference`, `runtime-artifact-conversion.cts`) landed
// separately and is exercised here only via its INSTALLED OUTPUT. #2873
// Task 3 (2026-08-14): re-verified against a real global+local double
// install — 4b has landed and E14 below is GREEN, not the known-RED case
// this comment block originally described. The "Red-first order" paragraph
// above is left as-is: it accurately records the matrix's ORIGINAL red-first
// plan, not a live claim about E14's current state.
/**
* Extract the `@`-include lines from an emitted markdown body — structural
* parsing, never substring/regex matching on the whole body (CONTRIBUTING.md
* "Prohibited: Raw Text Matching on Test Outputs"). Splits on newlines
* (CRLF-tolerant) and keeps only lines whose first character is `@`.
*
* @param {string} content
* @returns {string[]}
*/
function extractAtIncludeLines(content) {
return content.split(/\r?\n/).filter((line) => line.startsWith('@'));
}
describe('#2218 cross-scope shadowing', () => {
let root;
let projectDir;
let globalInstallResult;
let localInstallResult;
before(() => {
root = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-2218-shadow-'));
projectDir = path.join(root, 'myrepo');
fs.mkdirSync(projectDir, { recursive: true });
// Global half: cannot use runMinimalInstall here — its scope:'global'
// path pushes `--config-dir <root>`, which pins the install AT `<root>`
// itself (manifest at `<root>/gsd-file-manifest.json`), not at
// `<root>/.claude`. That is not the shape #2218 describes: the reporter's
// configuration is a HOME-resolved global install (no --config-dir)
// sitting alongside a project-local one. Spawn the installer directly,
// with HOME=root and no --config-dir, so it resolves its own config home
// the way a real global install does. Must run BEFORE the local half —
// order matters for this fixture (a separate test covers order-independence).
globalInstallResult = runNode([INSTALL_SCRIPT, '--claude', '--global'], {
cwd: root,
env: installerEnv({ HOME: root, USERPROFILE: root }),
timeoutMs: INSTALL_TIMEOUT_MS,
});
assert.strictEqual(globalInstallResult.exitCode, 0,
`global install exited with status ${globalInstallResult.exitCode} ` +
`(outcome=${globalInstallResult.outcome})\n` +
`stdout: ${globalInstallResult.stdout}\nstderr: ${globalInstallResult.stderr}`);
// Local half: runMinimalInstall cannot be reused for this either — for
// scope:'local' it sets cwd=root, which would install into
// `<root>/.claude` and collide with the global install above. Spawn the
// installer directly instead, with cwd pinned at the project dir.
localInstallResult = runNode([INSTALL_SCRIPT, '--claude', '--local'], {
cwd: projectDir,
env: installerEnv({ HOME: root, USERPROFILE: root }),
timeoutMs: INSTALL_TIMEOUT_MS,
});
assert.strictEqual(localInstallResult.exitCode, 0,
`local install exited with status ${localInstallResult.exitCode} ` +
`(outcome=${localInstallResult.outcome})\n` +
`stdout: ${localInstallResult.stdout}\nstderr: ${localInstallResult.stderr}`);
});
after(() => {
cleanup(root);
});
test('both installs land their own manifest', () => {
const globalManifestPath = path.join(root, '.claude', MANIFEST_NAME);
const localManifestPath = path.join(projectDir, '.claude', MANIFEST_NAME);
assert.ok(fs.existsSync(globalManifestPath), 'global manifest should exist');
assert.ok(fs.statSync(globalManifestPath).isFile(), 'global manifest should be a file');
assert.ok(fs.existsSync(localManifestPath), 'local manifest should exist');
assert.ok(fs.statSync(localManifestPath).isFile(), 'local manifest should be a file');
const globalManifest = JSON.parse(fs.readFileSync(globalManifestPath, 'utf8'));
const localManifest = JSON.parse(fs.readFileSync(localManifestPath, 'utf8'));
assert.strictEqual(globalManifest.scope, 'global');
assert.strictEqual(localManifest.scope, 'local');
});
test('the local install reports the shadowing it causes', () => {
// #2218/#2873: install-shadow-report.cjs does not exist yet — this
// require is the intended RED. buildShadowReport is the pure IR builder
// described in .gsd/phase/feat-2873-cross-scope-shadowing/40-design.md
// (row 3): claude installed at both G and L reports N triggers shadowed,
// winner skills@global, loser commands@local.
const { buildShadowReport } = require('../gsd-core/bin/lib/install-shadow-report.cjs');
const report = buildShadowReport('claude', { home: root, cwd: projectDir });
assert.strictEqual(report.shadowed, true);
assert.strictEqual(report.winner.kind, 'skills');
assert.strictEqual(report.winner.scope, 'global');
assert.strictEqual(report.shadowedSide.kind, 'commands');
assert.strictEqual(report.shadowedSide.scope, 'local');
assert.ok(report.triggers.length > 0, 'expected at least one shadowed trigger');
});
test('global-only install resolves the same spec file it does today', () => {
const skillPath = path.join(root, '.claude', 'skills', 'gsd-plan-phase', 'SKILL.md');
const content = fs.readFileSync(skillPath, 'utf8');
const atLines = extractAtIncludeLines(content);
assert.ok(
atLines.includes('@~/.claude/gsd-core/references/ui-brand.md'),
`expected the ui-brand reference @-line among: ${JSON.stringify(atLines)}`,
);
});
// #2218 / phase #2873: before 4b, the global SKILL.md's spec-root include
// was a static `@~/.claude/gsd-core/workflows/plan-phase.md` reference,
// which always resolved against the GLOBAL tree even when a coexisting
// local install has its own project-local copy of that workflow file.
// Phase 4b (`resolveSpecRootReference`, `runtime-artifact-conversion.cts`)
// replaces that static include with a two-step imperative form that names
// both candidate paths and lets the runtime prefer the local one when it
// exists. #2873 Task 3 (2026-08-14): re-verified GREEN against a real
// global+local double install — 4b landed after this test package was
// authored, so this is no longer the known-RED case the original comment
// above it described.
test('the winning global skill points at the project-local spec tree (E14)', () => {
const skillPath = path.join(root, '.claude', 'skills', 'gsd-plan-phase', 'SKILL.md');
const content = fs.readFileSync(skillPath, 'utf8');
const atLines = extractAtIncludeLines(content);
assert.ok(
!atLines.includes('@~/.claude/gsd-core/workflows/plan-phase.md'),
`expected the static global workflow @-line to be replaced, but found it among: ${JSON.stringify(atLines)}`,
);
// The reference @-include (a DIFFERENT spec root, row E4) survives
// untouched — structural proof 4b did not over-fire on this file.
assert.ok(
atLines.includes('@~/.claude/gsd-core/references/ui-brand.md'),
`expected the ui-brand reference @-line to survive among: ${JSON.stringify(atLines)}`,
);
const localSpecPath = path.join(projectDir, '.claude', 'gsd-core', 'workflows', 'plan-phase.md');
assert.ok(fs.existsSync(localSpecPath), 'local spec-root workflow file should exist on disk');
// Positive assertion, not just absence-of-the-old-include: the emitted
// body must actually NAME the project-local candidate path. Exact-string
// presence check on the literal candidate path `resolveSpecRootReference`
// emits (never a substring-scan for prose wording — CONTRIBUTING →
// "Prohibited: Raw Text Matching on Test Outputs"; this checks for the
// PATH token, not sentence phrasing).
assert.ok(
content.includes('.claude/gsd-core/workflows/plan-phase.md'),
`expected the emitted body to name the project-local candidate path, got: ${JSON.stringify(content)}`,
);
});
});