* test(#2470): failing-first — pi extension must satisfy pi's auto-discovery filter pi auto-discovers extensions/ entries through isExtensionFile(), which accepts only .ts and .js. GSD installs its extension as gsd.cjs, so pi silently skips it: no /gsd command, no error, no log line. Encodes pi's discovery PREDICATE rather than a literal filename, so the contract keeps holding across future renames, and adds the migration-006 test matrix for retiring the stale gsd.cjs left in pre-fix installs. Red until the fix lands. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * fix(#2470): install pi's extension as gsd.js so pi actually discovers it pi auto-discovers extensions/ entries via isExtensionFile(), which accepts only .ts and .js and skips everything else silently. capabilities/pi declared the dest as gsd.cjs, so the extension installed correctly and was then ignored forever: no /gsd command, no error, no log line. Install it as gsd.js. The in-repo source stays pi/gsd.cjs — tests require() it directly and .cjs is unambiguous CommonJS; only the installed name has to satisfy pi, and pi loads accepted files through jiti, which handles CJS and ESM alike. (The reporter's premise that ~/.pi/agent/package.json declares "type":"commonjs" does not hold — pi never writes that file.) Renaming an installed artifact requires a migration record, so add 006 to retire the stale gsd.cjs from pre-fix installs; without it the old path drops out of the manifest and uninstall can never remove it. The migration plans nothing for an unmanifested gsd.cjs: emitting remove-managed there would have the executor downgrade it to preserve-user and mark it blocked, failing the install for anyone who hand-placed their own file. Also pins body-parser >=2.3.0 (GHSA-v422-hmwv-36x6). The advisory reaches the production tree transitively via the Claude Agent SDK and fails the npm-integrity gate, blocking any PR; pinned via the existing overrides idiom. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * fix(#2470): address orthogonal review findings + register migration checksum Code review: - pi/gsd.cjs's install docstring still told readers to copy the file to extensions/gsd.cjs — the exact silently-broken state this PR fixes. Anyone following it recreated the bug. - Two stale extensions/gsd.cjs comments in install-minimal-hooks.test.cjs. Security review: - _installNativePluginIfDeclared confined nativePlugin.dir but joined nativePlugin.file onto the validated directory unchecked, so a descriptor whose file carried .., an absolute path, or a NUL byte would have written outside configHome. Not reachable in a shipped build (descriptors are first-party and compiled into the capability registry), but file is exactly the field this PR changes. Confine the full dest path instead; for a well-formed descriptor this resolves identically to the previous mkdir(dir) + join(dir, file). Covered by four new write-confinement tests. Also register migration 006 in the #670 EXPECTED_CHECKSUMS baseline — shipped migration bodies are locked to a committed checksum and a new migration fails CI until it is listed. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * fix(#2470): never dereference a symlinked managed path when snapshotting fs.copyFileSync follows symlinks, so a managed path replaced by a link had the REFERENT's bytes copied into the migration journal's rollback and backup trees — a gsd.cjs symlinked at a private key would land that key's contents under gsd-migration-journal/. Deletion was already safe (fs.rmSync unlinks the link, never the target); the copy was not. Nothing GSD installs is ever a symlink, so the faithful snapshot of a symlinked managed path is the link itself. copyPreservingSymlink recreates it, which keeps rollback fidelity (restore re-creates the same link) while never reading the referent. Scoped the pre-delete to the symlink branch only, so the regular-file path keeps copyFileSync's overwrite-in-place and a mid-restore failure cannot destroy the destination. The restore-side existence check moves to lstat, since existsSync follows a link whose target is gone and would silently skip the restore. This lives in the engine all six migrations share, so 000-005 are hardened too. Also regenerates the pi golden-parity hash: correcting pi/gsd.cjs's own install docstring changes the extension's content, which the golden suite caught. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * fix(#2470): symlink-preserve the in-apply failure-recovery restore too The previous commit routed three copy sites through copyPreservingSymlink but missed a fourth: the catch block inside applyInstallerMigrationPlan, which replays rollback snapshots taken earlier in the SAME apply attempt. Those snapshots are symlinks precisely because of that commit, so the raw copyFileSync there dereferenced them and wrote the referent's bytes to the LIVE install path — worse than the journal-tree leak it was meant to fix, since it is user-visible and at a predictable location. Verified by experiment rather than assertion: with the pre-fix line restored, the managed path comes back as a REGULAR FILE containing the referent's bytes; with the fix it comes back as a symlink and the bytes appear nowhere. The accompanying test injects the failure by letting the delete succeed and then throwing once, modelling a later step failing after the delete. That ordering is load-bearing — an earlier draft injected before the delete, which leaves the live path in place, so the pre-fix copyFileSync hit a same-file collision and threw instead of leaking. That draft passed against the bug it was written to catch; this one fails against it. Adds the missing rollback() coverage as well: a restored symlinked managed path must come back as a link pointing at its original target. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * test(#2470): read the backup location from the journal, not the plan The new backup-content assertion read backupRelPath off result.plan.actions, where it is always null: the planner reserves the field and apply chooses the concrete location, recording it in the journal. The assertion therefore failed on "backup path must be recorded for the user" rather than on anything about the behavior it was written to check. Read it from the journal, which is the authoritative record. Verified by executing all four new test bodies in-process against the built engine — the backup file exists and holds the locally patched content. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * chore(#2470): backfill changeset pr number to 2478 * chore(#2470): backfill changeset pr number to 2478 --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
2
tests/fixtures/golden-install-parity/pi.json
vendored
2
tests/fixtures/golden-install-parity/pi.json
vendored
@@ -1,7 +1,7 @@
|
||||
{
|
||||
".gsd-profile": "0e716a5fef4e6dc1",
|
||||
".gsd/defaults.json": "615261cfd3ae1c96",
|
||||
"extensions/gsd.cjs": "619cec0af9cfdadf",
|
||||
"extensions/gsd.js": "976c6546391caf8f",
|
||||
"gsd-core/.gsd-runtime": "94e95f0bb38f8e0f",
|
||||
"gsd-core/VERSION": "ef0deccd81a6723c",
|
||||
"gsd-core/bin/check-latest-version.cjs": "e4a224058c8f4d74",
|
||||
|
||||
2
tests/fixtures/install-tree/pi.json
vendored
2
tests/fixtures/install-tree/pi.json
vendored
@@ -1,7 +1,7 @@
|
||||
[
|
||||
".gsd-profile",
|
||||
".gsd/defaults.json",
|
||||
"extensions/gsd.cjs",
|
||||
"extensions/gsd.js",
|
||||
"gsd-core/.gsd-runtime",
|
||||
"gsd-core/VERSION",
|
||||
"gsd-core/bin/check-latest-version.cjs",
|
||||
|
||||
@@ -678,7 +678,7 @@ describe('#1755: .sh hooks are copied and executable after install', () => {
|
||||
// hooksSurface:'none', but each has a native plugin adapter that spawns the
|
||||
// staged hooks/*.js scripts as subprocesses (OpenCode's #1914
|
||||
// plugins/gsd-core.js via OpenCode's event bus; pi's #2102 Stage 2 pi/gsd.cjs
|
||||
// → extensions/gsd.cjs via pi.on(...) bridges; Kilo's plugins/gsd-core.js,
|
||||
// → extensions/gsd.js via pi.on(...) bridges; Kilo's plugins/gsd-core.js,
|
||||
// byte-identical to OpenCode's) — so for all three, the hooks are LIVE and
|
||||
// must keep being copied. ZCode has no plugin surface at all, so its staged
|
||||
// hooks are genuinely dead: that is the case #1821's fix removes. (#1821
|
||||
@@ -766,7 +766,7 @@ describe('#1821/#2305: ZCode receives no dead hook files; Kilo/OpenCode/Claude k
|
||||
});
|
||||
|
||||
// pi ALSO declares hooksSurface:'none', but — like OpenCode — it is NOT a
|
||||
// dead-weight case: pi's native extension (pi/gsd.cjs → extensions/gsd.cjs)
|
||||
// dead-weight case: pi's native extension (pi/gsd.cjs → extensions/gsd.js)
|
||||
// spawns the staged hooks/*.js scripts as bounded subprocesses (session_start
|
||||
// → gsd-ensure-canonical-path.js, before_agent_start → gsd-workflow-guard.js,
|
||||
// session_before_compact → gsd-context-monitor.js — #2102 Stage 2), and its
|
||||
@@ -775,8 +775,20 @@ describe('#1821/#2305: ZCode receives no dead hook files; Kilo/OpenCode/Claude k
|
||||
// pi (unlike Kilo/ZCode/Cursor/Cline/Trae/Copilot/Windsurf/Kimi) — pi is in
|
||||
// the OpenCode group, not the Kilo/ZCode group.
|
||||
test('pi --global install still copies hooks (spawned by the native extension) + hooks/lib/git-cmd.js + the extension itself', () => {
|
||||
// #2470: derive the extension filename from pi's own descriptor rather than
|
||||
// hardcoding it, and assert it satisfies pi's isExtensionFile() discovery
|
||||
// filter (.ts/.js only) — a dest pi cannot discover installs "successfully"
|
||||
// while /gsd never registers, which is exactly how this shipped broken.
|
||||
const piNativePlugin = JSON.parse(
|
||||
fs.readFileSync(path.join(__dirname, '..', 'capabilities', 'pi', 'capability.json'), 'utf8'),
|
||||
).runtime.hostBehaviors.nativePlugin;
|
||||
assert.ok(
|
||||
piNativePlugin.file.endsWith('.ts') || piNativePlugin.file.endsWith('.js'),
|
||||
`pi's installed extension "${piNativePlugin.file}" must end in .ts or .js — pi silently ` +
|
||||
'skips any other suffix during extensions/ auto-discovery (#2470)',
|
||||
);
|
||||
const { hookFiles, hooksLibExists, gitCmdExists, pluginExists } = installAndCollect('pi', {
|
||||
pluginRelPath: path.join('extensions', 'gsd.cjs'),
|
||||
pluginRelPath: path.join(piNativePlugin.dir, piNativePlugin.file),
|
||||
});
|
||||
const basenames = hookFiles.map((f) => path.basename(f));
|
||||
for (const expected of ['gsd-ensure-canonical-path.js', 'gsd-workflow-guard.js', 'gsd-context-monitor.js']) {
|
||||
@@ -787,7 +799,10 @@ describe('#1821/#2305: ZCode receives no dead hook files; Kilo/OpenCode/Claude k
|
||||
}
|
||||
assert.ok(hooksLibExists, 'pi install must create hooks/lib/');
|
||||
assert.ok(gitCmdExists, 'pi install must copy hooks/lib/git-cmd.js (the /gsd command tokenizer)');
|
||||
assert.ok(pluginExists, 'pi install must install extensions/gsd.cjs (the native-extension hook bridge)');
|
||||
assert.ok(
|
||||
pluginExists,
|
||||
`pi install must install ${piNativePlugin.dir}/${piNativePlugin.file} (the native-extension hook bridge)`,
|
||||
);
|
||||
});
|
||||
|
||||
// Positive control: guards against over-exclusion breaking runtimes that
|
||||
|
||||
@@ -2964,3 +2964,104 @@ describe('#2393: GSD_ALLOW_SYMLINKED_DEST opt-in for intentional symlinked-dest
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// _installNativePluginIfDeclared write-confinement (#2470)
|
||||
// ---------------------------------------------------------------------------
|
||||
//
|
||||
// The native-plugin copy previously confined only `nativePlugin.dir`, then
|
||||
// joined `nativePlugin.file` onto the validated directory unchecked. #2470
|
||||
// makes `file` a field we actively change (pi: gsd.cjs -> gsd.js), so the full
|
||||
// dest path is now confined. Descriptors are first-party and compiled into the
|
||||
// capability registry at build time, so this was never reachable in a shipped
|
||||
// build — these tests keep it that way.
|
||||
|
||||
describe('_installNativePluginIfDeclared write-confinement', () => {
|
||||
const engine = require('../gsd-core/bin/lib/install-engine.cjs');
|
||||
|
||||
/** Build a src tree containing the declared plugin source. */
|
||||
function stageSource() {
|
||||
const src = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-np-src-'));
|
||||
const full = path.join(src, 'pi', 'gsd.cjs');
|
||||
fs.mkdirSync(path.dirname(full), { recursive: true });
|
||||
fs.writeFileSync(full, "'use strict';\n// plugin\n", 'utf8');
|
||||
return src;
|
||||
}
|
||||
|
||||
const behaviorsWith = (file) => ({
|
||||
nativePlugin: { dir: 'extensions', file, source: 'pi/gsd.cjs' },
|
||||
});
|
||||
|
||||
test('happy path: declared dir/file lands inside configDir', () => {
|
||||
const configDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-np-cfg-'));
|
||||
const src = stageSource();
|
||||
try {
|
||||
engine._installNativePluginIfDeclared('pi', configDir, behaviorsWith('gsd.js'), src);
|
||||
assert.ok(
|
||||
fs.existsSync(path.join(configDir, 'extensions', 'gsd.js')),
|
||||
'plugin should be copied to <configDir>/extensions/gsd.js',
|
||||
);
|
||||
} finally {
|
||||
cleanup(configDir);
|
||||
cleanup(src);
|
||||
}
|
||||
});
|
||||
|
||||
const ESCAPE_CASES = [
|
||||
['traversal', '../../evil.js'],
|
||||
['deep traversal', '../../../../../../tmp/evil.js'],
|
||||
['NUL byte', 'gsd\u0000.js'],
|
||||
];
|
||||
|
||||
for (const [label, file] of ESCAPE_CASES) {
|
||||
test(`escape rejected: nativePlugin.file with ${label} → throws`, () => {
|
||||
const configDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-np-esc-'));
|
||||
const src = stageSource();
|
||||
try {
|
||||
assert.throws(
|
||||
() => engine._installNativePluginIfDeclared('pi', configDir, behaviorsWith(file), src),
|
||||
/escap|strict subpath|configHome|NUL byte/i,
|
||||
`nativePlugin.file=${JSON.stringify(file)} must be rejected, not joined onto the validated dir`,
|
||||
);
|
||||
} finally {
|
||||
cleanup(configDir);
|
||||
cleanup(src);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
test('nothing is written outside configDir when file tries to escape', () => {
|
||||
const configDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-np-out-'));
|
||||
const outside = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-np-outside-'));
|
||||
const src = stageSource();
|
||||
try {
|
||||
const escapeFile = path.join('..', '..', path.basename(outside), 'pwned.js');
|
||||
assert.throws(
|
||||
() => engine._installNativePluginIfDeclared('pi', configDir, behaviorsWith(escapeFile), src),
|
||||
/escap|strict subpath|configHome/i,
|
||||
);
|
||||
assert.ok(
|
||||
!fs.existsSync(path.join(outside, 'pwned.js')),
|
||||
'nothing may be written outside configDir',
|
||||
);
|
||||
} finally {
|
||||
cleanup(configDir);
|
||||
cleanup(outside);
|
||||
cleanup(src);
|
||||
}
|
||||
});
|
||||
|
||||
test('missing source is a silent no-op (unchanged behavior)', () => {
|
||||
const configDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-np-nosrc-'));
|
||||
const src = fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-np-emptysrc-'));
|
||||
try {
|
||||
assert.doesNotThrow(() =>
|
||||
engine._installNativePluginIfDeclared('pi', configDir, behaviorsWith('gsd.js'), src),
|
||||
);
|
||||
assert.ok(!fs.existsSync(path.join(configDir, 'extensions', 'gsd.js')));
|
||||
} finally {
|
||||
cleanup(configDir);
|
||||
cleanup(src);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -292,9 +292,19 @@ function assertFreshInstallContract(runtime, targetDir) {
|
||||
// adversarial-review fix — hooksSurface:'none' no longer implies
|
||||
// skipSharedHooksInstall for pi, mirroring OpenCode), so hooks/ + the
|
||||
// git-cmd.js tokenizer helper ARE part of the artifact surface now.
|
||||
// #2470: the dest filename comes from pi's descriptor, and must satisfy
|
||||
// pi's isExtensionFile() auto-discovery filter (.ts/.js only) — otherwise
|
||||
// the file installs but pi never loads it and /gsd never registers.
|
||||
const piNativePlugin = JSON.parse(
|
||||
fs.readFileSync(path.join(__dirname, '..', 'capabilities', 'pi', 'capability.json'), 'utf8')
|
||||
).runtime.hostBehaviors.nativePlugin;
|
||||
assert.ok(
|
||||
fs.existsSync(path.join(targetDir, 'extensions', 'gsd.cjs')),
|
||||
`${runtime} should install the native extension file at extensions/gsd.cjs`
|
||||
piNativePlugin.file.endsWith('.ts') || piNativePlugin.file.endsWith('.js'),
|
||||
`${runtime}'s extension "${piNativePlugin.file}" must end in .ts or .js for pi to discover it (#2470)`
|
||||
);
|
||||
assert.ok(
|
||||
fs.existsSync(path.join(targetDir, piNativePlugin.dir, piNativePlugin.file)),
|
||||
`${runtime} should install the native extension file at ${piNativePlugin.dir}/${piNativePlugin.file}`
|
||||
);
|
||||
assert.ok(
|
||||
fs.existsSync(path.join(targetDir, 'hooks', 'gsd-ensure-canonical-path.js')),
|
||||
|
||||
231
tests/installer-migration-pi-extension-ext.test.cjs
Normal file
231
tests/installer-migration-pi-extension-ext.test.cjs
Normal file
@@ -0,0 +1,231 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* TDD tests for installer migration 006:
|
||||
* 2026-07-20-pi-extension-cjs-to-js (#2470)
|
||||
*
|
||||
* #2470 renamed pi's installed native extension from `extensions/gsd.cjs` to
|
||||
* `extensions/gsd.js`, because pi's own auto-discovery filter
|
||||
* (`isExtensionFile()` in @earendil-works/pi-coding-agent) accepts only `.ts`
|
||||
* and `.js` and silently skips everything else. Installs made before that fix
|
||||
* still carry the stale, permanently-inert `extensions/gsd.cjs`; the installer
|
||||
* writes the new `.js` alongside it and would otherwise orphan the old file
|
||||
* forever (it drops out of the manifest, so uninstall never removes it).
|
||||
*
|
||||
* This migration retires the stale copy. Coverage follows the matrix in
|
||||
* docs/installer-migrations.md#authoring-workflow:
|
||||
* 1. metadata / authoring-guard conformance
|
||||
* 2. stale file absent -> empty plan (idempotent, fresh installs)
|
||||
* 3. stale file managed-pristine -> remove-managed
|
||||
* 4. stale file managed-modified -> backup-and-remove (never silent delete)
|
||||
* 5. stale file unknown -> NO action (never remove unowned files)
|
||||
* 6. the replacement gsd.js and neighbouring user files are never touched
|
||||
* 7. runtime scoping: pi only
|
||||
*/
|
||||
|
||||
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 migration = require('../gsd-core/bin/lib/installer-migrations/006-pi-extension-cjs-to-js.cjs');
|
||||
|
||||
const {
|
||||
classifyArtifact: realClassifyArtifact,
|
||||
readInstallManifest,
|
||||
} = require('../gsd-core/bin/lib/installer-migrations.cjs');
|
||||
|
||||
const STALE_REL = 'extensions/gsd.cjs';
|
||||
const CURRENT_REL = 'extensions/gsd.js';
|
||||
|
||||
function createTempDir() {
|
||||
return fs.mkdtempSync(path.join(os.tmpdir(), 'gsd-migration-006-test-'));
|
||||
}
|
||||
|
||||
function cleanup(dir) {
|
||||
// eslint-disable-next-line local/no-raw-rmsync-in-tests -- local cleanup in migration test; no helpers import available
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
|
||||
function writeFile(root, relPath, content) {
|
||||
const fullPath = path.join(root, relPath);
|
||||
fs.mkdirSync(path.dirname(fullPath), { recursive: true });
|
||||
fs.writeFileSync(fullPath, content, 'utf8');
|
||||
}
|
||||
|
||||
function writeManifest(root, files) {
|
||||
fs.writeFileSync(
|
||||
path.join(root, 'gsd-file-manifest.json'),
|
||||
JSON.stringify(
|
||||
{
|
||||
version: '1.7.0',
|
||||
timestamp: '2026-07-20T00:00:00.000Z',
|
||||
mode: 'full',
|
||||
files,
|
||||
},
|
||||
null,
|
||||
2,
|
||||
),
|
||||
'utf8',
|
||||
);
|
||||
}
|
||||
|
||||
function makePlanCtx(configDir) {
|
||||
const manifest = readInstallManifest(configDir);
|
||||
return {
|
||||
configDir,
|
||||
classifyArtifact: (relPath) => realClassifyArtifact(configDir, relPath, manifest),
|
||||
};
|
||||
}
|
||||
|
||||
/** sha256 hash in the manifest's own format, so a file reads as pristine. */
|
||||
function hashOf(root, relPath) {
|
||||
const crypto = require('node:crypto');
|
||||
return crypto
|
||||
.createHash('sha256')
|
||||
.update(fs.readFileSync(path.join(root, relPath)))
|
||||
.digest('hex');
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 1. Metadata
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('migration 006 metadata', () => {
|
||||
test('exports a single migration object with the required authoring fields', () => {
|
||||
assert.equal(typeof migration, 'object');
|
||||
assert.equal(typeof migration.id, 'string');
|
||||
assert.ok(migration.id.length > 0, 'id must be non-empty');
|
||||
assert.equal(typeof migration.title, 'string');
|
||||
assert.equal(typeof migration.description, 'string');
|
||||
assert.equal(typeof migration.introducedIn, 'string');
|
||||
assert.ok(Array.isArray(migration.scopes), 'scopes must be an array');
|
||||
assert.ok(migration.scopes.includes('global'), 'scopes must include global');
|
||||
assert.ok(migration.scopes.includes('local'), 'scopes must include local');
|
||||
assert.strictEqual(migration.destructive, true);
|
||||
assert.equal(typeof migration.plan, 'function');
|
||||
});
|
||||
|
||||
test('is scoped to pi only (no other runtime installs this artifact)', () => {
|
||||
assert.ok(Array.isArray(migration.runtimes), 'runtimes must be an explicit array');
|
||||
assert.deepEqual(migration.runtimes, ['pi']);
|
||||
});
|
||||
|
||||
test('id carries the expected date prefix and names the retired artifact', () => {
|
||||
assert.ok(
|
||||
migration.id.startsWith('2026-07-20-'),
|
||||
`id should start with the date prefix, got: ${migration.id}`,
|
||||
);
|
||||
assert.match(migration.id, /pi-extension/);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 2-5. plan() behaviour by classification
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('migration 006 plan()', () => {
|
||||
test('emits no actions when the stale extension is absent (fresh install, idempotent)', (t) => {
|
||||
const dir = createTempDir();
|
||||
t.after(() => cleanup(dir));
|
||||
|
||||
writeFile(dir, CURRENT_REL, '// current extension\n');
|
||||
writeManifest(dir, { [CURRENT_REL]: hashOf(dir, CURRENT_REL) });
|
||||
|
||||
const actions = migration.plan(makePlanCtx(dir));
|
||||
assert.deepEqual(actions, [], 'no stale file -> no actions');
|
||||
});
|
||||
|
||||
test('emits remove-managed for a pristine manifest-managed stale extension', (t) => {
|
||||
const dir = createTempDir();
|
||||
t.after(() => cleanup(dir));
|
||||
|
||||
writeFile(dir, STALE_REL, '// stale pre-#2470 extension\n');
|
||||
writeManifest(dir, { [STALE_REL]: hashOf(dir, STALE_REL) });
|
||||
|
||||
const actions = migration.plan(makePlanCtx(dir));
|
||||
assert.equal(actions.length, 1, `expected exactly one action, got ${JSON.stringify(actions)}`);
|
||||
assert.equal(actions[0].type, 'remove-managed');
|
||||
assert.equal(actions[0].relPath, STALE_REL);
|
||||
assert.ok(
|
||||
typeof actions[0].ownershipEvidence === 'string' && actions[0].ownershipEvidence.length > 0,
|
||||
'destructive actions require ownershipEvidence (authoring guard)',
|
||||
);
|
||||
assert.ok(
|
||||
typeof actions[0].reason === 'string' && actions[0].reason.length > 0,
|
||||
'action must carry a human-readable reason for dry-run output',
|
||||
);
|
||||
});
|
||||
|
||||
test('emits backup-and-remove when the user locally modified the stale extension', (t) => {
|
||||
const dir = createTempDir();
|
||||
t.after(() => cleanup(dir));
|
||||
|
||||
writeFile(dir, STALE_REL, '// stale pre-#2470 extension\n');
|
||||
// Manifest records a DIFFERENT hash -> managed-modified.
|
||||
writeManifest(dir, { [STALE_REL]: 'a'.repeat(64) });
|
||||
|
||||
const actions = migration.plan(makePlanCtx(dir));
|
||||
assert.equal(actions.length, 1);
|
||||
assert.equal(
|
||||
actions[0].type,
|
||||
'backup-and-remove',
|
||||
'a locally patched managed file must be backed up, never silently deleted',
|
||||
);
|
||||
assert.equal(actions[0].relPath, STALE_REL);
|
||||
assert.ok(actions[0].ownershipEvidence);
|
||||
});
|
||||
|
||||
test('emits NO action for an unknown (non-manifest) gsd.cjs — never remove unowned files', (t) => {
|
||||
const dir = createTempDir();
|
||||
t.after(() => cleanup(dir));
|
||||
|
||||
// File present but absent from the manifest -> classification 'unknown'.
|
||||
writeFile(dir, STALE_REL, '// hand-placed by the user\n');
|
||||
writeManifest(dir, {});
|
||||
|
||||
const actions = migration.plan(makePlanCtx(dir));
|
||||
assert.deepEqual(
|
||||
actions,
|
||||
[],
|
||||
'unknown files are preserved (docs/installer-migrations.md#ownership)',
|
||||
);
|
||||
});
|
||||
|
||||
test('never targets the replacement extension or neighbouring user files', (t) => {
|
||||
const dir = createTempDir();
|
||||
t.after(() => cleanup(dir));
|
||||
|
||||
writeFile(dir, STALE_REL, '// stale\n');
|
||||
writeFile(dir, CURRENT_REL, '// current\n');
|
||||
writeFile(dir, 'extensions/my-own-extension.js', '// user-authored\n');
|
||||
writeManifest(dir, {
|
||||
[STALE_REL]: hashOf(dir, STALE_REL),
|
||||
[CURRENT_REL]: hashOf(dir, CURRENT_REL),
|
||||
});
|
||||
|
||||
const actions = migration.plan(makePlanCtx(dir));
|
||||
const targeted = actions.map((a) => a.relPath);
|
||||
assert.deepEqual(targeted, [STALE_REL]);
|
||||
assert.ok(!targeted.includes(CURRENT_REL), 'must not remove the replacement extension');
|
||||
assert.ok(
|
||||
!targeted.includes('extensions/my-own-extension.js'),
|
||||
"must not touch a user's own extension sitting in the same directory",
|
||||
);
|
||||
});
|
||||
|
||||
test('plan() does not mutate disk (planning is pure)', (t) => {
|
||||
const dir = createTempDir();
|
||||
t.after(() => cleanup(dir));
|
||||
|
||||
writeFile(dir, STALE_REL, '// stale\n');
|
||||
writeManifest(dir, { [STALE_REL]: hashOf(dir, STALE_REL) });
|
||||
|
||||
migration.plan(makePlanCtx(dir));
|
||||
assert.ok(
|
||||
fs.existsSync(path.join(dir, STALE_REL)),
|
||||
'plan() must not remove anything — the executor owns mutation',
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1665,6 +1665,14 @@ test('shipped installer-migration checksums are locked to a committed baseline (
|
||||
// fix-forward migration widens the scanned surface without touching 000.
|
||||
'2026-07-17-opencode-baseline-commands-dir':
|
||||
'sha256:0f6080b5f9b75fb5adbe9664a71152e23a5336813453b0a77e4df6fd483ad38e',
|
||||
// Migration 006 (NEW, added here per this test's own sanctioned "adding a new
|
||||
// migration" case — not a shipped-body edit): retire pi's stale
|
||||
// extensions/gsd.cjs. #2470 renamed the installed extension to
|
||||
// extensions/gsd.js because pi's isExtensionFile() auto-discovery accepts
|
||||
// only .ts/.js and silently skips everything else; without this migration the
|
||||
// old path drops out of the manifest and uninstall can never remove it.
|
||||
'2026-07-20-pi-extension-cjs-to-js':
|
||||
'sha256:185fa926ae24d83cbdd95c31a9ad2cc8d123e176ad543669b3b0ed75e6ca6f4a',
|
||||
};
|
||||
|
||||
const { DEFAULT_MIGRATIONS_DIR, migrationChecksum: computeChecksum } = require('../gsd-core/bin/lib/installer-migrations.cjs');
|
||||
@@ -2565,3 +2573,240 @@ describe('migration.plan()', () => {
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Symlinked managed path: backup must never dereference (#2470 security review)
|
||||
// ---------------------------------------------------------------------------
|
||||
//
|
||||
// `fs.copyFileSync` follows symlinks. Before this hardening, a managed path
|
||||
// replaced by a link would have had the LINK TARGET's bytes copied into the
|
||||
// journal's backup tree — e.g. a `gsd.cjs` symlinked at a private key would
|
||||
// land that key's contents under gsd-migration-journal/. Nothing GSD installs
|
||||
// is ever a symlink, so the faithful snapshot is the link itself.
|
||||
|
||||
{
|
||||
const { describe, test } = require('node:test');
|
||||
describe('symlinked managed path is snapshotted as a link, never dereferenced', () => {
|
||||
const piExtensionMigration = require('../gsd-core/bin/lib/installer-migrations/006-pi-extension-cjs-to-js.cjs');
|
||||
const SECRET = 'TOP-SECRET-PRIVATE-KEY-MATERIAL\n';
|
||||
|
||||
test('backup-and-remove on a symlinked managed file copies the link, not the referent', (t) => {
|
||||
const configDir = createTempInstall();
|
||||
const secretDir = createTempInstall();
|
||||
try {
|
||||
const secretPath = path.join(secretDir, 'id_rsa');
|
||||
fs.writeFileSync(secretPath, SECRET, 'utf8');
|
||||
|
||||
const linkPath = path.join(configDir, 'extensions', 'gsd.cjs');
|
||||
fs.mkdirSync(path.dirname(linkPath), { recursive: true });
|
||||
try {
|
||||
fs.symlinkSync(secretPath, linkPath);
|
||||
} catch {
|
||||
t.skip('symlink creation unsupported on this platform/privilege');
|
||||
return;
|
||||
}
|
||||
|
||||
// Manifest records the path as managed with a hash that cannot match the
|
||||
// referent -> classification 'managed-modified' -> backup-and-remove.
|
||||
writeManifest(configDir, { 'extensions/gsd.cjs': sha256('the original extension\n') });
|
||||
|
||||
const result = runInstallerMigrations({
|
||||
configDir,
|
||||
runtime: 'pi',
|
||||
scope: 'global',
|
||||
migrations: [piExtensionMigration],
|
||||
now: () => '2026-07-20T00:00:00.000Z',
|
||||
});
|
||||
|
||||
const backupAction = result.plan.actions.find((a) => a.type === 'backup-and-remove');
|
||||
assert.ok(backupAction, 'expected a backup-and-remove action for the modified managed file');
|
||||
|
||||
// The referent is untouched and still holds its content.
|
||||
assert.ok(fs.existsSync(secretPath), 'symlink target must survive');
|
||||
assert.equal(fs.readFileSync(secretPath, 'utf8'), SECRET, 'symlink target content must be unchanged');
|
||||
|
||||
// The link itself is gone from the install tree.
|
||||
assert.equal(
|
||||
fs.lstatSync(linkPath, { throwIfNoEntry: false }),
|
||||
undefined,
|
||||
'the symlink at the managed path must be removed',
|
||||
);
|
||||
|
||||
// Nothing anywhere under configDir may contain the referent's bytes.
|
||||
const leaked = [];
|
||||
const walk = (dir) => {
|
||||
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
||||
const full = path.join(dir, entry.name);
|
||||
if (entry.isSymbolicLink()) continue; // a link is fine; its content is not copied
|
||||
if (entry.isDirectory()) { walk(full); continue; }
|
||||
let body;
|
||||
try { body = fs.readFileSync(full, 'utf8'); } catch { continue; }
|
||||
if (body.includes('TOP-SECRET')) leaked.push(path.relative(configDir, full));
|
||||
}
|
||||
};
|
||||
walk(configDir);
|
||||
assert.deepEqual(leaked, [], `symlink referent content leaked into: ${leaked.join(', ')}`);
|
||||
} finally {
|
||||
cleanup(configDir);
|
||||
cleanup(secretDir);
|
||||
}
|
||||
});
|
||||
|
||||
test('a regular managed file is still backed up by content (no behavior change)', (t) => {
|
||||
const configDir = createTempInstall();
|
||||
try {
|
||||
writeFile(configDir, 'extensions/gsd.cjs', 'locally patched extension\n');
|
||||
writeManifest(configDir, { 'extensions/gsd.cjs': sha256('the original extension\n') });
|
||||
|
||||
const result = runInstallerMigrations({
|
||||
configDir,
|
||||
runtime: 'pi',
|
||||
scope: 'global',
|
||||
migrations: [piExtensionMigration],
|
||||
now: () => '2026-07-20T00:00:00.000Z',
|
||||
});
|
||||
|
||||
const backupAction = result.plan.actions.find((a) => a.type === 'backup-and-remove');
|
||||
assert.ok(backupAction, 'expected backup-and-remove for the locally patched file');
|
||||
|
||||
// The PLAN carries backupRelPath: null — the concrete backup location is
|
||||
// chosen during apply and recorded in the journal, so read it from there.
|
||||
const journal = JSON.parse(fs.readFileSync(path.join(configDir, result.journalRelPath), 'utf8'));
|
||||
const journalled = journal.actions.find((a) => a.backupRelPath);
|
||||
assert.ok(journalled, 'apply must record the backup path in the journal for the user');
|
||||
const backupPath = path.join(configDir, journalled.backupRelPath);
|
||||
assert.equal(
|
||||
fs.readFileSync(backupPath, 'utf8'),
|
||||
'locally patched extension\n',
|
||||
'a real file must still be backed up by content so the user can recover it',
|
||||
);
|
||||
assert.ok(!fs.existsSync(path.join(configDir, 'extensions', 'gsd.cjs')));
|
||||
} finally {
|
||||
cleanup(configDir);
|
||||
}
|
||||
});
|
||||
|
||||
// In-flight failure recovery: when a later step of the SAME apply() attempt
|
||||
// throws, the catch block replays the rollback snapshots it already took.
|
||||
// Those snapshots are themselves symlinks, so a raw copy there dereferences
|
||||
// and writes the referent's bytes back to the LIVE install path — worse than
|
||||
// the journal-tree leak, because it is user-visible at a predictable path.
|
||||
//
|
||||
// The failure is injected by monkeypatching fs.rmSync (restored in finally)
|
||||
// rather than by chmod/permission tricks: deterministic, root- and
|
||||
// OS-independent. The delete of the managed path is allowed to SUCCEED and
|
||||
// then throws once, modelling a later step failing after the delete. That
|
||||
// ordering is load-bearing: if the live path still existed, the pre-fix
|
||||
// copyFileSync would hit a same-file collision and throw instead of leaking,
|
||||
// and this test would pass against the very bug it exists to catch.
|
||||
test('apply failure after a symlinked snapshot does not leak the referent into the live tree', (t) => {
|
||||
const configDir = createTempInstall();
|
||||
const secretDir = createTempInstall();
|
||||
const realRmSync = fs.rmSync;
|
||||
try {
|
||||
const secretPath = path.join(secretDir, 'id_rsa');
|
||||
fs.writeFileSync(secretPath, SECRET, 'utf8');
|
||||
|
||||
const linkPath = path.join(configDir, 'extensions', 'gsd.cjs');
|
||||
fs.mkdirSync(path.dirname(linkPath), { recursive: true });
|
||||
try {
|
||||
fs.symlinkSync(secretPath, linkPath);
|
||||
} catch {
|
||||
t.skip('symlink creation unsupported on this platform/privilege');
|
||||
return;
|
||||
}
|
||||
writeManifest(configDir, { 'extensions/gsd.cjs': sha256('the original extension\n') });
|
||||
|
||||
let fired = false;
|
||||
fs.rmSync = function patched(target, options) {
|
||||
const result = realRmSync.call(fs, target, options);
|
||||
if (!fired && path.resolve(String(target)) === path.resolve(linkPath)) {
|
||||
fired = true;
|
||||
throw new Error('injected post-delete failure');
|
||||
}
|
||||
return result;
|
||||
};
|
||||
|
||||
assert.throws(() => runInstallerMigrations({
|
||||
configDir,
|
||||
runtime: 'pi',
|
||||
scope: 'global',
|
||||
migrations: [piExtensionMigration],
|
||||
now: () => '2026-07-20T00:00:00.000Z',
|
||||
}), /injected post-delete failure/, 'the injected failure must propagate, not be swallowed');
|
||||
|
||||
fs.rmSync = realRmSync;
|
||||
|
||||
// The referent is untouched...
|
||||
assert.ok(fs.existsSync(secretPath));
|
||||
assert.equal(fs.readFileSync(secretPath, 'utf8'), SECRET);
|
||||
|
||||
// ...the managed path is restored as a LINK, not a dereferenced copy...
|
||||
const restored = fs.lstatSync(linkPath, { throwIfNoEntry: false });
|
||||
assert.ok(restored, 'failure recovery must restore the managed path');
|
||||
assert.ok(
|
||||
restored.isSymbolicLink(),
|
||||
'restored path must be a symlink — a regular file here means the referent was dereferenced into the live tree',
|
||||
);
|
||||
|
||||
// ...and its bytes appear nowhere under the install tree.
|
||||
const leaked = [];
|
||||
const walk = (dir) => {
|
||||
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
||||
const full = path.join(dir, entry.name);
|
||||
if (entry.isSymbolicLink()) continue;
|
||||
if (entry.isDirectory()) { walk(full); continue; }
|
||||
let body;
|
||||
try { body = fs.readFileSync(full, 'utf8'); } catch { continue; }
|
||||
if (body.includes('TOP-SECRET')) leaked.push(path.relative(configDir, full));
|
||||
}
|
||||
};
|
||||
walk(configDir);
|
||||
assert.deepEqual(leaked, [], `referent content leaked into: ${leaked.join(', ')}`);
|
||||
} finally {
|
||||
fs.rmSync = realRmSync;
|
||||
cleanup(configDir);
|
||||
cleanup(secretDir);
|
||||
}
|
||||
});
|
||||
|
||||
test('rollback() restores a symlinked managed path as a link, not a dereferenced copy', (t) => {
|
||||
const configDir = createTempInstall();
|
||||
const secretDir = createTempInstall();
|
||||
try {
|
||||
const targetPath = path.join(secretDir, 'id_rsa');
|
||||
fs.writeFileSync(targetPath, SECRET, 'utf8');
|
||||
|
||||
const linkPath = path.join(configDir, 'extensions', 'gsd.cjs');
|
||||
fs.mkdirSync(path.dirname(linkPath), { recursive: true });
|
||||
try {
|
||||
fs.symlinkSync(targetPath, linkPath);
|
||||
} catch {
|
||||
t.skip('symlink creation unsupported on this platform/privilege');
|
||||
return;
|
||||
}
|
||||
writeManifest(configDir, { 'extensions/gsd.cjs': sha256('the original extension\n') });
|
||||
|
||||
const result = runInstallerMigrations({
|
||||
configDir,
|
||||
runtime: 'pi',
|
||||
scope: 'global',
|
||||
migrations: [piExtensionMigration],
|
||||
now: () => '2026-07-20T00:00:00.000Z',
|
||||
});
|
||||
assert.equal(fs.lstatSync(linkPath, { throwIfNoEntry: false }), undefined, 'link removed by apply');
|
||||
|
||||
result.rollback();
|
||||
|
||||
const restored = fs.lstatSync(linkPath, { throwIfNoEntry: false });
|
||||
assert.ok(restored, 'rollback must restore the managed path');
|
||||
assert.ok(restored.isSymbolicLink(), 'restored path must be a symlink, not a dereferenced copy');
|
||||
assert.equal(fs.readlinkSync(linkPath), targetPath, 'restored link must point at the original target');
|
||||
assert.equal(fs.readFileSync(targetPath, 'utf8'), SECRET, 'target content must be untouched throughout');
|
||||
} finally {
|
||||
cleanup(configDir);
|
||||
cleanup(secretDir);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@@ -170,3 +170,53 @@ test('pi axes negotiate modelMode:"active" (the active-model steering axis)', ()
|
||||
const result = negotiateHostCapabilities(PI_AXES);
|
||||
assert.equal(result.effective.modelMode, 'active');
|
||||
});
|
||||
|
||||
// -- native-extension auto-discovery contract (#2470) -------------------------
|
||||
//
|
||||
// pi auto-discovers extensions by scanning <agentDir>/extensions/ and keeping
|
||||
// only names its `isExtensionFile()` predicate accepts:
|
||||
//
|
||||
// function isExtensionFile(name) {
|
||||
// return name.endsWith(".ts") || name.endsWith(".js");
|
||||
// }
|
||||
//
|
||||
// (@earendil-works/pi-coding-agent, packages/coding-agent/src/core/extensions/
|
||||
// loader.ts — verified upstream 2026-07-20.) A dest filename outside that set
|
||||
// is skipped SILENTLY: no /gsd command, no error, no log line. pi loads the
|
||||
// accepted file through jiti, which handles CommonJS and ESM alike, so the
|
||||
// extension's module format is irrelevant to discovery — only the suffix is.
|
||||
//
|
||||
// These assertions deliberately encode pi's PREDICATE rather than the literal
|
||||
// filename, so they keep protecting the contract if the extension is ever
|
||||
// renamed again, and they state the reason the rename mattered.
|
||||
|
||||
/** pi's upstream discovery predicate, mirrored verbatim. */
|
||||
function piIsExtensionFile(name) {
|
||||
return name.endsWith('.ts') || name.endsWith('.js');
|
||||
}
|
||||
|
||||
test('pi capability declares a native-extension dest filename pi will auto-discover (#2470)', () => {
|
||||
const np = PI_CAP.runtime.hostBehaviors.nativePlugin;
|
||||
assert.ok(np && np.file, 'pi must declare hostBehaviors.nativePlugin.file');
|
||||
assert.ok(
|
||||
piIsExtensionFile(np.file),
|
||||
`pi's installed extension "${np.file}" must end in .ts or .js — pi's isExtensionFile() ` +
|
||||
'auto-discovery filter silently skips every other suffix, so /gsd never registers (#2470)',
|
||||
);
|
||||
});
|
||||
|
||||
test('pi native-extension source stays CommonJS-explicit while the dest satisfies pi (#2470)', () => {
|
||||
const np = PI_CAP.runtime.hostBehaviors.nativePlugin;
|
||||
// The in-repo source keeps its .cjs suffix on purpose: tests require() it
|
||||
// directly and .cjs is unambiguous CommonJS regardless of any future
|
||||
// package.json "type" flip. Only the INSTALLED name must satisfy pi, and
|
||||
// jiti parses the copied file by content, not by suffix.
|
||||
assert.ok(
|
||||
np.source.endsWith('.cjs'),
|
||||
`pi's in-repo extension source should stay .cjs (explicit CommonJS), got "${np.source}"`,
|
||||
);
|
||||
assert.ok(
|
||||
fs.existsSync(path.join(__dirname, '..', np.source)),
|
||||
`pi's declared nativePlugin.source "${np.source}" must exist in the repo`,
|
||||
);
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user