Files
msd-core/tests/kilo-upgrades.test.cjs
0xdhx cc3ee301a7 fix(#2544): stage the CommonJS marker in GSD-owned dirs, not the config root (#2593)
* fix(#2544): stage the CommonJS marker in GSD-owned dirs, not the config root

installSharedHooksBundle wrote `{"type":"commonjs"}` over
<configRoot>/package.json unconditionally — no existence check, no merge,
no backup — on every install and every /gsd-update re-install. On the 11
affected runtimes that file is often user-owned; on OpenCode and Kilo it is
the documented place to declare local-plugin npm dependencies, so a user's
name/type/dependencies/scripts were destroyed on each run.

The uninstall path already read the file and unlinked it only on an exact
content match. That asymmetry was the defect: the discipline existed in the
codebase, it just was not applied on the write side.

Move the marker into the directories GSD creates and fills with its own .js
files — hooks/ (all shared-hooks runtimes, incl. Kimi's own root) and the
nativePlugin dir (plugins/ for OpenCode+Kilo, extensions/ for pi) — and stop
writing the config root entirely. New src/commonjs-marker.cts owns the marker
string plus one ownership predicate (absent / gsd-owned / foreign, fail-closed
on an unreadable file) shared by ensureCommonJsMarker and removeCommonJsMarker,
so install and uninstall cannot drift apart again.

Nothing else depended on the config-root marker: package identity is baked at
build time (#378/#498) and version resolution prefers gsd-core/VERSION and
already tolerates a missing root package.json (#1383) — Codex has installed
without one all along. A package.json in plugins/ or extensions/ is inert to
plugin discovery, which globs *.{ts,js} only (see installer-migration 006).

Uninstall retires the pre-fix config-root marker, so upgrading users are
cleaned up on removal, and still never touches a file it did not write.

* fix(#2544): point the changeset fragment at the filed PR

The fragment's `pr:` field is only knowable after `gh pr create` returns.

* fix(#2544): register commonjs-marker.cjs in the tsc-generated ESLint ignore set

bin/lib/commonjs-marker.cjs is tsc output (src/commonjs-marker.cts is the
linted source), so it belongs in the ADR-457 ignore list like its siblings.
Clears the lint-tests no-var failure and the repo-invariants
"linted xor ignored" migration-state test.

* fix(#2544): pin the kimi CommonJS marker to hooks/, not the ~/.kimi root

The UPGRADE 1 test still asserted the pre-#2544 marker location
(~/.kimi/package.json). The marker now lives inside ~/.kimi/hooks — the
directory GSD itself creates — matching the updated golden-install-parity
and install-tree fixtures. Also asserts the root marker is NOT written.

* fix(#2544): make the CommonJS marker write path non-fatal

Review round 2, Major 3 + Minor 1 + the stagedHooks nit.

ensureCommonJsMarker rethrew any non-EEXIST write error and neither call site
caught it, so EACCES on a read-only hooks/, EROFS, or ENOSPC aborted the whole
install with a raw stack trace. Every other marker interaction in the module is
best-effort — removeCommonJsMarker swallows unlink failures, classifyMarker
swallows read failures — and this was the write path, i.e. the one most likely
to fail on a locked-down config dir. It now returns a new 'failed' outcome and
both call sites warn and continue.

Sibling found while sweeping for the same defect class: fs.mkdirSync sat
OUTSIDE the try block, so an unwritable parent threw past the guard entirely.
Creating the directory is the same environmental hazard as writing into it, so
it moved inside.

Also in this file:

- The hooks marker is now gated on `stagedHooks && hooksOk`, not stagedHooks
  alone. stagedHooks is computed from the SOURCE listing before the copy loop,
  so it stays true when the copies land but verifyInstalled() then fails —
  marking a hooks/ GSD did not successfully populate claims an ownership the
  install did not earn.
- The uninstall rmdir of the native plugin dir is gated on GSD having actually
  removed something from it. Hoisting it out of the adapter-exists guard (so
  the marker-only case could prune) had silently widened it into deleting a
  user-created but empty plugins/ or extensions/ dir — the same "don't touch
  territory GSD didn't fill" principle this issue is about, inverted.
- Kimi's pre-#2544 marker at its native hook root (~/.kimi) is retired at the
  same call site that writes its replacement. That path is outside kimi's
  configDir, so installer-migration 007 structurally cannot reach it.

* fix(#2544): retire the stale config-root marker via installer-migration 007

Review round 2, Major 1 — the PR's headline claim was false for existing
installs. Upgraders kept BOTH markers: the new one under hooks/ and the stale
{"type":"commonjs"} at the config root, so their config root stayed pinned to
CommonJS and their dependency manifest stayed gone until they uninstalled.

The migration is unusual in one way, and it is the part worth reviewing: the
config-root marker was never recorded in gsd-file-manifest.json (writeManifest
records hooks/, agents/, commands/, scripts/ and the native plugin, never a root
package.json), so classifyArtifact answers 'unknown' for it and the planner's
own guard downgrades a remove-managed on an 'unknown' classification to
preserve-user. 007 therefore supplies the "purpose-built detector for an old
GSD-owned shape" that docs/installer-migrations.md#remove-managed sanctions —
exact content match, the same predicate removeCommonJsMarker has always used —
and declares the resulting classification on the action. A package.json with any
other content is left untouched, and there is deliberately no backup-and-remove
branch: a non-matching file here is not a patched GSD artifact, it is somebody
else's file.

Scope is all runtimes. The `runtimes` field is OMITTED rather than `[]`:
validateStringArray requires the field to be non-empty WHEN PRESENT, while the
runtime filter treats an empty array as "all" — so `runtimes: []` throws at plan
time and the migration never runs. The metadata test pins this.

Kimi is a deliberate carve-out, named in the migration's own header: its marker
lived at ~/.kimi, outside kimi's configDir, and migration relPaths are
structurally confined to configDir. It is retired by the installer instead.

Registration: shipped-migrations table, .gitignore for the emitted .cjs, the
EXPECTED_CHECKSUMS baseline, and the ESLint ignore set. That last one is not
copied from migration 006 by rote — 006 needs no entry because it imports
nothing, while 007 imports node builtins, so tsc emits its __importDefault
helper and the `var` in it trips no-var. This is the same lint gate that made
round 1 red.

* test(#2544): fault-injection and multi-runtime marker coverage

Review round 2, Major 2 + Minors 4 and 5.

Major 2 — CONTRIBUTING.md:514-531 is mandatory for install/uninstall flows and
the suite had no fs monkeypatching at all. Every branch now covered is one whose
doc comment claims it as the module's safety posture:

- classifyMarker non-ENOENT lstat error -> 'foreign' (the fail-closed rule),
  with an ENOENT control alongside it so the test discriminates rather than
  just asserting one side
- classifyMarker readFileSync throw -> 'foreign' (present-but-unreadable never
  downgrades to the permissive answer) — the fixture's bytes are exactly GSD's
  marker, so the test fails if the code ever answers on content it could not read
- a DIRECTORY at the marker path (CONTRIBUTING:521; the symlink case was already
  covered with a real symlink, the directory case needs no injection at all)
- the ensureCommonJsMarker TOCTOU EEXIST branch — the entire reason for flag:'wx'
- the new 'failed' outcome, for both writeFileSync (EACCES/EROFS/ENOSPC) and the
  mkdirSync that used to sit outside the guard
- removeCommonJsMarker unlink throw -> false

These save and restore fs methods in `finally` rather than using chmod 0o000,
which does not fault under root and would pass vacuously in root Docker and CI.

Minor 4 — uninstall was driven for opencode only. pi's extensions/ and both
kimi locations now have behavioral coverage, install and uninstall, each paired
with a user-authored-file case proving GSD leaves it alone.

Minor 5 — the stagedHooks gate had no assertion behind its stated reason.
A pre-existing, GSD-untouched hooks/ directory is now driven through a runtime
that declares skipSharedHooksInstall and asserted to stay marker-free, with its
user content intact.

Also regression-tests the uninstall rmdir gate from the previous commit: an
empty plugin dir GSD removed nothing from must survive.

* docs(#2544): correct stale marker prose, register the module, document the trade-off

Review round 2, Minors 2, 3 and 6.

Minor 2 — six files asserted the installed ROOT ships the synthetic marker.
None was load-bearing (all three walk-up consumers are VERSION-first with
try/catch and the marker never carried a `version`), but ADR-457:52 is the
rationale for keeping a generated module, so a future reader would mis-derive
the constraint from it. Each site is corrected to what is now true: the
installed tree carries no package.json with a .name at all, because the only
ones GSD stages are {"type":"commonjs"} markers and they now live in GSD's own
directories.

Two of the six needed more than a location swap. hooks/gsd-check-update-worker.js
and the platform-gate test both described `require('../package.json').name`
resolving to undefined; post-#2544 that require does not resolve at all, so the
history is kept accurate and the present-tense claim corrected rather than just
moved. And src/runtime-artifact-conversion.cts described the no-root-package.json
case as Codex-only — it is now every runtime, which strengthens that comment's
own argument for lazy resolution. The generated .cjs sibling needs no edit: it
is gitignored build output, not a tracked file.

Minor 3 — src/commonjs-marker.cts had no CONTEXT.md entry, unlike every peer
module, and CONTEXT.md is the #2 co-change partner of bin/install.js. Added,
including the fail-closed posture and the never-throws contract.

Minor 6 — the plugins//extensions/ marker shadows the config root for all .js
siblings, so an OpenCode/Kilo user's ESM plugin/*.js stays broken. That is
exactly what #2544's Fix section prescribed and it is disclosed in the PR body,
but the PR body is not documentation. It now lives in the OpenCode section of
docs/how-to/install-on-your-runtime.md, stated as a real constraint rather than
a pure improvement, with the .ts mitigation and a fallback for ESM plugins.

* test(#2544): attribute the CommonJS marker in the emitted-provenance rules

The differential emitted-attribution gate (#2723, landed on `next` after this
branch was cut) went red on the macOS shards once this PR rebased onto it. Two
distinct causes, both real gaps rather than noise:

1. `plugins/package.json` and `extensions/package.json` matched NO rule — the
   `native-plugin` rule covers `*.{js,cjs,mjs}` only, so the marker read as an
   unattributed emitted family.
2. `hooks/package.json` fell through to `hooks-built`, which attributes an
   emitted `hooks/<X>` to a repo source `hooks/<X>`. There is no
   `hooks/package.json` in the repo, so it resolved to a nonexistent path.

Cause 2 is exactly the failure already documented three lines above it for
Copilot's `gsd-session.json` — "a code literal, not a built script" — so the fix
follows that precedent rather than inventing one: `package.json` is excluded
from `hooks-built` the same way, and a dedicated `commonjs-marker` rule
attributes the family across all four roots it can appear in (both hooks roots
plus `plugins`/`extensions`) to the sources that actually emit it.

Deliberately a RULE, not an entry in tests/emitted-drift-ack.json. An ack is for
a one-off ripple and goes stale by design — the gate fails a stale ack precisely
so it cannot pre-clear the next change on that path. These markers are a
permanent part of the emitted tree from #2544 onward, so they need standing
attribution.

Verified by reproducing the CI failure locally with GSD_EMITTED_BASE: 3
provenance errors + 12 unattributed paths before, 35/35 green after.

* fix(#2544): route the #2717 hooks-surface marker helpers through commonjs-marker

#2717 landed a second copy of ensureCommonJsMarker/removeCommonJsMarkerIfGsdOwned
in src/runtime-hooks-surface.cts for the runtimes that stage .js hooks via
dedicated paths (cursor/windsurf/codex). That copy had drifted from this PR's
module on the two properties that matter:

  - ownership probe: `fs.existsSync` FOLLOWS symlinks and reports false for a
    DANGLING one, so a dangling package.json symlink classified as absent and
    the write went straight through it. Demonstrated: against the pre-fix copy,
    ensureCommonJsMarker() on a hooks/ dir holding a dangling package.json
    symlink returns true and creates {"type":"commonjs"} OUTSIDE that directory.
  - create: a plain writeFileSync leaves the classify->write window open, where
    commonjs-marker creates with flag:'wx' (O_EXCL).

Both helpers now delegate to src/commonjs-marker.cts, which is what this PR's
own docstring already claimed was the single place these rules are enforced.
Exported signatures are unchanged (still boolean), so bin/install.js and the
#2717 tests are unaffected.

The new subtest is the only coverage that fails if the duplicate is ever
reintroduced — the two implementations agree on every non-adversarial input, so
the existing suites pass against both.

* test(#2544): pin the stagedHooks gate on zcode, not windsurf

The Minor-5 coverage picked windsurf because hostBehaviors.skipSharedHooksInstall
kept it out of the shared hooks bundle, so GSD staged nothing into hooks/ and the
marker was correctly absent.

#2717 changed that premise: cursor/windsurf/codex now stage their .js hooks via
dedicated paths and get the marker beside those scripts. Measured on this tree,
windsurf stages 2 .js hooks and receives a marker — so the assertion was pinning
behaviour that is now wrong, not the gate it was written for.

ZCode is the durable choice: per #1821 it has hooksSurface:'none' AND no plugin
surface to spawn hooks, so GSD stages no .js there by either route (measured: 0
staged, no marker). The property under test is unchanged — a user-created hooks/
directory GSD never fills stays marker-free.

* test(#2544): use the shared cleanup helper in the migration test

Addresses the review's Major 1. The suppression's stated reason — "no helpers
import available" — was not correct: tests/helpers.cjs exports cleanup, and the
other test file added in this same PR imports it (tests/commonjs-marker.test.cjs).

The local reimplementation dropped two protections that are live on this repo's
windows-latest lane: the CWD guard (Windows cannot remove a directory that is the
current working directory) and the 20 x 250ms retry budget that absorbs the
deferred-scan handle Windows Defender holds on newly-written files.

Local function and suppression both removed; local/no-raw-rmsync-in-tests now
passes without one.

* test(#2544): expect hooks/package.json for the #2717 runtimes

The fresh-install contract table predates #2717, which stages cursor/windsurf/
codex .js hooks via dedicated paths and writes the CommonJS marker beside them.
All three therefore now receive hooks/package.json legitimately.

Measured on this tree: codex stages 3 .js hooks, cursor 6, windsurf 2 — each with
the marker; cline/copilot/trae/zcode stage none and get none, so their contracts
are unchanged.

* fix(#2544): gate the #2717 marker writes on having staged something

The three dedicated marker writers #2717 added ran unconditionally. Each one
mkdirs hooks/ up front and stages its scripts conditionally on the source
existing, so with an absent or empty hook source they created a directory,
filled it with nothing, and marked it as GSD's anyway.

That is the same write-into-someone-else's-territory this issue is about, and
installSharedHooksBundle already guards the identical case with `stagedHooks`.
The dedicated paths now carry the matching gate:

  - cursor / windsurf: `installedScripts.size > 0`
  - codex: a new `codexStagedHooks` flag. The enclosing guard only proves that
    hooks/dist EXISTS; it says nothing about whether any CODEX_HOOKS_TO_COPY
    entry landed.

Covered for cursor and windsurf by driving each writer against a src tree whose
hooks/ dir is empty. The codex leg is defensive and deliberately uncovered: its
trigger state needs a package tree where hooks/dist exists but holds none of the
allowlist, which is not constructible from a real checkout.

* test(#2544): scope the commonjs-marker sources per root

The rule declared one flat source list for every marker root, so
`extensions/package.json` was attributed to runtime-hooks-surface.cts (which
never writes there) and `.kimi/hooks/package.json` to install-engine.cts.

That is not merely untidy. emitted-diff.cjs accepts the FIRST satisfied source,
so a flat list containing bin/install.js let any change anywhere in that
13k-line file authorise marker drift for every root — the blanket escape hatch
this file's own agents-verbatim comment refuses for exactly the same reason.

Sources are now derived per root from ctx.rel. Note the rule ctx is
`{ rel, runtime }` and carries no `root`, so keying on ctx.root would have sent
every path down one branch silently.

* test(#2544): state precisely what the zcode assertion pins

The comment claimed the test pinned installSharedHooksBundle's `stagedHooks`
gate. It does not, and neither did the windsurf version it replaced: zcode
declares skipSharedHooksInstall, so the outer guard skips that helper entirely
and the gate is never evaluated. The test passes on the runtime exclusion.

What it does pin — the outcome a pre-existing, GSD-untouched hooks/ stays
marker-free — is still worth having, and is what the review asked for. The two
`staging zero hook scripts` tests are the ones that pin a real staged-nothing
gate. Comment corrected rather than left implying coverage that is not there.

---------

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

428 lines
21 KiB
JavaScript

'use strict';
/**
* kilo capability UPGRADES — ADR-1239 Phase D / #2093 (EoS/kilo).
*
* Drives the user-reachable surface (spawned `bin/install.js` via
* `runMinimalInstall`) plus targeted unit coverage to prove the four real
* upgrades Kilo contributes as part of the imperative-adapter migration:
*
* UPGRADE 1 — native hook-bus plugin: `.kilo/plugins/gsd-core.js`, a
* byte-identical copy of `.opencode/plugins/gsd-core.js` (Kilo is an
* OpenCode fork sharing the same plugin/extension event bus).
*
* UPGRADE 2 — active-model routing: `convertClaudeToKiloFrontmatter` now
* emits a `model:` field from the resolved model override instead of
* always stripping it (mirrors the OpenCode upgrade, #2256).
*
* UPGRADE 3 — MCP companion documented + reachable: `docs/how-to/connect-gsd-mcp-server.md`
* covers Kilo's `mcp`-keyed config (not `mcpServers`), and the companion the
* doc points at (`bin/gsd-mcp-server.js`) is proven live by spawning it and
* performing a real initialize + tools/list handshake (AC4: "test: connect
* and list tools") — mirrors tests/gsd-mcp-server-bin.test.cjs exactly.
*
* UPGRADE 4 — named subagent dispatch: GSD's specialist agents install as
* `<configDir>/agents/gsd-*.md` with `mode: subagent` + a `permission:`
* block — the slug Kilo's Task tool dispatches by.
*/
const { test, before } = 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 { runMinimalInstall, BUILD_SCRIPT } = require('./helpers/install-shared.cjs');
const { cleanup } = require('./helpers.cjs');
const { listAgentFiles } = require('./helpers/agent-roster.cjs');
const { convertClaudeToKiloFrontmatter } = require('../bin/install.js');
const { PROTOCOL_VERSION } = require('../gsd-core/bin/lib/mcp-server.cjs');
const MCP_SERVER_BIN = path.join(__dirname, '..', 'bin', 'gsd-mcp-server.js');
const KILO_CAP = JSON.parse(
fs.readFileSync(path.join(__dirname, '..', 'capabilities', 'kilo', 'capability.json'), 'utf8'),
);
const ADAPTER_SRC = path.join(__dirname, '..', '.kilo', 'plugins', 'gsd-core.js');
const OPENCODE_ADAPTER_SRC = path.join(__dirname, '..', '.opencode', 'plugins', 'gsd-core.js');
/** Extract the YAML frontmatter block (between the first pair of `---` lines), or null. */
function parseFrontmatter(content) {
const m = content.match(/^---\r?\n([\s\S]*?)\r?\n---/);
return m ? m[1] : null;
}
// ---------------------------------------------------------------------------
// UPGRADE 1: native hook-bus plugin (.kilo/plugins/gsd-core.js)
// ---------------------------------------------------------------------------
for (const scope of ['global', 'local']) {
test(`kilo --${scope}: installs .../plugins/gsd-core.js byte-identical to the repo source (UPGRADE 1)`, (t) => {
const { configDir, root } = runMinimalInstall({ runtime: 'kilo', scope });
t.after(() => cleanup(root));
const installedPluginPath = path.join(configDir, 'plugins', 'gsd-core.js');
assert.ok(fs.existsSync(installedPluginPath), `${installedPluginPath} must exist`);
const installed = fs.readFileSync(installedPluginPath);
const source = fs.readFileSync(ADAPTER_SRC);
assert.ok(installed.equals(source), 'installed plugin must byte-equal the repo .kilo/plugins/gsd-core.js source');
});
}
// Faithful emulation of a plugin loader: `getServerPlugin` accepts a bare
// function OR an object with a `.server` function (mirrors the OpenCode
// loader contract Kilo forked, tests/opencode-plugin-adapter.test.cjs).
function getServerPlugin(entry) {
if (typeof entry === 'function') return entry;
if (entry && typeof entry === 'object' && typeof entry.server === 'function') return entry.server;
return null;
}
function loaderExtract(mod) {
const servers = [];
for (const entry of Object.values(mod)) {
const s = getServerPlugin(entry);
if (!s) throw new TypeError('Plugin export is not a function');
servers.push(s);
}
return servers;
}
test('.kilo/plugins/gsd-core.js loads as raw CommonJS and exposes id "gsd-core" + server._internals (UPGRADE 1)', () => {
const mod = require(ADAPTER_SRC);
assert.equal(mod.id, 'gsd-core');
// NON-ENUMERABLE so it never lands in Object.values (would throw in the loader loop).
assert.ok(!Object.keys(mod).includes('id'), 'id must be non-enumerable');
const servers = loaderExtract(mod); // must not throw
assert.equal(servers.length, 1);
assert.equal(typeof servers[0], 'function');
assert.equal(typeof mod.server._internals, 'object');
assert.ok(mod.server._internals, 'server._internals must be present');
});
// DEFECT.GENERATIVE-FIX parity guard: .kilo/plugins/gsd-core.js is a deliberate
// byte-copy of .opencode/plugins/gsd-core.js (Kilo is an OpenCode fork sharing
// the same plugin/extension event bus, see the UPGRADE 1 doc comment above).
// Nothing enforces that copy relationship — a future edit to either file that
// forgets its twin would silently drift the two runtimes apart. This fails the
// instant that happens.
test('.kilo/plugins/gsd-core.js stays byte-identical to .opencode/plugins/gsd-core.js (Kilo is an OpenCode fork; parity guard, UPGRADE 1)', () => {
const kilo = fs.readFileSync(ADAPTER_SRC, 'utf8');
const opencode = fs.readFileSync(OPENCODE_ADAPTER_SRC, 'utf8');
assert.equal(
kilo,
opencode,
'.kilo/plugins/gsd-core.js and .opencode/plugins/gsd-core.js must stay byte-identical — ' +
'Kilo is an OpenCode fork and intentionally reuses the same plugin verbatim; if you edited ' +
'one, mirror the change into the other (or this guard will keep failing).',
);
});
// ---------------------------------------------------------------------------
// UPGRADE 2: active-model routing (convertClaudeToKiloFrontmatter)
// ---------------------------------------------------------------------------
const SAMPLE_AGENT = `---
name: gsd-executor
description: Executes GSD plans with atomic commits
tools: Read, Write, Edit, Bash, Grep, Glob
color: yellow
---
<role>
You are a GSD plan executor.
</role>`;
const SAMPLE_COMMAND = `---
name: gsd-execute-phase
description: Execute all plans in a phase
allowed-tools:
- Read
- Write
- Bash
---
Execute the phase plan.`;
test('UPGRADE 2: convertClaudeToKiloFrontmatter emits model: when isAgent + modelOverride is provided', () => {
const result = convertClaudeToKiloFrontmatter(SAMPLE_AGENT, { isAgent: true, modelOverride: 'anthropic/claude-sonnet-5' });
const frontmatter = result.split('---')[1];
assert.match(frontmatter, /^model: anthropic\/claude-sonnet-5$/m, 'model: field must carry the resolved override');
});
test('UPGRADE 2: convertClaudeToKiloFrontmatter emits NO model: when isAgent + modelOverride is null', () => {
const result = convertClaudeToKiloFrontmatter(SAMPLE_AGENT, { isAgent: true, modelOverride: null });
const frontmatter = result.split('---')[1];
assert.ok(!/^model:/m.test(frontmatter), 'model: field must be absent when no override is resolved');
});
test('UPGRADE 2: convertClaudeToKiloFrontmatter emits NO model: for commands, even with a modelOverride (commands strip)', () => {
const result = convertClaudeToKiloFrontmatter(SAMPLE_COMMAND, { isAgent: false, modelOverride: 'x' });
const frontmatter = result.split('---')[1];
assert.ok(!/^model:/m.test(frontmatter), 'commands never carry a model: field, regardless of modelOverride');
});
// Note: a bare runMinimalInstall does NOT configure a runtime model_overrides/
// model_profile_overrides config, so installed agents will NOT carry a model:
// line from a plain install — that is expected (readGsdEffectiveModelOverrides
// / readGsdRuntimeProfileResolver resolve to nothing) and is NOT a regression.
// The unit tests above are the correct surface for proving U2's "stop
// stripping, emit requested model" behavior change.
// ---------------------------------------------------------------------------
// UPGRADE 3: MCP companion documented
// ---------------------------------------------------------------------------
// allow-test-rule: docs-parity (#2093) — docs/how-to/connect-gsd-mcp-server.md
// must document Kilo's real mcp-keyed config (not mcpServers); the doc prose IS
// the canonical statement of that fact and there is no runtime API to enumerate
// it, so reading the file and asserting on its text is the only parity check
// available.
test('UPGRADE 3: docs/how-to/connect-gsd-mcp-server.md documents Kilo\'s mcp-keyed config', () => {
const docPath = path.join(__dirname, '..', 'docs', 'how-to', 'connect-gsd-mcp-server.md');
const doc = fs.readFileSync(docPath, 'utf8');
assert.match(doc, /Kilo/, 'doc must mention Kilo');
assert.match(doc, /`mcp` key \(\*\*not\*\* `mcpServers`\)/,
'doc must call out the mcp (not mcpServers) key for Kilo/OpenCode');
assert.ok(doc.includes('"mcp"'), 'doc must show the literal "mcp" config key');
assert.ok(doc.includes('opencode.jsonc') || doc.includes('opencode.json'),
'doc must name Kilo\'s native config file (shared with OpenCode\'s schema)');
});
// AC4 ("test: connect and list tools"): prove the companion Kilo's `mcp` config
// points at (bin/gsd-mcp-server.js) is actually reachable, not just documented.
// Mirrors tests/gsd-mcp-server-bin.test.cjs's spawn/handshake mechanism exactly
// (same shim, same line-delimited JSON-RPC over stdio, same clean-exit-on-EOF
// contract) rather than reinventing the protocol handshake.
test('UPGRADE 3: gsd-mcp-server companion is reachable — spawn, initialize, tools/list over stdio (AC4)', () => {
const stdin = [
JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'initialize' }),
JSON.stringify({ jsonrpc: '2.0', id: 2, method: 'tools/list' }),
].join('\n') + '\n';
const res = spawnSync(process.execPath, [MCP_SERVER_BIN], {
input: stdin,
encoding: 'utf-8',
timeout: 15000,
env: { ...process.env, GSD_TEST_MODE: '1' },
});
assert.strictEqual(res.status, 0, `gsd-mcp-server must exit cleanly on stdin EOF; stderr: ${res.stderr}`);
const lines = res.stdout.trim().split('\n').map((l) => JSON.parse(l));
assert.strictEqual(lines.length, 2, 'one response per request');
assert.strictEqual(lines[0].id, 1);
assert.strictEqual(lines[0].result.protocolVersion, PROTOCOL_VERSION, 'initialize handshake succeeds');
const toolNames = lines[1].result.tools.map((t) => t.name).sort();
assert.deepStrictEqual(
toolNames,
['gsd_invoke_command', 'gsd_read_state', 'gsd_write_state'],
'the companion Kilo\'s mcp config connects to advertises the real GSD tool surface',
);
});
// ---------------------------------------------------------------------------
// UPGRADE 4: named subagent dispatch (agents/*.md, mode: subagent)
// ---------------------------------------------------------------------------
const KILO_AGENT_PERMISSION_KEYS = [
'read', 'edit', 'bash', 'grep', 'glob', 'task',
'webfetch', 'websearch', 'skill', 'question', 'todowrite', 'list', 'codesearch', 'lsp',
];
for (const scope of ['global', 'local']) {
test(`kilo --${scope}: native agents/*.md subagent projection with mode: subagent (UPGRADE 4)`, (t) => {
const { configDir, root } = runMinimalInstall({ runtime: 'kilo', scope });
t.after(() => cleanup(root));
const agentsDir = path.join(configDir, 'agents');
assert.ok(fs.existsSync(agentsDir), `${agentsDir} must exist`);
const expectedNames = listAgentFiles();
assert.equal(expectedNames.length, 34,
'sanity: shipped GSD agent roster is 34 files — update this boundary if the roster changes');
const installedFiles = fs.readdirSync(agentsDir)
.filter((f) => f.startsWith('gsd-') && f.endsWith('.md'));
assert.ok(installedFiles.length >= expectedNames.length,
`expected at least ${expectedNames.length} installed agents under ${agentsDir}, got ${installedFiles.length}`);
for (const name of expectedNames) {
assert.ok(installedFiles.includes(`${name}.md`), `${name}.md must be installed under ${agentsDir}`);
}
for (const known of ['gsd-code-reviewer', 'gsd-planner', 'gsd-executor']) {
const filePath = path.join(agentsDir, `${known}.md`);
assert.ok(fs.existsSync(filePath), `${filePath} must exist`);
const content = fs.readFileSync(filePath, 'utf8');
const fm = parseFrontmatter(content);
assert.ok(fm, `${known}.md must have YAML frontmatter`);
assert.match(fm, /^name:\s*\S+/m, `${known}.md frontmatter must declare name:`);
assert.match(fm, /^mode:\s*subagent\s*$/m,
`${known}.md frontmatter must declare mode: subagent (the slug Kilo's Task tool dispatches by)`);
assert.match(fm, /^permission:\s*$/m, `${known}.md frontmatter must declare a permission: block`);
for (const key of KILO_AGENT_PERMISSION_KEYS) {
assert.match(fm, new RegExp(`^\\s+${key}:\\s*(allow|deny)\\s*$`, 'm'),
`${known}.md permission: block must declare ${key}: allow|deny`);
}
// Branding-residue checks are scoped to the FRONTMATTER — the part the
// opencode/kilo converter fully rewrites into Kilo-native form. The agent
// BODY legitimately retains Claude-Code source references byte-identical to
// opencode's installed agents (verified): the shared runtime-launcher shell
// preamble's git-root `.claude/` fallback
// (`${RUNTIME_DIR:-$(git rev-parse --show-toplevel)/.claude/…}`) and prose
// product-name mentions (e.g. "…inside a Claude Code worktree…"). These are
// family-wide launcher/prose artifacts, not kilo conversion defects — the
// opencode/kilo family, unlike qwen's aggressive converter, does not rewrite
// body prose.
assert.ok(!fm.includes('CLAUDE.md'), `${known}.md frontmatter must not contain residual "CLAUDE.md"`);
assert.ok(!fm.includes('Claude Code'), `${known}.md frontmatter must not contain residual "Claude Code"`);
assert.ok(!fm.includes('.claude/'), `${known}.md frontmatter must not contain residual ".claude/"`);
}
});
}
// -- boundary/negative: hooksSurface:'none' + subagentToolkit stays undocumented
test('capabilities/kilo/capability.json extendedHookEvents is exactly [] (hooksSurface: "none") and dispatch.subagentToolkit stays "undocumented"', () => {
assert.deepEqual(KILO_CAP.runtime.extendedHookEvents, []);
assert.equal(KILO_CAP.runtime.hooksSurface, 'none');
assert.equal(KILO_CAP.runtime.hostIntegration.dispatch.subagentToolkit, 'undocumented');
});
// ---------------------------------------------------------------------------
// #2305: the shared guard hooks Kilo's native plugin spawns must be STAGED.
//
// Kilo's capability descriptor used to declare BOTH hostBehaviors.nativePlugin
// (a plugin that spawns the shared PreToolUse guard scripts as subprocesses)
// AND hostBehaviors.skipSharedHooksInstall:true (which suppresses staging of
// hooks/*.js into the config dir). The plugin's runHook treats an absent hook
// script as a silent allow, so every guard it spawned no-opped on a normal
// Kilo install. OpenCode (same plugin, hooks staged) is the reference shape.
// ---------------------------------------------------------------------------
// hooks/dist is gitignored and built; the scoped CI lane does not run
// build:hooks, so a real install there would stage no hooks/ dir. Build it
// idempotently (mirrors golden-install-parity + install-minimal-hooks).
before(() => {
const build = spawnSync(process.execPath, [BUILD_SCRIPT], { encoding: 'utf8' });
assert.equal(build.status, 0, `build:hooks failed: ${build.stderr}`);
});
// The three PreToolUse guards the plugin spawns that ship today. When a new
// guard lands on the plugin's dispatch path, add it here.
const PLUGIN_GUARD_HOOKS = [
'gsd-prompt-guard.js',
'gsd-read-guard.js',
'gsd-worktree-path-guard.js',
'gsd-workflow-guard.js',
];
for (const scope of ['global', 'local']) {
test(`kilo --${scope}: stages the guard hook scripts where the native plugin resolves them (#2305)`, (t) => {
const { manifest, configDir, root } = runMinimalInstall({ runtime: 'kilo', scope });
t.after(() => cleanup(root));
// The shared hooks bundle lands in the config dir, next to gsd-core/.
for (const hook of PLUGIN_GUARD_HOOKS) {
const hookPath = path.join(configDir, 'hooks', hook);
assert.ok(fs.existsSync(hookPath), `${hookPath} must be staged by the install`);
}
// #2544: the CommonJS marker is staged INSIDE the directories GSD owns and
// fills — hooks/ (the staged guard scripts) and plugins/ (the native
// adapter) — never at the config root, which is user-writable territory on
// Kilo (where a package.json declares local-plugin npm dependencies).
for (const ownedDir of ['hooks', 'plugins']) {
const marker = path.join(configDir, ownedDir, 'package.json');
assert.ok(fs.existsSync(marker), `CommonJS package.json marker must be staged in ${ownedDir}/`);
assert.equal(JSON.parse(fs.readFileSync(marker, 'utf8')).type, 'commonjs');
}
assert.ok(!fs.existsSync(path.join(configDir, 'package.json')),
'the config root must not receive a GSD package.json (#2544)');
// Staged hooks are tracked in the manifest (drift/uninstall accounting).
assert.ok(manifest && manifest.files['hooks/gsd-prompt-guard.js'],
'manifest must track the staged guard hooks');
// The installed plugin's own walk-up resolution (hooks/ + gsd-core/ both
// present) lands on the config dir — i.e. HOOKS_DIR points at the staged
// scripts, closing the resolveRepoRoot fallback miss from #2305.
const installedPlugin = path.join(configDir, 'plugins', 'gsd-core.js');
assert.ok(fs.existsSync(installedPlugin), 'native plugin must be staged');
delete require.cache[require.resolve(installedPlugin)];
const mod = require(installedPlugin);
assert.equal(mod.server._internals.REPO_ROOT, fs.realpathSync(configDir),
'plugin REPO_ROOT must resolve to the config dir (hooks/ + gsd-core/ siblings)');
});
}
test('kilo: a disallowed write through the REAL installed tree is rejected by the worktree-path guard (#2305)', async (t) => {
const { configDir, root } = runMinimalInstall({ runtime: 'kilo', scope: 'global' });
t.after(() => cleanup(root));
// Build a GSD-shaped executor worktree: gsd-worktree-path-guard hard-blocks
// only when cwd is a linked worktree on a worktree-agent-* branch and the
// write targets an absolute path outside that worktree's toplevel.
const scratch = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-kilo-2305-')));
t.after(() => cleanup(scratch));
const mainRepo = path.join(scratch, 'main');
fs.mkdirSync(mainRepo, { recursive: true });
const git = (args, cwd) => {
const r = spawnSync('git', ['-c', 'user.email=t@t', '-c', 'user.name=t', ...args], { cwd, encoding: 'utf8' });
assert.equal(r.status, 0, `git ${args.join(' ')} failed: ${r.stderr}`);
return r;
};
git(['init', '-q'], mainRepo);
fs.writeFileSync(path.join(mainRepo, 'seed.md'), 'seed');
git(['add', 'seed.md'], mainRepo);
git(['commit', '-q', '-m', 'seed'], mainRepo);
const wt = path.join(scratch, 'wt');
git(['worktree', 'add', '-q', '-b', 'worktree-agent-2305', wt], mainRepo);
// Load the plugin exactly as installed and pin its cwd to the worktree.
const installedPlugin = path.join(configDir, 'plugins', 'gsd-core.js');
delete require.cache[require.resolve(installedPlugin)];
const mod = require(installedPlugin);
const handlers = await mod.server({ directory: wt });
// A write escaping the worktree back into the main repo must be BLOCKED —
// pre-#2305 no hook script was staged, so this silently resolved (allow).
await assert.rejects(
() => handlers['tool.execute.before'](
{ tool: 'write' },
{ args: { filePath: path.join(mainRepo, 'escape.md'), content: 'x' } },
),
/./,
'guard must reject the out-of-worktree write through the installed Kilo tree',
);
// Control: the same write kept inside the worktree passes.
await handlers['tool.execute.before'](
{ tool: 'write' },
{ args: { filePath: path.join(wt, 'inside.md'), content: 'x' } },
);
});
// Regression guard for the descriptor-contradiction CLASS, not just Kilo: a
// runtime whose nativePlugin spawns the shared hooks while its descriptor
// suppresses staging them re-creates #2305 for that runtime.
test('no capability declares BOTH hostBehaviors.nativePlugin and skipSharedHooksInstall:true (#2305)', () => {
const capsDir = path.join(__dirname, '..', 'capabilities');
for (const entry of fs.readdirSync(capsDir)) {
const capPath = path.join(capsDir, entry, 'capability.json');
if (!fs.existsSync(capPath)) continue;
const cap = JSON.parse(fs.readFileSync(capPath, 'utf8'));
const hb = cap.runtime && cap.runtime.hostBehaviors;
if (!hb || !hb.nativePlugin) continue;
assert.notEqual(hb.skipSharedHooksInstall, true,
`${entry}: declares a nativePlugin (which spawns the shared hooks) while ` +
'also declaring skipSharedHooksInstall:true — the hooks it depends on ' +
'would never be staged (#2305)');
}
});