Skip to content

armgit / ECC

Public Imported from GitHub
0

The agent harness performance optimization system. Skills, instincts, memory, security, and research-first development for Claude Code, Codex, Opencode, Cursor and beyond.

fix(install): integrate atomic state and global dry-run (#3486)

haelyra53dd92eef66a
diff --cc tests/lib/install-state.test.js
index 653a6bb10,ebbc33d5a..62c15e0b7
--- a/tests/lib/install-state.test.js
+++ b/tests/lib/install-state.test.js
@@@ -328,6 -328,161 +328,187 @@@ function runTests()
}
})) passed++; else failed++;
+ function makeState(targetRoot, statePath, marker) {
+ return createInstallState({
+ adapter: { id: 'claude-home' },
+ targetRoot,
+ installStatePath: statePath,
+ request: {
+ profile: 'core',
+ modules: [],
+ legacyLanguages: [],
+ legacyMode: false,
+ },
+ resolution: {
+ selectedModules: ['rules-core'],
+ skippedModules: [],
+ },
+ operations: [],
+ source: {
+ repoVersion: CURRENT_PACKAGE_VERSION,
+ repoCommit: 'abc123',
+ manifestVersion: 1,
+ },
+ lastValidatedAt: marker,
+ });
+ }
+
+ function listStagingFiles(dirPath) {
+ return fs.readdirSync(dirPath).filter(name => name.includes('.tmp'));
+ }
+
+ if (test('writeInstallState preserves the previous valid state when rename fails', () => {
+ const testDir = createTestDir();
+ const statePath = path.join(testDir, 'ecc-install-state.json');
+
+ try {
+ writeInstallState(statePath, makeState(testDir, statePath, '2026-01-01T00:00:00Z'));
+ const originalRenameSync = fs.renameSync;
+ fs.renameSync = () => { throw new Error('injected rename failure'); };
+ try {
+ assert.throws(
+ () => writeInstallState(statePath, makeState(testDir, statePath, '2026-02-01T00:00:00Z')),
+ /injected rename failure/
+ );
+ } finally {
+ fs.renameSync = originalRenameSync;
+ }
+ assert.strictEqual(readInstallState(statePath).lastValidatedAt, '2026-01-01T00:00:00Z');
+ assert.deepStrictEqual(listStagingFiles(testDir), []);
+ } finally {
+ cleanupTestDir(testDir);
+ }
+ })) passed++; else failed++;
+
+ if (test('writeInstallState cleans up staging files when the write fails', () => {
+ const testDir = createTestDir();
+ const statePath = path.join(testDir, 'ecc-install-state.json');
+
+ try {
+ const originalWriteFileSync = fs.writeFileSync;
+ fs.writeFileSync = () => { throw new Error('injected write failure'); };
+ try {
+ assert.throws(
+ () => writeInstallState(statePath, makeState(testDir, statePath, '2026-01-01T00:00:00Z')),
+ /injected write failure/
+ );
+ } finally {
+ fs.writeFileSync = originalWriteFileSync;
+ }
+ assert.ok(!fs.existsSync(statePath));
+ assert.deepStrictEqual(listStagingFiles(testDir), []);
+ } finally {
+ cleanupTestDir(testDir);
+ }
+ })) passed++; else failed++;
+
+ if (test('writeInstallState replaces symlinks instead of following them', () => {
+ if (process.platform === 'win32') return;
+ const testDir = createTestDir();
+ const statePath = path.join(testDir, 'ecc-install-state.json');
+ const targetPath = path.join(testDir, 'link-target.json');
+ fs.writeFileSync(targetPath, '{"untouched":true}\n');
+
+ try {
+ fs.symlinkSync(targetPath, statePath);
+ writeInstallState(statePath, makeState(testDir, statePath, '2026-01-01T00:00:00Z'));
+ assert.ok(fs.lstatSync(statePath).isFile());
+ assert.strictEqual(readInstallState(statePath).lastValidatedAt, '2026-01-01T00:00:00Z');
+ assert.strictEqual(fs.readFileSync(targetPath, 'utf8'), '{"untouched":true}\n');
+ } finally {
+ cleanupTestDir(testDir);
+ }
+ })) passed++; else failed++;
+
+ if (test('concurrent writeInstallState calls always leave a complete valid state', () => {
+ const testDir = createTestDir();
+ const statePath = path.join(testDir, 'ecc-install-state.json');
+ const markers = [
+ '2026-03-01T00:00:00Z', '2026-03-02T00:00:00Z', '2026-03-03T00:00:00Z',
+ '2026-03-04T00:00:00Z', '2026-03-05T00:00:00Z', '2026-03-06T00:00:00Z',
+ '2026-03-07T00:00:00Z', '2026-03-08T00:00:00Z', '2026-03-09T00:00:00Z',
+ ];
+
+ try {
+ writeInstallState(statePath, makeState(testDir, statePath, markers[0]));
- const { spawn } = require('child_process');
- const script = 'const fs = require("fs");' +
- 'const {readInstallState, writeInstallState} = require(process.env.REPO_ROOT + "/scripts/lib/install-state");' +
- 'for (let round = 0; round < 30; round += 1) {' +
- 'const state = readInstallState(process.env.STATE_PATH);' +
- 'state.lastValidatedAt = process.env.MARKER;' +
- 'writeInstallState(process.env.STATE_PATH, state);' +
- '}' +
- 'fs.writeFileSync(process.env.DONE_FILE, "ok");';
- const children = markers.slice(1).map(marker => {
- const tag = marker.replace(/:/g, '-');
- const doneFile = path.join(testDir, `done-${tag}.marker`);
- const errFile = path.join(testDir, `err-${tag}.log`);
- const errFd = fs.openSync(errFile, 'w');
- const child = spawn(process.execPath, ['-e', script], {
- stdio: ['ignore', 'ignore', errFd],
- env: {
- ...process.env,
- REPO_ROOT: path.join(__dirname, '..', '..'),
- STATE_PATH: statePath,
- MARKER: marker,
- DONE_FILE: doneFile,
- },
++ const { spawnSync } = require('child_process');
++ const supervisor = `
++ const fs = require('fs');
++ const assert = require('assert');
++ const { spawn } = require('child_process');
++ const { readInstallState } = require(process.env.ECC_STATE_MODULE);
++ const markers = JSON.parse(process.env.ECC_STATE_MARKERS);
++ const script = 'const { readInstallState, writeInstallState } = require(process.env.ECC_STATE_MODULE);' +
++ 'for (let round = 0; round < 30; round++) {' +
++ 'const state = readInstallState(process.env.ECC_STATE_PATH);' +
++ 'state.lastValidatedAt = process.env.ECC_STATE_MARKER;' +
++ 'writeInstallState(process.env.ECC_STATE_PATH, state); }';
++ const entries = markers.slice(1).map(marker => {
++ const child = spawn(process.execPath, ['-e', script], {
++ stdio: ['ignore', 'ignore', 'pipe'],
++ env: { ...process.env, ECC_STATE_MARKER: marker }
++ });
++ let stderr = '';
++ child.stderr.on('data', chunk => { stderr += chunk; });
++ let spawnError;
++ child.on('error', error => { spawnError = error; });
++ const closed = new Promise(resolve => child.on('close', code => {
++ resolve({ code, stderr, spawnError });
++ }));
++ return { child, closed };
+ });
- fs.closeSync(errFd);
- return { child, marker, doneFile, errFile };
++ let deadline;
++ let observer;
++ let observationError;
++ let observations = 0;
++ (async () => {
++ try {
++ observer = setInterval(() => {
++ try {
++ assert.ok(markers.includes(readInstallState(process.env.ECC_STATE_PATH).lastValidatedAt));
++ observations++;
++ } catch (error) { observationError = error; }
++ }, 5);
++ const results = await Promise.race([
++ Promise.all(entries.map(entry => entry.closed)),
++ new Promise((_, reject) => { deadline = setTimeout(() => reject(new Error('writer deadline')), 20000); })
++ ]);
++ if (observationError) throw observationError;
++ assert.ok(observations > 0, 'expected concurrent reads');
++ for (const result of results) {
++ if (result.spawnError) throw result.spawnError;
++ assert.strictEqual(result.code, 0, result.stderr);
++ assert.strictEqual(result.stderr, '');
++ }
++ } finally {
++ clearTimeout(deadline);
++ clearInterval(observer);
++ for (const entry of entries) {
++ if (entry.child.exitCode === null && entry.child.signalCode === null) entry.child.kill('SIGKILL');
++ }
++ await Promise.all(entries.map(entry => entry.closed));
++ }
++ })().catch(error => { console.error(error.stack); process.exitCode = 1; });
++ `;
++ const result = spawnSync(process.execPath, ['-e', supervisor], {
++ encoding: 'utf8',
++ timeout: 30000,
++ env: {
++ ...process.env,
++ ECC_STATE_MODULE: path.join(__dirname, '..', '..', 'scripts', 'lib', 'install-state.js'),
++ ECC_STATE_PATH: statePath,
++ ECC_STATE_MARKERS: JSON.stringify(markers),
++ },
+ });
- const deadline = Date.now() + 120000;
- for (;;) {
- const snapshot = readInstallState(statePath);
- assert.ok(markers.includes(snapshot.lastValidatedAt));
- const pending = children.filter(entry => !fs.existsSync(entry.doneFile));
- if (pending.length === 0) break;
- if (Date.now() > deadline) {
- const details = children.map(entry =>
- `${entry.marker}: ${fs.existsSync(entry.doneFile) ? 'done' : 'PENDING'} ${fs.readFileSync(entry.errFile, 'utf8')}`
- ).join('\n');
- throw new Error(`timed out waiting for concurrent writers\n${details}`);
- }
- Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 10);
- }
- for (const entry of children) {
- assert.strictEqual(fs.readFileSync(entry.errFile, 'utf8'), '', `writer ${entry.marker} failed`);
- }
++ assert.strictEqual(result.status, 0, result.stderr || String(result.error));
+ const final = readInstallState(statePath);
+ assert.ok(markers.includes(final.lastValidatedAt));
+ assert.deepStrictEqual(listStagingFiles(testDir), []);
+ } finally {
+ cleanupTestDir(testDir);
+ }
+ })) passed++; else failed++;
+
console.log(`\nResults: Passed: ${passed}, Failed: ${failed}`);
process.exit(failed > 0 ? 1 : 0);
}
diff --cc tests/scripts/install-dry-run.test.js
index 000000000,09f9ecea0..b05efcce3
mode 000000,100644..100644
--- a/tests/scripts/install-dry-run.test.js
+++ b/tests/scripts/install-dry-run.test.js
@@@ -1,0 -1,121 +1,153 @@@
+ 'use strict';
+
+ const assert = require('assert');
+ const fs = require('fs');
+ const os = require('os');
+ const path = require('path');
+ const { spawnSync } = require('child_process');
+
+ const repoRoot = path.join(__dirname, '..', '..');
+ const eccCli = path.join(repoRoot, 'scripts', 'ecc.js');
+
+ let passed = 0;
+ let failed = 0;
+
+ function test(name, fn) {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-install-dry-run-'));
+ try {
+ const projectRoot = path.join(root, 'project');
+ const homeDir = path.join(root, 'home');
+ fs.mkdirSync(projectRoot, { recursive: true });
+ fs.mkdirSync(homeDir, { recursive: true });
+ fn({ projectRoot, homeDir });
+ passed++;
+ console.log(` PASS ${name}`);
+ } catch (error) {
+ failed++;
+ console.error(` FAIL ${name}: ${error.stack}`);
+ } finally {
+ fs.rmSync(root, { recursive: true, force: true });
+ }
+ }
+
+ function makeEnv(homeDir) {
+ const env = {
+ ...process.env,
+ HOME: homeDir,
+ USERPROFILE: homeDir,
+ CODEX_HOME: path.join(homeDir, '.codex'),
+ XDG_CONFIG_HOME: path.join(homeDir, '.config'),
+ };
+ delete env.ECC_DRY_RUN;
++ delete env.CLAUDE_CONFIG_DIR;
++ delete env.ECC_AGENT_DATA_HOME;
++ delete env.OPENCODE_CONFIG_DIR;
+ return env;
+ }
+
+ function runEcc(args, context) {
+ return spawnSync(process.execPath, [eccCli, ...args], {
+ cwd: context.projectRoot,
+ encoding: 'utf8',
+ timeout: 120000,
+ env: makeEnv(context.homeDir),
+ });
+ }
+
+ function walkFiles(dirPath) {
+ const found = [];
+ const visit = current => {
+ for (const entry of fs.readdirSync(current, { withFileTypes: true })) {
+ const full = path.join(current, entry.name);
+ if (entry.isDirectory()) visit(full);
+ else if (entry.isFile()) found.push(full);
+ }
+ };
+ if (fs.existsSync(dirPath)) visit(dirPath);
+ return found.sort();
+ }
+
+ function findStateFiles(homeDir) {
+ return walkFiles(homeDir).filter(file => file.endsWith('ecc-install-state.json'));
+ }
+
+ function testInstallForms() {
+ for (const args of [
+ ['--dry-run', 'install', '--target', 'cursor', '--modules', 'rules-core'],
+ ['install', '--target', 'cursor', '--modules', 'rules-core', '--dry-run'],
+ ]) {
+ test(`dry-run install writes nothing (${args.slice(0, 2).join(' ')})`, context => {
+ const result = runEcc(args, context);
+ assert.strictEqual(result.status, 0, result.stderr);
+ assert.deepStrictEqual(walkFiles(context.homeDir), []);
+ assert.deepStrictEqual(walkFiles(context.projectRoot), []);
+ assert.deepStrictEqual(findStateFiles(context.homeDir), []);
+ });
+ }
+ }
+
+ function testRepairForms() {
+ for (const args of [
+ ['--dry-run', 'repair', '--target', 'cursor'],
+ ['repair', '--target', 'cursor', '--dry-run'],
+ ]) {
+ test(`dry-run repair preserves drift and state (${args.slice(0, 2).join(' ')})`, context => {
+ const installed = runEcc(['install', '--target', 'cursor', '--modules', 'rules-core'], context);
+ assert.strictEqual(installed.status, 0, installed.stderr);
+ const roots = [context.homeDir, context.projectRoot];
+ const stateFiles = roots.flatMap(findStateFiles);
+ assert.ok(stateFiles.length > 0, 'expected a real install to write state first');
+ const managedFile = roots.flatMap(walkFiles).find(
+ file => !file.endsWith('ecc-install-state.json') && !file.endsWith('.db')
+ );
+ assert.ok(managedFile, 'expected a real install to write managed files first');
+ fs.appendFileSync(managedFile, '\n# local drift marker\n');
+ const drifted = fs.readFileSync(managedFile, 'utf8');
+ const stateBefore = stateFiles.map(file => fs.readFileSync(file));
+
+ const result = runEcc(args, context);
+ assert.strictEqual(result.status, 0, result.stderr);
+ assert.strictEqual(fs.readFileSync(managedFile, 'utf8'), drifted);
+ assert.deepStrictEqual(
+ stateFiles.map(file => fs.readFileSync(file)),
+ stateBefore
+ );
+ });
+ }
+ }
+
++function testDryRunEnvironment() {
++ for (const value of ['1', 'true', '']) {
++ test(`direct install honors or rejects ECC_DRY_RUN=${JSON.stringify(value)}`, context => {
++ const result = spawnSync(process.execPath, [eccCli, 'install', '--target', 'cursor', '--modules', 'rules-core'], {
++ cwd: context.projectRoot,
++ encoding: 'utf8',
++ timeout: 120000,
++ env: { ...makeEnv(context.homeDir), ECC_DRY_RUN: value },
++ });
++ assert.strictEqual(result.status, value === '1' ? 0 : 1, result.stderr);
++ if (value !== '1') assert.ok(result.stderr.includes('ECC_DRY_RUN'));
++ assert.deepStrictEqual(walkFiles(context.homeDir), []);
++ assert.deepStrictEqual(walkFiles(context.projectRoot), []);
++ });
++ }
++ test('explicit dry-run remains active with ECC_DRY_RUN=0', context => {
++ const result = spawnSync(process.execPath, [eccCli, 'install', '--target', 'cursor', '--modules', 'rules-core', '--dry-run'], {
++ cwd: context.projectRoot,
++ encoding: 'utf8',
++ timeout: 120000,
++ env: { ...makeEnv(context.homeDir), ECC_DRY_RUN: '0' },
++ });
++ assert.strictEqual(result.status, 0, result.stderr);
++ assert.deepStrictEqual(walkFiles(context.homeDir), []);
++ assert.deepStrictEqual(walkFiles(context.projectRoot), []);
++ });
++}
++
+ console.log('\nInstall dry-run CLI regression tests:\n');
+ testInstallForms();
++testDryRunEnvironment();
+ testRepairForms();
+
+ console.log(`\nResults: Passed: ${passed}, Failed: ${failed}`);
+ process.exitCode = failed ? 1 : 0;