* test(#3072): add failing-first coverage for the mcp served catalog 55 input-class rows from the phase test matrix, across four suites: the catalog module over injected readFile/readDir seams, the protocol surface through handleMessage, the install-vs-catalog parity gate, and fast-check properties for uri round-trip, traversal refusal, and pagination partition. src/mcp-catalog.cts lands as a skeleton whose functions throw, so the suites fail on BEHAVIOR rather than on a missing module. The REASON enum is real so tests assert typed codes instead of message prose. Hostile coverage for the one client-controlled path surface (resources/read): dot-dot and backslash traversal, percent- and double-encoded traversal, absolute posix and windows paths, file:// scheme, null byte, symlink escape, unindexed sibling, non-string and empty uri, wrong root segment. IO faults are injected by monkeypatching the seam, never chmod 0o000 - root bypasses mode bits, so a permission-based test silently passes with zero coverage in root CI. Refs #3072 * feat(#3072): serve the mcp catalog as resources and prompts gsd-mcp-server now serves GSD's own content alongside its three tools: the workflow, reference and command tree as MCP resources (resources/list, cursor paginated, and resources/read over gsd://<segment>/<relpath> uris) and the 71 commands/gsd/*.md as MCP prompts keyed by bare command name. initialize advertises resources and prompts, and deliberately does not advertise subscribe or listChanged - the catalog is fixed for a server process lifetime, so declaring a notification we never send would be a lie a host acts on. Composition scope is SHARED, not re-declared. shouldCompose lives in src/mcp-catalog.cts and bin/install.js now imports it instead of carrying its own regex, so the served catalog and the installed file floor cannot drift on what gets composed. Proven behavior-preserving across all 2871 tracked paths plus windows-backslash, absolute and near-miss-prefix cases: zero mismatches. tests/mcp-catalog-parity.test.cjs asserts served text equals the installer composition-stage text over the real tree, with anti-vacuity guards requiring both a marker-bearing workflow and a non-composed file in the comparison set. Two measurements corrected the literal issue text. Composition is scoped to gsd-core/workflows/ only, because a reference or command that documents marker syntax with an unfenced example would otherwise be parsed as carrying a real marker and have that line lossily dropped. And parity is asserted at the composition stage rather than against an emitted runtime tree, since install applies per-runtime path rewrites afterwards and the catalog is host-agnostic, so byte equality with any one runtime would be false by construction. resources/read is the one client-controlled path surface and is guarded in two independent layers: the uri must be an exact key in the prebuilt index, which defeats every traversal string by construction, and the mapped path is then re-checked with validatePath so a symlink planted inside a root after indexing is still refused. Also fixes a real drift defect found while here: SERVER_VERSION was hardcoded 1.7.0 while the package is at 1.9.1. It now resolves lazily from VERSION or package.json, reusing the precedent in runtime-artifact-conversion. Closes #3072 * test(#3072): make the catalog parity gate drive the real installer Review found the parity gate vacuous: it never imported or spawned bin/install.js, and recomputed the installer side with the SAME shouldCompose and composeWorkflow the catalog calls internally. It therefore proved only that src/mcp-catalog.cts is self-consistent. The old row 52 compared shouldCompose against a regex literal frozen in the test file rather than against the installer at all. An inline divergent regex re-added to bin/install.js - the exact regression ADR-1671 asks this gate to catch - would have left the suite green. The gate now spawns a real bin/install.js and compares the composition DECISION, observed as gsd:section marker survival, against what the catalog serves for the same files. Marker presence is the right observable because the installer applies per-runtime path rewrites after composing while the catalog applies none, so raw byte equality between the two surfaces is false by construction and must not be asserted. Sensitivity was proven, not assumed: overlaying the shouldCompose export that bin/install.js imports so it always returns false makes a real spawned install leave autonomous.md's markers in place while the catalog still strips them, and the row 48 assertion diverges. Anti-vacuity guards are kept and extended - the comparison set must be non-empty, must contain a workflow that actually carries markers, must contain a file the predicate declines to compose, and the install must have emitted a non-zero file count. The marker-documenting reference case has no instance in the real tree, so it uses an overlay fixture built with the same technique workflow-fragments-emission.install.test.cjs already uses. Renamed to .install.test.cjs so it lands in the install suite it now belongs to. Refs #3072 * test(#3072): retarget the unknown-method assertion off a now-implemented method tests/gsd-mcp-server.test.cjs used 'resources/read' as its example of an UNKNOWN JSON-RPC method. The served catalog implements that method, so it now returns -32602 (no uri supplied) rather than -32601. The remote runner caught it deterministically on both linux lanes: -32602 !== -32601. The test's intent is still correct and worth keeping, so it is corrected rather than deleted or weakened. It now uses 'resources/subscribe', which the server deliberately does not implement and deliberately does not advertise in initialize's capabilities, because it never sends the corresponding notification. That turns the assertion into a real contract - the advertised capability surface and the implemented method surface agree - instead of an arbitrary method name a future feature could invalidate the same way. Swept the rest of the suite for other assertions pinning the newly implemented methods; this was the only one. Refs #3072 * chore(#3072): backfill changeset PR number 3083 * test(#3072): make the catalog fake fs separator-agnostic for windows CI caught this on windows-latest (22 and 24): every catalog fixture indexed ZERO entries, surfaced by the anti-vacuity guards as 'fixture catalog must actually index resources for this property to mean anything'. Mechanism: makeFakeFs keyed its dirMap/fileMap on POSIX-joined paths (${root}/${rel}), while production buildCatalog looks paths up with path.join, which is backslash-separated on Windows. Every lookup missed, tryReadDir returned null, and the catalog came back empty. Production is NOT at fault and is unchanged. The same CI run proves it: on windows-latest the real-filesystem tests all passed, including 'installer composition decision matches the served catalog for every file in the real installed tree' and the row-51 non-vacuity proof against a real spawned installer. A real Windows fs accepts both separators; the FAKE did not, so the fake was the unfaithful one and is what changed. Lookup keys are now normalized unconditionally with .replace(/\\/g,'/') in readDir and readFile - never path.sep-conditional, never platform-gated. The row-42/43 injected-fault wrappers got the same treatment, since they compared raw production paths against POSIX-literal fixtures. No assertion was weakened, and the anti-vacuity guards that caught this are untouched - they are the reason this surfaced as a loud failure instead of a suite that silently asserted nothing on Windows. Refs #3072 --------- Co-authored-by: sim <sim@local>
This commit is contained in:
@@ -98,8 +98,16 @@ test('tools/call: missing tool name is a JSON-RPC invalid-params error', () => {
|
||||
assert.match(res.error.message, /requires string "name"/);
|
||||
});
|
||||
|
||||
// Previously used 'resources/read' as the example unknown method, but that
|
||||
// stopped being unknown once the served catalog shipped in #3072.
|
||||
// 'resources/subscribe' is DELIBERATELY not implemented and deliberately NOT
|
||||
// advertised in initialize's capabilities, because the server never sends the
|
||||
// corresponding notification. So this assertion now pins a real contract --
|
||||
// the advertised capability surface and the implemented method surface agree
|
||||
// -- rather than an arbitrary method name that a future feature could
|
||||
// invalidate the same way.
|
||||
test('unknown method: JSON-RPC method-not-found (-32601)', () => {
|
||||
const res = handleMessage({ jsonrpc: '2.0', id: 8, method: 'resources/read' });
|
||||
const res = handleMessage({ jsonrpc: '2.0', id: 8, method: 'resources/subscribe' });
|
||||
assert.strictEqual(res.error.code, -32601);
|
||||
assert.match(res.error.message, /Method not found/);
|
||||
});
|
||||
|
||||
327
tests/mcp-catalog-parity.install.test.cjs
Normal file
327
tests/mcp-catalog-parity.install.test.cjs
Normal file
@@ -0,0 +1,327 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* mcp-catalog-parity.install.test.cjs — the anti-drift gate mandated by
|
||||
* ADR-1671 ("Dual-surface drift if any future MCP channel is added —
|
||||
* requires parity assertions"), issue #3072 (epic #1671 Phase B),
|
||||
* `.gsd/phase/feat-3072-mcp-served-catalog/40-design.md` "The parity
|
||||
* assertion".
|
||||
*
|
||||
* ## PRIOR DEFECT (review BLOCKER, fixed by this rewrite)
|
||||
*
|
||||
* The original `tests/mcp-catalog-parity.test.cjs` never imported, spawned,
|
||||
* or otherwise exercised `bin/install.js`. It recomputed the "installer
|
||||
* side" by calling `shouldCompose`/`composeWorkflow` directly — the SAME
|
||||
* functions the catalog itself calls — so it only proved `src/mcp-catalog.cts`
|
||||
* is self-consistent with itself. Its row-52 assertion compared
|
||||
* `shouldCompose` against a regex literal frozen inside the test file, never
|
||||
* against `bin/install.js`'s real behavior. Net effect: a re-introduced,
|
||||
* divergent inline composition-scope regex in `bin/install.js` (the exact
|
||||
* regression `ADR-1671:309` `DEFECT.GENERATIVE-FIX` warns about) would have
|
||||
* stayed GREEN.
|
||||
*
|
||||
* This file instead drives a REAL spawned `bin/install.js` (via
|
||||
* `tests/helpers/install-shared.cjs`'s `runMinimalInstall` — the same driver
|
||||
* `tests/workflow-fragments-emission.install.test.cjs` and
|
||||
* `tests/agent-fragments-emission.install.test.cjs` use) and compares its
|
||||
* REAL emitted output against the catalog's served content, renamed to
|
||||
* `.install.test.cjs` to land in the slow `install` suite (`npm run
|
||||
* test:install`) alongside those files.
|
||||
*
|
||||
* ## Why marker PRESENCE, not byte-equality
|
||||
*
|
||||
* `bin/install.js` applies per-runtime path rewrites (`~/.claude/` -> the
|
||||
* runtime's prefix, attribution stamping, per-runtime `.md` converters)
|
||||
* AFTER composition (`shouldCompose`/`composeWorkflow`, just below in
|
||||
* `copyWithPathReplacement`). The catalog is host-agnostic and applies none
|
||||
* of those rewrites. Raw byte-equality between an emitted file and served
|
||||
* content is therefore FALSE BY CONSTRUCTION for every file whose content
|
||||
* embeds a rewritten path or attribution stamp. What DOES survive every
|
||||
* rewrite untouched is the COMPOSITION DECISION itself: did this file's
|
||||
* `<!-- gsd:section` markers get stripped or not? Marker-token presence is
|
||||
* that observable (the same detector
|
||||
* `tests/workflow-fragments-emission.install.test.cjs`'s
|
||||
* `noSectionMarkerLeaksIntoEmittedArtifacts` already uses), and it is
|
||||
* insensitive to every rewrite that runs after composition.
|
||||
*
|
||||
* ## Single representative runtime
|
||||
*
|
||||
* `shouldCompose`/`composeWorkflow` do not depend on runtime — only the
|
||||
* REWRITES applied after composition do, and this gate's marker-presence
|
||||
* comparison is deliberately blind to those. A multi-runtime loop would
|
||||
* therefore just re-run the identical composition decision N times; one real
|
||||
* spawned install (`claude`, the canonical host per `src/mcp-catalog.cts`'s
|
||||
* own module doc) is sufficient real-install evidence for what this gate
|
||||
* checks, and keeps this already-slow suite bounded.
|
||||
*/
|
||||
|
||||
const { describe, test } = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const os = require('node:os');
|
||||
const path = require('node:path');
|
||||
const { spawnSync } = require('node:child_process');
|
||||
|
||||
const { cleanup } = require('./helpers.cjs');
|
||||
const { runMinimalInstall, installerEnv } = require('./helpers/install-shared.cjs');
|
||||
const { buildOverlayRepo } = require('./helpers/overlay-repo.cjs');
|
||||
|
||||
const { buildCatalog, readResource, shouldCompose } = require('../gsd-core/bin/lib/mcp-catalog.cjs');
|
||||
|
||||
const REPO_ROOT = path.resolve(__dirname, '..');
|
||||
const MARKER_TOKEN = 'gsd:section';
|
||||
|
||||
/** Recursively collect `.md` file paths under `absDir`, relative to `REPO_ROOT`, POSIX-normalized. */
|
||||
function collectMarkdownFiles(absDir, out = []) {
|
||||
let entries;
|
||||
try {
|
||||
entries = fs.readdirSync(absDir, { withFileTypes: true });
|
||||
} catch {
|
||||
return out;
|
||||
}
|
||||
for (const entry of entries) {
|
||||
const abs = path.join(absDir, entry.name);
|
||||
if (entry.isDirectory()) {
|
||||
collectMarkdownFiles(abs, out);
|
||||
} else if (entry.isFile() && entry.name.endsWith('.md')) {
|
||||
out.push(path.relative(REPO_ROOT, abs).replace(/\\/g, '/'));
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function realParitySet() {
|
||||
return [
|
||||
...collectMarkdownFiles(path.join(REPO_ROOT, 'gsd-core', 'workflows')),
|
||||
...collectMarkdownFiles(path.join(REPO_ROOT, 'gsd-core', 'references')),
|
||||
];
|
||||
}
|
||||
|
||||
/** `gsd-core/workflows/x.md` -> `gsd://workflows/x.md`; `gsd-core/references/y.md` -> `gsd://references/y.md`. */
|
||||
function toResourceUri(relPath) {
|
||||
const m = /^gsd-core\/(workflows|references)\/(.+)$/.exec(relPath);
|
||||
if (!m) throw new Error(`fixture bug: unexpected relPath shape ${relPath}`);
|
||||
return `gsd://${m[1]}/${m[2]}`;
|
||||
}
|
||||
|
||||
function hasMarker(text) {
|
||||
return text.includes(MARKER_TOKEN);
|
||||
}
|
||||
|
||||
/**
|
||||
* Spawn a (possibly overlaid) `bin/install.js` at global scope and assert it
|
||||
* succeeded. Mirrors `workflow-fragments-emission.install.test.cjs`'s and
|
||||
* `fragment-single-edit-propagation.install.test.cjs`'s own `spawnGlobalInstall`
|
||||
* / `installOverlay` — kept local per those files' own documented rationale:
|
||||
* it is a thin spawn wrapper with no independent mechanism (unlike
|
||||
* `buildOverlayRepo`, which IS imported/reused), so a local copy carries none
|
||||
* of the "generative fix divergence" risk.
|
||||
*/
|
||||
function installOverlay(overlayRoot, runtime, extraArgs = []) {
|
||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), `gsd-3072-parity-dest-${runtime}-`));
|
||||
const installScript = path.join(overlayRoot, 'bin', 'install.js');
|
||||
const args = [
|
||||
'--preserve-symlinks',
|
||||
'--preserve-symlinks-main',
|
||||
installScript,
|
||||
`--${runtime}`,
|
||||
'--global',
|
||||
'--config-dir',
|
||||
root,
|
||||
...extraArgs,
|
||||
];
|
||||
const result = spawnSync(process.execPath, args, {
|
||||
cwd: root,
|
||||
encoding: 'utf8',
|
||||
env: installerEnv({ HOME: root, USERPROFILE: root }),
|
||||
});
|
||||
return { configDir: root, root, result };
|
||||
}
|
||||
|
||||
// ─── row 48 — the real gate ─────────────────────────────────────────────────
|
||||
|
||||
describe('the parity gate — real installer vs real catalog', () => {
|
||||
test('installer composition decision matches the served catalog for every file in the real installed tree (row 48/52)', (t) => {
|
||||
const catalog = buildCatalog({ root: REPO_ROOT });
|
||||
const install = runMinimalInstall({ runtime: 'claude', scope: 'global' });
|
||||
t.after(() => cleanup(install.root));
|
||||
|
||||
// Anti-vacuity guard: the installer must actually have emitted files —
|
||||
// proves the spawned install really ran (not a silent no-op / early exit).
|
||||
const emittedFileCount = install.manifest && install.manifest.files
|
||||
? Object.keys(install.manifest.files).length
|
||||
: 0;
|
||||
assert.ok(
|
||||
emittedFileCount > 0,
|
||||
'the installer must have emitted at least one file — proves the real install actually ran',
|
||||
);
|
||||
|
||||
const relPaths = realParitySet();
|
||||
assert.ok(relPaths.length > 0, 'the real parity set must be non-empty');
|
||||
|
||||
let comparedCount = 0;
|
||||
let markerBearingWorkflowSeen = false;
|
||||
let nonComposedFileSeen = false;
|
||||
|
||||
for (const relPath of relPaths) {
|
||||
const emittedPath = path.join(install.configDir, relPath);
|
||||
const uri = toResourceUri(relPath);
|
||||
if (!fs.existsSync(emittedPath) || !catalog.resources.has(uri)) continue; // outside this gate's install/catalog intersection
|
||||
|
||||
comparedCount += 1;
|
||||
const sourceText = fs.readFileSync(path.join(REPO_ROOT, relPath), 'utf8');
|
||||
const emittedText = fs.readFileSync(emittedPath, 'utf8');
|
||||
const servedText = readResource(catalog, uri).text;
|
||||
|
||||
const markersPresentInEmitted = hasMarker(emittedText);
|
||||
const markersPresentInServed = hasMarker(servedText);
|
||||
|
||||
// row 48: the two independently-produced surfaces (a real spawned
|
||||
// installer vs. the catalog's own composition) must agree on whether
|
||||
// this file's markers were stripped.
|
||||
assert.equal(
|
||||
markersPresentInEmitted,
|
||||
markersPresentInServed,
|
||||
`${relPath}: composition decision diverged between the real installer (markers present=${markersPresentInEmitted}) and the served catalog (markers present=${markersPresentInServed})`,
|
||||
);
|
||||
|
||||
// row 52 replacement: the installer's OBSERVABLE composition behavior
|
||||
// (not a re-declared regex) must match shouldCompose's own verdict —
|
||||
// composed files never retain markers; declined files are untouched.
|
||||
const composedAccordingToPredicate = shouldCompose(relPath);
|
||||
const expectedEmittedHasMarker = composedAccordingToPredicate ? false : hasMarker(sourceText);
|
||||
assert.equal(
|
||||
markersPresentInEmitted,
|
||||
expectedEmittedHasMarker,
|
||||
`${relPath}: real installer output does not match shouldCompose's verdict (shouldCompose=${composedAccordingToPredicate})`,
|
||||
);
|
||||
|
||||
if (composedAccordingToPredicate && hasMarker(sourceText)) markerBearingWorkflowSeen = true;
|
||||
if (!composedAccordingToPredicate) nonComposedFileSeen = true;
|
||||
}
|
||||
|
||||
assert.ok(comparedCount > 0, 'the comparison set must be non-empty — else the gate proves nothing');
|
||||
assert.ok(
|
||||
markerBearingWorkflowSeen,
|
||||
'the comparison set must include >=1 workflow that actually carries markers in source, else every comparison is a byte-identical no-op',
|
||||
);
|
||||
assert.ok(
|
||||
nonComposedFileSeen,
|
||||
'the comparison set must include >=1 file the predicate declines to compose, else a predicate that always returns true would still pass',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
// ─── row 50 — a marker-documenting non-workflow composes on neither surface ─
|
||||
//
|
||||
// No real gsd-core/references/*.md or commands/gsd/*.md file documents the
|
||||
// `<!-- gsd:section -->` marker syntax as of this change (verified: `grep -rl
|
||||
// "gsd:section" gsd-core/references/ commands/gsd/` is empty). This test
|
||||
// therefore uses a SYNTHETIC fixture: an overlay (`buildOverlayRepo`, the
|
||||
// established technique — see `nonWorkflowMarkdownWithMarkerShapedLineIsNot
|
||||
// Composed` in `workflow-fragments-emission.install.test.cjs`, which
|
||||
// pioneered this exact fixture content) that overrides the real, existing
|
||||
// `gsd-core/references/context-budget.md` leaf with a doc that documents
|
||||
// marker syntax via a deliberately UNCLOSED marker-shaped example line — so
|
||||
// if a regression ever ran composeWorkflow over it, parsing would THROW
|
||||
// loudly (never silently mis-parse), which is what makes this a real
|
||||
// negative control rather than a fixture that would coincidentally pass
|
||||
// either way.
|
||||
|
||||
describe('a marker-documenting non-workflow composes on neither surface (row 50)', () => {
|
||||
test('reference doc content is present verbatim in source, in the real installed tree, and in the catalog served over the same tree', (t) => {
|
||||
const nonWorkflowDoc =
|
||||
'# Marker syntax\n\nExample (deliberately unfenced and unclosed to prove non-composition):\n\n<!-- gsd:section id="x" when="always" -->\nnever closed on purpose\n';
|
||||
const target = 'gsd-core/references/context-budget.md';
|
||||
|
||||
assert.equal(shouldCompose(target), false, 'precondition: a references/ path must never be composed');
|
||||
|
||||
const overlayRepo = buildOverlayRepo({ [target]: nonWorkflowDoc });
|
||||
t.after(() => cleanup(overlayRepo));
|
||||
|
||||
const dest = installOverlay(overlayRepo, 'claude');
|
||||
t.after(() => cleanup(dest.root));
|
||||
assert.equal(
|
||||
dest.result.status,
|
||||
0,
|
||||
`install must succeed: a non-workflow doc's marker-shaped line must never reach composeWorkflow\nstderr: ${dest.result.stderr}`,
|
||||
);
|
||||
|
||||
const emittedPath = path.join(dest.configDir, target);
|
||||
assert.ok(fs.existsSync(emittedPath), 'emitted context-budget.md is missing');
|
||||
assert.equal(
|
||||
fs.readFileSync(emittedPath, 'utf8'),
|
||||
nonWorkflowDoc,
|
||||
'a marker-documenting reference doc must be emitted byte-identical by the real installer (never composed)',
|
||||
);
|
||||
|
||||
// Catalog served over the SAME tree the installer just read from (the
|
||||
// overlay), not REPO_ROOT — REPO_ROOT has no such fixture on disk.
|
||||
const catalog = buildCatalog({ root: overlayRepo });
|
||||
const servedText = readResource(catalog, toResourceUri(target)).text;
|
||||
assert.equal(
|
||||
servedText,
|
||||
nonWorkflowDoc,
|
||||
'a marker-documenting reference doc must be served byte-identical by the catalog (never composed)',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
// ─── row 51 — the gate is non-vacuous against a REAL installer regression ──
|
||||
//
|
||||
// Simulates the exact regression class this gate exists to catch: a
|
||||
// composition-scope predicate that diverges reaching the REAL bin/install.js
|
||||
// emit path — not a hand-duplicated regex living only in this test file (the
|
||||
// prior defect this rewrite fixes). Overlays
|
||||
// `gsd-core/bin/lib/mcp-catalog.cjs`'s `shouldCompose` export — the ONE thing
|
||||
// `bin/install.js` imports from that module (`const { shouldCompose } =
|
||||
// require('../gsd-core/bin/lib/mcp-catalog.cjs')`) — with one that never
|
||||
// composes anything, exactly what a reverted or independently-diverged
|
||||
// inline regex in `bin/install.js` would produce. `composeWorkflow` itself
|
||||
// is left untouched, so the install still succeeds; it simply never gets
|
||||
// called for any file.
|
||||
|
||||
describe('the parity gate is non-vacuous against a real installer regression (row 51)', () => {
|
||||
test('a broken shouldCompose reaching the real bin/install.js produces a detectable installer/catalog divergence', (t) => {
|
||||
const brokenPredicateRepo = buildOverlayRepo({
|
||||
'gsd-core/bin/lib/mcp-catalog.cjs': 'module.exports = { shouldCompose: () => false };\n',
|
||||
});
|
||||
t.after(() => cleanup(brokenPredicateRepo));
|
||||
|
||||
const dest = installOverlay(brokenPredicateRepo, 'claude');
|
||||
t.after(() => cleanup(dest.root));
|
||||
assert.equal(
|
||||
dest.result.status,
|
||||
0,
|
||||
`broken-predicate install must still succeed (composeWorkflow simply never runs)\nstderr: ${dest.result.stderr}`,
|
||||
);
|
||||
|
||||
const target = 'gsd-core/workflows/autonomous.md';
|
||||
const sourceText = fs.readFileSync(path.join(REPO_ROOT, target), 'utf8');
|
||||
assert.ok(
|
||||
hasMarker(sourceText),
|
||||
'precondition: the fixture workflow must actually carry markers, or this simulation proves nothing',
|
||||
);
|
||||
|
||||
const emittedPath = path.join(dest.configDir, target);
|
||||
assert.ok(fs.existsSync(emittedPath), 'broken-predicate install is missing autonomous.md');
|
||||
const emittedText = fs.readFileSync(emittedPath, 'utf8');
|
||||
|
||||
// The real, non-overlaid catalog is unaffected by the overlay — it still
|
||||
// composes autonomous.md and strips its markers.
|
||||
const catalog = buildCatalog({ root: REPO_ROOT });
|
||||
const servedText = readResource(catalog, toResourceUri(target)).text;
|
||||
|
||||
assert.equal(hasMarker(emittedText), true, 'broken-predicate install unexpectedly composed anyway');
|
||||
assert.equal(hasMarker(servedText), false, 'the real, non-overlaid catalog unexpectedly failed to compose');
|
||||
|
||||
// This is row 48's own assertion, run against a REAL spawned installer
|
||||
// that regressed exactly the way ADR-1671:309 warns about: it must
|
||||
// DIVERGE here, proving row 48 would have gone RED had this shipped.
|
||||
assert.notEqual(
|
||||
hasMarker(emittedText),
|
||||
hasMarker(servedText),
|
||||
'a broken installer-side predicate must produce a detectable emitted/served divergence, or row 48 would stay green through this exact regression',
|
||||
);
|
||||
});
|
||||
});
|
||||
179
tests/mcp-catalog.property.test.cjs
Normal file
179
tests/mcp-catalog.property.test.cjs
Normal file
@@ -0,0 +1,179 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Failing-first property-based tests for src/mcp-catalog.cts (compiled to
|
||||
* gsd-core/bin/lib/mcp-catalog.cjs) — issue #3072 (epic #1671 Phase B),
|
||||
* `.gsd/phase/feat-3072-mcp-served-catalog/40-design.md`.
|
||||
*
|
||||
* Covers 50-test-matrix.md rows 53-55:
|
||||
* (a) every indexed uri round-trips through readResource
|
||||
* (b) no generated traversal-shaped string ever resolves to a read
|
||||
* (c) pagination partitions the resource list for any page size
|
||||
*
|
||||
* Uses the shared `fast-check` global config (`tests/helpers/
|
||||
* fast-check-setup.cjs`: numRuns 200, seed 42, overridable via
|
||||
* `GSD_FC_SEED`) — same pattern as `tests/adr-parser.property.test.cjs`.
|
||||
* Fixtures are built over the SAME injected `readFile`/`readDir` seam used
|
||||
* throughout `tests/mcp-catalog.test.cjs` — never real filesystem
|
||||
* permission tricks.
|
||||
*/
|
||||
|
||||
const { describe, test } = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fc = require('./helpers/fast-check-setup.cjs');
|
||||
|
||||
const { buildCatalog, readResource, listResources, getPrompt } = require('../gsd-core/bin/lib/mcp-catalog.cjs');
|
||||
|
||||
// ─── shared fixture: a small, fixed catalog over injected seams ────────────
|
||||
|
||||
function dirEntry(name, isDir) {
|
||||
return { name, isDirectory: () => isDir };
|
||||
}
|
||||
|
||||
function makeFakeFs(root, files) {
|
||||
const abs = (rel) => (rel ? `${root}/${rel}` : root);
|
||||
const fileMap = new Map(Object.entries(files).map(([rel, content]) => [abs(rel), content]));
|
||||
const dirMap = new Map();
|
||||
for (const rel of Object.keys(files)) {
|
||||
const parts = rel.split('/');
|
||||
for (let i = 0; i < parts.length; i++) {
|
||||
const dirRel = parts.slice(0, i).join('/');
|
||||
const dirAbs = abs(dirRel);
|
||||
const isLast = i === parts.length - 1;
|
||||
if (!dirMap.has(dirAbs)) dirMap.set(dirAbs, new Map());
|
||||
dirMap.get(dirAbs).set(parts[i], dirEntry(parts[i], !isLast));
|
||||
}
|
||||
}
|
||||
// Production (`buildCatalog`) resolves paths via `path.join`, which is
|
||||
// backslash-separated on Windows; this fake's maps are keyed POSIX. A real
|
||||
// `fs` accepts both separators, so the fake must too — normalize the
|
||||
// incoming lookup key unconditionally (never process.platform-gated).
|
||||
// Caught by CI on windows-latest: every lookup missed, the fake indexed
|
||||
// zero entries, and the anti-vacuity guards correctly flagged it.
|
||||
const norm = (p) => String(p).replace(/\\/g, '/');
|
||||
const readDir = (absPath) => {
|
||||
const m = dirMap.get(norm(absPath));
|
||||
if (!m) throw new Error(`ENOENT (fake fs): ${absPath}`);
|
||||
return [...m.values()];
|
||||
};
|
||||
const readFile = (absPath) => {
|
||||
const key = norm(absPath);
|
||||
if (!fileMap.has(key)) throw new Error(`ENOENT (fake fs): ${absPath}`);
|
||||
return fileMap.get(key);
|
||||
};
|
||||
return { root, readFile, readDir };
|
||||
}
|
||||
|
||||
const FIXTURE_RESOURCE_COUNT = 9;
|
||||
const FIXTURE_PROMPT_COUNT = 4;
|
||||
|
||||
function buildFixtureCatalog() {
|
||||
const files = {};
|
||||
for (let i = 0; i < FIXTURE_RESOURCE_COUNT; i++) {
|
||||
const segment = i % 2 === 0 ? 'workflows' : 'references';
|
||||
files[`gsd-core/${segment}/entry-${i}.md`] = `# entry ${i}\n\nbody text for entry ${i}\n`;
|
||||
}
|
||||
for (let i = 0; i < FIXTURE_PROMPT_COUNT; i++) {
|
||||
files[`commands/gsd/cmd-${i}.md`] = `# cmd ${i}\n\nprompt body ${i}\n`;
|
||||
}
|
||||
const fake = makeFakeFs('/fake-root-property', files);
|
||||
return buildCatalog({ root: fake.root, readFile: fake.readFile, readDir: fake.readDir });
|
||||
}
|
||||
|
||||
// ─── row 53: every indexed uri round-trips ──────────────────────────────────
|
||||
|
||||
describe('property: every indexed uri round-trips (row 53)', () => {
|
||||
test('readResource succeeds and returns the same uri for every indexed resource', () => {
|
||||
const catalog = buildFixtureCatalog();
|
||||
const uris = [...catalog.resources.keys()];
|
||||
assert.ok(uris.length > 0, 'fixture catalog must actually index resources for this property to mean anything');
|
||||
|
||||
fc.assert(
|
||||
fc.property(fc.constantFrom(...uris), (uri) => {
|
||||
const result = readResource(catalog, uri);
|
||||
assert.equal(result.uri, uri);
|
||||
assert.equal(typeof result.text, 'string');
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
test('getPrompt succeeds and returns the same name for every indexed prompt', () => {
|
||||
const catalog = buildFixtureCatalog();
|
||||
const names = [...catalog.prompts.keys()];
|
||||
assert.ok(names.length > 0, 'fixture catalog must actually index prompts for this property to mean anything');
|
||||
|
||||
fc.assert(
|
||||
fc.property(fc.constantFrom(...names), (name) => {
|
||||
const result = getPrompt(catalog, name);
|
||||
assert.equal(typeof result.description, 'string');
|
||||
assert.ok(Array.isArray(result.messages) && result.messages.length >= 1);
|
||||
})
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
// ─── row 54: no generated traversal string ever resolves ───────────────────
|
||||
|
||||
describe('property: generated traversal strings never resolve (row 54)', () => {
|
||||
test('readResource always refuses arbitrary traversal-shaped uris', () => {
|
||||
const catalog = buildFixtureCatalog();
|
||||
|
||||
const traversalSegment = fc.constantFrom('..', '..%2f', '%2e%2e', '..\\', '%252e%252e%252f');
|
||||
const rootSegment = fc.constantFrom('workflows', 'references');
|
||||
const suffix = fc.stringMatching(/^[a-z0-9-]{0,12}$/);
|
||||
|
||||
const traversalUri = fc
|
||||
.tuple(rootSegment, fc.array(traversalSegment, { minLength: 1, maxLength: 6 }), suffix)
|
||||
.map(([root, segments, tail]) => `gsd://${root}/${segments.join('/')}${tail}.md`);
|
||||
|
||||
fc.assert(
|
||||
fc.property(traversalUri, (uri) => {
|
||||
assert.throws(
|
||||
() => readResource(catalog, uri),
|
||||
undefined,
|
||||
`a traversal-shaped uri must never resolve to a successful read: ${uri}`
|
||||
);
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
test('readResource always refuses arbitrary absolute-path-shaped uris', () => {
|
||||
const catalog = buildFixtureCatalog();
|
||||
|
||||
const absolutePath = fc.oneof(
|
||||
fc.stringMatching(/^\/[a-z0-9/_-]{1,40}$/),
|
||||
fc.stringMatching(/^[A-Z]:\\[A-Za-z0-9\\_-]{1,40}$/)
|
||||
);
|
||||
|
||||
fc.assert(
|
||||
fc.property(absolutePath, (p) => {
|
||||
assert.throws(() => readResource(catalog, p), undefined, `an absolute-path-shaped uri must never resolve to a successful read: ${p}`);
|
||||
})
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
// ─── row 55: pagination is a partition ──────────────────────────────────────
|
||||
|
||||
describe('property: pagination partitions the list for any page size (row 55)', () => {
|
||||
test('pages concatenate to the full list with no dupes and no gaps, for any page size >= 1', () => {
|
||||
const catalog = buildFixtureCatalog();
|
||||
const full = listResources(catalog, { pageSize: 10_000 }).resources.map((r) => r.uri);
|
||||
assert.ok(full.length > 0);
|
||||
|
||||
fc.assert(
|
||||
fc.property(fc.integer({ min: 1, max: full.length + 3 }), (pageSize) => {
|
||||
const collected = [];
|
||||
let cursor;
|
||||
for (let guard = 0; guard < full.length + 5; guard++) {
|
||||
const page = listResources(catalog, { pageSize, cursor });
|
||||
assert.ok(page.resources.length <= pageSize, `a page must never exceed the requested pageSize ${pageSize}`);
|
||||
collected.push(...page.resources.map((r) => r.uri));
|
||||
if (page.nextCursor === undefined) break;
|
||||
cursor = page.nextCursor;
|
||||
}
|
||||
assert.deepEqual(collected, full, `pages for pageSize=${pageSize} must reassemble the full list with no dupes/gaps`);
|
||||
})
|
||||
);
|
||||
});
|
||||
});
|
||||
648
tests/mcp-catalog.test.cjs
Normal file
648
tests/mcp-catalog.test.cjs
Normal file
@@ -0,0 +1,648 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Failing-first unit tests for src/mcp-catalog.cts (compiled to
|
||||
* gsd-core/bin/lib/mcp-catalog.cjs) — issue #3072 (epic #1671 Phase B),
|
||||
* `.gsd/phase/feat-3072-mcp-served-catalog/40-design.md`.
|
||||
*
|
||||
* Covers 50-test-matrix.md rows 4-30 and 37-47: the catalog module's own
|
||||
* surface (buildCatalog / readResource / listResources / getPrompt /
|
||||
* shouldCompose) exercised over INJECTED `readFile`/`readDir` seams, never
|
||||
* real filesystem permission tricks (`chmod 0o000` is forbidden — root
|
||||
* bypasses mode bits and the test would silently pass with zero coverage in
|
||||
* CI; CONTRIBUTING.md, `40-design.md` "Known-defect gauntlet").
|
||||
*
|
||||
* `listResources` is a delegation surface this suite requires beyond the
|
||||
* design's four headline exports (`buildCatalog`, `readResource`,
|
||||
* `getPrompt`, `shouldCompose`) — see the module doc comment in
|
||||
* `src/mcp-catalog.cts` for why: pagination over the resource index is
|
||||
* catalog-module responsibility so `handleMessage` stays thin (design
|
||||
* "Shape" section).
|
||||
*
|
||||
* The module is a SKELETON right now — every function throws
|
||||
* `'not implemented'` — so every test below fails on BEHAVIOR, not on
|
||||
* `MODULE_NOT_FOUND`. No source-grep (CONTRIBUTING.md): every assertion is
|
||||
* on typed values (`REASON` codes, structured Map/array shapes) — never on
|
||||
* rendered text via `.includes()`/`.match()`.
|
||||
*/
|
||||
|
||||
const { describe, test } = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { createTempDir, cleanup } = require('./helpers.cjs');
|
||||
|
||||
const {
|
||||
buildCatalog,
|
||||
readResource,
|
||||
listResources,
|
||||
shouldCompose,
|
||||
REASON,
|
||||
} = require('../gsd-core/bin/lib/mcp-catalog.cjs');
|
||||
const { composeWorkflow } = require('../gsd-core/bin/lib/workflow-fragments.cjs');
|
||||
|
||||
// ─── Fixture helpers ────────────────────────────────────────────────────────
|
||||
|
||||
/** Build a `gsd://<segment>/<relPath>` resource uri, matching the design's `gsd://workflows/...` hostile-input examples. */
|
||||
function resourceUri(segment, relPath) {
|
||||
return `gsd://${segment}/${relPath}`;
|
||||
}
|
||||
|
||||
function dirEntry(name, isDir) {
|
||||
return { name, isDirectory: () => isDir };
|
||||
}
|
||||
|
||||
/**
|
||||
* Build an injected `readFile`/`readDir` seam pair over an in-memory file
|
||||
* map (POSIX relative paths -> content), so IO faults are testable by
|
||||
* monkeypatching the returned functions directly — never `chmod 0o000`.
|
||||
*
|
||||
* @param {string} root - a POSIX-style fake root path, never touched on real disk
|
||||
* @param {Record<string, string>} files - relative-path -> file content
|
||||
*/
|
||||
function makeFakeFs(root, files) {
|
||||
const abs = (rel) => (rel ? `${root}/${rel}` : root);
|
||||
const fileMap = new Map(Object.entries(files).map(([rel, content]) => [abs(rel), content]));
|
||||
const dirMap = new Map();
|
||||
for (const rel of Object.keys(files)) {
|
||||
const parts = rel.split('/');
|
||||
for (let i = 0; i < parts.length; i++) {
|
||||
const dirRel = parts.slice(0, i).join('/');
|
||||
const dirAbs = abs(dirRel);
|
||||
const isLast = i === parts.length - 1;
|
||||
if (!dirMap.has(dirAbs)) dirMap.set(dirAbs, new Map());
|
||||
dirMap.get(dirAbs).set(parts[i], dirEntry(parts[i], !isLast));
|
||||
}
|
||||
}
|
||||
// Production (`buildCatalog`) resolves paths via `path.join`, which is
|
||||
// backslash-separated on Windows; this fake's maps are keyed POSIX. A real
|
||||
// `fs` accepts both separators, so the fake must too — normalize the
|
||||
// incoming lookup key unconditionally (never process.platform-gated).
|
||||
// Caught by CI on windows-latest: every lookup missed, the fake indexed
|
||||
// zero entries, and the anti-vacuity guards correctly flagged it.
|
||||
const norm = (p) => String(p).replace(/\\/g, '/');
|
||||
const readDir = (absPath) => {
|
||||
const m = dirMap.get(norm(absPath));
|
||||
if (!m) {
|
||||
const err = new Error(`ENOENT (fake fs): ${absPath}`);
|
||||
throw err;
|
||||
}
|
||||
return [...m.values()];
|
||||
};
|
||||
const readFile = (absPath) => {
|
||||
const key = norm(absPath);
|
||||
if (!fileMap.has(key)) {
|
||||
const err = new Error(`ENOENT (fake fs): ${absPath}`);
|
||||
throw err;
|
||||
}
|
||||
return fileMap.get(key);
|
||||
};
|
||||
return { root, readFile, readDir };
|
||||
}
|
||||
|
||||
/** Save/restore `process.cwd` around `fn`. Standalone helper — try/finally is permitted here (CONTRIBUTING.md "Setup and Cleanup"). */
|
||||
function withMockedCwd(fakeCwd, fn) {
|
||||
const original = process.cwd;
|
||||
process.cwd = () => fakeCwd;
|
||||
try {
|
||||
return fn();
|
||||
} finally {
|
||||
process.cwd = original;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Attempt to build a root containing a symlink that escapes it. Standalone
|
||||
* helper — try/catch for environment-capability probing (not cleanup
|
||||
* masking) lives here, out of the test body.
|
||||
*/
|
||||
function setupSymlinkEscapeFixture() {
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
try {
|
||||
const root = createTempDir('mcp-catalog-symlink-root-');
|
||||
const outsideTarget = createTempDir('mcp-catalog-symlink-outside-');
|
||||
fs.mkdirSync(path.join(root, 'gsd-core', 'workflows'), { recursive: true });
|
||||
fs.writeFileSync(path.join(outsideTarget, 'secret.md'), 'top secret');
|
||||
fs.symlinkSync(path.join(outsideTarget, 'secret.md'), path.join(root, 'gsd-core', 'workflows', 'evil.md'));
|
||||
return { ok: true, root, outsideTarget };
|
||||
} catch {
|
||||
return { ok: false };
|
||||
}
|
||||
}
|
||||
|
||||
// A small marked workflow + a small marked-syntax-documenting reference,
|
||||
// reused by several rows below.
|
||||
const markedWorkflow = [
|
||||
'before prose',
|
||||
'<!-- gsd:section id="sec-a" when="always" -->',
|
||||
'body line',
|
||||
'<!-- /gsd:section -->',
|
||||
'after prose',
|
||||
].join('\n');
|
||||
|
||||
const unmarkedContent = ['# Plain document', '', 'Ordinary prose, no markers here.', ''].join('\n');
|
||||
|
||||
// A reference doc that DOCUMENTS marker syntax with an unfenced example —
|
||||
// the exact F1 defect class (design "F1" / row 13).
|
||||
const documentsMarkerSyntax = [
|
||||
'# How markers work',
|
||||
'',
|
||||
'A section marker pair looks like this:',
|
||||
'',
|
||||
'<!-- gsd:section id="example" when="always" -->',
|
||||
'example body',
|
||||
'<!-- /gsd:section -->',
|
||||
'',
|
||||
'That is the whole grammar.',
|
||||
'',
|
||||
].join('\n');
|
||||
|
||||
// ─── resources/list (rows 4-10) ─────────────────────────────────────────────
|
||||
|
||||
describe('resources/list — catalog module', () => {
|
||||
test('lists every catalog resource with required fields (row 4)', () => {
|
||||
const fake = makeFakeFs('/fake-root', {
|
||||
'gsd-core/workflows/a.md': unmarkedContent,
|
||||
'gsd-core/references/b.md': unmarkedContent,
|
||||
});
|
||||
const catalog = buildCatalog({ root: fake.root, readFile: fake.readFile, readDir: fake.readDir });
|
||||
assert.equal(catalog.resources.size, 2);
|
||||
for (const entry of catalog.resources.values()) {
|
||||
assert.equal(typeof entry.uri, 'string');
|
||||
assert.equal(typeof entry.name, 'string');
|
||||
assert.equal(typeof entry.title, 'string');
|
||||
assert.equal(typeof entry.description, 'string');
|
||||
assert.equal(typeof entry.mimeType, 'string');
|
||||
assert.ok(entry.mimeType.length > 0);
|
||||
}
|
||||
});
|
||||
|
||||
test('listing order is deterministic across calls (row 5)', () => {
|
||||
const fake = makeFakeFs('/fake-root', {
|
||||
'gsd-core/workflows/z.md': unmarkedContent,
|
||||
'gsd-core/workflows/a.md': unmarkedContent,
|
||||
'gsd-core/references/m.md': unmarkedContent,
|
||||
});
|
||||
const catalog = buildCatalog({ root: fake.root, readFile: fake.readFile, readDir: fake.readDir });
|
||||
const first = listResources(catalog).resources.map((r) => r.uri);
|
||||
const second = listResources(catalog).resources.map((r) => r.uri);
|
||||
assert.deepEqual(first, second);
|
||||
assert.deepEqual(first, [...first].sort(), 'order must be sorted by uri, not readdir order');
|
||||
});
|
||||
|
||||
test('pagination at page-1 / page / page+1 (row 6)', () => {
|
||||
const makeCatalogOfSize = (n) => {
|
||||
const files = {};
|
||||
for (let i = 0; i < n; i++) files[`gsd-core/workflows/w${i}.md`] = unmarkedContent;
|
||||
const fake = makeFakeFs('/fake-root', files);
|
||||
return buildCatalog({ root: fake.root, readFile: fake.readFile, readDir: fake.readDir });
|
||||
};
|
||||
|
||||
const pageSize = 2;
|
||||
|
||||
const below = listResources(makeCatalogOfSize(pageSize - 1), { pageSize });
|
||||
assert.equal(below.resources.length, pageSize - 1);
|
||||
assert.equal(below.nextCursor, undefined, 'a page under the page size is already the last page');
|
||||
|
||||
const exact = listResources(makeCatalogOfSize(pageSize), { pageSize });
|
||||
assert.equal(exact.resources.length, pageSize);
|
||||
assert.equal(exact.nextCursor, undefined, 'a full final page omits nextCursor');
|
||||
|
||||
const over = listResources(makeCatalogOfSize(pageSize + 1), { pageSize });
|
||||
assert.equal(over.resources.length, pageSize);
|
||||
assert.notEqual(over.nextCursor, undefined, 'a page short of the total must carry nextCursor');
|
||||
});
|
||||
|
||||
test('paginated pages reassemble the full list (row 7)', () => {
|
||||
const files = {};
|
||||
for (let i = 0; i < 7; i++) files[`gsd-core/workflows/w${i}.md`] = unmarkedContent;
|
||||
const fake = makeFakeFs('/fake-root', files);
|
||||
const catalog = buildCatalog({ root: fake.root, readFile: fake.readFile, readDir: fake.readDir });
|
||||
|
||||
const full = listResources(catalog, { pageSize: 100 }).resources.map((r) => r.uri);
|
||||
|
||||
const collected = [];
|
||||
let cursor;
|
||||
for (let guard = 0; guard < 20; guard++) {
|
||||
const page = listResources(catalog, { pageSize: 3, cursor });
|
||||
collected.push(...page.resources.map((r) => r.uri));
|
||||
if (page.nextCursor === undefined) break;
|
||||
cursor = page.nextCursor;
|
||||
}
|
||||
|
||||
assert.deepEqual(collected, full, 'concatenated pages must equal the unpaginated list exactly once, no dupes, no gaps');
|
||||
});
|
||||
|
||||
test('unknown cursor errors rather than restarting (row 8)', () => {
|
||||
const fake = makeFakeFs('/fake-root', { 'gsd-core/workflows/a.md': unmarkedContent });
|
||||
const catalog = buildCatalog({ root: fake.root, readFile: fake.readFile, readDir: fake.readDir });
|
||||
assert.throws(
|
||||
() => listResources(catalog, { cursor: 'not-a-real-cursor' }),
|
||||
(err) => err.reason === REASON.UNKNOWN_CURSOR
|
||||
);
|
||||
});
|
||||
|
||||
test('empty catalog lists empty (row 9)', () => {
|
||||
const fake = makeFakeFs('/fake-root', {});
|
||||
const catalog = buildCatalog({ root: fake.root, readFile: fake.readFile, readDir: fake.readDir });
|
||||
const page = listResources(catalog);
|
||||
assert.deepEqual(page.resources, []);
|
||||
assert.equal(page.nextCursor, undefined);
|
||||
});
|
||||
|
||||
test('single-entry catalog needs no cursor (row 10)', () => {
|
||||
const fake = makeFakeFs('/fake-root', { 'gsd-core/references/only.md': unmarkedContent });
|
||||
const catalog = buildCatalog({ root: fake.root, readFile: fake.readFile, readDir: fake.readDir });
|
||||
const page = listResources(catalog);
|
||||
assert.equal(page.resources.length, 1);
|
||||
assert.equal(page.nextCursor, undefined);
|
||||
});
|
||||
});
|
||||
|
||||
// ─── resources/read (rows 11-30) ────────────────────────────────────────────
|
||||
|
||||
describe('resources/read — catalog module (client-controlled path surface)', () => {
|
||||
test('reads a workflow with markers stripped (row 11)', () => {
|
||||
const fake = makeFakeFs('/fake-root', { 'gsd-core/workflows/w.md': markedWorkflow });
|
||||
const catalog = buildCatalog({ root: fake.root, readFile: fake.readFile, readDir: fake.readDir });
|
||||
const result = readResource(catalog, resourceUri('workflows', 'w.md'));
|
||||
assert.equal(result.text, composeWorkflow(markedWorkflow, { sourcePath: 'gsd-core/workflows/w.md' }));
|
||||
assert.equal(result.uri, resourceUri('workflows', 'w.md'));
|
||||
});
|
||||
|
||||
test('reads a reference verbatim (row 12)', () => {
|
||||
const fake = makeFakeFs('/fake-root', { 'gsd-core/references/r.md': unmarkedContent });
|
||||
const catalog = buildCatalog({ root: fake.root, readFile: fake.readFile, readDir: fake.readDir });
|
||||
const result = readResource(catalog, resourceUri('references', 'r.md'));
|
||||
assert.equal(result.text, unmarkedContent);
|
||||
});
|
||||
|
||||
test('a doc documenting marker syntax is never composed (row 13 — the F1 defect)', () => {
|
||||
const fake = makeFakeFs('/fake-root', { 'gsd-core/references/documents-markers.md': documentsMarkerSyntax });
|
||||
const catalog = buildCatalog({ root: fake.root, readFile: fake.readFile, readDir: fake.readDir });
|
||||
const result = readResource(catalog, resourceUri('references', 'documents-markers.md'));
|
||||
assert.equal(result.text, documentsMarkerSyntax, 'a reference that documents marker syntax must be served byte-identical, never composed');
|
||||
});
|
||||
|
||||
test('markers are stripped only under workflows/ (row 14)', () => {
|
||||
const fake = makeFakeFs('/fake-root', {
|
||||
'gsd-core/workflows/w.md': markedWorkflow,
|
||||
'gsd-core/references/r.md': markedWorkflow,
|
||||
});
|
||||
const catalog = buildCatalog({ root: fake.root, readFile: fake.readFile, readDir: fake.readDir });
|
||||
const workflowText = readResource(catalog, resourceUri('workflows', 'w.md')).text;
|
||||
const referenceText = readResource(catalog, resourceUri('references', 'r.md')).text;
|
||||
assert.notEqual(workflowText, markedWorkflow, 'the workflow copy must be composed (markers stripped)');
|
||||
assert.equal(referenceText, markedWorkflow, 'the identical text under references/ must be served verbatim');
|
||||
});
|
||||
|
||||
test('unmarked workflow composes byte-identical (row 15)', () => {
|
||||
const fake = makeFakeFs('/fake-root', { 'gsd-core/workflows/w.md': unmarkedContent });
|
||||
const catalog = buildCatalog({ root: fake.root, readFile: fake.readFile, readDir: fake.readDir });
|
||||
const result = readResource(catalog, resourceUri('workflows', 'w.md'));
|
||||
assert.equal(result.text, unmarkedContent, 'composing an unmarked document is a structural no-op, not a budget trick');
|
||||
});
|
||||
|
||||
test('unknown uri errors rather than returning empty (row 16)', () => {
|
||||
const fake = makeFakeFs('/fake-root', { 'gsd-core/workflows/a.md': unmarkedContent });
|
||||
const catalog = buildCatalog({ root: fake.root, readFile: fake.readFile, readDir: fake.readDir });
|
||||
assert.throws(
|
||||
() => readResource(catalog, resourceUri('workflows', 'totally-made-up.md')),
|
||||
(err) => err.reason === REASON.UNKNOWN_RESOURCE
|
||||
);
|
||||
});
|
||||
|
||||
const catalogForHostileUris = () => {
|
||||
const fake = makeFakeFs('/fake-root', { 'gsd-core/workflows/a.md': unmarkedContent });
|
||||
return buildCatalog({ root: fake.root, readFile: fake.readFile, readDir: fake.readDir });
|
||||
};
|
||||
|
||||
test('rejects dot-dot traversal (row 17)', () => {
|
||||
const catalog = catalogForHostileUris();
|
||||
assert.throws(
|
||||
() => readResource(catalog, 'gsd://workflows/../../../etc/passwd'),
|
||||
(err) => err.reason === REASON.TRAVERSAL_REFUSED
|
||||
);
|
||||
});
|
||||
|
||||
test('rejects backslash traversal (row 18)', () => {
|
||||
const catalog = catalogForHostileUris();
|
||||
assert.throws(
|
||||
() => readResource(catalog, 'gsd://workflows/..\\..\\secrets.md'),
|
||||
(err) => err.reason === REASON.TRAVERSAL_REFUSED
|
||||
);
|
||||
});
|
||||
|
||||
test('rejects percent-encoded traversal (row 19)', () => {
|
||||
const catalog = catalogForHostileUris();
|
||||
assert.throws(
|
||||
() => readResource(catalog, 'gsd://workflows/%2e%2e%2fsecrets.md'),
|
||||
(err) => err.reason === REASON.TRAVERSAL_REFUSED
|
||||
);
|
||||
});
|
||||
|
||||
test('rejects double-encoded traversal (row 20)', () => {
|
||||
const catalog = catalogForHostileUris();
|
||||
assert.throws(
|
||||
() => readResource(catalog, 'gsd://workflows/%252e%252e%252fsecrets.md'),
|
||||
(err) => err.reason === REASON.TRAVERSAL_REFUSED
|
||||
);
|
||||
});
|
||||
|
||||
test('rejects absolute posix path (row 21)', () => {
|
||||
const catalog = catalogForHostileUris();
|
||||
assert.throws(
|
||||
() => readResource(catalog, '/etc/passwd'),
|
||||
(err) => err.reason === REASON.TRAVERSAL_REFUSED
|
||||
);
|
||||
});
|
||||
|
||||
test('rejects absolute windows path (row 22)', () => {
|
||||
const catalog = catalogForHostileUris();
|
||||
assert.throws(
|
||||
() => readResource(catalog, 'C:\\Windows\\win.ini'),
|
||||
(err) => err.reason === REASON.TRAVERSAL_REFUSED
|
||||
);
|
||||
});
|
||||
|
||||
test('rejects a file:// uri (row 23)', () => {
|
||||
const catalog = catalogForHostileUris();
|
||||
assert.throws(
|
||||
() => readResource(catalog, 'file:///etc/passwd'),
|
||||
(err) => err.reason === REASON.INVALID_URI
|
||||
);
|
||||
});
|
||||
|
||||
test('rejects a uri containing a null byte (row 24)', () => {
|
||||
const catalog = catalogForHostileUris();
|
||||
assert.throws(
|
||||
() => readResource(catalog, 'gsd://workflows/a.md\u0000.txt'),
|
||||
(err) => err.reason === REASON.TRAVERSAL_REFUSED
|
||||
);
|
||||
});
|
||||
|
||||
test('rejects a symlink escaping the root (row 25)', (t) => {
|
||||
const fixture = setupSymlinkEscapeFixture();
|
||||
if (!fixture.ok) {
|
||||
t.skip('symlink creation not permitted on this platform/environment');
|
||||
return;
|
||||
}
|
||||
t.after(() => {
|
||||
cleanup(fixture.root);
|
||||
cleanup(fixture.outsideTarget);
|
||||
});
|
||||
|
||||
const catalog = buildCatalog({ root: fixture.root });
|
||||
assert.throws(
|
||||
() => readResource(catalog, resourceUri('workflows', 'evil.md')),
|
||||
(err) => err.reason === REASON.TRAVERSAL_REFUSED
|
||||
);
|
||||
});
|
||||
|
||||
test('an unindexed sibling is not readable (row 26)', () => {
|
||||
// "c.md" is never part of the build-time file map — it is not on the
|
||||
// catalog's disk snapshot at all, simulating a file added post-startup.
|
||||
// Index membership, not disk existence, is the sole authority.
|
||||
const fake = makeFakeFs('/fake-root', {
|
||||
'gsd-core/workflows/a.md': unmarkedContent,
|
||||
'gsd-core/workflows/b.md': unmarkedContent,
|
||||
});
|
||||
const catalog = buildCatalog({ root: fake.root, readFile: fake.readFile, readDir: fake.readDir });
|
||||
assert.throws(
|
||||
() => readResource(catalog, resourceUri('workflows', 'c.md')),
|
||||
(err) => err.reason === REASON.UNKNOWN_RESOURCE
|
||||
);
|
||||
});
|
||||
|
||||
test('non-indexed file types are not served (row 27)', () => {
|
||||
const fake = makeFakeFs('/fake-root', {
|
||||
'gsd-core/workflows/a.md': unmarkedContent,
|
||||
'gsd-core/workflows/section-manifest.json': '{}',
|
||||
});
|
||||
const catalog = buildCatalog({ root: fake.root, readFile: fake.readFile, readDir: fake.readDir });
|
||||
assert.equal(catalog.resources.size, 1, 'the .json sibling must not be indexed');
|
||||
assert.throws(
|
||||
() => readResource(catalog, resourceUri('workflows', 'section-manifest.json')),
|
||||
(err) => err.reason === REASON.UNKNOWN_RESOURCE
|
||||
);
|
||||
});
|
||||
|
||||
test('non-string uri is rejected as invalid params (row 28)', () => {
|
||||
const catalog = catalogForHostileUris();
|
||||
for (const bad of [42, {}, null, undefined, [], true]) {
|
||||
assert.throws(
|
||||
() => readResource(catalog, bad),
|
||||
(err) => err.reason === REASON.INVALID_PARAMS,
|
||||
`expected INVALID_PARAMS for uri=${JSON.stringify(bad)}`
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test('empty uri is rejected (row 29)', () => {
|
||||
const catalog = catalogForHostileUris();
|
||||
assert.throws(
|
||||
() => readResource(catalog, ''),
|
||||
(err) => err.reason === REASON.INVALID_URI
|
||||
);
|
||||
});
|
||||
|
||||
test('unknown root segment is rejected (row 30)', () => {
|
||||
const catalog = catalogForHostileUris();
|
||||
assert.throws(
|
||||
() => readResource(catalog, 'gsd://bogus-root-segment/a.md'),
|
||||
(err) => err.reason === REASON.UNKNOWN_ROOT
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
// ─── content correctness / CRLF (rows 37-41) ────────────────────────────────
|
||||
|
||||
describe('content correctness — catalog module', () => {
|
||||
test('CRLF content survives serving (row 37)', () => {
|
||||
const content = ['line one', 'line two', 'line three', ''].join('\r\n');
|
||||
const fake = makeFakeFs('/fake-root', { 'gsd-core/references/r.md': content });
|
||||
const catalog = buildCatalog({ root: fake.root, readFile: fake.readFile, readDir: fake.readDir });
|
||||
const result = readResource(catalog, resourceUri('references', 'r.md'));
|
||||
assert.equal(result.text, content);
|
||||
});
|
||||
|
||||
test('mixed line endings survive serving (row 38)', () => {
|
||||
const content = 'line one\r\nline two\nline three\r\nline four\n';
|
||||
const fake = makeFakeFs('/fake-root', { 'gsd-core/references/r.md': content });
|
||||
const catalog = buildCatalog({ root: fake.root, readFile: fake.readFile, readDir: fake.readDir });
|
||||
const result = readResource(catalog, resourceUri('references', 'r.md'));
|
||||
assert.equal(result.text, content);
|
||||
});
|
||||
|
||||
test('missing trailing newline is preserved (row 39)', () => {
|
||||
const content = ['line one', 'line two, no trailing newline after this'].join('\n');
|
||||
const fake = makeFakeFs('/fake-root', { 'gsd-core/references/r.md': content });
|
||||
const catalog = buildCatalog({ root: fake.root, readFile: fake.readFile, readDir: fake.readDir });
|
||||
const result = readResource(catalog, resourceUri('references', 'r.md'));
|
||||
assert.equal(result.text, content);
|
||||
assert.equal(result.text.endsWith('\n'), false);
|
||||
});
|
||||
|
||||
test('an empty file serves as empty text (row 40)', () => {
|
||||
const fake = makeFakeFs('/fake-root', { 'gsd-core/references/empty.md': '' });
|
||||
const catalog = buildCatalog({ root: fake.root, readFile: fake.readFile, readDir: fake.readDir });
|
||||
const result = readResource(catalog, resourceUri('references', 'empty.md'));
|
||||
assert.equal(result.text, '');
|
||||
});
|
||||
|
||||
test('unicode content is preserved (row 41)', () => {
|
||||
const content = ['# 日本語のタイトル', '', 'emoji check: 🎉🚀 café naïve', ''].join('\n');
|
||||
const fake = makeFakeFs('/fake-root', { 'gsd-core/references/r.md': content });
|
||||
const catalog = buildCatalog({ root: fake.root, readFile: fake.readFile, readDir: fake.readDir });
|
||||
const result = readResource(catalog, resourceUri('references', 'r.md'));
|
||||
assert.equal(result.text, content);
|
||||
assert.equal(Buffer.byteLength(result.text, 'utf8'), Buffer.byteLength(content, 'utf8'));
|
||||
});
|
||||
});
|
||||
|
||||
// ─── IO faults, injected via the seam (rows 42-45) ──────────────────────────
|
||||
|
||||
describe('IO faults — injected via the seam, never chmod', () => {
|
||||
test('one unreadable file does not break the catalog (row 42)', () => {
|
||||
const fake = makeFakeFs('/fake-root', {
|
||||
'gsd-core/workflows/good.md': unmarkedContent,
|
||||
'gsd-core/workflows/bad.md': unmarkedContent,
|
||||
});
|
||||
const badAbsPath = `${fake.root}/gsd-core/workflows/bad.md`;
|
||||
const realReadFile = fake.readFile;
|
||||
const faultyReadFile = (absPath) => {
|
||||
// Same separator-normalization as makeFakeFs: a production-supplied
|
||||
// absPath may be backslash-joined on Windows.
|
||||
if (String(absPath).replace(/\\/g, '/') === badAbsPath) throw new Error('injected read failure');
|
||||
return realReadFile(absPath);
|
||||
};
|
||||
|
||||
const catalog = buildCatalog({ root: fake.root, readFile: faultyReadFile, readDir: fake.readDir });
|
||||
|
||||
const goodUri = resourceUri('workflows', 'good.md');
|
||||
const badUri = resourceUri('workflows', 'bad.md');
|
||||
|
||||
assert.doesNotThrow(() => readResource(catalog, goodUri), 'the healthy resource must remain readable');
|
||||
assert.throws(
|
||||
() => readResource(catalog, badUri),
|
||||
(err) => err.reason === REASON.READ_FAILED
|
||||
);
|
||||
|
||||
const listedUris = listResources(catalog).resources.map((r) => r.uri);
|
||||
assert.ok(listedUris.includes(goodUri));
|
||||
assert.ok(listedUris.includes(badUri), 'the failing resource must stay listable even though it cannot be read');
|
||||
});
|
||||
|
||||
test('a directory read failure fails closed (row 43)', () => {
|
||||
const fake = makeFakeFs('/fake-root', { 'gsd-core/workflows/a.md': unmarkedContent });
|
||||
const workflowsDirAbs = `${fake.root}/gsd-core/workflows`;
|
||||
const realReadDir = fake.readDir;
|
||||
const faultyReadDir = (absPath) => {
|
||||
// Same separator-normalization as makeFakeFs: a production-supplied
|
||||
// absPath may be backslash-joined on Windows.
|
||||
if (String(absPath).replace(/\\/g, '/') === workflowsDirAbs) throw new Error('injected directory read failure');
|
||||
return realReadDir(absPath);
|
||||
};
|
||||
assert.throws(
|
||||
() => buildCatalog({ root: fake.root, readFile: fake.readFile, readDir: faultyReadDir }),
|
||||
(err) => err.reason === REASON.READ_FAILED,
|
||||
'a directory listing failure must surface as a typed error, never a silently partial catalog'
|
||||
);
|
||||
});
|
||||
|
||||
test('a malformed marker is contained to its file (row 44)', () => {
|
||||
const malformed = ['before', '<!-- gsd:section id="x" when="always" -->', 'never closed'].join('\n');
|
||||
const fake = makeFakeFs('/fake-root', {
|
||||
'gsd-core/workflows/good.md': unmarkedContent,
|
||||
'gsd-core/workflows/bad.md': malformed,
|
||||
});
|
||||
const catalog = buildCatalog({ root: fake.root, readFile: fake.readFile, readDir: fake.readDir });
|
||||
|
||||
const goodUri = resourceUri('workflows', 'good.md');
|
||||
const badUri = resourceUri('workflows', 'bad.md');
|
||||
|
||||
assert.doesNotThrow(() => readResource(catalog, goodUri));
|
||||
assert.throws(
|
||||
() => readResource(catalog, badUri),
|
||||
(err) => err.reason === REASON.READ_FAILED
|
||||
);
|
||||
|
||||
const listedUris = listResources(catalog).resources.map((r) => r.uri);
|
||||
assert.ok(listedUris.includes(goodUri));
|
||||
assert.ok(listedUris.includes(badUri), 'the other 325 resources must stay listable and readable — one bad file must not take down the catalog');
|
||||
});
|
||||
|
||||
test('absent root does not fall back to cwd (row 45)', () => {
|
||||
const calledPaths = [];
|
||||
const missingRoot = '/fake-root-that-does-not-exist-anywhere';
|
||||
const recordingReadDir = (absPath) => {
|
||||
calledPaths.push(absPath);
|
||||
throw new Error(`ENOENT (fake fs): ${absPath}`);
|
||||
};
|
||||
const recordingReadFile = (absPath) => {
|
||||
calledPaths.push(absPath);
|
||||
throw new Error(`ENOENT (fake fs): ${absPath}`);
|
||||
};
|
||||
|
||||
let threw = false;
|
||||
let catalog;
|
||||
try {
|
||||
catalog = buildCatalog({ root: missingRoot, readFile: recordingReadFile, readDir: recordingReadDir });
|
||||
} catch (err) {
|
||||
threw = true;
|
||||
assert.equal(typeof err.reason, 'string', 'a build failure for an absent root must be a typed CatalogError, never a bare crash');
|
||||
}
|
||||
if (!threw) {
|
||||
assert.equal(catalog.resources.size, 0);
|
||||
assert.equal(catalog.prompts.size, 0);
|
||||
}
|
||||
|
||||
const realCwd = process.cwd();
|
||||
for (const p of calledPaths) {
|
||||
assert.notEqual(String(p).replace(/\\/g, '/'), realCwd.replace(/\\/g, '/'), 'buildCatalog must never fall back to reading process.cwd()');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// ─── resolution / scoping (rows 46-47) ──────────────────────────────────────
|
||||
|
||||
describe('resolution / scoping — module location vs cwd', () => {
|
||||
test('catalog resolves from module location not cwd (row 46)', (t) => {
|
||||
const decoyCwd = createTempDir('mcp-catalog-decoy-cwd-');
|
||||
t.after(() => cleanup(decoyCwd));
|
||||
|
||||
const catalog = withMockedCwd(decoyCwd, () => buildCatalog({}));
|
||||
assert.ok(
|
||||
catalog.resources.size > 50,
|
||||
`expected the real package's ~110 workflows + ~103 references regardless of a decoy cwd, got ${catalog.resources.size}`
|
||||
);
|
||||
});
|
||||
|
||||
test('a project-local gsd-core is never a catalog root (row 47)', (t) => {
|
||||
const decoyCwd = createTempDir('mcp-catalog-decoy-project-');
|
||||
t.after(() => cleanup(decoyCwd));
|
||||
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
fs.mkdirSync(path.join(decoyCwd, 'gsd-core', 'workflows'), { recursive: true });
|
||||
fs.writeFileSync(path.join(decoyCwd, 'gsd-core', 'workflows', 'trap.md'), 'decoy content that must never be served');
|
||||
|
||||
const catalog = withMockedCwd(decoyCwd, () => buildCatalog({}));
|
||||
|
||||
const uris = [...catalog.resources.keys()];
|
||||
assert.equal(
|
||||
uris.includes(resourceUri('workflows', 'trap.md')),
|
||||
false,
|
||||
"a project-local gsd-core/ present at ctx.cwd's decoy location must never become a catalog root"
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
// ─── shouldCompose — the F1 predicate (exercised directly, supplements rows 12-15) ──
|
||||
|
||||
describe('shouldCompose — the shared F1 predicate', () => {
|
||||
test('shouldCompose is true only for paths under gsd-core/workflows/', () => {
|
||||
assert.equal(shouldCompose('gsd-core/workflows/plan-phase.md'), true);
|
||||
assert.equal(shouldCompose('gsd-core/references/foo.md'), false);
|
||||
assert.equal(shouldCompose('commands/gsd/plan-phase.md'), false);
|
||||
});
|
||||
});
|
||||
111
tests/mcp-server-catalog.test.cjs
Normal file
111
tests/mcp-server-catalog.test.cjs
Normal file
@@ -0,0 +1,111 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Failing-first protocol-surface tests for the MCP served catalog — issue
|
||||
* #3072 (epic #1671 Phase B), `.gsd/phase/feat-3072-mcp-served-catalog/
|
||||
* 40-design.md`.
|
||||
*
|
||||
* Covers 50-test-matrix.md rows 1-3 and 31-36: `resources`/`prompts`
|
||||
* capability advertisement, tool-surface independence, and the
|
||||
* `prompts/list` / `prompts/get` JSON-RPC surface — all exercised through
|
||||
* `handleMessage` (`src/mcp-server.cts`, compiled to
|
||||
* `gsd-core/bin/lib/mcp-server.cjs`), mirroring `tests/gsd-mcp-server.test.cjs`'s
|
||||
* own structure and require path.
|
||||
*
|
||||
* `handleMessage` does not yet route `resources/*`/`prompts/*` at all — every
|
||||
* such request currently falls through to the generic `METHOD_NOT_FOUND`
|
||||
* (-32601) default case. Rows that expect a SPECIFIC refusal (not just "any
|
||||
* error") therefore assert the JSON-RPC error code is NOT -32601, so the
|
||||
* assertion cannot pass by accident against today's blanket fallthrough
|
||||
* (rows 33, 35). No source-grep (CONTRIBUTING.md): every assertion is on
|
||||
* typed JSON-RPC response fields, never on rendered prose.
|
||||
*/
|
||||
|
||||
const { describe, test } = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { handleMessage } = require('../gsd-core/bin/lib/mcp-server.cjs');
|
||||
|
||||
const METHOD_NOT_FOUND = -32601;
|
||||
const INVALID_PARAMS = -32602;
|
||||
|
||||
// ─── initialize / capabilities (rows 1-3) ───────────────────────────────────
|
||||
|
||||
describe('initialize / capabilities', () => {
|
||||
test('initialize advertises resources and prompts (row 1)', () => {
|
||||
const res = handleMessage({ jsonrpc: '2.0', id: 1, method: 'initialize' });
|
||||
assert.ok(res.result, 'initialize must succeed');
|
||||
const caps = res.result.capabilities;
|
||||
assert.ok(caps && typeof caps.tools === 'object', 'capabilities.tools must remain declared');
|
||||
assert.ok(caps && typeof caps.resources === 'object', 'capabilities.resources must be declared alongside tools');
|
||||
assert.ok(caps && typeof caps.prompts === 'object', 'capabilities.prompts must be declared alongside tools');
|
||||
});
|
||||
|
||||
test('initialize does not advertise unimplemented notifications (row 2)', () => {
|
||||
const res = handleMessage({ jsonrpc: '2.0', id: 1, method: 'initialize' });
|
||||
const resourcesCap = res.result && res.result.capabilities && res.result.capabilities.resources;
|
||||
assert.ok(resourcesCap && typeof resourcesCap === 'object', 'capabilities.resources must exist before its shape can be checked');
|
||||
assert.equal(Object.prototype.hasOwnProperty.call(resourcesCap, 'subscribe'), false, 'resources capability must not declare subscribe — nothing ever sends the notification');
|
||||
assert.equal(Object.prototype.hasOwnProperty.call(resourcesCap, 'listChanged'), false, 'resources capability must not declare listChanged — nothing ever sends the notification');
|
||||
});
|
||||
|
||||
test('catalog addition does not disturb the tool surface (row 3)', () => {
|
||||
const res = handleMessage({ jsonrpc: '2.0', id: 1, method: 'tools/list' });
|
||||
assert.ok(res.result, 'tools/list must succeed');
|
||||
const names = res.result.tools.map((tool) => tool.name).sort();
|
||||
assert.deepEqual(names, ['gsd_invoke_command', 'gsd_read_state', 'gsd_write_state']);
|
||||
});
|
||||
});
|
||||
|
||||
// ─── prompts (rows 31-36) ────────────────────────────────────────────────────
|
||||
|
||||
describe('prompts — protocol surface', () => {
|
||||
test('lists commands as prompts by bare name (row 31)', () => {
|
||||
const res = handleMessage({ jsonrpc: '2.0', id: 1, method: 'prompts/list' });
|
||||
assert.equal(res.error, undefined, 'prompts/list must not error');
|
||||
assert.ok(res.result && Array.isArray(res.result.prompts), 'result.prompts must be an array');
|
||||
assert.equal(res.result.prompts.length, 71, 'must list all 71 commands/gsd/*.md as prompts');
|
||||
for (const p of res.result.prompts) {
|
||||
assert.equal(typeof p.name, 'string');
|
||||
assert.equal(p.name.includes('/'), false, 'name must be the bare command, not a path');
|
||||
assert.equal(p.name.endsWith('.md'), false, 'name must not carry the .md extension');
|
||||
}
|
||||
});
|
||||
|
||||
test('gets a prompt in message form (row 32)', () => {
|
||||
const res = handleMessage({ jsonrpc: '2.0', id: 1, method: 'prompts/get', params: { name: 'plan-phase' } });
|
||||
assert.equal(res.error, undefined, 'prompts/get on a known name must not error');
|
||||
assert.equal(typeof res.result.description, 'string');
|
||||
assert.ok(Array.isArray(res.result.messages) && res.result.messages.length >= 1);
|
||||
const msg = res.result.messages[0];
|
||||
assert.equal(msg.role, 'user');
|
||||
assert.equal(msg.content.type, 'text');
|
||||
assert.equal(typeof msg.content.text, 'string');
|
||||
});
|
||||
|
||||
test('unknown prompt name errors (row 33)', () => {
|
||||
const res = handleMessage({ jsonrpc: '2.0', id: 1, method: 'prompts/get', params: { name: 'not-a-real-command-xyz' } });
|
||||
assert.ok(res.error, 'an unknown prompt name must produce a JSON-RPC error, not a success');
|
||||
assert.equal(res.result, undefined);
|
||||
assert.notEqual(res.error.code, METHOD_NOT_FOUND, 'must be a semantic unknown-prompt refusal, not merely the current unimplemented-method fallthrough');
|
||||
});
|
||||
|
||||
test('arguments are accepted and ignored (row 34)', () => {
|
||||
const withoutArgs = handleMessage({ jsonrpc: '2.0', id: 1, method: 'prompts/get', params: { name: 'plan-phase' } });
|
||||
const withArgs = handleMessage({ jsonrpc: '2.0', id: 2, method: 'prompts/get', params: { name: 'plan-phase', arguments: { phase: '3' } } });
|
||||
assert.equal(withoutArgs.error, undefined, 'prompts/get without arguments must succeed');
|
||||
assert.equal(withArgs.error, undefined, 'prompts/get with arguments must be accepted, not rejected');
|
||||
assert.deepEqual(withArgs.result, withoutArgs.result, 'no command template takes injected arguments today — content must be unchanged');
|
||||
});
|
||||
|
||||
test('prompt name is not a path (row 35)', () => {
|
||||
const res = handleMessage({ jsonrpc: '2.0', id: 1, method: 'prompts/get', params: { name: '../../../etc/passwd' } });
|
||||
assert.ok(res.error, 'a path-shaped prompt name must be refused, not treated as a valid lookup key');
|
||||
assert.notEqual(res.error.code, METHOD_NOT_FOUND, 'must be a semantic name-is-not-a-path refusal, not merely the current unimplemented-method fallthrough');
|
||||
});
|
||||
|
||||
test('missing prompt name is invalid params (row 36)', () => {
|
||||
const res = handleMessage({ jsonrpc: '2.0', id: 1, method: 'prompts/get', params: {} });
|
||||
assert.ok(res.error, 'a missing required "name" must error');
|
||||
assert.equal(res.error.code, INVALID_PARAMS, 'must be JSON-RPC INVALID_PARAMS (-32602)');
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user