A PR whose diff is entirely under docs/ runs zero tests, so a guard whose INPUT
is shipped prose cannot protect the PR lane of the diffs it exists to check. Its
only firing opportunity is after merge, on the shared branch -- which is how next
went red on dacae9273 while the PR that caused it (#3746) was green on every
check.
The docs-lint job in .github/workflows/docs-required.yml -- an ALREADY-REQUIRED
context -- now selects and runs the docs guards that read the specific docs files
the PR changed.
scripts/docs-guard-registry.cjs test file -> the docs paths it reads (63)
scripts/select-docs-guards.cjs pure (changedPaths, registry) -> test files
scripts/lint-docs-guard-registration.cjs drift guard, wired into lint:ci
scripts/ci-test-scope.cjs is NOT touched -- `git diff origin/next --` on it is
empty -- so #764's saving stands and its 21 pinning tests are untouched.
Selection: exact path; trailing-slash directory prefix (boundary-checked --
docs/adrenaline.md does NOT match docs/adr/, which a naive startsWith gets
wrong); and '*' for the 6 entries that walk docs/ generally or read a computed
path. Unknown maps to '*' -- guessing narrow is how a guard silently stops
running. Measured: a typo fix selects 6 of 63; docs/AGENTS.md selects 12;
docs/COMMANDS.md selects 18.
Four things this got wrong first, each found by an independent reviewer or by
probe, and each having been asserted safe in a comment:
1. The registry started as a RULE in ci-test-scope.cjs's RULES, on the theory
that classify()'s !codeChanged normalization made it inert. True for
docs-ONLY diffs; false for MIXED docs+code diffs, where codeChanged is true
and the normalization never runs:
node scripts/ci-test-scope.cjs --files "docs/a.md src/semver.cts"
with the RULE: 25 targeted_tests
origin/next: 3 targeted_tests
Category error: RULES is the scoped lane's input; a docs-guard registry is a
lane manifest for a consumer that never calls classify(). Extracted; pinned
by value.
2. The second attempt was a dedicated workflow with paths: [docs/**]. Such a
workflow never reports on a non-docs PR, so it can never be a required
context without hanging every non-docs PR -- and a non-required check does not
block a merge, so the guard would have been advisory and #3753 unfixed.
docs-required.yml already has no paths: filter, already supplies the required
docs-lint context, already computes docs_changed, and already ran one docs
guard gated on it. Generalizing that step needs no ruleset edit at all.
3. The registry and the drift lint were built from ONE path-segment heuristic, so
both were blind identically -- and blind at the guard that motivated the issue.
The reader-call regex required a character BEFORE its keyword, so a callee
named exactly read( / load( / parse( / doc( / file( / content( could never
match; and only an INLINE path.join(ROOT,'docs','X.md') argument was caught,
missing the two-step-via-variable form -- the MAJORITY spelling -- plus
template literals and concatenation. Detector 1 fired on 14 of ~450 files, so
35 genuine guards sat unregistered while the lint reported 0 violations,
including cursor-reviewer (reads docs/COMMANDS.md, asserts
.includes('--cursor')) and inventory-headings-countfree. The "accepted blind
spot" this shipped with was the common case, not a fringe.
4. With detection fixed the true population is 115 files: 63 genuine guards, 52
incidental. Running all 63 in a REQUIRED check on a one-line typo fix is the
cost #764 exists to avoid -- install.test.cjs is 7840 lines and reads exactly
one docs file, docs/AGENTS.md, for its frontmatter. Dropping it reproduces the
bug; running it for a typo elsewhere is waste. Hence the map.
Then a second review round found six more, all fixed here:
- fragment-single-edit-propagation.install.test.cjs was EXEMPTED as
"overlay fixture only". False: it reads the real docs/registries/eos.json and
asserts on a registry entry name, and reads the real ADR-0001 and asserts its
H1. A docs-only PR touching either would have gone green and red next -- #3753
shipping again, from inside the fix for it. Now registered against both paths,
and all 52 remaining exemptions were re-audited one by one.
- The SUITES-collision guard compared RAW registry keys, but run-tests.cjs strips
a leading `tests/` BEFORE its suite check. So it caught 'all' and missed
'tests/all' -- the only spelling that can actually occur, since every key
carries the prefix. One typo would have run all 824 test files inside the
required job. Now normalized the same way run-tests.cjs normalizes.
- The lint failed OPEN on an unreadable tests dir or candidate file: 0 violations,
ok:true. A guard that cannot read its input must never report success.
- The exemption ratchet gated identity only, so a baselined file that later
STARTED asserting on shipped docs stayed exempt silently -- 52 permanently blind
files. The baseline now fingerprints the docs paths each exempted file
references and fails when that set changes, naming what changed.
- The exemption marker was still honored inside a multi-line template literal in
the header window. The scanner now tracks template-literal and block-comment
state.
- `git diff --name-only | grep '^docs/'` silently dropped C-quoted non-ASCII docs
paths, making docs_changed=false a green zero-guard check. Both call sites now
pass -c core.quotepath=false.
- The run step was gated on hashFiles(), which a force-committed
.docs-guard-tests.txt would satisfy. The step now rm -f's both scratch files
first and gates on an output it sets itself.
Three empty states, deliberately distinct, because conflating them rebuilds
#3753: an empty or malformed registry HARD-FAILS; docs changed with no guard
covering them logs and skips; no docs change is already gated. The middle state
must never be expressed as an empty --files-from, which prints `no tests in suite
"all"` and exits 0 -- a green check that guarded nothing. With the current
registry that state is unreachable, because the six '*' entries always match;
the branch is kept as defensive handling for a future registry and says so.
timeout-minutes: 15 bounds the required job against a hanging fork-supplied test;
it had none. npm ci was added because the job never installed dependencies -- the
previous single-file step got away without it, the registry does not.
docs/contributing/docs-guard-registration.md documents the rule, following its
sibling cross-platform-portability-rules.md, and CONTRIBUTING.md's CI Test
Quality Checks table links to it. It is also load-bearing: without a docs/ file
in the diff this PR would not have triggered its own lane, shipping an
unexercised change to a required check.
One unrelated fix, included because this PR surfaced it and CLAUDE.md forbids
deferring a defect found while working. On this branch's first CI run,
`full test (windows-latest, 24, shard 3/3)` was CANCELLED at exactly 30 minutes;
tests were still passing 0.8s before the cancel, so it is a wall-clock timeout,
not a hang, and a cancelled job reddens `Required tests`.
The cause is not this PR's test file, which costs ~60ms. Shard composition is
unstable: adding ONE file to the unit suite reshuffled 115 of 268 files between
shards, and shard 3 drew a heavier mix. Underneath that is a real pre-existing
defect. tests/ci-test-job-timeout-budget.test.cjs requires every lane's budget to
be >= 1.5x its MEASURED cost -- "a lane that got slower must be re-budgeted, not
excused" -- and its test-full entry recorded 19m from a windows-22 shard. That is
stale. Measured on `next` with none of this PR's changes present: 26m18s (run
32614439702, windows-latest/24 shard 3/3), 23m36s and 23m17s on shard 2/3. So the
lane costs ~26m and the 30-minute cap carried 1.14x headroom, not 1.5x. The gate
had been out of compliance with its own rule; this PR was merely the file
addition that reshuffled shard 3 past the cliff.
Fixed as that file prescribes: measuredMinutes 19 -> 27 with fresh evidence, and
test-full timeout-minutes 30 -> 45. The rule's minimum for 27m is 41; 45 is
deliberately above it because the reshuffle means per-shard worst case moves run
to run, and a budget pinned to the exact minimum would be re-breached by the next
test file anyone adds. Only that one job's timeout changed; test.yml's scope,
matrix and steps are untouched, so #764's saving is unaffected.
Raising that cap let the Windows shard finish (28m45s, inside 45) and uncovered
a real failure the 30-minute cancel had been masking:
`new quick-task branch branches off origin/main (#2916)` died with
`outcome=timed_out exitCode=null`, SIGTERM, at the 15000ms bound.
tests/quick-branching.test.cjs:149 `runStep` runs a `#!/usr/bin/env bash` script
executing MULTIPLE git commands, but was bound to GIT_TIMEOUT_MS (15000) -- the
norm for a SINGLE git plumbing call. tests/helpers/timeouts.cjs already documents
this exact failure and exists to fix it: HOOK_FANOUT_TIMEOUT_MS was created after
PR #3285 recorded "outcome=timed_out exitCode=null at exactly the 15000ms probe
bound while every other lane passed the same commit", and calls that "a bound
sized for the wrong class, not a slow machine". Our failure is that case
verbatim, so both sites move to the class norm rather than to a bigger number.
The same class also failed on `next` itself 21 hours earlier -- run 32608945654,
windows-latest/24 shard 1/3, `plan touching only src/ in a submodule project
keeps worktree isolation ENABLED` -- where tests/worktree-safety.test.cjs:5845
`runGate` fans out to `git config --file .gitmodules` under a hardcoded 30000.
Fixed too, since it is a defect in the tree regardless of which branch surfaced
it.
A survey of the whole tests/ tree found the same class-mismatch at further
bash fan-out sites bound under 60000ms, and the maintainer approved sweeping
them rather than leaving them latent to surface the same way one at a time. 16
fan-out sites across 16 files now use the class norm.
The sweep is class-correctness, not raising numbers until things pass. Sites
were moved ONLY where the bash body demonstrably spawns something (git, node,
npm, a CLI); self-contained shell snippets were left where they are, and are
listed as deliberately unchanged: pure if/printf bodies (copilot-install), pure
array/case builtins (code-review-pipeline-regression:638), a documented
pure-shell gsd_run stub (host-integration), single-process hook calls
(workflow-guard:222/271/302), and a deliberately tight 5000ms fast-check hook
(gsd-write-guard.property). Nothing was lowered. process-seam.test.cjs:513
(literal 300) is untouched on purpose -- it tests timeout BEHAVIOR, so raising
it would destroy what it asserts.
Shared file-level constants were the trap here, and were handled per file rather
than by redefinition: GIT_TIMEOUT_MS has ~15 users in git-base-branch and only 1
is a fan-out; WORKTREE_TIMEOUT_MS has 16 users in worktree.test.cjs and 3 are;
PROBE_TIMEOUT_MS has several in three more files. In each the CALL SITE was
changed and the constant left alone, so no single-plumbing-call site silently
inherited a 60s bound. The one exception is hooks-opt-in.test.cjs, where
HOOK_TIMEOUT_MS has exactly one consumer -- spawnHook, the fan-out itself -- so
redefining it is identical in effect and reads better.
Only two of these sites have actually been observed failing. The rest cite that
shared class and those two run ids rather than inventing evidence of their own.
Co-authored-by: sim <sim@local>
467 lines
22 KiB
JavaScript
467 lines
22 KiB
JavaScript
// docs-guard-exempt: opencode.ai/docs/... is an external URL citation in comments, not a repo path.
|
|
'use strict';
|
|
|
|
/**
|
|
* Regression coverage for #2329: OpenCode install target writes slash
|
|
* commands to `command/` (singular); OpenCode discovers them from
|
|
* `commands/` (plural), so none of the ~71 `/gsd-*` commands appear in the
|
|
* OpenCode TUI.
|
|
*
|
|
* Per OpenCode's own docs (opencode.ai/docs/commands/), the documented
|
|
* discovery directories are the plural `commands/` (global
|
|
* `~/.config/opencode/commands/`, per-project `.opencode/commands/`).
|
|
* OpenCode ALSO accepts singular names for backwards compatibility per its
|
|
* config docs, but the reporter empirically confirmed on OpenCode 1.17.13
|
|
* that `command/` (what GSD currently writes) is NOT discovered and that
|
|
* `mv command commands` fixes it. These tests assert only what GSD
|
|
* controls: where GSD writes its command files.
|
|
*
|
|
* Four sites must agree (Generative Fix Divergence guard, repo rule):
|
|
* - capabilities/opencode/capability.json:28 (global artifactLayout commands.destSubpath)
|
|
* - capabilities/opencode/capability.json:46 (local artifactLayout commands.destSubpath)
|
|
* - capabilities/opencode/capability.json:91 (hostBehaviors.flatCommandDir)
|
|
* - bin/install.js:9352 (writeManifest's separate hardcoded
|
|
* `manifest.files['command/' + file]` literal)
|
|
*
|
|
* See also tests/runtime-artifact-layout-descriptor-drive.test.cjs, whose
|
|
* GOLDEN table was updated in lockstep with this file (opencode/global and
|
|
* opencode/local destSubpath entries) — that is the canonical descriptor-
|
|
* layer pin; this file covers the full install → manifest → migration
|
|
* behavior end to end.
|
|
*/
|
|
|
|
const { describe, test } = require('node:test');
|
|
const assert = require('node:assert/strict');
|
|
const fs = require('node:fs');
|
|
const path = require('node:path');
|
|
const { runNode } = require('./helpers/process-seam.cjs');
|
|
|
|
const {
|
|
runMinimalInstall,
|
|
installerEnv,
|
|
INSTALL_SCRIPT,
|
|
} = require('./helpers/install-shared.cjs');
|
|
// #3145: class-norm timeout, not a per-suite value — see helpers/timeouts.cjs.
|
|
const { INSTALL_TIMEOUT_MS } = require('./helpers/timeouts.cjs');
|
|
const { cleanup } = require('./helpers.cjs');
|
|
const {
|
|
resolveRuntimeArtifactLayout,
|
|
} = require('../gsd-core/bin/lib/runtime-artifact-layout.cjs');
|
|
|
|
const CAPABILITY_PATH = path.join(__dirname, '..', 'capabilities', 'opencode', 'capability.json');
|
|
const EXPECTED_COMMAND_DIR = 'commands';
|
|
|
|
/** Re-run the installer against an EXISTING configDir/root to simulate an
|
|
* upgrade/reapply pass (the installer runs its migration planner on every
|
|
* invocation — see bin/install.js installAllRuntimes -> install() ->
|
|
* runInstallerMigrations, unconditional, not gated on first-install).
|
|
* #3547 — `configDir` is the runtime's REAL global home (<root>/<globalSuffix>),
|
|
* the same shape runMinimalInstall now installs into; reinstalling into the
|
|
* bare <root> would target a different config home and never see the
|
|
* fabricated legacy state. */
|
|
function reinstallOpencode(root, configDir = null, scope = 'global') {
|
|
const args = [INSTALL_SCRIPT, '--opencode'];
|
|
let cwd = process.cwd();
|
|
if (scope === 'global') {
|
|
args.push('--global', '--config-dir', configDir || root);
|
|
} else {
|
|
args.push('--local');
|
|
cwd = root;
|
|
}
|
|
const r = runNode(args, {
|
|
cwd,
|
|
env: installerEnv({ HOME: root, USERPROFILE: root }),
|
|
timeoutMs: INSTALL_TIMEOUT_MS,
|
|
});
|
|
return { status: r.exitCode, stdout: r.stdout, stderr: r.stderr };
|
|
}
|
|
|
|
function gsdMdFiles(dir) {
|
|
if (!fs.existsSync(dir)) return [];
|
|
return fs.readdirSync(dir).filter((f) => f.startsWith('gsd-') && f.endsWith('.md'));
|
|
}
|
|
|
|
/**
|
|
* #2329: fabricate a pre-fix "legacy" OpenCode install fixture.
|
|
*
|
|
* Under the FIXED installer, a fresh install lands its command files
|
|
* straight into commands/ (plural) and never creates command/ (singular) —
|
|
* that is the fix working correctly. So the pre-fix "existing install with a
|
|
* populated command/ dir" starting state a real upgrading user has can no
|
|
* longer be reproduced by simply calling the installer once (as a prior
|
|
* version of these tests assumed); it must be fabricated by hand-rewriting a
|
|
* fresh install's output into the shape the OLD, buggy installer actually
|
|
* left on disk.
|
|
*
|
|
* The migration under test (_migrateLegacyOpencodeCommandDir in
|
|
* src/install-engine.cts) only deletes a command/<file> entry when
|
|
* classifyArtifact() proves it GSD-managed via gsd-file-manifest.json (key
|
|
* `command/<file>` present, hash matches or was locally modified — see
|
|
* installerMigrations.classifyArtifact). A legacyDir populated with files but
|
|
* no matching manifest entries would classify as 'unknown' and never be
|
|
* touched, silently turning the migration tests into no-ops. So this helper
|
|
* also rewrites the manifest's `commands/<file>` keys to `command/<file>`
|
|
* (matching the OLD writeManifest's opencodeCommandDir-prefix behavior)
|
|
* alongside physically moving the files, so the fabricated state is exactly
|
|
* what a pre-fix install would have left: files AND a manifest that proves
|
|
* GSD manages them at the legacy path.
|
|
*
|
|
* @param {string} configDir
|
|
* @param {object} [opts]
|
|
* @param {boolean} [opts.keepPluralDir=false] - when true, leaves the
|
|
* (now-empty) commands/ dir in place instead of removing it. Used by the
|
|
* both-dirs-exist scenario, which separately seeds commands/ with
|
|
* unrelated content after calling this helper.
|
|
* @returns {{legacyDir:string, pluralDir:string, manifestPath:string, movedFiles:string[]}}
|
|
*/
|
|
function fabricateLegacyOpencodeCommandDir(configDir, opts = {}) {
|
|
const { keepPluralDir = false } = opts;
|
|
const legacyDir = path.join(configDir, 'command');
|
|
const pluralDir = path.join(configDir, 'commands');
|
|
const manifestPath = path.join(configDir, 'gsd-file-manifest.json');
|
|
|
|
const movedFiles = gsdMdFiles(pluralDir);
|
|
assert.ok(
|
|
movedFiles.length >= 60,
|
|
`fabricateLegacyOpencodeCommandDir: expected a fresh install to have ` +
|
|
`populated >=60 gsd-*.md files under ${pluralDir} before fabrication, got ${movedFiles.length}`
|
|
);
|
|
|
|
fs.mkdirSync(legacyDir, { recursive: true });
|
|
for (const file of movedFiles) {
|
|
fs.renameSync(path.join(pluralDir, file), path.join(legacyDir, file));
|
|
}
|
|
if (!keepPluralDir && fs.existsSync(pluralDir) && fs.readdirSync(pluralDir).length === 0) {
|
|
fs.rmdirSync(pluralDir);
|
|
}
|
|
|
|
const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
|
|
for (const file of movedFiles) {
|
|
const commandsKey = `commands/${file}`;
|
|
const legacyKey = `command/${file}`;
|
|
assert.ok(
|
|
Object.prototype.hasOwnProperty.call(manifest.files, commandsKey),
|
|
`fabricateLegacyOpencodeCommandDir: manifest is missing expected key ${commandsKey} — ` +
|
|
'cannot fabricate a manifest-proven legacy fixture'
|
|
);
|
|
manifest.files[legacyKey] = manifest.files[commandsKey];
|
|
delete manifest.files[commandsKey];
|
|
}
|
|
fs.writeFileSync(manifestPath, JSON.stringify(manifest, null, 2), 'utf8');
|
|
|
|
return { legacyDir, pluralDir, manifestPath, movedFiles };
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// 1 + 2. Command files land under commands/ (plural); command/ (singular)
|
|
// is never created — both scopes.
|
|
// ---------------------------------------------------------------------------
|
|
|
|
describe('#2329: opencode install writes commands to commands/ (plural), not command/ (singular)', () => {
|
|
for (const scope of ['global', 'local']) {
|
|
test(`opencode --${scope}: command files land under commands/, and command/ does NOT exist`, (t) => {
|
|
const { configDir, root } = runMinimalInstall({ runtime: 'opencode', scope });
|
|
t.after(() => cleanup(root));
|
|
|
|
const pluralDir = path.join(configDir, 'commands');
|
|
const singularDir = path.join(configDir, 'command');
|
|
|
|
const pluralFiles = gsdMdFiles(pluralDir);
|
|
assert.ok(
|
|
pluralFiles.length >= 60,
|
|
`expected >=60 gsd-*.md command files under ${pluralDir}, got ${pluralFiles.length}. ` +
|
|
`OpenCode discovers commands from commands/ (plural) per opencode.ai/docs/commands/.`
|
|
);
|
|
assert.ok(
|
|
pluralFiles.includes('gsd-help.md'),
|
|
`gsd-help.md must exist under ${pluralDir}`
|
|
);
|
|
|
|
assert.ok(
|
|
!fs.existsSync(singularDir),
|
|
`${singularDir} must NOT exist — OpenCode does not discover commands from the singular ` +
|
|
'command/ dir (empirically confirmed on OpenCode 1.17.13, issue #2329)'
|
|
);
|
|
});
|
|
}
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// 3. Manifest records files under the commands/ prefix, not command/.
|
|
// ---------------------------------------------------------------------------
|
|
|
|
describe('#2329: opencode install manifest records the commands/ prefix', () => {
|
|
test('manifest.files keys use "commands/" prefix; none use "command/"', (t) => {
|
|
const { manifest, root } = runMinimalInstall({ runtime: 'opencode', scope: 'global' });
|
|
t.after(() => cleanup(root));
|
|
|
|
assert.ok(manifest && manifest.files, 'manifest.files must exist');
|
|
const keys = Object.keys(manifest.files);
|
|
|
|
const pluralKeys = keys.filter((k) => k.startsWith('commands/'));
|
|
assert.ok(
|
|
pluralKeys.length >= 60,
|
|
`expected >=60 manifest keys under "commands/", got ${pluralKeys.length}. ` +
|
|
`Sample keys: ${keys.slice(0, 5).join(', ')}`
|
|
);
|
|
|
|
const singularKeys = keys.filter((k) => k.startsWith('command/'));
|
|
assert.deepStrictEqual(
|
|
singularKeys, [],
|
|
'no manifest key may use the old singular "command/" prefix — ' +
|
|
'this is the bin/install.js:9352 writeManifest hardcode this issue must fix'
|
|
);
|
|
});
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// 4. Single source of truth: the two destSubpath declarations,
|
|
// hostBehaviors.flatCommandDir, and the descriptor-driven layout resolver
|
|
// all agree on "commands" — and the manifest prefix is DERIVED from the
|
|
// descriptor, not a separate hardcoded literal (Generative Fix
|
|
// Divergence guard).
|
|
// ---------------------------------------------------------------------------
|
|
|
|
describe('#2329: opencode command-dir declarations are a single source of truth', () => {
|
|
test('capability.json global/local artifactLayout commands.destSubpath === "commands"', () => {
|
|
const cap = JSON.parse(fs.readFileSync(CAPABILITY_PATH, 'utf8'));
|
|
const globalCommands = cap.runtime.artifactLayout.global.find((k) => k.kind === 'commands');
|
|
const localCommands = cap.runtime.artifactLayout.local.find((k) => k.kind === 'commands');
|
|
|
|
assert.ok(globalCommands, 'capability.json global artifactLayout must have a commands kind');
|
|
assert.ok(localCommands, 'capability.json local artifactLayout must have a commands kind');
|
|
|
|
assert.strictEqual(
|
|
globalCommands.destSubpath, EXPECTED_COMMAND_DIR,
|
|
'capabilities/opencode/capability.json global commands.destSubpath must be "commands" (#2329)'
|
|
);
|
|
assert.strictEqual(
|
|
localCommands.destSubpath, EXPECTED_COMMAND_DIR,
|
|
'capabilities/opencode/capability.json local commands.destSubpath must be "commands" (#2329)'
|
|
);
|
|
});
|
|
|
|
test('capability.json hostBehaviors.flatCommandDir === "commands"', () => {
|
|
const cap = JSON.parse(fs.readFileSync(CAPABILITY_PATH, 'utf8'));
|
|
assert.strictEqual(
|
|
cap.runtime.hostBehaviors.flatCommandDir, EXPECTED_COMMAND_DIR,
|
|
'capabilities/opencode/capability.json runtime.hostBehaviors.flatCommandDir must be "commands" (#2329)'
|
|
);
|
|
});
|
|
|
|
test('resolveRuntimeArtifactLayout("opencode", ...) commands kind destSubpath === "commands" for both scopes', () => {
|
|
for (const scope of ['global', 'local']) {
|
|
const layout = resolveRuntimeArtifactLayout('opencode', '/tmp/fake-opencode-config-dir', scope);
|
|
const commandsKind = layout.kinds.find((k) => k.kind === 'commands');
|
|
assert.ok(commandsKind, `opencode/${scope} layout must have a commands kind`);
|
|
assert.strictEqual(
|
|
commandsKind.destSubpath, EXPECTED_COMMAND_DIR,
|
|
`resolveRuntimeArtifactLayout('opencode', dir, '${scope}').kinds commands.destSubpath must be "commands" (#2329)`
|
|
);
|
|
}
|
|
});
|
|
|
|
test('installed manifest prefix is derived from the descriptor value, not a separate hardcoded literal (bin/install.js:9352 guard)', (t) => {
|
|
const cap = JSON.parse(fs.readFileSync(CAPABILITY_PATH, 'utf8'));
|
|
const globalCommands = cap.runtime.artifactLayout.global.find((k) => k.kind === 'commands');
|
|
const descriptorPrefix = globalCommands.destSubpath;
|
|
|
|
const { manifest, root } = runMinimalInstall({ runtime: 'opencode', scope: 'global' });
|
|
t.after(() => cleanup(root));
|
|
|
|
const keys = Object.keys(manifest.files);
|
|
const descriptorPrefixKeys = keys.filter((k) => k.split('/')[0] === descriptorPrefix);
|
|
assert.ok(
|
|
descriptorPrefixKeys.length >= 60,
|
|
`manifest must record command files under the descriptor's "${descriptorPrefix}/" prefix ` +
|
|
`(read from capability.json), got ${descriptorPrefixKeys.length} matching keys. This proves ` +
|
|
'bin/install.js:9352 derives its manifest prefix from the same descriptor value instead of a ' +
|
|
'separately-hardcoded literal — a divergence would silently break the manifest even after the ' +
|
|
'capability.json descriptor is fixed.'
|
|
);
|
|
});
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// 5. Migration: an existing install with a populated command/ dir is
|
|
// migrated cleanly on upgrade/reapply — without destroying user content.
|
|
// ---------------------------------------------------------------------------
|
|
|
|
describe('#2329: upgrading an install with an orphaned command/ dir migrates it to commands/ safely', () => {
|
|
test('reinstall relocates all gsd-owned files from command/ into commands/ and removes the now-empty orphan', (t) => {
|
|
// Under the FIXED source, a first install writes straight into commands/
|
|
// (plural) — that's the fix working. To exercise the upgrade/migration
|
|
// path, fabricate the pre-fix "legacy" starting state a real upgrading
|
|
// user has (populated command/ dir + a manifest that proves GSD manages
|
|
// those files at the legacy path) by hand-rewriting a fresh install's
|
|
// output — see fabricateLegacyOpencodeCommandDir's doc comment.
|
|
const { configDir, root } = runMinimalInstall({ runtime: 'opencode', scope: 'global' });
|
|
t.after(() => cleanup(root));
|
|
|
|
const legacyDir = path.join(configDir, 'command');
|
|
const pluralDir = path.join(configDir, 'commands');
|
|
|
|
const { movedFiles } = fabricateLegacyOpencodeCommandDir(configDir);
|
|
const filesBefore = new Set(movedFiles);
|
|
assert.ok(filesBefore.size >= 60, `sanity: expected >=60 gsd command files from the first install, got ${filesBefore.size}`);
|
|
// Sanity: the migration must genuinely FIRE against this fixture, not
|
|
// no-op — confirm the legacy dir is populated and commands/ is gone
|
|
// before the reinstall runs.
|
|
assert.ok(gsdMdFiles(legacyDir).length >= 60, 'sanity: legacyDir must be populated before reinstall');
|
|
assert.ok(!fs.existsSync(pluralDir), 'sanity: pluralDir must not exist before reinstall (fabricated pre-fix state)');
|
|
|
|
const result = reinstallOpencode(root, configDir, 'global');
|
|
assert.strictEqual(
|
|
result.status, 0,
|
|
`reinstall (upgrade) must exit 0\nstdout: ${result.stdout}\nstderr: ${result.stderr}`
|
|
);
|
|
|
|
const filesAfter = new Set(gsdMdFiles(pluralDir));
|
|
assert.deepStrictEqual(
|
|
[...filesAfter].sort(), [...filesBefore].sort(),
|
|
'after the upgrade reinstall, commands/ must contain the exact same gsd-* command file set ' +
|
|
'that was previously under command/'
|
|
);
|
|
|
|
assert.ok(
|
|
!fs.existsSync(legacyDir),
|
|
'the orphaned command/ dir must be removed once fully migrated — it held only GSD-owned files ' +
|
|
'(all present, unmodified, in the manifest), so removing it is safe and expected'
|
|
);
|
|
});
|
|
|
|
test('an unrelated user file placed inside command/ survives the migration (not destroyed)', (t) => {
|
|
const { configDir, root } = runMinimalInstall({ runtime: 'opencode', scope: 'global' });
|
|
t.after(() => cleanup(root));
|
|
|
|
const legacyDir = path.join(configDir, 'command');
|
|
const pluralDir = path.join(configDir, 'commands');
|
|
|
|
fabricateLegacyOpencodeCommandDir(configDir);
|
|
// Sanity: the migration must genuinely fire against this fixture.
|
|
assert.ok(gsdMdFiles(legacyDir).length >= 60, 'sanity: legacyDir must be populated before reinstall');
|
|
assert.ok(!fs.existsSync(pluralDir), 'sanity: pluralDir must not exist before reinstall (fabricated pre-fix state)');
|
|
|
|
const userContent = 'precious user notes — not a GSD-managed file\n';
|
|
const userFileLegacy = path.join(legacyDir, 'my-notes.md');
|
|
fs.writeFileSync(userFileLegacy, userContent, 'utf8');
|
|
|
|
const result = reinstallOpencode(root, configDir, 'global');
|
|
assert.strictEqual(
|
|
result.status, 0,
|
|
`reinstall (upgrade) must exit 0\nstdout: ${result.stdout}\nstderr: ${result.stderr}`
|
|
);
|
|
|
|
// The migration must actually have happened (commands/ now populated) —
|
|
// otherwise "the user file is still where it was" would be a vacuous pass.
|
|
assert.ok(
|
|
gsdMdFiles(pluralDir).length >= 60,
|
|
`commands/ must contain the migrated gsd-* command set after the upgrade, got ` +
|
|
`${gsdMdFiles(pluralDir).length}`
|
|
);
|
|
|
|
// The unrelated file is not a GSD-managed artifact (no manifest entry —
|
|
// it never matched the "gsd-*.md" filter GSD tracks), so it must never
|
|
// be silently deleted. It may legitimately end up EITHER left in place
|
|
// in the (now GSD-file-free) command/ dir, OR carried over into
|
|
// commands/ alongside the migrated files — either is safe; deletion is
|
|
// not.
|
|
const userFilePlural = path.join(pluralDir, 'my-notes.md');
|
|
const survivedInLegacy = fs.existsSync(userFileLegacy);
|
|
const survivedInPlural = fs.existsSync(userFilePlural);
|
|
assert.ok(
|
|
survivedInLegacy || survivedInPlural,
|
|
'unrelated user file my-notes.md must survive the migration (either in place under command/, ' +
|
|
'or carried over to commands/) — it must NOT be deleted as collateral damage'
|
|
);
|
|
const survivingPath = survivedInLegacy ? userFileLegacy : userFilePlural;
|
|
assert.strictEqual(
|
|
fs.readFileSync(survivingPath, 'utf8'), userContent,
|
|
'unrelated user file content must be byte-identical after the migration'
|
|
);
|
|
});
|
|
|
|
test('both-dirs-exist case: pre-existing unrelated content already in commands/ is not clobbered while command/ is still relocated', (t) => {
|
|
const { configDir, root } = runMinimalInstall({ runtime: 'opencode', scope: 'global' });
|
|
t.after(() => cleanup(root));
|
|
|
|
const legacyDir = path.join(configDir, 'command');
|
|
const pluralDir = path.join(configDir, 'commands');
|
|
|
|
fabricateLegacyOpencodeCommandDir(configDir, { keepPluralDir: true });
|
|
|
|
// Simulate a commands/ dir that already independently exists (e.g. the
|
|
// user manually created it while working around #2329, or a partial
|
|
// prior migration attempt left it behind) with content GSD does not own.
|
|
fs.mkdirSync(pluralDir, { recursive: true });
|
|
const preexistingPath = path.join(pluralDir, 'unrelated-project-doc.md');
|
|
const preexistingContent = 'unrelated content that already lived in commands/\n';
|
|
fs.writeFileSync(preexistingPath, preexistingContent, 'utf8');
|
|
|
|
const filesBefore = new Set(gsdMdFiles(legacyDir));
|
|
assert.ok(filesBefore.size >= 60, `sanity: expected >=60 gsd command files in command/, got ${filesBefore.size}`);
|
|
// Sanity: the migration must genuinely fire against this fixture — the
|
|
// manifest must actually prove ownership of the legacy files (not just
|
|
// their physical presence), otherwise classifyArtifact would treat them
|
|
// as 'unknown' and the migration would silently no-op.
|
|
const manifestBefore = JSON.parse(fs.readFileSync(path.join(configDir, 'gsd-file-manifest.json'), 'utf8'));
|
|
const legacyManifestKeys = Object.keys(manifestBefore.files).filter((k) => k.startsWith('command/'));
|
|
assert.ok(
|
|
legacyManifestKeys.length >= 60,
|
|
`sanity: manifest must record >=60 "command/" keys before reinstall, got ${legacyManifestKeys.length}`
|
|
);
|
|
|
|
const result = reinstallOpencode(root, configDir, 'global');
|
|
assert.strictEqual(
|
|
result.status, 0,
|
|
`reinstall (upgrade) must exit 0\nstdout: ${result.stdout}\nstderr: ${result.stderr}`
|
|
);
|
|
|
|
// Pre-existing unrelated content in commands/ must survive untouched.
|
|
assert.ok(
|
|
fs.existsSync(preexistingPath),
|
|
'pre-existing unrelated-project-doc.md in commands/ must not be deleted by the migration'
|
|
);
|
|
assert.strictEqual(
|
|
fs.readFileSync(preexistingPath, 'utf8'), preexistingContent,
|
|
'pre-existing unrelated file content in commands/ must be untouched'
|
|
);
|
|
|
|
// All gsd command files must now be present in commands/ too.
|
|
const filesAfter = new Set(gsdMdFiles(pluralDir));
|
|
for (const f of filesBefore) {
|
|
assert.ok(filesAfter.has(f), `${f} must be present in commands/ after the upgrade (was in command/ before)`);
|
|
}
|
|
});
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// 6. No collateral: another flat-command-dir runtime (Kilo) is unaffected.
|
|
// ---------------------------------------------------------------------------
|
|
//
|
|
// NOTE: this test is expected to PASS both before and after the #2329 fix —
|
|
// it is a regression guard against the fix accidentally widening scope to
|
|
// Kilo (which also uses a flat, singular `command/` dir per its own
|
|
// capability.json and is NOT part of this issue), not a red-phase test for
|
|
// the bug itself.
|
|
|
|
describe('#2329: the fix must not affect other runtimes\' command output directories', () => {
|
|
test('kilo global install still writes to command/ (singular) — unaffected by the opencode-only fix', (t) => {
|
|
const { configDir, root } = runMinimalInstall({ runtime: 'kilo', scope: 'global' });
|
|
t.after(() => cleanup(root));
|
|
|
|
const singularDir = path.join(configDir, 'command');
|
|
const pluralDir = path.join(configDir, 'commands');
|
|
|
|
assert.ok(
|
|
gsdMdFiles(singularDir).length >= 60,
|
|
`kilo must still write its command files to the singular command/ dir, got ` +
|
|
`${gsdMdFiles(singularDir).length} files under ${singularDir}`
|
|
);
|
|
assert.ok(
|
|
!fs.existsSync(pluralDir),
|
|
`kilo must NOT gain a commands/ (plural) dir as collateral from the opencode-only #2329 fix`
|
|
);
|
|
});
|
|
});
|