Files
msd-core/tests/issue-766-plugin-manifest.test.cjs
0xdhx c61dd49d95 enhance(#2255): blocking catastrophic-shrink guard for curated .planning/ writes (#2301)
* feat(#2255): blocking catastrophic-shrink guard for .planning writes

Adds hooks/gsd-write-guard.js, a PreToolUse hook that hard-blocks
(decision: 'block', exit 2) a whole-file Write collapsing a curated
.planning/ artifact (ROADMAP.md, .planning/milestones/*-ROADMAP.md,
STATE.md) below 40% of its on-disk line count. Files under 40 lines
are exempt; GSD_ALLOW_PLANNING_SHRINK=1 (named in the block message)
bypasses for legitimate milestone resets.

Fix 3 of #973 — the only defense independent of per-agent tool config.
Registered on the Claude plugin surface (hooks.json), settings-json
runtimes (runtime-hooks-surface.cts, self-contained pattern), Kimi
spec, and the OpenCode/Kilo plugin buses. Golden install fixtures and
INVENTORY regenerated; regression tests negative-controlled (16/16
RED with the hook absent, 16/16 GREEN with it present).

* chore(#2255): backfill changeset pr number to 2301

* enhance(#2255): address review — fail-closed reads, typed block output, registration, property test

Review fixes for trek-e's CHANGES_REQUESTED on PR #2301:

- Blocker 2: register gsd-write-guard.js in BUNDLED_GSD_HOOK_FILES
  (no-shipping-drift test).
- Blocker 3: update the always-on hook enumerations in ADR-766 and
  CONTEXT.md from six to seven.
- Major 4: fail CLOSED on non-ENOENT read errors — only a missing file
  (new-file Write) passes; EACCES/EISDIR/ELOOP/etc now block, with a
  typed readError field and the override still honored. Tested, with a
  negative control against the pre-fix hook.
- Major 5: fast-check property test for the SHRINK_RATIO/FLOOR_LINES
  budget contract (blocked ⟺ newLines < oldLines*SHRINK_RATIO above the
  floor; sub-floor always exempt), boundary examples pinned.
- Major 6: block output now carries typed oldLines/newLines/
  overrideEnvVar fields; tests assert on those instead of regexing the
  free-form reason string.
- Minor: CURATED_PATTERNS are case-insensitive (case-insensitive-FS
  bypass on macOS/Windows); limit+1 boundary tests added for both the
  floor and the ratio.

* enhance(#2255): engage the write guard on Kimi's native payload shape

The guard shipped with Claude-vocabulary checks (tool_name 'Write',
tool_input.file_path), which #2304 showed leaves a guard dormant on
Kimi: the [[hooks]] matcher is registered pre-translated but kimi-cli
forwards its native payload verbatim — tool_name 'WriteFile' (bare or
module-qualified) and tool_input.path per its tool schemas
(src/kimi_cli/tools/file/write.py). The guard matched, saw an unknown
name, and exited 0.

Apply the same per-guard normalization PR #2326 gives the three
sibling guards (name + field mapping, inlined — hook scripts stage as
standalone files), and write the block reason to stderr as well as
stdout JSON: Kimi feeds stderr, not stdout, back to the model on
exit 2, so a stdout-only reason blocks without telling the model why
or naming the documented override.

Regression tests pipe Kimi-shaped payloads (engage, qualified-name,
stderr-reason) plus exemption pins (StrReplaceFile stays out of scope
by design; non-curated paths pass) — verified red against the pre-fix
guard, green after.

* enhance(#2255): rebase onto next; regenerate golden-parity fixtures

* enhance(#2255): wire the escape hatch into complete-milestone's reorganize step

Review Blocker 1: the guard hard-blocked /gsd:complete-milestone's ROADMAP
reorganize — the tree's only legitimate milestone reset and the exact caller
GSD_ALLOW_PLANNING_SHRINK was built for. The reorganize step now performs the
rewrite through a shell write with the hatch set on the command (a hook
inherits the runtime env, so a bare Write cannot carry a per-step override),
and a binding test derives the env var name from the guard's typed output and
asserts (a) the workflow step sets it and (b) the guard passes the identical
catastrophic payload under it — so the next complete-milestone.md edit cannot
silently re-break the wiring.

* enhance(#2255): drop dead Edit-class mapping from normalizeKimiPayload

Review Major 1: StrReplaceFile -> 'Edit' and the old_string/new_string
reconstruction were unreachable-by-effect — the guard exits 0 for any
tool_name !== 'Write', so nothing ever read the fields they set, leaving
guaranteed-surviving mutants against the Stryker bar. The map now carries
only WriteFile -> 'Write'; the StrReplaceFile exemption test message states
the fall-through it actually exercises.

* enhance(#2255): review minors — American spellings; writeSync before exit(2)

Minor 1: normalised/normalise -> American house style. Minor 2: the two
block paths wrote stdout+stderr via async pipe writes then exit(2) —
async-on-Windows, unflushed at exit; fs.writeSync(1/2, ...) makes the block
payload durable.

* enhance(#2255): assert stderr equals the typed reason, not raw prose

Minor 3: the last raw-text match in the suite pinned override-name prose on
stderr. The contract is "stderr carries the reason Kimi feeds back" — now
asserted as stderr non-empty and byte-equal to the parsed stdout.reason.

* enhance(#2255): bind the write-guard's Kimi normalization into the parity test

Review Major 2: the guard's normalizeKimiPayload is a 4th inlined copy with
nothing binding it. This extends PR #2326's kimi-guard-normalization-parity
test (same path and helpers, authored as a superset so either merge order
resolves cleanly): sibling byte-parity is existence-gated zero-or-all —
trivially green until #2326 lands, full-strength after — and the write-guard
copy is bound semantically (map is the value-inverse of convertKimiToolName;
the Kimi name for Write must map, or the guard is dormant on Kimi; the
path -> file_path half must be present). Byte-parity is deliberately not
asserted for this copy: it legitimately omits the Edit-class mapping
(Major 1 — dead code in a Write-only guard).

* enhance(#2255): refresh golden-parity fixtures for revised guard + workflow

* chore(#2255): regenerate golden fixtures after rebase onto next

The committed fixture hashes were generated against a tree predating
next's latest 11 commits, which independently modified the same
install-parity surface. Rebased onto next and regenerated with
`npm run gen:golden`.

Verified: against upstream/next the regenerated fixtures differ by
exactly this PR's own entries -- hooks/gsd-write-guard.js (new),
hooks/managed-hooks-registry.cjs, plugins/gsd-core.js, and
gsd-core/workflows/complete-milestone.md. No unrelated drift.

* fix(#2255): regenerate workflow size baseline for complete-milestone

`complete-milestone.md` grew 31071 -> 32061 (+990) when the round-2
review fix bound GSD_ALLOW_PLANNING_SHRINK=1 into the reorganize step,
but tests/workflow-size-baseline.json was never regenerated. The
per-file workflow baseline test (issue #1074) failed on
ubuntu-latest/22 and both macOS shard 1/3 jobs.

The growth is justified: it is the escape-hatch binding requested in
review round 2 (the guard must not hard-block the tree's only
legitimate milestone reset), not incidental bloat.

Regenerated via `npm run size:baseline`; the diff is exactly the one
entry.

* chore(#2255): regenerate golden fixtures and size baseline after rebase onto next

* enhance(#2255): bind the shrink escape hatch mechanically — single-use sentinel the guard consumes

Round-5 M1: the per-step `GSD_ALLOW_PLANNING_SHRINK=1 tee` prefix was inert
(no PreToolUse hook exists on Bash in this family; the write succeeded by
dodging the guard, not by the override firing) and the protection was prose.
The hatch is now a transport code consults: complete-milestone's reorganize
step arms `.planning/.gsd-allow-shrink` with the target's path, keeps the
Write tool as the sanctioned path, and the guard — at the block point only —
verifies the sentinel is fresh (15 min) and names the pending target, then
CONSUMES it and allows that one write. Path-bound + single-use + freshness
keep it from becoming a standing unlock. The env var remains as the
interactive transport, where it can actually reach the hook.

Regression tests written first (negative control: 3 failed pre-fix): the
armed-sentinel Write passes and consumes; stale does not exempt; a token for
a different file neither exempts nor is consumed; the binding test now takes
the sentinel name from the guard's typed output (overrideSentinel), asserts
the step arms it, and asserts the step no longer routes the rewrite around
Write via a shell pipe.

Also in this commit, same file:
- m2: block emission is exception-safe — emitBlock() wraps both writeSync
  sites in their own try/catch that still exits 2, so an EPIPE can no longer
  convert fail-closed into the outer catch's fail-open.
- Header discloses the two reviewed design limits (cumulative sequential
  shrink; lexical match vs symlinked paths) per round-5 scoping.

* docs(#2255): document the sentinel transport across guard surfaces; changeset ends with the (#2255) parenthetical (m4)

USER-GUIDE bullet, INVENTORY row (en + ja/ko/pt/zh), the
runtime-hooks-surface registration comment, and the changeset now describe
both hatches — the single-use sentinel for workflow steps and the env var
for interactive use — instead of implying a per-step env can reach a hook.
The changeset's trailing `Resolves #2255.` prose becomes the `(#2255)`
parenthetical the repo's fragments use (round-5 m4).

* chore(#2255): regenerate derived families on the rebased tree (full sweep)

Full generator sweep after rebasing onto next @ the body-parser-patched
lockfile: build, gen-inventory-manifest, gen:golden, size:baseline. Every
regen delta verified to be either a PR-owned entry (gsd-write-guard.js,
complete-milestone.md, INVENTORY/USER-GUIDE) or exact convergence to next's
committed value for entries our arbitrary-side conflict resolution had left
stale (all 18 runtime fixtures checked mechanically).

* test(#2255): use helpers.cleanup for sentinel teardown, not raw fs.rmSync

The repo's local/no-raw-rmsync-in-tests rule exists for the Windows-EBUSY
retry budget; the sentinel disarm now rides it like every other teardown.

* chore(#2255): regenerate derived families after rebase onto next

Full sweep on the rebased tree (build -> gen-inventory-manifest ->
gen:golden -> size:baseline). Every delta is either a PR-owned entry
(hooks/gsd-write-guard.js, its registration surfaces
hooks/managed-hooks-registry.cjs and the two plugin buses,
gsd-core/workflows/complete-milestone.md) or exact convergence to
next's committed value across all 18 runtime fixtures.

* chore(#2255): regenerate derived families after rebase onto next @ a5180d96

Rebase onto current `next` (a5180d96) resolved 12 conflicting
golden-install-parity fixtures; all regenerated via the full generator
sweep (build, gen:golden, size:baseline) rather than a single generator.

`lint:generated-sync` reports every generated artifact in sync. All 45
differing fixture keys and the single workflow-size-baseline entry map
to files this PR actually touches; no foreign drift.

* fix(#2255): remove the stale unguarded reorganize_roadmap step (round-8 blocker)

complete-milestone.md carried a second ROADMAP-collapsing step,
`reorganize_roadmap`, distinct from the sentinel-armed
`reorganize_roadmap_and_delete_originals` this PR wired. It is a vestige
of the pre-archive-then-reorganize design: it sits BEFORE
archive_milestone, so executing it as written would collapse ROADMAP.md
before the archive snapshots the full phase detail — and its Write is
exactly the shape gsd-write-guard hard-blocks, with no hatch armed. The
file's own success criteria describe only one reorganize outcome
(Backlog-preserving, overwrite-in-place — the later step's properties),
and archive_milestone points forward to "the reorganize step".

Removed rather than wired, per the round-8 review's confirm-and-remove
option. A new binding test asserts the sentinel-armed step is the ONLY
reorganize step in the workflow, so an unguarded collapse step cannot be
silently reintroduced (negative-controlled: fails against the pre-fix
tree). Golden-parity fixtures and the size baseline regenerate for the
shrunk file; every changed fixture key is complete-milestone.md's own.

* test(#2255): document why the read-error injection is a path collision, not an fs monkeypatch

Round-8 nit: the non-ENOENT tests inject via a directory-at-target-path
collision instead of the repo's fs-method monkeypatch pattern. That is
deliberate, not drift — runHook exercises the hook as a spawnSync child
process, so an in-process fs.readFileSync patch (the pattern the cited
siblings use on require'd, in-process code) can never reach the code
under test. Record the reasoning at the injection site.

* chore(#2255): regenerate derived families after rebase onto next @ 0d08c320

Rebase onto current next (0d08c320) for the CONFLICTING/DIRTY state. All 32
conflicts were generated artifacts (19 golden-install-parity, 12 install-tree,
workflow-size-baseline); resolved arbitrarily and regenerated via a full
generator sweep (build, gen:golden, size:baseline, gen-inventory-manifest)
rather than hand-merged. No source conflicts.

Regen diff verified against the PR's changed-file set: 7 distinct differing
keys, all PR-owned (gsd-write-guard.js, managed-hooks-registry.cjs,
plugins/gsd-core.js, complete-milestone.md, and their .kimi mirrors).
lint:generated-sync clean.

* chore(#2255): regenerate derived families after rebase onto next @ 9138271b

Conflict set was 20 paths, every one a generated artifact, zero source
conflicts — resolved arbitrarily during the replay and regenerated here,
per the maintainer's round-9 recipe (never hand-merged).

Generator sweep (not just gen:golden): npm run build, gen:golden,
size:baseline, gen-inventory-manifest, gen:registry. INVENTORY-MANIFEST
came back byte-identical, so the merged value was already correct.

Regen diff verified == PR-touched entries: every differing leaf key
attributes to a file this PR changes (complete-milestone.md, the guard,
managed-hooks-registry.cjs, both plugin buses) — derived from the
changed-file set, not a feature-name filter.

* fix(#2255): port the #2595 Kimi-payload hardening the base landed for the sibling guards

Self-found via the round-10 base sweep: a8b40fa5 (#2547/PR #2595) hardened
gsd-prompt/read/worktree-path-guard's normalizeKimiPayload after this PR was
authored, and this guard carried all three pre-fix shapes:

- `path` now wins outright over a model-supplied `file_path` — kimi-cli's
  WriteFile schema carries no `file_path`, so a payload pairing a curated
  `path` with a spurious `file_path: ""` had the guard reading '' and
  exiting 0 while kimi-cli wrote to `path` (one-key bypass, no crash needed).
- null/primitive payloads pass through deliberately instead of throwing into
  the fail-open catch.
- the `file_path` read is typed (`typeof === 'string'`), closing the
  crash-to-allow on `[]`/`{}` — this is what the base-added
  kimi-guard-typed-payload-reads scan flags.

Negative-controlled: the shadowing payload exits 0 against the pre-fix guard
and 2 against this one.

* fix(#2255): round 9 Major 2 — stop printing the sentinel recipe in the agent-facing denial

The block message ended by telling the blocked agent exactly how to arm the
single-use sentinel — handing the #973 actor a mechanical self-authorization
in the moment it is blocked. The recipe is gone from the prose; the
corrective advice and the env override's name stay (the latter is a #2255
acceptance criterion, and a per-step env prefix cannot reach a hook anyway),
and the typed overrideSentinel field stays for the binding tests. The hatch
remains documented in USER-GUIDE.md and complete-milestone.md, where humans
and the workflow engine read.

* fix(#2255): round 9 Minors 1-2 — realpath-resolve the target before the curated match; disclose the /i Linux cost

Minor 1: a Write to a non-curated path that symlinks into a curated file was
not matched while writeFileSync followed the link — the target is now
realpath-resolved before the curated match (ENOENT keeps the lexical
resolution so new-file Writes still pass; any other realpath error falls
through to the read, which fails closed). Negative-controlled: the symlink
payload exits 0 against the pre-fix guard, 2 against this one. Test skips on
win32, where symlink creation needs privilege.

Minor 2: the header's design-limits block now names the unconditional /i
cost on case-sensitive Linux (a genuinely distinct .planning/roadmap.md is
also treated as curated) next to the stateless limit, and drops the closed
symlink limit.

* test(#2255): round 9 Minors 3-4 — CRLF counting pin + a passing Write leaves a fresh sentinel unburned

Minor 3: countLines' split('\n') is CRLF-safe for a count (the \r rides
along), confirmed by trace in the review — this pins it against this repo's
recurring CRLF regressions, on both sides of the compare and at the 40%
boundary.

Minor 4: consumeSentinelFor runs only after the ratio check would block, so
a within-tolerance Write never burns the workflow's token — true by
construction, previously un-asserted.

* fix(#2255): round 9 Major 3 — correct the stale env-var line in archive_milestone's summary

complete-milestone.md's "After archival" bullet still said the reorganize
happens "under GSD_ALLOW_PLANNING_SHRINK=1" — the wording from the round-2
design this PR's own history rejected in round 5 (a per-step env var cannot
reach a hook; setting it in a Bash step silently does nothing). It now points
at the sentinel mechanics the reorganize step actually documents, matching
that step and USER-GUIDE.md.

* docs(#2255): round 9 Major 1 — user-facing docs state the stateless per-Write limit

The changeset and USER-GUIDE described the guard as covering "catastrophically
shrinks" with no caveat, while the stateless design was disclosed only in the
hook header — an operator reading the shipped docs would conclude iterative
erosion is covered. Both surfaces now state the per-Write comparison and the
erosion non-goal explicitly, in line with what the guard does.

* fix(#2255): round 10 Blocker 1 — arm the hatch in the roadmapper's curated writes

gsd-roadmapper Step 7 Writes both .planning/ROADMAP.md and .planning/STATE.md
wholesale, and /gsd:new-milestone spawns it against the OUTGOING milestone's
files. new-milestone's `phases.clear` archives phase DIRECTORIES, never
ROADMAP.md, so nothing compacts it first, and no ordering rule forces
/gsd:complete-milestone to run before /gsd:new-milestone.

Measured against the shipped hook at the #973 file size (292 lines): a new
4-phase roadmap lands at 18.2% and an 8-phase one at 31.8% — both blocked; only
a 12-phase replacement (45.5%) clears. So the collapse is reachable on a
first-party flow, which is the failure mode #2255 para 4 says the guard must not
have.

Arms the single-use sentinel immediately before each Write, one per target
(the token is path-bound and single-use, so one arming cannot cover both), and
gates each arming on `[ -f ]` so the /gsd:new-project path — where the guard
already exempts via ENOENT — strands no unconsumed token.

Binding test derives the sentinel name from the guard's own typed output, so a
rename on either side fails the suite instead of silently unwiring the hatch.
Negative-controlled: 2 assertions fail against the pre-fix roadmapper.

* docs(#2255): round 10 Major 2 — scope the claim to the guarantee that ships

The sentinel is a plain file, so an agent that would reason past an advisory
can arm one with a single Bash call it is already permitted to make. The
"only defense independent of per-agent tool config" framing outran that, and
the changeset was on its way into CHANGELOG.md.

Retitles the claim on all three surfaces (changeset, guard header, USER-GUIDE)
to what the guard actually delivers: it blocks accidental and single-shot
collapse and is not a defense against a determined agent; what it converts is
"ignore a sentence" into "take one deliberate, path-bound, single-use,
auditable action".

Pinned by test on the DURABLE surfaces only — the guard header and USER-GUIDE.
The changeset fragment is deliberately not pinned: it is consumed at release,
so a test reading it would start failing the moment the release lands. The
bound-statement assertion normalizes comment markers and whitespace first, so
it pins the claim rather than the paragraph's line wrapping.

Negative-controlled: both assertions fail against the pre-fix surfaces.

* test(#2255): acknowledge the roadmapper growth from the round 10 Blocker 1 wiring

The emitted-attribution gate (#2719/#2767) flags gsd-roadmapper.md growing 1130
bytes without an acknowledgment. The growth is the Blocker 1 sentinel wiring
plus the rationale a future editor needs to keep it, so it gets an ack fragment
rather than a silencing regen — the gate's own message is explicit that there is
nothing left to regenerate.

Fragment is PR-scoped (2301-…) per the gate's naming instruction, and uses the
plain-string reason form the shipped fragments use.

Verified against the TRUE upstream tip, not the fork's origin/next: a stale
origin made this same gate report unrelated phantom drift (1 emitted path + 6
grown files + 5 stale acks) that vanishes when GSD_EMITTED_BASE is pinned.

* test(#2255): renumber the roadmapper PROSE_ALLOWLIST pin after the Step 7 wiring

CI red on shard 2/3, all four platforms. The #2751 gate keys PROSE_ALLOWLIST on
{file, line}; the Blocker 1 wiring added 18 lines above the allowlisted
parenthetical in agents/gsd-roadmapper.md, moving it 624 -> 642. Both halves of
the gate then fired: the moved line reads as a new offender, and the stale
entry no longer matches anything.

Line content at 642 is byte-identical to what the entry describes — a
descriptive "e.g." naming SDK queries a user could run — so this is a
renumber, not a re-classification.

Swept the defect class rather than the instance: agents/gsd-roadmapper.md is
the only line-pinned reference to any file this round changed.

Negative-controlled: both assertions fail against the un-renumbered allowlist.

---------

Co-authored-by: Tom Boucher <trekkie@nomorestars.com>
2026-08-01 21:19:49 -04:00

972 lines
45 KiB
JavaScript

'use strict';
/**
* Regression tests for issue #766: additive Claude Code plugin manifest.
*
* Asserts structural and semantic correctness of:
* .claude-plugin/plugin.json — plugin manifest
* hooks/hooks.json — plugin hook wiring
*
* Section C1 validates plugin.json against the snapshotted schema fixture
* (tests/fixtures/plugin-manifest-schema.json) using explicit structural
* assertions instead of an Ajv dependency, so this gate runs unconditionally
* without requiring ajv in devDependencies.
*/
const { test, describe, beforeEach, afterEach } = require('node:test');
const assert = require('node:assert/strict');
const fs = require('fs');
const os = require('os');
const path = require('path');
const { spawnSync } = require('child_process');
const ROOT = path.resolve(__dirname, '..');
const identity = require(path.join(ROOT, 'gsd-core', 'bin', 'lib', 'package-identity.cjs'));
const pkg = require(path.join(ROOT, 'package.json'));
const { MANAGED_HOOKS } = require(path.join(ROOT, 'hooks', 'managed-hooks-registry.cjs'));
const { cleanup } = require('./helpers.cjs');
const PLUGIN_JSON_PATH = path.join(ROOT, '.claude-plugin', 'plugin.json');
const HOOKS_JSON_PATH = path.join(ROOT, 'hooks', 'hooks.json');
// ─── Section A: plugin.json ───────────────────────────────────────────────────
describe('A: .claude-plugin/plugin.json', () => {
let manifest;
test('exists and is valid JSON', () => {
assert.ok(fs.existsSync(PLUGIN_JSON_PATH), '.claude-plugin/plugin.json must exist');
const raw = fs.readFileSync(PLUGIN_JSON_PATH, 'utf-8');
manifest = JSON.parse(raw); // throws on invalid JSON
assert.ok(typeof manifest === 'object' && manifest !== null, 'manifest must be a JSON object');
});
test('name equals identity.binName ("gsd-core")', (t) => {
if (!manifest) { t.skip('manifest could not be parsed'); return; }
assert.equal(manifest.name, identity.binName, `name should be "${identity.binName}"`);
});
test('name is kebab-case, no colons, spaces, or uppercase', (t) => {
if (!manifest) { t.skip('manifest could not be parsed'); return; }
assert.match(
manifest.name,
/^[a-z0-9]+(?:-[a-z0-9]+)*$/,
'name must be kebab-case (no colon, space, or uppercase) to be namespace-safe'
);
});
test('version matches package.json version', (t) => {
if (!manifest) { t.skip('manifest could not be parsed'); return; }
assert.equal(manifest.version, pkg.version, `.claude-plugin/plugin.json version (${manifest.version}) must match package.json version (${pkg.version}). When bumping the package version, update .claude-plugin/plugin.json \`version\` to match — Claude Code plugin --strict validation requires a version field and the plugin manifest must track the package version. (#766)`);
});
test('repository equals identity.repoUrl', (t) => {
if (!manifest) { t.skip('manifest could not be parsed'); return; }
assert.equal(manifest.repository, identity.repoUrl, 'repository must equal identity.repoUrl');
});
test('homepage equals identity.repoUrl', (t) => {
if (!manifest) { t.skip('manifest could not be parsed'); return; }
assert.equal(manifest.homepage, identity.repoUrl, 'homepage must equal identity.repoUrl');
});
test('license matches package.json license', (t) => {
if (!manifest) { t.skip('manifest could not be parsed'); return; }
assert.equal(manifest.license, pkg.license, 'license must match package.json');
});
test('author.name is a non-empty string', (t) => {
if (!manifest) { t.skip('manifest could not be parsed'); return; }
assert.ok(
manifest.author && typeof manifest.author.name === 'string' && manifest.author.name.trim().length > 0,
'author.name must be a non-empty string'
);
});
test('commands field is "./commands/gsd/" and that dir exists with at least one .md file', (t) => {
if (!manifest) { t.skip('manifest could not be parsed'); return; }
assert.equal(manifest.commands, './commands/gsd/', 'commands must be "./commands/gsd/"');
const resolvedDir = path.resolve(path.dirname(PLUGIN_JSON_PATH), '..', manifest.commands);
assert.ok(fs.existsSync(resolvedDir), `resolved commands dir must exist: ${resolvedDir}`);
const mdFiles = fs.readdirSync(resolvedDir).filter(f => f.endsWith('.md'));
assert.ok(mdFiles.length > 0, `commands dir must contain at least one .md file`);
});
test('hooks field is "./hooks/hooks.json" and that file exists', (t) => {
if (!manifest) { t.skip('manifest could not be parsed'); return; }
assert.equal(manifest.hooks, './hooks/hooks.json', 'hooks must be "./hooks/hooks.json"');
const resolvedHooks = path.resolve(path.dirname(PLUGIN_JSON_PATH), '..', manifest.hooks);
assert.ok(fs.existsSync(resolvedHooks), `resolved hooks file must exist: ${resolvedHooks}`);
});
test('no "$schema" key (intentionally omitted)', (t) => {
if (!manifest) { t.skip('manifest could not be parsed'); return; }
assert.ok(!Object.prototype.hasOwnProperty.call(manifest, '$schema'), 'plugin.json must NOT contain a $schema key');
});
});
// ─── Section B: hooks/hooks.json ─────────────────────────────────────────────
describe('B: hooks/hooks.json', () => {
let hooksConfig;
test('exists and is valid JSON with top-level "hooks" object', () => {
assert.ok(fs.existsSync(HOOKS_JSON_PATH), 'hooks/hooks.json must exist');
const raw = fs.readFileSync(HOOKS_JSON_PATH, 'utf-8');
hooksConfig = JSON.parse(raw);
assert.ok(
typeof hooksConfig === 'object' && hooksConfig !== null &&
typeof hooksConfig.hooks === 'object' && hooksConfig.hooks !== null,
'hooks.json must have a top-level "hooks" object'
);
});
test('every event name is a known Claude Code lifecycle event', (t) => {
if (!hooksConfig) { t.skip('hooks.json could not be parsed'); return; }
// Complete set of Claude Code hook events as of #770 (SubagentStop, Stop,
// PreCompact, FileChanged added in #770; prior set was SessionStart,
// PreToolUse, PostToolUse from #766).
const validEvents = new Set([
'SessionStart', 'PreToolUse', 'PostToolUse',
'SubagentStop', 'Stop', 'PreCompact', 'FileChanged',
]);
for (const eventName of Object.keys(hooksConfig.hooks)) {
assert.ok(validEvents.has(eventName), `Unknown hook event: "${eventName}"`);
}
});
test('every hook entry has type "command" and command contains ${CLAUDE_PLUGIN_ROOT}', (t) => {
if (!hooksConfig) { t.skip('hooks.json could not be parsed'); return; }
for (const [eventName, eventEntries] of Object.entries(hooksConfig.hooks)) {
assert.ok(Array.isArray(eventEntries), `Event "${eventName}" must be an array`);
for (const entry of eventEntries) {
assert.ok(Array.isArray(entry.hooks), `Entry in "${eventName}" must have a hooks array`);
for (const hook of entry.hooks) {
assert.equal(hook.type, 'command', `All hook entries must have type "command" (got "${hook.type}")`);
assert.ok(
typeof hook.command === 'string' && hook.command.includes('${CLAUDE_PLUGIN_ROOT}'),
`Hook command must contain "\${CLAUDE_PLUGIN_ROOT}": ${hook.command}`
);
}
}
}
});
test('every referenced script file exists on disk and its basename is in MANAGED_HOOKS', (t) => {
if (!hooksConfig) { t.skip('hooks.json could not be parsed'); return; }
// Extract script path: substring after ${CLAUDE_PLUGIN_ROOT}/ up to next "
const scriptPathRe = /\$\{CLAUDE_PLUGIN_ROOT\}\/([^"]+)/g;
const allScripts = [];
for (const eventEntries of Object.values(hooksConfig.hooks)) {
for (const entry of eventEntries) {
for (const hook of entry.hooks) {
const matches = [...hook.command.matchAll(scriptPathRe)];
for (const m of matches) {
allScripts.push(m[1]);
}
}
}
}
assert.ok(allScripts.length > 0, 'Should have found at least one script path in hooks.json');
for (const scriptPath of allScripts) {
const fullPath = path.join(ROOT, scriptPath);
assert.ok(fs.existsSync(fullPath), `Script referenced in hooks.json does not exist on disk: ${fullPath}`);
const basename = path.basename(scriptPath);
assert.ok(
MANAGED_HOOKS.includes(basename),
`Script basename "${basename}" is not listed in hooks/managed-hooks-registry.cjs MANAGED_HOOKS`
);
}
});
test('all seven always-on hooks are wired', (t) => {
if (!hooksConfig) { t.skip('hooks.json could not be parsed'); return; }
const REQUIRED_HOOKS = [
'gsd-check-update.js',
'gsd-prompt-guard.js',
'gsd-read-guard.js',
'gsd-worktree-path-guard.js',
'gsd-write-guard.js',
'gsd-context-monitor.js',
'gsd-read-injection-scanner.js',
];
// Collect all basenames wired in hooks.json
const wiredBasenames = new Set();
const scriptPathRe = /\$\{CLAUDE_PLUGIN_ROOT\}\/hooks\/([^"]+)/g;
for (const eventEntries of Object.values(hooksConfig.hooks)) {
for (const entry of eventEntries) {
for (const hook of entry.hooks) {
const matches = [...hook.command.matchAll(scriptPathRe)];
for (const m of matches) {
wiredBasenames.add(m[1]);
}
}
}
}
for (const required of REQUIRED_HOOKS) {
assert.ok(wiredBasenames.has(required), `Required hook "${required}" is not wired in hooks/hooks.json`);
}
});
test('gsd-context-monitor.js entry has timeout === 10', (t) => {
if (!hooksConfig) { t.skip('hooks.json could not be parsed'); return; }
let found = false;
for (const eventEntries of Object.values(hooksConfig.hooks)) {
for (const entry of eventEntries) {
for (const hook of entry.hooks) {
if (hook.command && hook.command.includes('gsd-context-monitor.js')) {
found = true;
assert.equal(hook.timeout, 10, 'gsd-context-monitor.js must have timeout === 10');
}
}
}
}
assert.ok(found, 'gsd-context-monitor.js entry was not found in hooks.json');
});
});
// ─── Section C: Unconditional JSON schema gate + opportunistic CLI integration ──
//
// The `claude plugin validate --strict` binary is absent on CI, so Section C was
// previously SKIPPED there — the only full-schema gate never ran. This section
// replaces the skip-on-absent pattern with two tiers:
//
// C1 (UNCONDITIONAL) — Validate plugin.json against a snapshotted JSON schema
// fixture that captures the fields `--strict` requires. Runs on every
// platform, every CI job, every local run. A bug that removes `version`
// or changes `name` to an invalid form goes red immediately.
//
// C2 (OPPORTUNISTIC) — When the `claude` binary IS on PATH, also run
// `claude plugin validate <temp-plugin-root> --strict` as an end-to-end
// smoke test. This tier provides defence-in-depth for schema changes
// Claude Code may introduce that the fixture hasn't yet captured.
//
describe('C: plugin.json schema validation', () => {
const SCHEMA_FIXTURE_PATH = path.join(__dirname, 'fixtures', 'plugin-manifest-schema.json');
// ── C1: Unconditional structural gate ────────────────────────────────────────
//
// Validates plugin.json against the required fields from the snapshotted
// schema fixture (tests/fixtures/plugin-manifest-schema.json) using explicit
// structural assertions. This avoids a runtime dependency on `ajv` (which is
// only a transitive dep) while providing identical coverage for the fields that
// `claude plugin validate --strict` requires.
//
// Required fields and constraints are derived directly from SCHEMA_FIXTURE_PATH.
// If the fixture changes (new required field, new pattern), update this test too.
test('C1: plugin.json satisfies the snapshotted Claude Code plugin schema (unconditional)', () => {
assert.ok(
fs.existsSync(SCHEMA_FIXTURE_PATH),
`Schema fixture must exist: ${SCHEMA_FIXTURE_PATH}`
);
assert.ok(
fs.existsSync(PLUGIN_JSON_PATH),
`.claude-plugin/plugin.json must exist: ${PLUGIN_JSON_PATH}`
);
const manifest = JSON.parse(fs.readFileSync(PLUGIN_JSON_PATH, 'utf-8'));
const schema = JSON.parse(fs.readFileSync(SCHEMA_FIXTURE_PATH, 'utf-8'));
const errors = [];
const schemaRequired = Array.isArray(schema.required) ? schema.required : [];
const schemaProps = (schema.properties && typeof schema.properties === 'object') ? schema.properties : {};
// Helper: assert a required field exists with the expected type.
function requireField(key, type) {
if (!(key in manifest)) {
errors.push(`"${key}" is required but missing`);
} else if (typeof manifest[key] !== type) {
errors.push(`"${key}" must be a ${type}, got ${typeof manifest[key]}`);
}
}
// Derive required fields and their types directly from the schema fixture.
// Each required field whose "properties" entry has a primitive "type" is
// checked via requireField; "object"-typed fields are handled below.
for (const key of schemaRequired) {
const propDef = schemaProps[key];
const fieldType = propDef && propDef.type;
if (fieldType === 'object') {
// Object fields are validated with deeper checks below.
continue;
}
requireField(key, fieldType || 'string');
}
// Validate "object"-typed required fields from the schema.
// For each such field, check existence, type, and any nested "required" sub-fields.
for (const key of schemaRequired) {
const propDef = schemaProps[key];
if (!propDef || propDef.type !== 'object') continue;
if (!(key in manifest)) {
errors.push(`"${key}" is required but missing`);
} else if (typeof manifest[key] !== 'object' || manifest[key] === null) {
errors.push(`"${key}" must be an object`);
} else {
// Validate nested required sub-fields declared in the schema.
const nestedRequired = Array.isArray(propDef.required) ? propDef.required : [];
const nestedProps = (propDef.properties && typeof propDef.properties === 'object') ? propDef.properties : {};
for (const subKey of nestedRequired) {
const subDef = nestedProps[subKey];
const subType = subDef && subDef.type;
if (!(subKey in manifest[key])) {
errors.push(`"${key}.${subKey}" is required but missing`);
} else if (subType && typeof manifest[key][subKey] !== subType) {
errors.push(`"${key}.${subKey}" must be a ${subType}, got ${typeof manifest[key][subKey]}`);
}
// minLength check for nested string sub-fields
if (subType === 'string' && subDef.minLength !== undefined) {
if (typeof manifest[key][subKey] === 'string' && manifest[key][subKey].length < subDef.minLength) {
errors.push(`"${key}.${subKey}" must have minLength ${subDef.minLength}`);
}
}
}
}
}
// Derive pattern and minLength constraints from the schema fixture properties.
for (const key of schemaRequired) {
const propDef = schemaProps[key];
if (!propDef || propDef.type === 'object') continue;
const value = manifest[key];
if (propDef.pattern && typeof value === 'string') {
const re = new RegExp(propDef.pattern);
if (!re.test(value)) {
errors.push(`"${key}" must match ${propDef.pattern}, got "${value}"`);
}
}
if (propDef.minLength !== undefined && typeof value === 'string') {
if (value.length < propDef.minLength) {
errors.push(`"${key}" must have minLength ${propDef.minLength}, got length ${value.length}`);
}
}
}
if (errors.length > 0) {
assert.fail(
`plugin.json fails structural validation against ${path.relative(ROOT, SCHEMA_FIXTURE_PATH)}:\n` +
errors.map(e => ` - ${e}`).join('\n') +
`\n\nFull manifest:\n${JSON.stringify(manifest, null, 2)}`
);
}
});
// ── C2: Opportunistic CLI integration (skipped when claude not on PATH) ──────
const claudeAvailable = (() => {
try {
const result = spawnSync('claude', ['--version'], { encoding: 'utf-8', timeout: 5000 });
return result.status === 0;
} catch (_) {
return false;
}
})();
test(
'C2: claude plugin validate --strict exits 0 (opportunistic — skip when claude not on PATH)',
{ skip: !claudeAvailable ? 'claude binary not on PATH' : false },
() => {
const pluginRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-plugin-validate-'));
try {
fs.mkdirSync(path.join(pluginRoot, '.claude-plugin'), { recursive: true });
fs.copyFileSync(PLUGIN_JSON_PATH, path.join(pluginRoot, '.claude-plugin', 'plugin.json'));
fs.symlinkSync(path.join(ROOT, 'commands'), path.join(pluginRoot, 'commands'), 'dir');
fs.symlinkSync(path.join(ROOT, 'hooks'), path.join(pluginRoot, 'hooks'), 'dir');
fs.symlinkSync(path.join(ROOT, 'skills'), path.join(pluginRoot, 'skills'), 'dir');
const result = spawnSync('claude', ['plugin', 'validate', pluginRoot, '--strict'], {
cwd: ROOT,
encoding: 'utf-8',
timeout: 15000,
});
assert.equal(
result.status,
0,
`claude plugin validate ${pluginRoot} --strict exited with ${result.status}.\nstdout: ${result.stdout}\nstderr: ${result.stderr}`
);
} finally {
cleanup(pluginRoot);
}
}
);
});
// ─── Section D: Always-on hook contract (drift guard) ────────────────────────
describe('D: always-on hook contract drift guard', () => {
/**
* Parses hooks.json and builds a map:
* event -> matcher (or '' for no-matcher) -> [{script, timeout}]
*
* script: basename of the .js/.sh file referenced in the command string
* timeout: numeric value from hook.timeout, or undefined if absent
*/
function buildHookMap() {
const raw = fs.readFileSync(HOOKS_JSON_PATH, 'utf-8');
const hooksConfig = JSON.parse(raw);
const scriptRe = /\$\{CLAUDE_PLUGIN_ROOT\}\/hooks\/([^\s"]+)/;
const map = {};
for (const [eventName, eventEntries] of Object.entries(hooksConfig.hooks)) {
map[eventName] = map[eventName] || {};
for (const entry of eventEntries) {
const matcher = entry.matcher || '';
map[eventName][matcher] = map[eventName][matcher] || [];
for (const hook of entry.hooks) {
const m = hook.command.match(scriptRe);
if (m) {
map[eventName][matcher].push({
script: m[1],
timeout: hook.timeout,
});
}
}
}
}
return map;
}
test('SessionStart: one no-matcher group with gsd-ensure-canonical-path.js then gsd-check-update.js', () => {
// #997: gsd-ensure-canonical-path.js is wired alongside gsd-check-update.js
// in the single SessionStart no-matcher group. It must run FIRST so the
// canonical ~/.claude/gsd-core path (and its @-include targets) exist before
// any other SessionStart logic that may read the bundled tree.
const map = buildHookMap();
const groups = map['SessionStart'];
assert.ok(groups, 'SessionStart must be present in hooks.json');
// There must be exactly one entry group (key '' = no matcher)
const noMatcherHooks = groups[''];
assert.ok(
Array.isArray(noMatcherHooks) && noMatcherHooks.length === 2,
`SessionStart no-matcher group must contain exactly two hooks; got: ${JSON.stringify(noMatcherHooks)}`
);
assert.equal(
noMatcherHooks[0].script, 'gsd-ensure-canonical-path.js',
'gsd-ensure-canonical-path.js must be the FIRST SessionStart hook (#997)'
);
assert.equal(
noMatcherHooks[0].timeout, 5,
'gsd-ensure-canonical-path.js must have a small timeout (5s) — symlink setup is fast'
);
assert.equal(
noMatcherHooks[1].script, 'gsd-check-update.js',
'gsd-check-update.js must remain a SessionStart hook'
);
assert.equal(noMatcherHooks[1].timeout, undefined, 'gsd-check-update.js must NOT have a timeout field');
});
test('PreToolUse Write|Edit group: gsd-prompt-guard.js (timeout 5) + gsd-read-guard.js (timeout 5)', () => {
const map = buildHookMap();
const groups = map['PreToolUse'];
assert.ok(groups, 'PreToolUse must be present in hooks.json');
const hooks = groups['Write|Edit'];
assert.ok(
Array.isArray(hooks) && hooks.length === 2,
`PreToolUse Write|Edit must have exactly 2 hooks; got: ${JSON.stringify(hooks)}`
);
assert.equal(hooks[0].script, 'gsd-prompt-guard.js', 'first hook must be gsd-prompt-guard.js');
assert.equal(hooks[0].timeout, 5, 'gsd-prompt-guard.js must have timeout 5');
assert.equal(hooks[1].script, 'gsd-read-guard.js', 'second hook must be gsd-read-guard.js');
assert.equal(hooks[1].timeout, 5, 'gsd-read-guard.js must have timeout 5');
});
test('PreToolUse Write|Edit|MultiEdit group: gsd-worktree-path-guard.js (timeout 5)', () => {
const map = buildHookMap();
const groups = map['PreToolUse'];
assert.ok(groups, 'PreToolUse must be present in hooks.json');
const hooks = groups['Write|Edit|MultiEdit'];
assert.ok(
Array.isArray(hooks) && hooks.length === 1,
`PreToolUse Write|Edit|MultiEdit must have exactly 1 hook; got: ${JSON.stringify(hooks)}`
);
assert.equal(hooks[0].script, 'gsd-worktree-path-guard.js', 'hook must be gsd-worktree-path-guard.js');
assert.equal(hooks[0].timeout, 5, 'gsd-worktree-path-guard.js must have timeout 5');
});
test('PreToolUse Write group: gsd-write-guard.js (timeout 5)', () => {
const map = buildHookMap();
const groups = map['PreToolUse'];
assert.ok(groups, 'PreToolUse must be present in hooks.json');
// #2255: catastrophic-shrink guard for curated .planning/ writes — its own
// matcher group because it guards Write payloads only (Edit/MultiEdit are
// scoped by construction and out of scope by design).
const hooks = groups['Write'];
assert.ok(
Array.isArray(hooks) && hooks.length === 1,
`PreToolUse Write must have exactly 1 hook; got: ${JSON.stringify(hooks)}`
);
assert.equal(hooks[0].script, 'gsd-write-guard.js', 'hook must be gsd-write-guard.js');
assert.equal(hooks[0].timeout, 5, 'gsd-write-guard.js must have timeout 5');
});
test('PostToolUse Bash|Edit|Write|MultiEdit|Agent|Task group: gsd-context-monitor.js (timeout 10)', () => {
const map = buildHookMap();
const groups = map['PostToolUse'];
assert.ok(groups, 'PostToolUse must be present in hooks.json');
const hooks = groups['Bash|Edit|Write|MultiEdit|Agent|Task'];
assert.ok(
Array.isArray(hooks) && hooks.length === 1,
`PostToolUse Bash|Edit|Write|MultiEdit|Agent|Task must have exactly 1 hook; got: ${JSON.stringify(hooks)}`
);
assert.equal(hooks[0].script, 'gsd-context-monitor.js', 'hook must be gsd-context-monitor.js');
assert.equal(hooks[0].timeout, 10, 'gsd-context-monitor.js must have timeout 10');
});
test('PostToolUse Read|WebFetch|WebSearch group: gsd-read-injection-scanner.js (timeout 5)', () => {
const map = buildHookMap();
const groups = map['PostToolUse'];
assert.ok(groups, 'PostToolUse must be present in hooks.json');
// #1577: the injection scanner now also covers WebFetch/WebSearch ingress,
// so the matcher is the combined "Read|WebFetch|WebSearch" group.
const hooks = groups['Read|WebFetch|WebSearch'];
assert.ok(
Array.isArray(hooks) && hooks.length === 1,
`PostToolUse Read|WebFetch|WebSearch must have exactly 1 hook; got: ${JSON.stringify(hooks)}`
);
assert.equal(hooks[0].script, 'gsd-read-injection-scanner.js', 'hook must be gsd-read-injection-scanner.js');
assert.equal(hooks[0].timeout, 5, 'gsd-read-injection-scanner.js must have timeout 5');
});
});
// ─── Section E: Config-gated hooks must be absent from hooks.json ─────────────
describe('E: config-gated (opt-in) hooks must not appear in hooks.json', () => {
const CONFIG_GATED_HOOKS = [
'gsd-workflow-guard.js',
'gsd-validate-commit.sh',
'gsd-graphify-update.sh',
'gsd-session-state.sh',
'gsd-phase-boundary.sh',
'gsd-update-banner.js',
'gsd-statusline.js',
'gsd-check-update-worker.js',
];
test('none of the config-gated hook basenames appear in hooks.json command strings', () => {
const raw = fs.readFileSync(HOOKS_JSON_PATH, 'utf-8');
// Check raw text — simple and resistant to structure changes
for (const hookBasename of CONFIG_GATED_HOOKS) {
assert.ok(
!raw.includes(hookBasename),
`Config-gated hook "${hookBasename}" must NOT appear in hooks/hooks.json ` +
`(it is opt-in and must not run unconditionally on the plugin path)`
);
}
});
});
// ─── Section F: #997 canonical-path hook registration ────────────────────────
//
// gsd-ensure-canonical-path.js must be shipped + wired so plugin installs get a
// real ~/.claude/gsd-core directory (with the immutable bundled subdirs
// symlinked) — otherwise every `@~/.claude/gsd-core/...` include in agents /
// commands / templates resolves to nothing and agents fail (#997).
describe('F: #997 gsd-ensure-canonical-path.js is shipped and wired', () => {
const HOOK_BASENAME = 'gsd-ensure-canonical-path.js';
test('hook source file exists in hooks/', () => {
assert.ok(
fs.existsSync(path.join(ROOT, 'hooks', HOOK_BASENAME)),
`hooks/${HOOK_BASENAME} must exist on disk`
);
});
test('hook is listed in HOOKS_TO_COPY (build-hooks.js) so it ships to dist', () => {
const { HOOKS_TO_COPY } = require(path.join(ROOT, 'scripts', 'build-hooks.js'));
assert.ok(
HOOKS_TO_COPY.includes(HOOK_BASENAME),
`${HOOK_BASENAME} must be in HOOKS_TO_COPY or it never ships to hooks/dist`
);
});
test('hook is listed in MANAGED_HOOKS (staleness detection)', () => {
assert.ok(
MANAGED_HOOKS.includes(HOOK_BASENAME),
`${HOOK_BASENAME} must be in MANAGED_HOOKS so it is checked for staleness after update`
);
});
test('hook is wired in hooks.json SessionStart with ${CLAUDE_PLUGIN_ROOT}', () => {
const hooksConfig = JSON.parse(fs.readFileSync(HOOKS_JSON_PATH, 'utf-8'));
const sessionStart = hooksConfig.hooks.SessionStart || [];
let wired = false;
for (const entry of sessionStart) {
for (const hook of entry.hooks || []) {
if (hook.command && hook.command.includes(HOOK_BASENAME)) {
wired = true;
assert.ok(
hook.command.includes('${CLAUDE_PLUGIN_ROOT}'),
'canonical-path hook command must use ${CLAUDE_PLUGIN_ROOT}'
);
}
}
}
assert.ok(wired, `${HOOK_BASENAME} must be wired under SessionStart in hooks.json`);
});
});
// ─── Section G: #997 ensureCanonicalPath() behavioral regression ─────────────
//
// Drives the hook's exported pure core with fake home / fake plugin-root layouts
// to prove the actual canonical-path bootstrap behaviour: creates symlinks for a
// plugin layout, no-ops for classic installs, preserves user files, prunes stale
// links (self-heal after `claude plugin update`), and handles boundary cases
// (missing bundled dir, pre-existing real dir, pre-existing user file at a link
// target). Behavioral — calls the exported function and asserts the resulting
// filesystem state, not source text.
describe('G: #997 ensureCanonicalPath() behavioural regression', () => {
const { ensureCanonicalPath, dirLinkType, MANAGED_SUBDIRS } =
require(path.join(ROOT, 'hooks', 'gsd-ensure-canonical-path.js'));
test('win32 uses a junction; other platforms use a dir symlink', () => {
// Junction correctness is an explicit requirement but real junctions can
// only be created on Windows. Assert the platform→fs.symlinkSync type
// mapping directly so the win32 branch is covered on any host.
assert.equal(dirLinkType('win32'), 'junction', 'win32 must use a junction');
assert.equal(dirLinkType('linux'), 'dir', 'POSIX must use a dir symlink');
assert.equal(dirLinkType('darwin'), 'dir', 'POSIX must use a dir symlink');
});
let tmp;
beforeEach(() => {
tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-997-'));
});
afterEach(() => {
// eslint-disable-next-line local/no-raw-rmsync-in-tests -- per-test temp cleanup, swallows ENOENT
try { fs.rmSync(tmp, { recursive: true, force: true }); } catch { /* ignore */ }
});
// Build a fake plugin layout: <tmp>/plugin/gsd-core/<subdir>/marker.md and a
// separate fake home <tmp>/home with an (initially absent) .claude dir.
function makePluginLayout(subdirs = MANAGED_SUBDIRS) {
const pluginRoot = path.join(tmp, 'plugin');
const bundled = path.join(pluginRoot, 'gsd-core');
for (const sub of subdirs) {
fs.mkdirSync(path.join(bundled, sub), { recursive: true });
fs.writeFileSync(path.join(bundled, sub, 'marker.md'), `bundled ${sub}`);
}
const homeDir = path.join(tmp, 'home');
fs.mkdirSync(path.join(homeDir, '.claude'), { recursive: true });
return { pluginRoot, homeDir, bundled };
}
test('plugin layout: creates ~/.claude/gsd-core with all subdirs symlinked to the bundle', () => {
const { pluginRoot, homeDir, bundled } = makePluginLayout();
const result = ensureCanonicalPath({ pluginRoot, homeDir, platform: 'linux', env: {} });
assert.equal(result.status, 'ensured', `expected ensured; got ${JSON.stringify(result)}`);
const canonical = path.join(homeDir, '.claude', 'gsd-core');
assert.ok(fs.existsSync(canonical), 'canonical dir must exist');
for (const sub of MANAGED_SUBDIRS) {
const linkPath = path.join(canonical, sub);
const st = fs.lstatSync(linkPath);
assert.ok(st.isSymbolicLink(), `${sub} must be a symlink`);
assert.equal(
fs.realpathSync(linkPath),
fs.realpathSync(path.join(bundled, sub)),
`${sub} link must resolve to the bundled subdir`
);
// The @-include target now resolves to real bundled content.
assert.equal(
fs.readFileSync(path.join(linkPath, 'marker.md'), 'utf-8'),
`bundled ${sub}`,
`@-include into ${sub} must resolve to bundled content (this is the #997 fix)`
);
}
assert.deepEqual(result.linked.sort(), [...MANAGED_SUBDIRS].sort());
});
test('idempotent: a second run with the same layout re-affirms links and changes nothing', () => {
const { pluginRoot, homeDir } = makePluginLayout();
ensureCanonicalPath({ pluginRoot, homeDir, platform: 'linux', env: {} });
const second = ensureCanonicalPath({ pluginRoot, homeDir, platform: 'linux', env: {} });
assert.equal(second.status, 'ensured');
assert.deepEqual(second.linked.sort(), [...MANAGED_SUBDIRS].sort());
assert.deepEqual(second.prunedStale, []);
assert.deepEqual(second.preserved, []);
});
test('classic install: real bundled subdirs at canonical path → no-op (never touched)', () => {
const { pluginRoot, homeDir } = makePluginLayout();
// Simulate a classic bin/install.js layout: canonical dir is a REAL dir with
// REAL subdirs (not symlinks).
const canonical = path.join(homeDir, '.claude', 'gsd-core');
for (const sub of MANAGED_SUBDIRS) {
fs.mkdirSync(path.join(canonical, sub), { recursive: true });
fs.writeFileSync(path.join(canonical, sub, 'real.md'), `classic ${sub}`);
}
const result = ensureCanonicalPath({ pluginRoot, homeDir, platform: 'linux', env: {} });
assert.equal(result.status, 'noop');
assert.equal(result.reason, 'classic-install');
for (const sub of MANAGED_SUBDIRS) {
const st = fs.lstatSync(path.join(canonical, sub));
assert.ok(st.isDirectory() && !st.isSymbolicLink(), `${sub} must stay a real dir`);
}
});
test('no plugin context: CLAUDE_PLUGIN_ROOT unset → no-op (classic/npm install path)', () => {
const { homeDir } = makePluginLayout();
const result = ensureCanonicalPath({ pluginRoot: undefined, homeDir, platform: 'linux', env: {} });
assert.equal(result.status, 'noop');
assert.equal(result.reason, 'no-plugin-bundle');
assert.ok(!fs.existsSync(path.join(homeDir, '.claude', 'gsd-core')), 'must not create canonical dir');
});
test('boundary: bundled gsd-core dir missing under plugin root → no-op', () => {
const pluginRoot = path.join(tmp, 'plugin-empty');
fs.mkdirSync(pluginRoot, { recursive: true }); // no gsd-core/ inside
const homeDir = path.join(tmp, 'home');
fs.mkdirSync(path.join(homeDir, '.claude'), { recursive: true });
const result = ensureCanonicalPath({ pluginRoot, homeDir, platform: 'linux', env: {} });
assert.equal(result.status, 'noop');
assert.equal(result.reason, 'no-plugin-bundle');
});
test('preserve: a real user file at a managed link target is never clobbered', () => {
const { pluginRoot, homeDir } = makePluginLayout();
const canonical = path.join(homeDir, '.claude', 'gsd-core');
fs.mkdirSync(canonical, { recursive: true });
// User (or partial state) put a REAL directory at 'references' with content.
fs.mkdirSync(path.join(canonical, 'references'), { recursive: true });
fs.writeFileSync(path.join(canonical, 'references', 'USER-NOTES.md'), 'precious');
const result = ensureCanonicalPath({ pluginRoot, homeDir, platform: 'linux', env: {} });
// 'references' is a real dir → classic detection kicks in and the whole op
// is a no-op, preserving everything. Either way, the user file survives.
assert.ok(
fs.existsSync(path.join(canonical, 'references', 'USER-NOTES.md')),
'user file under a managed target must survive'
);
assert.equal(
fs.readFileSync(path.join(canonical, 'references', 'USER-NOTES.md'), 'utf-8'),
'precious'
);
void result;
});
test('preserve user-generated top-level file (USER-PROFILE.md) while linking subdirs', () => {
const { pluginRoot, homeDir } = makePluginLayout();
const canonical = path.join(homeDir, '.claude', 'gsd-core');
fs.mkdirSync(canonical, { recursive: true });
// A user-generated file at the TOP of the canonical dir (not a managed
// subdir) — must never be removed. No managed subdir is real yet, so the
// hook proceeds to link them.
fs.writeFileSync(path.join(canonical, 'USER-PROFILE.md'), 'my profile');
const result = ensureCanonicalPath({ pluginRoot, homeDir, platform: 'linux', env: {} });
assert.equal(result.status, 'ensured');
assert.ok(
fs.existsSync(path.join(canonical, 'USER-PROFILE.md')),
'USER-PROFILE.md must survive canonical-path setup'
);
assert.equal(fs.readFileSync(path.join(canonical, 'USER-PROFILE.md'), 'utf-8'), 'my profile');
// And subdirs are still linked.
for (const sub of MANAGED_SUBDIRS) {
assert.ok(fs.lstatSync(path.join(canonical, sub)).isSymbolicLink(), `${sub} linked`);
}
});
test('self-heal: a stale symlink (pointing at a removed prior plugin version) is pruned and recreated', () => {
const { pluginRoot, homeDir } = makePluginLayout();
const canonical = path.join(homeDir, '.claude', 'gsd-core');
fs.mkdirSync(canonical, { recursive: true });
// Simulate a stale link left by a previous plugin version that has since
// been removed (claude plugin update rotated the version dir).
const stalePrior = path.join(tmp, 'plugin-OLD', 'gsd-core', 'references');
fs.mkdirSync(stalePrior, { recursive: true });
const linkPath = path.join(canonical, 'references');
fs.symlinkSync(stalePrior, linkPath, 'dir');
// eslint-disable-next-line local/no-raw-rmsync-in-tests -- simulate removed prior version
fs.rmSync(path.join(tmp, 'plugin-OLD'), { recursive: true, force: true });
assert.ok(!fs.existsSync(linkPath), 'precondition: link now dangles (target removed)');
const result = ensureCanonicalPath({ pluginRoot, homeDir, platform: 'linux', env: {} });
assert.equal(result.status, 'ensured');
assert.ok(result.prunedStale.includes('references'), 'stale references link must be pruned');
// Now resolves to the CURRENT bundle.
assert.equal(
fs.realpathSync(linkPath),
fs.realpathSync(path.join(pluginRoot, 'gsd-core', 'references')),
'references must now point at the current bundled tree'
);
});
test('self-heal: a managed symlink pointing at the wrong (but existing) target is repointed', () => {
const { pluginRoot, homeDir } = makePluginLayout();
const canonical = path.join(homeDir, '.claude', 'gsd-core');
fs.mkdirSync(canonical, { recursive: true });
// A link to some OTHER real directory (e.g. a different plugin version still
// on disk). It is a valid link but points at the wrong place.
const otherDir = path.join(tmp, 'plugin-OTHER', 'gsd-core', 'workflows');
fs.mkdirSync(otherDir, { recursive: true });
fs.symlinkSync(otherDir, path.join(canonical, 'workflows'), 'dir');
const result = ensureCanonicalPath({ pluginRoot, homeDir, platform: 'linux', env: {} });
assert.equal(result.status, 'ensured');
assert.equal(
fs.realpathSync(path.join(canonical, 'workflows')),
fs.realpathSync(path.join(pluginRoot, 'gsd-core', 'workflows')),
'workflows must be repointed to the current bundle'
);
});
test('security: bundled gsd-core that symlinks OUTSIDE the plugin root is rejected', () => {
const pluginRoot = path.join(tmp, 'plugin-evil');
fs.mkdirSync(pluginRoot, { recursive: true });
// Attacker places a symlink at <pluginRoot>/gsd-core pointing outside root.
const outside = path.join(tmp, 'OUTSIDE');
fs.mkdirSync(path.join(outside, 'references'), { recursive: true });
fs.symlinkSync(outside, path.join(pluginRoot, 'gsd-core'), 'dir');
const homeDir = path.join(tmp, 'home');
fs.mkdirSync(path.join(homeDir, '.claude'), { recursive: true });
const result = ensureCanonicalPath({ pluginRoot, homeDir, platform: 'linux', env: {} });
assert.equal(result.status, 'noop', 'a bundled tree resolving outside the plugin root must be rejected');
assert.equal(result.reason, 'no-plugin-bundle');
assert.ok(
!fs.existsSync(path.join(homeDir, '.claude', 'gsd-core', 'references')),
'must NOT link the canonical path at content outside the plugin root'
);
});
test('CLAUDE_CONFIG_DIR honoured: canonical path is created under the custom config dir', () => {
const { pluginRoot, homeDir } = makePluginLayout();
const customCfg = path.join(tmp, 'custom-cfg');
fs.mkdirSync(customCfg, { recursive: true });
const result = ensureCanonicalPath({
pluginRoot, homeDir, platform: 'linux',
env: { CLAUDE_CONFIG_DIR: customCfg },
});
assert.equal(result.status, 'ensured');
assert.equal(result.canonicalDir, path.join(customCfg, 'gsd-core'));
assert.ok(fs.lstatSync(path.join(customCfg, 'gsd-core', 'references')).isSymbolicLink());
});
test('canonical path is itself a symlink → no-op (never writes links through a user-pointed symlink)', () => {
// A user pointed ~/.claude/gsd-core at some other directory via a symlink.
// The hook must NOT create managed links through it into a dir it does not
// own — it bails as a no-op.
const { pluginRoot, homeDir } = makePluginLayout();
const userTarget = path.join(tmp, 'user-gsd');
fs.mkdirSync(userTarget, { recursive: true });
const canonical = path.join(homeDir, '.claude', 'gsd-core');
fs.symlinkSync(userTarget, canonical, 'dir');
const result = ensureCanonicalPath({ pluginRoot, homeDir, platform: 'linux', env: {} });
assert.equal(result.status, 'noop');
assert.equal(result.reason, 'canonical-is-symlink');
// No managed links were written into the user's target directory.
for (const sub of MANAGED_SUBDIRS) {
assert.ok(
!fs.existsSync(path.join(userTarget, sub)),
`must not write ${sub} link through the user symlink`
);
}
});
test('uniform result contract: every status carries the four action arrays', () => {
const { pluginRoot, homeDir } = makePluginLayout();
const noop = ensureCanonicalPath({ pluginRoot: undefined, homeDir, platform: 'linux', env: {} });
for (const k of ['linked', 'prunedStale', 'preserved', 'skipped']) {
assert.ok(Array.isArray(noop[k]), `noop result.${k} must be an array, not undefined`);
}
const ensured = ensureCanonicalPath({ pluginRoot, homeDir, platform: 'linux', env: {} });
for (const k of ['linked', 'prunedStale', 'preserved', 'skipped']) {
assert.ok(Array.isArray(ensured[k]), `ensured result.${k} must be an array`);
}
});
test('security: a bundled subdir that symlinks OUTSIDE the bundle is skipped, not linked', () => {
// Defence-in-depth: even within a (validated) plugin root, a tampered
// bundle that ships <bundle>/references as a symlink escaping the bundle
// must NOT be exposed at the canonical path.
const { pluginRoot, homeDir, bundled } = makePluginLayout(['workflows']);
// Plant an escaping symlink at <bundle>/references → outside the bundle.
const outside = path.join(tmp, 'OUTSIDE-references');
fs.mkdirSync(outside, { recursive: true });
fs.writeFileSync(path.join(outside, 'evil.md'), 'evil');
fs.symlinkSync(outside, path.join(bundled, 'references'), 'dir');
const result = ensureCanonicalPath({ pluginRoot, homeDir, platform: 'linux', env: {} });
assert.equal(result.status, 'ensured');
assert.ok(result.linked.includes('workflows'), 'legit subdir still linked');
assert.ok(result.skipped.includes('references'), 'escaping subdir must be skipped');
assert.ok(
!fs.existsSync(path.join(homeDir, '.claude', 'gsd-core', 'references')),
'canonical path must NOT expose the escaping subdir'
);
});
test('partial bundle: only ships some subdirs → links those, skips absent ones', () => {
const { pluginRoot, homeDir } = makePluginLayout(['references', 'workflows']);
const result = ensureCanonicalPath({ pluginRoot, homeDir, platform: 'linux', env: {} });
assert.equal(result.status, 'ensured');
assert.deepEqual(result.linked.sort(), ['references', 'workflows']);
assert.deepEqual(
result.skipped.sort(),
['bin', 'contexts', 'templates'].sort(),
'subdirs not present in the bundle must be skipped, not errored'
);
});
});
// ─── Section H: skills surface projection (#1596 — Phase B-provide) ──────────
//
// ADR-766 originally projected commands + hooks but NOT skills. Phase B-provide
// (#1596) adds a build-generated `skills/` dir + a `skills` manifest field so
// plugin-installed GSD exposes `gsd-core:<skill>` the native Claude Code way.
// The skills are generated from `commands/gsd/*.md` by
// `scripts/gen-plugin-skills.cjs` using `convertClaudeCommandToClaudeSkill`.
describe('H: skills surface projection (#1596)', () => {
const SKILLS_DIR = path.resolve(ROOT, 'skills');
test('plugin.json declares skills: "./skills/"', () => {
const manifest = JSON.parse(fs.readFileSync(PLUGIN_JSON_PATH, 'utf-8'));
assert.equal(
manifest.skills, './skills/',
'plugin.json must declare "skills": "./skills/" so Claude Code discovers plugin skills (#1596)'
);
});
test('skills/ dir exists with at least one gsd-*/SKILL.md', () => {
assert.ok(fs.existsSync(SKILLS_DIR), `skills/ dir must exist (run: npm run gen:plugin-skills -- --write): ${SKILLS_DIR}`);
const entries = fs.readdirSync(SKILLS_DIR, { withFileTypes: true });
const skillDirs = entries.filter(e => e.isDirectory() && e.name.startsWith('gsd-'));
assert.ok(skillDirs.length > 0, 'skills/ must contain at least one gsd-*/ directory');
// Each must have a SKILL.md
for (const dir of skillDirs) {
const skillMd = path.join(SKILLS_DIR, dir.name, 'SKILL.md');
assert.ok(fs.existsSync(skillMd), `${dir.name}/SKILL.md must exist`);
}
});
test('every generated SKILL.md has name: and description: frontmatter', () => {
assert.ok(fs.existsSync(SKILLS_DIR), 'skills/ must exist');
const skillDirs = fs.readdirSync(SKILLS_DIR, { withFileTypes: true })
.filter(e => e.isDirectory() && e.name.startsWith('gsd-'));
assert.ok(skillDirs.length > 0, 'must have at least one skill dir');
for (const dir of skillDirs) {
const raw = fs.readFileSync(path.join(SKILLS_DIR, dir.name, 'SKILL.md'), 'utf-8');
const fmMatch = raw.match(/^---\r?\n([\s\S]*?)\r?\n---/);
assert.ok(fmMatch, `${dir.name}/SKILL.md must have frontmatter`);
const fm = fmMatch[1];
assert.ok(/^\s*name:\s*\S/m.test(fm), `${dir.name}/SKILL.md frontmatter must have a name: field`);
assert.ok(/^\s*description:\s*\S/m.test(fm), `${dir.name}/SKILL.md frontmatter must have a description: field`);
}
});
test('parity: one skill dir per command file (DEFECT.GENERATIVE-FIX)', () => {
const commandsDir = path.resolve(ROOT, 'commands', 'gsd');
const commandFiles = fs.readdirSync(commandsDir).filter(f => f.endsWith('.md'));
const skillDirs = fs.readdirSync(SKILLS_DIR, { withFileTypes: true })
.filter(e => e.isDirectory() && e.name.startsWith('gsd-'));
assert.equal(
skillDirs.length, commandFiles.length,
`skills/gsd-*/ count (${skillDirs.length}) must equal commands/gsd/*.md count (${commandFiles.length}). ` +
`Run: npm run gen:plugin-skills -- --write`
);
});
});