Merge remote-tracking branch 'origin/main' into maint/pr-2866-current

This commit is contained in:
haelyra
2026-08-28 18:29:35 -04:00
118 changed files with 3850 additions and 368 deletions
+48
View File
@@ -7,6 +7,7 @@ const path = require('path');
const {
beginLegacySyncState,
detectLegacyCodexSync,
finalizeLegacySyncState,
recordLegacySyncPath,
rollbackLegacyCodexSync,
@@ -521,6 +522,53 @@ function runTests() {
fs.rmSync(homeDir, { recursive: true, force: true });
})) passed += 1; else failed += 1;
if (test('detectLegacyCodexSync surfaces unreadable AGENTS.md instead of reporting clean', () => {
// hasMarkerBlock previously swallowed every read/open error and returned false,
// which made detectLegacyCodexSync claim a clean home even when AGENTS.md was
// unreadable (EACCES, EMFILE, ...). The fix is to rethrow every error except
// ENOENT (a missing file is a legitimate "no marker" signal).
const homeDir = tempDir('legacy-codex-home-');
const codexHome = path.join(homeDir, '.codex');
const agentsPath = path.join(codexHome, 'AGENTS.md');
fs.mkdirSync(codexHome, { recursive: true });
fs.writeFileSync(agentsPath, '# User instructions\n<!-- BEGIN ECC -->\n<!-- END ECC -->\n');
// chmod 000 to make AGENTS.md unreadable. Skip when running as root because
// root bypasses mode bits and the test would not exercise the error path.
if (typeof process.getuid === 'function' && process.getuid() !== 0) {
fs.chmodSync(agentsPath, 0o000);
let threw = null;
try {
detectLegacyCodexSync(codexHome);
} catch (error) {
threw = error;
}
assert.ok(threw, 'detectLegacyCodexSync must propagate the read error');
assert.notStrictEqual(threw && threw.code, 'ENOENT');
fs.chmodSync(agentsPath, 0o600);
} else {
// Root path: simulate the same failure by replacing AGENTS.md with a
// directory — openRegularFileNoFollow then throws EACCES-on-open on
// Linux when the path resolves to a non-regular file.
fs.rmSync(agentsPath);
fs.mkdirSync(agentsPath);
let threw = null;
try {
detectLegacyCodexSync(codexHome);
} catch (error) {
threw = error;
}
assert.ok(threw, 'detectLegacyCodexSync must propagate the inspection error');
fs.rmSync(agentsPath, { recursive: true });
}
// Sanity check: a missing AGENTS.md is still treated as no-marker (not an error).
fs.rmSync(agentsPath, { force: true });
assert.strictEqual(detectLegacyCodexSync(codexHome), false);
fs.rmSync(homeDir, { recursive: true, force: true });
})) passed += 1; else failed += 1;
console.log(`\nResults: Passed: ${passed}, Failed: ${failed}`);
process.exit(failed > 0 ? 1 : 0);
}
+6 -1
View File
@@ -83,6 +83,11 @@ function runTests() {
assert.deepStrictEqual(kimi.scopes, [
{ id: 'project', targetId: 'kimi', root: './.kimi-code' },
]);
const opencode = getHarnessCapability('opencode');
assert.match(opencode.destinationResolution, /OPENCODE_CONFIG_DIR/);
assert.match(opencode.destinationResolution, /XDG_CONFIG_HOME/);
assert.match(opencode.destinationResolution, /~\/\.config\/opencode/);
})) passed++; else failed++;
if (test('keeps every advanced target attached to its registered root and scope', () => {
@@ -90,7 +95,7 @@ function runTests() {
cursor: ['project', './.cursor'],
antigravity: ['project', './.agents'],
gemini: ['project', './.gemini'],
opencode: ['home', '~/.opencode'],
opencode: ['home', '~/.config/opencode'],
codebuddy: ['project', './.codebuddy'],
joycode: ['project', './.joycode'],
qwen: ['home', '~/.qwen'],
+125 -12
View File
@@ -1,6 +1,7 @@
'use strict';
const assert = require('assert');
const crypto = require('crypto');
const fs = require('fs');
const os = require('os');
const path = require('path');
@@ -38,8 +39,14 @@ function createFixture(options = {}) {
const target = options.target || 'claude';
const targetRoot = target === 'claude'
? path.join(homeDir, '.claude')
: path.join(projectRoot, '.claude');
const installStatePath = path.join(targetRoot, 'ecc', 'install-state.json');
: path.join(projectRoot, target === 'cursor' ? '.cursor' : '.claude');
const installStatePath = target === 'cursor'
? path.join(targetRoot, 'ecc-install-state.json')
: path.join(targetRoot, 'ecc', 'install-state.json');
const adapterId = target === 'claude'
? 'claude-home'
: target === 'cursor' ? 'cursor-project' : 'claude-project';
const adapterKind = target === 'claude' ? 'home' : 'project';
const skillFiles = options.skillFiles || {
'SKILL.md': '# Current ECC skill\n',
'references/guide.md': '# Current ECC guide\n',
@@ -61,9 +68,9 @@ function createFixture(options = {}) {
schemaVersion: 'ecc.install.v1',
installedAt: new Date().toISOString(),
target: {
id: target === 'claude' ? 'claude-home' : 'claude-project',
id: adapterId,
target,
kind: target === 'claude' ? 'home' : 'project',
kind: adapterKind,
root: targetRoot,
installStatePath,
},
@@ -100,9 +107,9 @@ function createFixture(options = {}) {
mode: 'manifest',
target,
adapter: {
id: target === 'claude' ? 'claude-home' : 'claude-project',
id: adapterId,
target,
kind: target === 'claude' ? 'home' : 'project',
kind: adapterKind,
},
targetRoot,
installRoot: targetRoot,
@@ -130,6 +137,9 @@ function seedLegacyInstall(fixture, options = {}) {
? operation.sourceRelativePath.split(path.sep).join('\\')
: operation.sourceRelativePath,
destinationPath,
contentSha256: crypto.createHash('sha256')
.update(fs.readFileSync(destinationPath))
.digest('hex'),
};
});
@@ -233,12 +243,17 @@ function runTests() {
fs.mkdirSync(path.dirname(otherLegacyPath), { recursive: true });
fs.writeFileSync(otherSourcePath, '# Other source\n');
fs.writeFileSync(otherLegacyPath, '# Other legacy managed skill\n');
const otherLegacyOperation = createOperation(
'other-module',
fixture.sourceRoot,
otherSourceRelativePath,
otherLegacyPath
);
const otherLegacyOperation = {
...createOperation(
'other-module',
fixture.sourceRoot,
otherSourceRelativePath,
otherLegacyPath
),
contentSha256: crypto.createHash('sha256')
.update(fs.readFileSync(otherLegacyPath))
.digest('hex'),
};
writeInstallState(fixture.installStatePath, {
...fixture.plan.statePreview,
operations: [...legacyOperations, otherLegacyOperation],
@@ -433,6 +448,104 @@ function runTests() {
}
})) passed++; else failed++;
if (test('merges managed operations across selective installs for enabled and disabled migrations', () => {
for (const target of ['claude', 'cursor']) {
const fixture = createFixture({ target });
try {
applyInstallPlan(fixture.plan);
const extraSourceRelativePath = path.join('skills', 'extra-skill', 'SKILL.md');
const extraSourcePath = path.join(fixture.sourceRoot, extraSourceRelativePath);
const extraDestinationPath = path.join(
fixture.targetRoot,
'skills',
'extra-skill',
'SKILL.md'
);
fs.mkdirSync(path.dirname(extraSourcePath), { recursive: true });
fs.writeFileSync(extraSourcePath, '# Extra ECC skill\n');
const extraOperation = createOperation(
'skill-extra',
fixture.sourceRoot,
extraSourceRelativePath,
extraDestinationPath
);
const extraPlan = {
...fixture.plan,
operations: [extraOperation],
statePreview: {
...fixture.plan.statePreview,
request: {
...fixture.plan.statePreview.request,
modules: [],
includeComponents: ['skill-extra'],
},
resolution: {
selectedModules: [],
skippedModules: [],
},
operations: [extraOperation],
},
};
applyInstallPlan(extraPlan);
const stateAfterExtraInstall = readInstallState(fixture.installStatePath);
assert.ok(fixture.operations.every(operation => (
stateAfterExtraInstall.operations.some(recorded => (
recorded.destinationPath === operation.destinationPath
))
)));
assert.ok(stateAfterExtraInstall.operations.some(operation => (
operation.destinationPath === extraDestinationPath
)));
const updatedExtraOperation = {
...extraOperation,
moduleId: 'skill-extra-updated',
};
applyInstallPlan({
...extraPlan,
operations: [updatedExtraOperation],
statePreview: {
...extraPlan.statePreview,
operations: [updatedExtraOperation],
},
});
const stateAfterMetadataUpdate = readInstallState(fixture.installStatePath);
const updatedExtraRecords = stateAfterMetadataUpdate.operations.filter(operation => (
operation.destinationPath === extraDestinationPath
));
assert.strictEqual(updatedExtraRecords.length, 1);
assert.strictEqual(updatedExtraRecords[0].moduleId, 'skill-extra-updated');
const retry = applyInstallPlan(fixture.plan);
assert.deepStrictEqual(retry.skippedOperations, []);
const stateAfterRetry = readInstallState(fixture.installStatePath);
for (const originalOperation of fixture.operations) {
assert.strictEqual(
stateAfterRetry.operations.filter(operation => (
operation.destinationPath === originalOperation.destinationPath
)).length,
1,
`retry must record ${originalOperation.destinationPath} exactly once`
);
}
const retainedExtraRecords = stateAfterRetry.operations.filter(operation => (
operation.destinationPath === extraDestinationPath
));
assert.strictEqual(retainedExtraRecords.length, 1);
assert.strictEqual(retainedExtraRecords[0].moduleId, 'skill-extra-updated');
const uninstall = runUninstall(fixture);
assert.strictEqual(uninstall.summary.errorCount, 0);
assert.ok(fixture.operations.every(operation => !fs.existsSync(operation.destinationPath)));
assert.ok(!fs.existsSync(extraDestinationPath));
} finally {
cleanup(fixture.tempDir);
}
}
})) passed++; else failed++;
if (test('tracks a partial migration so retry and uninstall remain safe', () => {
const fixture = createFixture();
try {
+4
View File
@@ -55,6 +55,7 @@ function writeLegacySourceFixture(root) {
writeFile(root, path.join('rules', 'common', 'node_modules', 'ignored.md'), '# Ignored\n');
writeFile(root, path.join('rules', 'common', '.git', 'ignored.md'), '# Ignored\n');
writeFile(root, path.join('rules', 'common', '__pycache__', 'ignored.cpython-314.pyc'), 'ignored\n');
writeFile(root, path.join('rules', 'common', '.pytest_cache', 'ignored.md'), '# Ignored\n');
writeFile(root, path.join('rules', 'common', 'stray.pyc'), 'ignored\n');
writeFile(root, path.join('rules', 'common', 'stray.pyo'), 'ignored\n');
writeFile(root, path.join('rules', 'common', 'stray.pyd'), 'ignored\n');
@@ -116,6 +117,7 @@ function writeManifestSourceFixture(root) {
writeFile(root, path.join('src', 'node_modules', 'ignored.js'), 'console.log("ignored");\n');
writeFile(root, path.join('src', '.git', 'ignored.js'), 'console.log("ignored");\n');
writeFile(root, path.join('src', '__pycache__', 'ignored.cpython-314.pyc'), 'ignored\n');
writeFile(root, path.join('src', '.pytest_cache', 'ignored.md'), '# Ignored\n');
writeFile(root, path.join('src', 'stray.pyc'), 'ignored\n');
writeFile(root, path.join('src', 'stray.pyo'), 'ignored\n');
writeFile(root, path.join('src', 'stray.pyd'), 'ignored\n');
@@ -201,6 +203,7 @@ function runTests() {
assert.ok(!plan.operations.some(operation => operation.sourceRelativePath.includes('node_modules')));
assert.ok(!plan.operations.some(operation => operation.sourceRelativePath.includes('.git')));
assert.ok(!plan.operations.some(operation => operation.sourceRelativePath.includes('__pycache__')));
assert.ok(!plan.operations.some(operation => operation.sourceRelativePath.includes('.pytest_cache')));
assert.ok(!plan.operations.some(operation => /\.(?:pyc|pyo|pyd)$/.test(operation.sourceRelativePath)));
assert.deepStrictEqual(plan.statePreview.request.legacyLanguages, ['typescript', 'missing-lang', '../bad']);
assert.strictEqual(plan.statePreview.request.legacyMode, true);
@@ -371,6 +374,7 @@ function runTests() {
assert.ok(!normalizedSources.some(source => source.includes('node_modules')));
assert.ok(!normalizedSources.some(source => source.includes('.git')));
assert.ok(!normalizedSources.some(source => source.includes('__pycache__')));
assert.ok(!normalizedSources.some(source => source.includes('.pytest_cache')));
assert.ok(!normalizedSources.some(source => /\.(?:pyc|pyo|pyd)$/.test(source)));
assert.ok(plan.operations.some(operation => (
operation.sourceRelativePath === path.join('.claude-plugin', 'plugin.json')
+82 -1
View File
@@ -100,7 +100,7 @@ function writeCursorState(projectRoot, overrides = {}) {
}
function createOpencodeStateOptions(homeDir, overrides = {}) {
const targetRoot = overrides.targetRoot || path.join(homeDir, '.opencode');
const targetRoot = overrides.targetRoot || path.join(homeDir, '.config', 'opencode');
const installStatePath = overrides.installStatePath || path.join(targetRoot, 'ecc-install-state.json');
return {
@@ -357,6 +357,87 @@ function runTests() {
}
})) passed++; else failed++;
if (test('OpenCode discovery, doctor, and uninstall honor the explicit config root', () => {
const homeDir = createTempDir('install-lifecycle-opencode-home-');
const projectRoot = createTempDir('install-lifecycle-opencode-project-');
const targetRoot = path.join(homeDir, 'custom-opencode');
const installStatePath = path.join(targetRoot, 'ecc-install-state.json');
const sourceRelativePath = path.join('rules', 'common', 'coding-style.md');
const sourcePath = path.join(REPO_ROOT, sourceRelativePath);
const destinationPath = path.join(targetRoot, 'rules', 'common', 'coding-style.md');
const env = { OPENCODE_CONFIG_DIR: targetRoot };
try {
fs.mkdirSync(path.dirname(destinationPath), { recursive: true });
fs.copyFileSync(sourcePath, destinationPath);
writeState(installStatePath, {
adapter: { id: 'opencode-home', target: 'opencode', kind: 'home' },
targetRoot,
installStatePath,
request: {
profile: null,
modules: [],
includeComponents: [],
excludeComponents: [],
legacyLanguages: [],
legacyMode: false,
},
resolution: { selectedModules: [], skippedModules: [] },
operations: [{
kind: 'copy-file',
moduleId: 'rules-core',
sourcePath,
sourceRelativePath,
destinationPath,
strategy: 'preserve-relative-path',
ownership: 'managed',
scaffoldOnly: false,
contentSha256: crypto.createHash('sha256')
.update(fs.readFileSync(destinationPath))
.digest('hex'),
}],
source: {
repoVersion: CURRENT_PACKAGE_VERSION,
repoCommit: null,
manifestVersion: CURRENT_MANIFEST_VERSION,
},
});
const records = discoverInstalledStates({
homeDir,
projectRoot,
targets: ['opencode'],
env,
});
assert.strictEqual(records.length, 1);
assert.strictEqual(records[0].exists, true);
assert.strictEqual(records[0].installStatePath, installStatePath);
const doctor = buildDoctorReport({
repoRoot: REPO_ROOT,
homeDir,
projectRoot,
targets: ['opencode'],
env,
});
assert.strictEqual(doctor.results.length, 1);
assert.strictEqual(doctor.results[0].installStatePath, installStatePath);
const uninstall = uninstallInstalledStates({
homeDir,
projectRoot,
targets: ['opencode'],
env,
});
assert.strictEqual(uninstall.results[0].status, 'uninstalled');
assert.ok(!fs.existsSync(destinationPath));
assert.ok(!fs.existsSync(installStatePath));
} finally {
cleanup(homeDir);
cleanup(projectRoot);
}
})) passed++; else failed++;
if (test('doctor reports missing managed files as an error', () => {
const homeDir = createTempDir('install-lifecycle-home-');
const projectRoot = createTempDir('install-lifecycle-project-');
@@ -0,0 +1,132 @@
'use strict';
const assert = require('assert');
const fs = require('fs');
const os = require('os');
const path = require('path');
const { applyInstallPlan } = require('../../scripts/lib/install/apply');
const { readInstallState } = require('../../scripts/lib/install-state');
const { uninstallInstalledStates } = require('../../scripts/lib/install-lifecycle');
let passed = 0;
let failed = 0;
function makePlan(root, moduleId, fileName) {
const targetRoot = path.join(root, '.cursor');
const installStatePath = path.join(targetRoot, 'ecc-install-state.json');
const sourcePath = path.join(root, 'source', moduleId, fileName);
const destinationPath = path.join(targetRoot, 'skills', moduleId, fileName);
fs.mkdirSync(path.dirname(sourcePath), { recursive: true });
fs.writeFileSync(sourcePath, `${moduleId}\n`);
const operation = {
kind: 'copy-file',
moduleId,
sourcePath,
sourceRelativePath: path.join('skills', moduleId, fileName),
destinationPath,
strategy: 'preserve-relative-path',
ownership: 'managed',
scaffoldOnly: false,
};
return {
mode: 'manifest',
target: 'cursor',
adapter: { id: 'cursor-project', target: 'cursor', kind: 'project' },
targetRoot,
installRoot: targetRoot,
installStatePath,
operations: [operation],
statePreview: {
schemaVersion: 'ecc.install.v1',
installedAt: new Date().toISOString(),
target: {
id: 'cursor-project',
target: 'cursor',
kind: 'project',
root: targetRoot,
installStatePath,
},
request: {
profile: null,
modules: [moduleId],
includeComponents: [],
excludeComponents: [],
legacyLanguages: [],
legacyMode: false,
},
resolution: { selectedModules: [moduleId], skippedModules: [] },
source: { manifestVersion: 1 },
operations: [operation],
},
warnings: [],
};
}
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-selective-reinstall-'));
try {
const first = makePlan(root, 'first-module', 'FIRST.md');
const second = makePlan(root, 'second-module', 'SECOND.md');
applyInstallPlan(first);
fs.writeFileSync(first.operations[0].destinationPath, 'user-modified\n');
applyInstallPlan(second);
const state = readInstallState(first.installStatePath);
assert.deepStrictEqual(
new Set(state.operations.map(operation => operation.moduleId)),
new Set(['first-module', 'second-module']),
'a later selective install must preserve earlier managed ownership'
);
const result = uninstallInstalledStates({ projectRoot: root, targets: ['cursor'] });
assert.strictEqual(result.summary.errorCount, 0);
assert.strictEqual(
fs.readFileSync(first.operations[0].destinationPath, 'utf8'),
'user-modified\n',
'selective reinstall must not claim modified retained content'
);
assert.ok(!fs.existsSync(second.operations[0].destinationPath));
console.log(' ✓ selective reinstall preserves cumulative ownership without claiming user changes');
passed += 1;
} catch (error) {
console.log(` ✗ ${error.message}`);
failed += 1;
} finally {
fs.rmSync(root, { recursive: true, force: true });
}
const partialRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-partial-non-claude-'));
try {
const copied = makePlan(partialRoot, 'copied-module', 'COPIED.md');
const missing = makePlan(partialRoot, 'missing-module', 'MISSING.md');
fs.rmSync(missing.operations[0].sourcePath);
const partialPlan = {
...copied,
operations: [copied.operations[0], missing.operations[0]],
statePreview: {
...copied.statePreview,
operations: [copied.operations[0], missing.operations[0]],
},
};
assert.throws(() => applyInstallPlan(partialPlan), /ENOENT/);
assert.ok(fs.existsSync(copied.operations[0].destinationPath));
const checkpoint = readInstallState(copied.installStatePath);
assert.ok(checkpoint.operations.some(operation => (
operation.destinationPath === copied.operations[0].destinationPath
)));
const result = uninstallInstalledStates({ projectRoot: partialRoot, targets: ['cursor'] });
assert.strictEqual(result.summary.errorCount, 0);
assert.ok(!fs.existsSync(copied.operations[0].destinationPath));
console.log(' ✓ failed non-Claude install checkpoints managed files for uninstall');
passed += 1;
} catch (error) {
console.log(` ✗ ${error.message}`);
failed += 1;
} finally {
fs.rmSync(partialRoot, { recursive: true, force: true });
}
console.log(`\nResults: Passed: ${passed}, Failed: ${failed}`);
process.exit(failed > 0 ? 1 : 0);
+73 -4
View File
@@ -6,12 +6,14 @@ const assert = require('assert');
const fs = require('fs');
const os = require('os');
const path = require('path');
const { spawnSync } = require('child_process');
const {
getInstallTargetAdapter,
listInstallTargetAdapters,
planInstallTargetScaffold,
} = require('../../scripts/lib/install-targets/registry');
const { resolveInvocationEnvironment } = require('../../scripts/lib/invocation-environment');
function normalizedRelativePath(value) {
return String(value || '').replace(/\\/g, '/');
@@ -629,8 +631,8 @@ function runTests() {
if (test('resolves qwen adapter root and install-state path from home dir', () => {
const adapter = getInstallTargetAdapter('qwen');
const homeDir = '/Users/example';
const root = adapter.resolveRoot({ homeDir });
const statePath = adapter.getInstallStatePath({ homeDir });
const root = adapter.resolveRoot({ homeDir, env: {} });
const statePath = adapter.getInstallStatePath({ homeDir, env: {} });
assert.strictEqual(adapter.id, 'qwen-home');
assert.strictEqual(adapter.target, 'qwen');
@@ -639,6 +641,70 @@ function runTests() {
assert.strictEqual(statePath, path.join(homeDir, '.qwen', 'ecc-install-state.json'));
})) passed++; else failed++;
if (test('opencode adapter honors config overrides in priority order', () => {
const adapter = getInstallTargetAdapter('opencode');
const homeDir = '/Users/example';
const xdgRoot = path.join(homeDir, 'xdg');
const explicitRoot = path.join(homeDir, 'custom-opencode');
assert.strictEqual(
adapter.resolveRoot({
homeDir,
env: {
XDG_CONFIG_HOME: xdgRoot,
OPENCODE_CONFIG_DIR: explicitRoot,
},
}),
path.resolve(explicitRoot)
);
assert.strictEqual(
adapter.resolveRoot({ homeDir, env: { XDG_CONFIG_HOME: xdgRoot } }),
path.join(path.resolve(xdgRoot), 'opencode')
);
assert.strictEqual(
adapter.getInstallStatePath({
homeDir,
env: { OPENCODE_CONFIG_DIR: explicitRoot },
}),
path.join(path.resolve(explicitRoot), 'ecc-install-state.json')
);
})) passed++; else failed++;
if (test('opencode adapter isolates an explicit home from ambient config overrides', () => {
const homeDir = '/Users/isolated';
const registryPath = path.join(__dirname, '..', '..', 'scripts', 'lib', 'install-targets', 'registry.js');
const child = spawnSync(process.execPath, ['-e', [
'const { getInstallTargetAdapter } = require(process.env.ECC_TEST_REGISTRY);',
'const root = getInstallTargetAdapter(\'opencode\').resolveRoot({ homeDir: process.env.ECC_TEST_HOME });',
'process.stdout.write(JSON.stringify(root));',
].join('\n')], {
encoding: 'utf8',
env: {
...process.env,
ECC_TEST_REGISTRY: registryPath,
ECC_TEST_HOME: homeDir,
OPENCODE_CONFIG_DIR: '/runner/global/opencode',
XDG_CONFIG_HOME: '/runner/global/xdg',
},
});
assert.strictEqual(child.status, 0, child.stderr);
assert.strictEqual(
JSON.parse(child.stdout),
path.join(path.resolve(homeDir), '.config', 'opencode')
);
})) passed++; else failed++;
if (test('invocation environments are immutable snapshots', () => {
const source = { OPENCODE_CONFIG_DIR: '/custom/opencode' };
const selected = resolveInvocationEnvironment({ env: source });
const ambient = resolveInvocationEnvironment();
assert.notStrictEqual(selected, source);
assert.notStrictEqual(ambient, process.env);
selected.OPENCODE_CONFIG_DIR = '/mutated';
assert.strictEqual(source.OPENCODE_CONFIG_DIR, '/custom/opencode');
})) passed++; else failed++;
if (test('qwen adapter supports lookup by target and adapter id', () => {
const byTarget = getInstallTargetAdapter('qwen');
const byId = getInstallTargetAdapter('qwen-home');
@@ -1073,8 +1139,11 @@ function runTests() {
assert.strictEqual(adapter.id, 'opencode-home');
assert.strictEqual(adapter.target, 'opencode');
assert.strictEqual(adapter.kind, 'home');
assert.strictEqual(root, path.join(homeDir, '.opencode'));
assert.strictEqual(statePath, path.join(homeDir, '.opencode', 'ecc-install-state.json'));
assert.strictEqual(root, path.join(path.resolve(homeDir), '.config', 'opencode'));
assert.strictEqual(
statePath,
path.join(path.resolve(homeDir), '.config', 'opencode', 'ecc-install-state.json')
);
})) passed++; else failed++;
if (test('opencode adapter validate reports an error when compiled plugin is missing', () => {
+8
View File
@@ -192,6 +192,14 @@ test('returns null for missing transcript (no conversation to summarize)', () =>
if (orig !== undefined) process.env.ECC_SKIP_LLM_SUMMARY = orig;
});
test('marks the spawned summarizer so its Stop hook cannot create resume state', () => {
const source = fs.readFileSync(
path.join(__dirname, '..', '..', 'scripts', 'lib', 'llm-summary.js'),
'utf8'
);
assert.match(source, /ECC_LLM_SUMMARY_SUBPROCESS:\s*'1'/);
});
// --- Results ---
console.log('\n=== Test Results ===');
console.log(`Passed: ${passed}`);
+73
View File
@@ -4,6 +4,7 @@ const assert = require('assert');
const fs = require('fs');
const os = require('os');
const path = require('path');
const { spawnSync } = require('child_process');
const {
MCP_SCHEMA_VERSION,
@@ -184,6 +185,78 @@ test('opencode reader splits command array and reads environment', () => {
assert.strictEqual(records.find(r => r.name === 'disabledtool').enabled, false);
});
test('opencode reader honors OPENCODE_CONFIG_DIR before XDG_CONFIG_HOME', () => {
const home = tmpHome();
const explicitRoot = path.join(home, 'explicit-opencode');
const xdgRoot = path.join(home, 'xdg');
for (const root of [explicitRoot, path.join(xdgRoot, 'opencode')]) {
fs.mkdirSync(root, { recursive: true });
fs.writeFileSync(path.join(root, 'opencode.json'), JSON.stringify({
mcp: {
[root === explicitRoot ? 'explicit' : 'xdg']: {
type: 'local',
command: ['node'],
},
},
}), 'utf8');
}
const explicit = readOpencodeMcp({
homeDir: home,
env: {
OPENCODE_CONFIG_DIR: explicitRoot,
XDG_CONFIG_HOME: xdgRoot,
},
});
assert.deepStrictEqual(explicit.map(record => record.name), ['explicit']);
const xdg = readOpencodeMcp({
homeDir: home,
env: { XDG_CONFIG_HOME: xdgRoot },
});
assert.deepStrictEqual(xdg.map(record => record.name), ['xdg']);
});
test('opencode reader isolates an explicit home from ambient config overrides', () => {
const home = tmpHome();
const configRoot = path.join(home, '.config', 'opencode');
const ambientRoot = path.join(home, 'runner-global-opencode');
fs.mkdirSync(configRoot, { recursive: true });
fs.mkdirSync(ambientRoot, { recursive: true });
fs.writeFileSync(path.join(configRoot, 'opencode.json'), JSON.stringify({
mcp: { isolated: { type: 'local', command: ['node'] } },
}), 'utf8');
fs.writeFileSync(path.join(ambientRoot, 'opencode.json'), JSON.stringify({
mcp: { leaked: { type: 'local', command: ['node'] } },
}), 'utf8');
const readerPath = path.join(
__dirname,
'..',
'..',
'scripts',
'lib',
'mcp-inventory',
'readers',
'opencode.js'
);
const child = spawnSync(process.execPath, ['-e', [
'const { readOpencodeMcp } = require(process.env.ECC_TEST_READER);',
'const names = readOpencodeMcp({ homeDir: process.env.ECC_TEST_HOME }).map(record => record.name);',
'process.stdout.write(JSON.stringify(names));',
].join('\n')], {
encoding: 'utf8',
env: {
...process.env,
ECC_TEST_READER: readerPath,
ECC_TEST_HOME: home,
OPENCODE_CONFIG_DIR: ambientRoot,
},
});
assert.strictEqual(child.status, 0, child.stderr);
assert.deepStrictEqual(JSON.parse(child.stdout), ['isolated']);
});
test('collectMcpInventory merges harnesses, detects fragmentation + drift, redacts secrets', () => {
const home = tmpHome();
// claude + opencode agree on github (consistent); codex github uses a
+46
View File
@@ -175,6 +175,52 @@ function writeManagedState(plan, overrides = {}) {
}
});
await test('rejects managed preflight plans without an install-state path', () => {
const root = tempDir('ecc-guided-missing-state-');
try {
const source = path.join(root, 'source.md');
writeFile(source, 'ecc\n');
const plan = managedPlan(root, [{
kind: 'copy-file',
sourcePath: source,
destinationPath: path.join(root, 'AGENTS.md'),
}]);
delete plan.installStatePath;
assert.throws(
() => preflightManagedPlan(plan),
/install-state path is required/i
);
} finally {
fs.rmSync(root, { recursive: true, force: true });
}
});
await test('rejects an identical copy source that is a symbolic link', () => {
if (process.platform === 'win32') return;
const root = tempDir('ecc-guided-source-symlink-');
try {
const realSource = path.join(root, 'real-source.md');
const linkedSource = path.join(root, 'linked-source.md');
const destination = path.join(root, 'AGENTS.md');
writeFile(realSource, 'same\n');
writeFile(destination, 'same\n');
fs.symlinkSync(realSource, linkedSource);
const plan = managedPlan(root, [{
kind: 'copy-file',
sourcePath: linkedSource,
destinationPath: destination,
}]);
assert.throws(
() => preflightManagedPlan(plan),
/symbolic link|regular non-symlink/i
);
} finally {
fs.rmSync(root, { recursive: true, force: true });
}
});
await test('rejects valid install-state from a different managed target identity', () => {
const root = tempDir('ecc-guided-forged-target-');
try {
+25
View File
@@ -0,0 +1,25 @@
function isPackEntry(value) {
return value !== null && typeof value === 'object' && !Array.isArray(value);
}
function getNpmPackEntry(output, packageName) {
const matchesPackage = value => (
isPackEntry(value) && value.name === packageName
);
if (Array.isArray(output)) {
return output.find(matchesPackage);
}
if (!isPackEntry(output)) {
return undefined;
}
if (matchesPackage(output[packageName])) {
return output[packageName];
}
return Object.values(output).find(matchesPackage);
}
module.exports = { getNpmPackEntry };
+68
View File
@@ -0,0 +1,68 @@
const assert = require('assert');
const { getNpmPackEntry } = require('./npm-pack-output');
let passed = 0;
let failed = 0;
function test(name, fn) {
try {
fn();
console.log(` ✓ ${name}`);
passed += 1;
} catch (error) {
console.log(` ✗ ${name}`);
console.error(` ${error.message}`);
failed += 1;
}
}
test('reads the npm 11 array response', () => {
const entry = getNpmPackEntry([
{ name: 'unrelated-package', filename: 'unrelated-package-1.0.0.tgz' },
{ name: 'ecc-universal', filename: 'ecc-universal-2.2.0.tgz' },
], 'ecc-universal');
assert.strictEqual(entry.filename, 'ecc-universal-2.2.0.tgz');
});
test('reads the npm 12 package-keyed response', () => {
const entry = getNpmPackEntry({
'ecc-universal': {
name: 'ecc-universal',
filename: 'ecc-universal-2.2.0.tgz',
},
}, 'ecc-universal');
assert.strictEqual(entry.filename, 'ecc-universal-2.2.0.tgz');
});
test('finds a requested package in a generic object response', () => {
const entry = getNpmPackEntry({
unrelated: { name: 'unrelated-package', filename: 'unrelated-package-1.0.0.tgz' },
target: { name: 'ecc-universal', filename: 'ecc-universal-2.2.0.tgz' },
}, 'ecc-universal');
assert.strictEqual(entry.filename, 'ecc-universal-2.2.0.tgz');
});
test('returns undefined for empty or malformed responses', () => {
assert.strictEqual(getNpmPackEntry([], 'ecc-universal'), undefined);
assert.strictEqual(getNpmPackEntry({}, 'ecc-universal'), undefined);
assert.strictEqual(getNpmPackEntry(null, 'ecc-universal'), undefined);
assert.strictEqual(
getNpmPackEntry([
{ name: 'unrelated-package', filename: 'unrelated-package-1.0.0.tgz' },
], 'ecc-universal'),
undefined
);
assert.strictEqual(
getNpmPackEntry({
unrelated: { name: 'unrelated-package', filename: 'unrelated-package-1.0.0.tgz' },
}, 'ecc-universal'),
undefined
);
});
console.log(`\nPassed: ${passed}`);
console.log(`Failed: ${failed}`);
process.exit(failed > 0 ? 1 : 0);
+389
View File
@@ -0,0 +1,389 @@
'use strict';
const assert = require('assert');
const crypto = require('crypto');
const fs = require('fs');
const os = require('os');
const path = require('path');
const { applyInstallPlan } = require('../../scripts/lib/install/apply');
const { createManifestInstallPlan } = require('../../scripts/lib/install-executor');
const {
buildDoctorReport,
discoverInstalledStates,
repairInstalledStates,
uninstallInstalledStates,
} = require('../../scripts/lib/install-lifecycle');
const { createInstallState, writeInstallState } = require('../../scripts/lib/install-state');
const {
cleanupLegacyOpencodeInstall,
getLegacyOpencodeLocation,
inspectLegacyOpencodeState,
removeVerifiedLegacyFile,
} = require('../../scripts/lib/install/opencode-legacy-migration');
const REPO_ROOT = path.join(__dirname, '..', '..');
const SOURCE_RELATIVE_PATH = path.join('skills', 'skill-comply', 'SKILL.md');
let passed = 0;
let failed = 0;
function test(name, fn) {
try {
fn();
console.log(` ✓ ${name}`);
passed += 1;
} catch (error) {
console.log(` ✗ ${name}`);
console.log(` Error: ${error.message}`);
failed += 1;
}
}
function digest(content) {
return crypto.createHash('sha256').update(content).digest('hex');
}
function seedLegacyInstall(homeDir, options = {}) {
const targetRoot = path.join(homeDir, '.opencode');
const installStatePath = path.join(targetRoot, 'ecc-install-state.json');
const destinationPath = path.join(targetRoot, SOURCE_RELATIVE_PATH);
const sourceContent = fs.readFileSync(path.join(REPO_ROOT, SOURCE_RELATIVE_PATH));
const installedContent = options.modified ? Buffer.from('user-modified\n') : sourceContent;
fs.mkdirSync(path.dirname(destinationPath), { recursive: true });
fs.writeFileSync(destinationPath, installedContent);
const operation = {
kind: 'copy-file',
moduleId: 'workflow-quality',
sourceRelativePath: SOURCE_RELATIVE_PATH,
destinationPath,
strategy: 'preserve-relative-path',
ownership: 'managed',
scaffoldOnly: false,
contentSha256: digest(sourceContent),
};
const operations = [operation];
if (options.includeJsonOperation) {
const configPath = path.join(targetRoot, 'opencode.json');
fs.writeFileSync(configPath, JSON.stringify({ plugin: ['ecc'] }, null, 2) + '\n');
operations.push({
kind: 'merge-json',
moduleId: 'opencode-plugin',
sourceRelativePath: '.opencode/opencode.json',
destinationPath: configPath,
strategy: 'merge-json',
ownership: 'managed',
scaffoldOnly: false,
mergePayload: { plugin: ['ecc'] },
previousExists: false,
previousContent: null,
});
}
const state = createInstallState({
adapter: { id: 'opencode-home', target: 'opencode', kind: 'home' },
targetRoot,
installStatePath,
request: {
profile: null,
modules: ['workflow-quality'],
includeComponents: [],
excludeComponents: [],
legacyLanguages: [],
legacyMode: false,
},
resolution: { selectedModules: ['workflow-quality'], skippedModules: [] },
source: {
repoVersion: require('../../package.json').version,
repoCommit: 'legacy-opencode-test',
manifestVersion: require('../../manifests/install-modules.json').version,
},
operations,
});
writeInstallState(installStatePath, state);
return { targetRoot, installStatePath, destinationPath };
}
function canonicalPlan(homeDir, env) {
return createManifestInstallPlan({
sourceRoot: REPO_ROOT,
target: 'opencode',
moduleIds: ['workflow-quality'],
projectRoot: homeDir,
homeDir,
...(env ? { env } : {}),
exemptValidationCodes: ['opencode-plugin-not-built'],
});
}
console.log('\n=== Testing OpenCode legacy migration ===\n');
test('legacy inspection distinguishes absent, invalid, and unreadable state', () => {
const homeDir = fs.mkdtempSync(path.join(os.tmpdir(), 'opencode-legacy-inspect-'));
try {
const location = getLegacyOpencodeLocation(homeDir);
assert.strictEqual(inspectLegacyOpencodeState(null).status, 'absent');
assert.strictEqual(inspectLegacyOpencodeState(location).status, 'absent');
fs.mkdirSync(location.targetRoot, { recursive: true });
fs.mkdirSync(location.installStatePath);
assert.strictEqual(inspectLegacyOpencodeState(location).status, 'invalid');
fs.rmSync(location.installStatePath, { recursive: true, force: true });
fs.writeFileSync(location.installStatePath, '{not-json', 'utf8');
const unreadable = inspectLegacyOpencodeState(location);
assert.strictEqual(unreadable.status, 'unreadable');
assert.ok(unreadable.error.includes(location.installStatePath));
assert.deepStrictEqual(cleanupLegacyOpencodeInstall(null), {
detected: false,
complete: false,
removedPaths: [],
retainedPaths: [],
warnings: [],
});
} finally {
fs.rmSync(homeDir, { recursive: true, force: true });
}
});
test('discovery and doctor surface the legacy managed root', () => {
const homeDir = fs.mkdtempSync(path.join(os.tmpdir(), 'opencode-legacy-discover-'));
try {
const legacy = seedLegacyInstall(homeDir);
const records = discoverInstalledStates({ homeDir, projectRoot: homeDir, targets: ['opencode'] });
assert.strictEqual(records.length, 2);
assert.strictEqual(records[0].exists, false);
assert.strictEqual(records[1].installStatePath, legacy.installStatePath);
assert.strictEqual(records[1].legacyLayout, 'opencode');
const doctor = buildDoctorReport({
repoRoot: REPO_ROOT,
homeDir,
projectRoot: homeDir,
targets: ['opencode'],
});
assert.ok(doctor.results.some(result => (
result.issues.some(issue => issue.code === 'legacy-opencode-layout')
)));
} finally {
fs.rmSync(homeDir, { recursive: true, force: true });
}
});
test('uninstall removes unchanged legacy-managed files and preserves user content', () => {
const homeDir = fs.mkdtempSync(path.join(os.tmpdir(), 'opencode-legacy-uninstall-'));
try {
const legacy = seedLegacyInstall(homeDir);
const sentinelPath = path.join(legacy.targetRoot, 'user.txt');
fs.writeFileSync(sentinelPath, 'keep\n');
const result = uninstallInstalledStates({ homeDir, projectRoot: homeDir, targets: ['opencode'] });
assert.strictEqual(result.summary.errorCount, 0, JSON.stringify(result));
assert.ok(!fs.existsSync(legacy.destinationPath));
assert.ok(!fs.existsSync(legacy.installStatePath));
assert.strictEqual(fs.readFileSync(sentinelPath, 'utf8'), 'keep\n');
} finally {
fs.rmSync(homeDir, { recursive: true, force: true });
}
});
test('a canonical install migrates unchanged legacy ownership', () => {
const homeDir = fs.mkdtempSync(path.join(os.tmpdir(), 'opencode-legacy-apply-'));
try {
const legacy = seedLegacyInstall(homeDir);
const result = applyInstallPlan(canonicalPlan(homeDir));
assert.ok(result.applied);
assert.ok(fs.existsSync(path.join(homeDir, '.config', 'opencode', 'ecc-install-state.json')));
assert.ok(!fs.existsSync(legacy.installStatePath));
assert.ok(!fs.existsSync(legacy.destinationPath));
} finally {
fs.rmSync(homeDir, { recursive: true, force: true });
}
});
test('a canonical install migrates legacy ownership when its config root is overridden', () => {
const homeDir = fs.mkdtempSync(path.join(os.tmpdir(), 'opencode-legacy-custom-root-'));
try {
const legacy = seedLegacyInstall(homeDir);
const configRoot = path.join(homeDir, 'custom', 'opencode');
const result = applyInstallPlan(canonicalPlan(homeDir, {
OPENCODE_CONFIG_DIR: configRoot,
}));
assert.ok(result.applied);
assert.ok(fs.existsSync(path.join(configRoot, 'ecc-install-state.json')));
assert.ok(!fs.existsSync(legacy.installStatePath));
assert.ok(!fs.existsSync(legacy.destinationPath));
} finally {
fs.rmSync(homeDir, { recursive: true, force: true });
}
});
test('legacy non-file operations do not block canonical cleanup or repair', () => {
const applyHome = fs.mkdtempSync(path.join(os.tmpdir(), 'opencode-legacy-json-apply-'));
const repairHome = fs.mkdtempSync(path.join(os.tmpdir(), 'opencode-legacy-json-repair-'));
try {
const legacyApply = seedLegacyInstall(applyHome, { includeJsonOperation: true });
applyInstallPlan(canonicalPlan(applyHome));
assert.ok(!fs.existsSync(legacyApply.installStatePath));
assert.ok(fs.existsSync(path.join(legacyApply.targetRoot, 'opencode.json')));
const legacyRepair = seedLegacyInstall(repairHome, { includeJsonOperation: true });
const result = repairInstalledStates({
repoRoot: REPO_ROOT,
homeDir: repairHome,
projectRoot: repairHome,
targets: ['opencode'],
});
const canonicalStatePath = path.join(
repairHome,
'.config',
'opencode',
'ecc-install-state.json'
);
assert.strictEqual(result.summary.errorCount, 0, JSON.stringify(result));
assert.ok(fs.existsSync(canonicalStatePath));
assert.ok(!fs.existsSync(legacyRepair.installStatePath));
assert.ok(fs.existsSync(path.join(legacyRepair.targetRoot, 'opencode.json')));
} finally {
fs.rmSync(applyHome, { recursive: true, force: true });
fs.rmSync(repairHome, { recursive: true, force: true });
}
});
test('repair migrates a legacy install while preserving modified legacy files', () => {
const homeDir = fs.mkdtempSync(path.join(os.tmpdir(), 'opencode-legacy-repair-'));
try {
const legacy = seedLegacyInstall(homeDir, { modified: true });
const result = repairInstalledStates({
repoRoot: REPO_ROOT,
homeDir,
projectRoot: homeDir,
targets: ['opencode'],
});
assert.strictEqual(result.summary.errorCount, 0, JSON.stringify(result));
assert.ok(fs.existsSync(path.join(homeDir, '.config', 'opencode', 'ecc-install-state.json')));
assert.strictEqual(fs.readFileSync(legacy.destinationPath, 'utf8'), 'user-modified\n');
assert.ok(fs.existsSync(legacy.installStatePath));
} finally {
fs.rmSync(homeDir, { recursive: true, force: true });
}
});
test('migration never follows a legacy managed-file symlink', () => {
const homeDir = fs.mkdtempSync(path.join(os.tmpdir(), 'opencode-legacy-symlink-'));
try {
const legacy = seedLegacyInstall(homeDir);
const victimPath = path.join(homeDir, 'victim.txt');
fs.writeFileSync(victimPath, 'do-not-delete\n');
fs.rmSync(legacy.destinationPath);
try {
fs.symlinkSync(victimPath, legacy.destinationPath);
} catch (error) {
if (process.platform === 'win32' && error.code === 'EPERM') {
console.log(' (symlink unsupported on this platform; skipping)');
return;
}
throw error;
}
const result = applyInstallPlan(canonicalPlan(homeDir));
assert.ok(result.warnings.some(warning => warning.includes('Legacy OpenCode migration')));
assert.strictEqual(fs.readFileSync(victimPath, 'utf8'), 'do-not-delete\n');
assert.ok(fs.lstatSync(legacy.destinationPath).isSymbolicLink());
assert.ok(fs.existsSync(legacy.installStatePath));
} finally {
fs.rmSync(homeDir, { recursive: true, force: true });
}
});
test('legacy cleanup never overwrites a file created during quarantine recovery', () => {
const homeDir = fs.mkdtempSync(path.join(os.tmpdir(), 'opencode-legacy-no-clobber-'));
const targetRoot = path.join(homeDir, '.opencode');
const destinationPath = path.join(targetRoot, 'managed.md');
let quarantinePath = null;
let effectiveSafePath = destinationPath;
let userDescriptor = null;
const openDescriptors = [];
try {
fs.mkdirSync(targetRoot, { recursive: true });
fs.writeFileSync(destinationPath, 'managed-old\n');
const originalDescriptor = fs.openSync(destinationPath, 'r');
openDescriptors.push(originalDescriptor);
const originalStat = fs.fstatSync(originalDescriptor, { bigint: true });
let injected = false;
const fileSystem = new Proxy(fs, {
get(target, property) {
if (property === 'renameSync') {
return (sourcePath, targetPath) => {
fs.renameSync(sourcePath, targetPath);
effectiveSafePath = sourcePath;
quarantinePath = targetPath;
};
}
if (property === 'lstatSync') {
return (filePath, options) => {
if (!injected && quarantinePath && filePath === quarantinePath) {
injected = true;
const stat = fs.fstatSync(originalDescriptor, options);
userDescriptor = fs.openSync(effectiveSafePath, 'wx+', 0o600);
openDescriptors.push(userDescriptor);
fs.writeFileSync(userDescriptor, 'user-new\n');
return new Proxy(stat, {
get(statTarget, statProperty) {
if (statProperty === 'ino') return statTarget.ino + 1n;
const value = Reflect.get(statTarget, statProperty, statTarget);
return typeof value === 'function' ? value.bind(statTarget) : value;
},
});
}
return fs.lstatSync(filePath, options);
};
}
const value = Reflect.get(target, property, target);
return typeof value === 'function' ? value.bind(target) : value;
},
});
assert.throws(
() => removeVerifiedLegacyFile(
{ destinationPath, stat: originalStat },
{ targetRoot },
fileSystem
),
error => {
assert.strictEqual(error.code, 'EEXIST');
assert.strictEqual(error.retainedPath, quarantinePath);
return true;
}
);
const destinationStat = fs.lstatSync(destinationPath, { bigint: true });
const userStat = fs.fstatSync(userDescriptor, { bigint: true });
const retainedStat = fs.lstatSync(quarantinePath, { bigint: true });
const managedStat = fs.fstatSync(originalDescriptor, { bigint: true });
assert.strictEqual(destinationStat.dev, userStat.dev);
assert.strictEqual(destinationStat.ino, userStat.ino);
assert.strictEqual(retainedStat.dev, managedStat.dev);
assert.strictEqual(retainedStat.ino, managedStat.ino);
const userContent = Buffer.alloc(Buffer.byteLength('user-new\n'));
const managedContent = Buffer.alloc(Buffer.byteLength('managed-old\n'));
fs.readSync(userDescriptor, userContent, 0, userContent.length, 0);
fs.readSync(originalDescriptor, managedContent, 0, managedContent.length, 0);
assert.strictEqual(userContent.toString('utf8'), 'user-new\n');
assert.strictEqual(managedContent.toString('utf8'), 'managed-old\n');
} finally {
for (const descriptor of openDescriptors) {
try {
fs.closeSync(descriptor);
} catch (_error) {
// Best-effort fixture cleanup.
}
}
fs.rmSync(homeDir, { recursive: true, force: true });
if (quarantinePath) {
fs.rmSync(path.dirname(quarantinePath), { recursive: true, force: true });
}
}
});
console.log(`\nResults: Passed: ${passed}, Failed: ${failed}`);
process.exit(failed > 0 ? 1 : 0);