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(sessions): serialize alias read-modify-write operations

Yann Robertob1ba495997d0
diff --git a/scripts/lib/install/claude-settings-lock.js b/scripts/lib/install/claude-settings-lock.js
index 164e887ec..88c72580f 100644
--- a/scripts/lib/install/claude-settings-lock.js
+++ b/scripts/lib/install/claude-settings-lock.js
@@ -141,22 +141,36 @@ function recoverSettingsLock(lockPath, label = 'Claude settings') {
}
}
-function acquireSettingsLock(settingsPath, { label = 'Claude settings' } = {}) {
+function acquireSettingsLock(settingsPath, { label = 'Claude settings', timeoutMs = 0 } = {}) {
+ if (!Number.isFinite(timeoutMs) || timeoutMs < 0) {
+ throw new TypeError('Lock timeoutMs must be a finite non-negative number.');
+ }
const lockPath = `${settingsPath}.ecc.lock`;
+ const deadline = performance.now() + timeoutMs;
+ const sleeper = new Int32Array(new SharedArrayBuffer(4));
fs.mkdirSync(path.dirname(settingsPath), { recursive: true });
- try {
- return createSettingsLock(lockPath, label);
- } catch (error) {
- if (!error || error.code !== 'EEXIST') {
- throw error;
+ while (true) {
+ try {
+ return createSettingsLock(lockPath, label);
+ } catch (error) {
+ if (!error || error.code !== 'EEXIST') throw error;
+ }
+ try {
+ const recovered = recoverSettingsLock(lockPath, label);
+ if (recovered) return recovered;
+ } catch (error) {
+ // A different writer can acquire or release between inspection and recovery.
+ if (!error || (error.code !== 'EEXIST' && !(timeoutMs > 0 && error.code === 'ENOENT'))) throw error;
+ }
+ const remaining = deadline - performance.now();
+ if (remaining <= 0) {
+ throw new Error(
+ `Another ECC process is updating ${label}: ${settingsPath}. `
+ + `If no ECC process is active, inspect and remove ${lockPath}.`
+ );
}
+ Atomics.wait(sleeper, 0, 0, Math.min(10, remaining));
}
- const recovered = recoverSettingsLock(lockPath, label);
- if (recovered) return recovered;
- throw new Error(
- `Another ECC process is updating ${label}: ${settingsPath}. `
- + `If no ECC process is active, inspect and remove ${lockPath}.`
- );
}
function runWithSettingsLock(settingsPath, callback) {
diff --git a/scripts/lib/session-aliases.js b/scripts/lib/session-aliases.js
index bfc846315..b57664472 100644
--- a/scripts/lib/session-aliases.js
+++ b/scripts/lib/session-aliases.js
@@ -5,10 +5,11 @@
const fs = require('fs');
const path = require('path');
+const { writeFileAtomic } = require('./atomic-write');
+const { acquireSettingsLock } = require('./install/claude-settings-lock');
const {
getClaudeDir,
- ensureDir,
readFile,
log
} = require('./utils');
@@ -80,76 +81,81 @@ function loadAliases() {
}
}
-/**
- * Save aliases to file with atomic write
- * @param {object} aliases - Aliases object to save
- * @returns {boolean} Success status
- */
-function saveAliases(aliases) {
- const aliasesPath = getAliasesPath();
- const tempPath = aliasesPath + '.tmp';
- const backupPath = aliasesPath + '.bak';
-
- try {
- // Update metadata
- aliases.metadata = {
- totalCount: Object.keys(aliases.aliases).length,
- lastUpdated: new Date().toISOString()
- };
-
- const content = JSON.stringify(aliases, null, 2);
-
- // Ensure directory exists
- ensureDir(path.dirname(aliasesPath));
-
- // Create backup if file exists
- if (fs.existsSync(aliasesPath)) {
- fs.copyFileSync(aliasesPath, backupPath);
- }
-
- // Atomic write: write to temp file, then rename
- fs.writeFileSync(tempPath, content, 'utf8');
-
- // On Windows, rename fails with EEXIST if destination exists, so delete first.
- // On Unix/macOS, rename(2) atomically replaces the destination — skip the
- // delete to avoid an unnecessary non-atomic window between unlink and rename.
- if (process.platform === 'win32' && fs.existsSync(aliasesPath)) {
- fs.unlinkSync(aliasesPath);
- }
- fs.renameSync(tempPath, aliasesPath);
+// Reject callback reentry instead of allowing a nested write to be overwritten
+// by the outer transaction's snapshot.
+const activeWrites = new Set();
- // Remove backup on success
- if (fs.existsSync(backupPath)) {
- fs.unlinkSync(backupPath);
- }
+function withAliasesLock(callback, failure) {
+ const aliasesPath = path.resolve(getAliasesPath());
+ if (activeWrites.has(aliasesPath)) {
+ log('[Aliases] Cannot write aliases from inside an alias transaction');
+ return failure;
+ }
- return true;
- } catch (err) {
- log(`[Aliases] Error saving aliases: ${err.message}`);
-
- // Restore from backup if exists
- if (fs.existsSync(backupPath)) {
- try {
- fs.copyFileSync(backupPath, aliasesPath);
- log('[Aliases] Restored from backup');
- } catch (restoreErr) {
- log(`[Aliases] Failed to restore backup: ${restoreErr.message}`);
- }
- }
+ let release;
+ try {
+ release = acquireSettingsLock(aliasesPath, { label: 'session aliases', timeoutMs: 5000 });
+ } catch (error) {
+ log(`[Aliases] Error locking aliases: ${error.message}`);
+ return failure;
+ }
- // Clean up temp file (best-effort)
+ activeWrites.add(aliasesPath);
+ let result;
+ let primaryError;
+ let callbackFailed = false;
+ let releaseError;
+ try {
+ result = callback();
+ } catch (error) {
+ callbackFailed = true;
+ primaryError = error;
+ } finally {
try {
- if (fs.existsSync(tempPath)) {
- fs.unlinkSync(tempPath);
- }
- } catch {
- // Non-critical: temp file will be overwritten on next save
+ release();
+ } catch (error) {
+ releaseError = error;
}
+ activeWrites.delete(aliasesPath);
+ }
+ if (callbackFailed) {
+ if (releaseError) log(`[Aliases] Error releasing aliases lock: ${releaseError.message}`);
+ throw primaryError;
+ }
+ if (releaseError) {
+ log(`[Aliases] Error releasing aliases lock: ${releaseError.message}`);
+ return failure;
+ }
+ return result;
+}
+function saveAliasesUnlocked(aliases) {
+ try {
+ const snapshot = {
+ ...aliases,
+ metadata: {
+ totalCount: Object.keys(aliases.aliases).length,
+ lastUpdated: new Date().toISOString()
+ }
+ };
+ writeFileAtomic(getAliasesPath(), JSON.stringify(snapshot, null, 2));
+ return true;
+ } catch (error) {
+ log(`[Aliases] Error saving aliases: ${error.message}`);
return false;
}
}
+/**
+ * Atomically replace the complete snapshot. This does not merge snapshots
+ * loaded by callers before acquiring the lock; use the mutators for updates.
+ * @param {object} aliases - Complete aliases snapshot
+ * @returns {boolean} Success status
+ */
+function saveAliases(aliases) {
+ return withAliasesLock(() => saveAliasesUnlocked(aliases), false);
+}
+
/**
* Resolve an alias to get session path
* @param {string} alias - Alias name to resolve
@@ -185,7 +191,7 @@ function resolveAlias(alias) {
* @param {string} title - Optional title for the alias
* @returns {object} Result with success status and message
*/
-function setAlias(alias, sessionPath, title = null) {
+function setAliasUnlocked(alias, sessionPath, title = null) {
// Validate alias name
if (!alias || alias.length === 0) {
return { success: false, error: 'Alias name cannot be empty' };
@@ -221,7 +227,7 @@ function setAlias(alias, sessionPath, title = null) {
title: title || null
};
- if (saveAliases(data)) {
+ if (saveAliasesUnlocked(data)) {
return {
success: true,
isNew,
@@ -278,7 +284,7 @@ function listAliases(options = {}) {
* @param {string} alias - Alias name to delete
* @returns {object} Result with success status
*/
-function deleteAlias(alias) {
+function deleteAliasUnlocked(alias) {
const data = loadAliases();
if (!data.aliases[alias]) {
@@ -288,7 +294,7 @@ function deleteAlias(alias) {
const deleted = data.aliases[alias];
delete data.aliases[alias];
- if (saveAliases(data)) {
+ if (saveAliasesUnlocked(data)) {
return {
success: true,
alias,
@@ -305,7 +311,7 @@ function deleteAlias(alias) {
* @param {string} newAlias - New alias name
* @returns {object} Result with success status
*/
-function renameAlias(oldAlias, newAlias) {
+function renameAliasUnlocked(oldAlias, newAlias) {
const data = loadAliases();
if (!data.aliases[oldAlias]) {
@@ -340,7 +346,7 @@ function renameAlias(oldAlias, newAlias) {
aliasData.updatedAt = new Date().toISOString();
data.aliases[newAlias] = aliasData;
- if (saveAliases(data)) {
+ if (saveAliasesUnlocked(data)) {
return {
success: true,
oldAlias,
@@ -349,12 +355,8 @@ function renameAlias(oldAlias, newAlias) {
};
}
- // Restore old alias and remove new alias on failure
- data.aliases[oldAlias] = aliasData;
- delete data.aliases[newAlias];
- // Attempt to persist the rollback
- saveAliases(data);
- return { success: false, error: 'Failed to save renamed alias — rolled back to original' };
+ // Atomic replacement leaves the original snapshot intact on failure.
+ return { success: false, error: 'Failed to save renamed alias' };
}
/**
@@ -379,7 +381,7 @@ function resolveSessionAlias(aliasOrId) {
* @param {string|null} title - New title (string or null to clear)
* @returns {object} Result with success status
*/
-function updateAliasTitle(alias, title) {
+function updateAliasTitleUnlocked(alias, title) {
if (title !== null && typeof title !== 'string') {
return { success: false, error: 'Title must be a string or null' };
}
@@ -393,7 +395,7 @@ function updateAliasTitle(alias, title) {
data.aliases[alias].title = title || null;
data.aliases[alias].updatedAt = new Date().toISOString();
- if (saveAliases(data)) {
+ if (saveAliasesUnlocked(data)) {
return {
success: true,
alias,
@@ -431,7 +433,7 @@ function getAliasesForSession(sessionPath) {
* @param {Function} sessionExists - Function to check if session exists
* @returns {object} Cleanup result
*/
-function cleanupAliases(sessionExists) {
+function cleanupAliasesUnlocked(sessionExists) {
if (typeof sessionExists !== 'function') {
return { totalChecked: 0, removed: 0, removedAliases: [], error: 'sessionExists must be a function' };
}
@@ -446,7 +448,7 @@ function cleanupAliases(sessionExists) {
}
}
- if (removed.length > 0 && !saveAliases(data)) {
+ if (removed.length > 0 && !saveAliasesUnlocked(data)) {
log('[Aliases] Failed to save after cleanup');
return {
success: false,
@@ -465,6 +467,31 @@ function cleanupAliases(sessionExists) {
};
}
+function setAlias(alias, sessionPath, title = null) {
+ return withAliasesLock(() => setAliasUnlocked(alias, sessionPath, title),
+ { success: false, error: 'Failed to save alias' });
+}
+
+function deleteAlias(alias) {
+ return withAliasesLock(() => deleteAliasUnlocked(alias),
+ { success: false, error: 'Failed to delete alias' });
+}
+
+function renameAlias(oldAlias, newAlias) {
+ return withAliasesLock(() => renameAliasUnlocked(oldAlias, newAlias),
+ { success: false, error: 'Failed to save renamed alias' });
+}
+
+function updateAliasTitle(alias, title) {
+ return withAliasesLock(() => updateAliasTitleUnlocked(alias, title),
+ { success: false, error: 'Failed to update alias title' });
+}
+
+function cleanupAliases(sessionExists) {
+ return withAliasesLock(() => cleanupAliasesUnlocked(sessionExists),
+ { success: false, totalChecked: 0, removed: 0, removedAliases: [], error: 'Failed to save after cleanup' });
+}
+
module.exports = {
getAliasesPath,
loadAliases,
diff --git a/tests/lib/claude-settings-lock.test.js b/tests/lib/claude-settings-lock.test.js
new file mode 100644
index 000000000..905255804
--- /dev/null
+++ b/tests/lib/claude-settings-lock.test.js
@@ -0,0 +1,148 @@
+'use strict';
+const assert = require('assert');
+const fs = require('fs');
+const os = require('os');
+const path = require('path');
+const { spawn } = require('child_process');
+const { acquireSettingsLock } = require('../../scripts/lib/install/claude-settings-lock');
+
+async function owner(root, settingsPath) {
+ const child = spawn(process.execPath, [
+ path.join(__dirname, 'helpers', 'settings-lock-worker.js'), root, settingsPath,
+ ], { env: { ...process.env, HOME: root, USERPROFILE: root, ECC_AGENT_DATA_HOME: path.join(root, '.claude') },
+ stdio: ['ignore', 'ignore', 'pipe'] });
+ let stderr = '';
+ child.stderr.on('data', data => { stderr += data; });
+ child.done = new Promise((resolve, reject) => {
+ child.on('error', reject);
+ child.on('close', (code, signal) => resolve({ code, signal, stderr }));
+ });
+ child.done.catch(() => {});
+ const deadline = Date.now() + 10000;
+ try {
+ while (!fs.existsSync(path.join(root, 'held'))) {
+ if (child.exitCode !== null || Date.now() > deadline) throw new Error('Owner failed: ' + stderr);
+ await new Promise(resolve => setTimeout(resolve, 10));
+ }
+ return child;
+ } catch (error) {
+ child.kill('SIGKILL');
+ await child.done;
+ throw error;
+ }
+}
+async function withOwner(callback) {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-settings-wait-'));
+ const settingsPath = path.join(root, '.claude', 'session-aliases.json');
+ let child;
+ try {
+ child = await owner(root, settingsPath);
+ await callback(root, settingsPath, child);
+ } finally {
+ if (child) {
+ if (child.exitCode === null && child.signalCode === null) child.kill('SIGKILL');
+ await child.done;
+ }
+ fs.rmSync(root, { recursive: true, force: true });
+ }
+}
+const cases = [
+ ['default contention is fail-fast; optional timeout is bounded and leaves owner intact', () => withOwner((_root, file) => {
+ const before = fs.readFileSync(file + '.ecc.lock', 'utf8');
+ assert.throws(() => acquireSettingsLock(file), /Another ECC process/);
+ const start = performance.now();
+ assert.throws(() => acquireSettingsLock(file, { timeoutMs: 50 }), /Another ECC process/);
+ assert.ok(performance.now() - start >= 40, 'Waits for the configured deadline');
+ assert.ok(performance.now() - start < 5000, 'Does not wait indefinitely');
+ assert.strictEqual(fs.readFileSync(file + '.ecc.lock', 'utf8'), before);
+ assert.deepStrictEqual(fs.readdirSync(path.dirname(file)), ['session-aliases.json.ecc.lock']);
+ })],
+ ['waiting succeeds when the real owner releases after the first contention', () => withOwner(async (root, file, child) => {
+ const originalLink = fs.linkSync;
+ let contended = false;
+ fs.linkSync = function (source, target) {
+ try { return originalLink.apply(this, arguments); }
+ catch (error) {
+ if (target === file + '.ecc.lock' && error.code === 'EEXIST') {
+ contended = true;
+ fs.writeFileSync(path.join(root, 'release'), '');
+ }
+ throw error;
+ }
+ };
+ let release;
+ try { release = acquireSettingsLock(file, { timeoutMs: 2000 }); }
+ finally { fs.linkSync = originalLink; }
+ assert.ok(contended);
+ release();
+ const result = await child.done;
+ assert.strictEqual(result.code, 0, result.stderr);
+ assert.ok(!fs.existsSync(file + '.ecc.lock'));
+ })],
+ ['a killed owner is recovered by the next alias transaction', () => withOwner(async (root, file, child) => {
+ child.kill('SIGKILL');
+ await child.done;
+ const saved = { HOME: process.env.HOME, USERPROFILE: process.env.USERPROFILE, ECC_AGENT_DATA_HOME: process.env.ECC_AGENT_DATA_HOME };
+ Object.assign(process.env, { HOME: root, USERPROFILE: root, ECC_AGENT_DATA_HOME: path.dirname(file) });
+ try {
+ const aliases = require('../../scripts/lib/session-aliases');
+ assert.strictEqual(aliases.setAlias('recovered', '/session').success, true);
+ assert.ok(aliases.loadAliases().aliases.recovered);
+ assert.deepStrictEqual(fs.readdirSync(path.dirname(file)), ['session-aliases.json']);
+ } finally {
+ for (const [key, value] of Object.entries(saved)) {
+ if (value === undefined) delete process.env[key]; else process.env[key] = value;
+ }
+ }
+ })],
+ ['non-contention errors propagate without retry', () => withOwner((_root, file) => {
+ const originalLink = fs.linkSync;
+ const expected = Object.assign(new Error('disk failure'), { code: 'EIO' });
+ let attempts = 0;
+ fs.linkSync = () => { attempts++; throw expected; };
+ try {
+ assert.throws(() => acquireSettingsLock(file, { timeoutMs: 2000 }), error => error === expected);
+ assert.strictEqual(attempts, 1);
+ } finally { fs.linkSync = originalLink; }
+ })],
+ ['recovery tolerates a lock disappearing between inspection and quarantine', () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-lock-disappeared-'));
+ const file = path.join(root, 'settings.json');
+ const lock = file + '.ecc.lock';
+ fs.writeFileSync(lock, '{}');
+ fs.utimesSync(lock, new Date(0), new Date(0));
+ const originalRename = fs.renameSync;
+ let raced = false;
+ fs.renameSync = function (source, target) {
+ if (source === lock && target.includes('.stale-') && !raced) {
+ raced = true;
+ fs.unlinkSync(lock);
+ }
+ return originalRename.apply(this, arguments);
+ };
+ try {
+ const release = acquireSettingsLock(file, { timeoutMs: 100 });
+ assert.ok(raced);
+ release();
+ assert.deepStrictEqual(fs.readdirSync(root), []);
+ } finally {
+ fs.renameSync = originalRename;
+ fs.rmSync(root, { recursive: true, force: true });
+ }
+ }],
+ ['invalid timeout is rejected before touching disk', () => {
+ for (const timeoutMs of [-1, NaN, Infinity, '1']) {
+ assert.throws(() => acquireSettingsLock('unused', { timeoutMs }), /timeoutMs/);
+ }
+ }],
+];
+(async () => {
+ let passed = 0;
+ let failed = 0;
+ for (const [name, run] of cases) {
+ try { await run(); passed++; console.log('PASS ' + name); }
+ catch (error) { failed++; console.error('FAIL ' + name + ': ' + error.stack); }
+ }
+ console.log('Results: Passed: ' + passed + ', Failed: ' + failed);
+ process.exitCode = failed ? 1 : 0;
+})();
diff --git a/tests/lib/helpers/session-alias-worker.js b/tests/lib/helpers/session-alias-worker.js
new file mode 100644
index 000000000..ae9cdc7df
--- /dev/null
+++ b/tests/lib/helpers/session-alias-worker.js
@@ -0,0 +1,39 @@
+'use strict';
+const fs = require('fs');
+const path = require('path');
+const [root, role, action] = process.argv.slice(2);
+const aliasesPath = path.join(root, '.claude', 'session-aliases.json');
+const pause = new Int32Array(new SharedArrayBuffer(4));
+const mark = name => fs.writeFileSync(path.join(root, name), '');
+const readFileSync = fs.readFileSync;
+const linkSync = fs.linkSync;
+let paused = false;
+// Announce a lock attempt OR a captured read; the parent needs no scheduling guess.
+fs.linkSync = function (source, target) {
+ if (target === aliasesPath + '.ecc.lock') mark(role + '.attempt');
+ return linkSync.apply(this, arguments);
+};
+fs.readFileSync = function (file) {
+ const result = readFileSync.apply(this, arguments);
+ if (file === aliasesPath && !paused) {
+ paused = true;
+ mark(role + '.attempt');
+ mark(role + '.read');
+ const deadline = Date.now() + 15000;
+ while (!fs.existsSync(path.join(root, role + '.release'))) {
+ if (Date.now() > deadline) throw new Error('Read barrier timed out');
+ Atomics.wait(pause, 0, 0, 10);
+ }
+ }
+ return result;
+};
+const aliases = require('../../../scripts/lib/session-aliases');
+const actions = {
+ set: () => aliases.setAlias('beta', '/beta'),
+ delete: () => aliases.deleteAlias('existing'),
+ rename: () => aliases.renameAlias('existing', 'renamed'),
+ title: () => aliases.updateAliasTitle('existing', 'Updated'),
+ cleanup: () => aliases.cleanupAliases(session => session !== '/existing'),
+};
+const result = role === 'alpha' ? aliases.setAlias('alpha', '/alpha') : actions[action]();
+process.stdout.write(JSON.stringify(result));
diff --git a/tests/lib/helpers/settings-lock-worker.js b/tests/lib/helpers/settings-lock-worker.js
new file mode 100644
index 000000000..75aad5375
--- /dev/null
+++ b/tests/lib/helpers/settings-lock-worker.js
@@ -0,0 +1,14 @@
+'use strict';
+const fs = require('fs');
+const path = require('path');
+const { acquireSettingsLock } = require('../../../scripts/lib/install/claude-settings-lock');
+const [root, settingsPath] = process.argv.slice(2);
+const release = acquireSettingsLock(settingsPath);
+fs.writeFileSync(path.join(root, 'held'), '');
+const deadline = Date.now() + 15000;
+const sleeper = new Int32Array(new SharedArrayBuffer(4));
+while (!fs.existsSync(path.join(root, 'release'))) {
+ if (Date.now() > deadline) throw new Error('Owner release barrier timed out');
+ Atomics.wait(sleeper, 0, 0, 10);
+}
+release();
diff --git a/tests/lib/session-aliases-concurrency.test.js b/tests/lib/session-aliases-concurrency.test.js
new file mode 100644
index 000000000..dcec7b30a
--- /dev/null
+++ b/tests/lib/session-aliases-concurrency.test.js
@@ -0,0 +1,87 @@
+'use strict';
+const assert = require('assert');
+const fs = require('fs');
+const os = require('os');
+const path = require('path');
+const { spawn } = require('child_process');
+const worker = path.join(__dirname, 'helpers', 'session-alias-worker.js');
+
+async function waitFor(file, children) {
+ const deadline = Date.now() + 10000;
+ while (!fs.existsSync(file)) {
+ for (const child of children) {
+ if (child.exitCode !== null || child.signalCode !== null) throw new Error('Child exited before barrier: ' + file);
+ }
+ if (Date.now() > deadline) throw new Error('Barrier timed out: ' + file);
+ await new Promise(resolve => setTimeout(resolve, 10));
+ }
+}
+function start(root, role, action) {
+ const child = spawn(process.execPath, [worker, root, role, action], {
+ env: { ...process.env, HOME: root, USERPROFILE: root, ECC_AGENT_DATA_HOME: path.join(root, '.claude') },
+ stdio: ['ignore', 'pipe', 'pipe'],
+ });
+ let stdout = '';
+ let stderr = '';
+ child.stdout.on('data', data => { stdout += data; });
+ child.stderr.on('data', data => { stderr += data; });
+ child.done = new Promise((resolve, reject) => {
+ child.on('error', reject);
+ child.on('close', (code, signal) => {
+ if (code !== 0) reject(new Error('Worker failed: ' + code + '/' + signal + ' ' + stderr));
+ else {
+ try { resolve(JSON.parse(stdout)); } catch (error) { reject(error); }
+ }
+ });
+ });
+ child.done.catch(() => {});
+ return child;
+}
+async function race(action) {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-alias-race-'));
+ const dataDir = path.join(root, '.claude');
+ fs.mkdirSync(dataDir);
+ const aliasesPath = path.join(dataDir, 'session-aliases.json');
+ fs.writeFileSync(aliasesPath, JSON.stringify({
+ version: '1.0',
+ aliases: { existing: { sessionPath: '/existing', createdAt: '2026-01-01', title: 'Original' } },
+ metadata: {},
+ }));
+ const children = [];
+ const timer = setTimeout(() => children.forEach(child => child.kill('SIGKILL')), 20000);
+ try {
+ const alpha = start(root, 'alpha', action);
+ children.push(alpha);
+ await waitFor(path.join(root, 'alpha.read'), children);
+ const beta = start(root, 'beta', action);
+ children.push(beta);
+ await waitFor(path.join(root, 'beta.attempt'), children);
+ fs.writeFileSync(path.join(root, 'alpha.release'), '');
+ assert.strictEqual((await alpha.done).success, true);
+ fs.writeFileSync(path.join(root, 'beta.release'), '');
+ assert.strictEqual((await beta.done).success, true);
+ const data = JSON.parse(fs.readFileSync(aliasesPath, 'utf8'));
+ assert.ok(data.aliases.alpha, action + ' must preserve the preceding writer');
+ if (action === 'set') assert.ok(data.aliases.beta);
+ if (['delete', 'cleanup', 'rename'].includes(action)) assert.ok(!data.aliases.existing);
+ if (action === 'rename') assert.ok(data.aliases.renamed);
+ if (action === 'title') assert.strictEqual(data.aliases.existing.title, 'Updated');
+ assert.strictEqual(data.metadata.totalCount, Object.keys(data.aliases).length);
+ assert.deepStrictEqual(fs.readdirSync(dataDir), ['session-aliases.json']);
+ } finally {
+ clearTimeout(timer);
+ for (const child of children) {
+ if (child.exitCode === null && child.signalCode === null) child.kill('SIGKILL');
+ }
+ await Promise.allSettled(children.map(child => child.done));
+ fs.rmSync(root, { recursive: true, force: true });
+ }
+}
+(async () => {
+ let failed = 0;
+ for (const action of ['set', 'delete', 'rename', 'title', 'cleanup']) {
+ try { await race(action); console.log('PASS concurrent ' + action); }
+ catch (error) { failed++; console.error('FAIL concurrent ' + action + ': ' + error.message); }
+ }
+ process.exitCode = failed ? 1 : 0;
+})();
diff --git a/tests/lib/session-aliases.test.js b/tests/lib/session-aliases.test.js
index 0b2554cb1..f2593b033 100644
--- a/tests/lib/session-aliases.test.js
+++ b/tests/lib/session-aliases.test.js
@@ -18,6 +18,8 @@ const tmpHome = path.join(os.tmpdir(), `ecc-alias-test-${Date.now()}`);
fs.mkdirSync(path.join(tmpHome, '.claude'), { recursive: true });
const origHome = process.env.HOME;
const origUserProfile = process.env.USERPROFILE;
+const origAgentDataHome = process.env.ECC_AGENT_DATA_HOME;
+delete process.env.ECC_AGENT_DATA_HOME;
process.env.HOME = tmpHome;
process.env.USERPROFILE = tmpHome; // Windows: os.homedir() uses USERPROFILE
@@ -767,18 +769,16 @@ function runTests() {
assert.strictEqual(resolved.title, 'Original Title');
})) passed++; else failed++;
- // ── Round 33: saveAliases backup restoration ──
- console.log('\nsaveAliases backup/restore (Round 33):');
+ // ── Round 33: saveAliases atomic publication ──
+ console.log('\nsaveAliases atomic publication (Round 33):');
- if (test('saveAliases creates backup before write and removes on success', () => {
+ if (test('saveAliases publishes a snapshot without leaving staging files', () => {
resetAliases();
aliases.setAlias('backup-test', '/path/backup');
- // After successful save, .bak file should NOT exist
- const aliasesPath = path.join(tmpHome, '.claude', 'session-aliases.json');
- const backupPath = aliasesPath + '.bak';
- assert.ok(!fs.existsSync(backupPath), 'Backup should be removed after successful save');
+ const aliasesPath = aliases.getAliasesPath();
assert.ok(fs.existsSync(aliasesPath), 'Main aliases file should exist');
+ assert.deepStrictEqual(fs.readdirSync(path.dirname(aliasesPath)), ['session-aliases.json']);
})) passed++; else failed++;
if (test('saveAliases with non-serializable data returns false and preserves existing file', () => {
@@ -795,7 +795,7 @@ function runTests() {
const result = aliases.saveAliases(circular);
assert.strictEqual(result, false, 'Should return false');
- // The file should still have the old content (restored from backup or untouched)
+ // The file should still have the old content (untouched)
const contentAfter = fs.readFileSync(aliasesPath, 'utf8');
assert.ok(contentAfter.includes('before-fail'),
'Original aliases data should be preserved after failed save');
@@ -843,10 +843,10 @@ function runTests() {
assert.strictEqual(data.metadata.totalCount, 5, 'Metadata count should match actual aliases');
})) passed++; else failed++;
- // ── Round 56: Windows platform unlink-before-rename code path ──
+ // ── Round 56: Windows platform atomic replacement ──
console.log('\nRound 56: Windows platform atomic write path:');
- if (test('Windows platform mock: unlinks existing file before rename', () => {
+ if (test('Windows platform mock: replaces existing file without unlinking it', () => {
resetAliases();
// First create an alias so the file exists
const r1 = aliases.setAlias('win-initial', '2026-01-01-abc123-session.tmp');
@@ -854,12 +854,17 @@ function runTests() {
const aliasesPath = aliases.getAliasesPath();
assert.ok(fs.existsSync(aliasesPath), 'Aliases file should exist before win32 test');
- // Mock process.platform to 'win32' to trigger the unlink-before-rename path
+ // Check that Windows uses replacement without deleting the published file
+ const originalUnlink = fs.unlinkSync;
+ fs.unlinkSync = function (file) {
+ assert.notStrictEqual(file, aliasesPath, 'Never unlink the published aliases file');
+ return originalUnlink.apply(this, arguments);
+ };
const origPlatform = Object.getOwnPropertyDescriptor(process, 'platform');
Object.defineProperty(process, 'platform', { value: 'win32', configurable: true });
try {
- // This save triggers the Windows code path: unlink existing → rename temp
+ // Replace the snapshot while preserving the original until publication
const r2 = aliases.setAlias('win-updated', '2026-02-01-def456-session.tmp');
assert.strictEqual(r2.success, true, 'setAlias should succeed under win32 mock');
@@ -875,6 +880,7 @@ function runTests() {
assert.ok(!fs.existsSync(aliasesPath + '.tmp'), 'No temp file should remain');
assert.ok(!fs.existsSync(aliasesPath + '.bak'), 'No backup file should remain');
} finally {
+ fs.unlinkSync = originalUnlink;
// Restore original platform descriptor
if (origPlatform) {
Object.defineProperty(process, 'platform', origPlatform);
@@ -1091,9 +1097,10 @@ function runTests() {
assert.strictEqual(result.success, false, 'Should fail when save is blocked');
assert.ok(result.error.includes('Failed to save after cleanup'),
`Should return cleanup save failure error, got: ${result.error}`);
- assert.strictEqual(result.removed, 1, 'Should report 1 removed alias');
- assert.ok(result.removedAliases.some(a => a.name === 'remove-me'),
- 'Should report remove-me in removedAliases');
+ assert.strictEqual(result.removed, 0, 'No cleanup runs without the transaction lock');
+ assert.deepStrictEqual(result.removedAliases, []);
+ assert.strictEqual(result.totalChecked, 0);
+ assert.ok(freshAliases.resolveAlias('remove-me'), 'Published aliases stay unchanged');
} finally {
try { fs.chmodSync(isoClaudeDir, 0o755); } catch { /* best-effort */ }
process.env.HOME = savedHome;
@@ -1210,53 +1217,34 @@ function runTests() {
resetAliases();
})) passed++; else failed++;
- // ── Round 90: saveAliases backup restore double failure (inner catch restoreErr) ──
- console.log('\nRound 90: saveAliases (backup restore double failure):');
-
- if (test('saveAliases triggers inner restoreErr catch when both save and restore fail', () => {
- // session-aliases.js lines 131-137: When saveAliases fails (outer catch),
- // it tries to restore from backup. If the restore ALSO fails, the inner
- // catch at line 135 logs restoreErr. No existing test creates this double-fault.
- if (process.platform === 'win32' || process.getuid?.() === 0) {
- console.log(' (skipped — chmod ineffective on Windows/root)');
- return;
- }
- const isoHome = path.join(os.tmpdir(), `ecc-r90-restore-fail-${Date.now()}`);
- const claudeDir = path.join(isoHome, '.claude');
- fs.mkdirSync(claudeDir, { recursive: true });
-
- // Pre-create a backup file while directory is still writable
- const backupPath = path.join(claudeDir, 'session-aliases.json.bak');
- fs.writeFileSync(backupPath, JSON.stringify({ aliases: {}, version: '1.0' }));
-
- // Make .claude directory read-only (0o555):
- // 1. writeFileSync(tempPath) → EACCES (can't create file in read-only dir) — outer catch
- // 2. copyFileSync(backupPath, aliasesPath) → EACCES (can't create target) — inner catch (line 135)
- fs.chmodSync(claudeDir, 0o555);
-
- const origH = process.env.HOME;
- const origP = process.env.USERPROFILE;
- process.env.HOME = isoHome;
- process.env.USERPROFILE = isoHome;
-
+ // Failed publication must preserve the original bytes, even under win32.
+ if (test('failed replacement preserves published aliases and removes only its staging file', () => {
+ resetAliases();
+ aliases.setAlias('preserved', '/original');
+ const aliasesPath = aliases.getAliasesPath();
+ const before = fs.readFileSync(aliasesPath, 'utf8');
+ const originalRename = fs.renameSync;
+ const staged = [];
+ fs.renameSync = function (source, target) {
+ if (target === aliasesPath) {
+ staged.push(source);
+ const error = new Error('replacement denied');
+ error.code = 'EPERM';
+ throw error;
+ }
+ return originalRename.apply(this, arguments);
+ };
try {
- delete require.cache[require.resolve('../../scripts/lib/session-aliases')];
- delete require.cache[require.resolve('../../scripts/lib/utils')];
- const freshAliases = require('../../scripts/lib/session-aliases');
-
- const result = freshAliases.saveAliases({ aliases: { x: 1 }, version: '1.0' });
- assert.strictEqual(result, false, 'Should return false when save fails');
-
- // Backup should still exist (restore also failed, so backup was not consumed)
- assert.ok(fs.existsSync(backupPath), 'Backup should still exist after double failure');
+ assert.strictEqual(aliases.saveAliases({ aliases: { replacement: { sessionPath: '/new' } } }), false);
+ assert.strictEqual(aliases.renameAlias('preserved', 'changed').success, false);
+ assert.strictEqual(fs.readFileSync(aliasesPath, 'utf8'), before);
+ assert.strictEqual(staged.length, 2, 'Each failed operation attempts one publication');
+ assert.notStrictEqual(staged[0], staged[1], 'Each write has its own staging file');
+ assert.deepStrictEqual(fs.readdirSync(path.dirname(aliasesPath)), ['session-aliases.json']);
} finally {
- process.env.HOME = origH;
- process.env.USERPROFILE = origP;
- delete require.cache[require.resolve('../../scripts/lib/session-aliases')];
- delete require.cache[require.resolve('../../scripts/lib/utils')];
- try { fs.chmodSync(claudeDir, 0o755); } catch { /* best-effort */ }
- fs.rmSync(isoHome, { recursive: true, force: true });
+ fs.renameSync = originalRename;
}
+ assert.strictEqual(aliases.setAlias('after-failure', '/next').success, true, 'Lock is released after failure');
})) passed++; else failed++;
// ── Round 95: renameAlias with same old and new name (self-rename) ──
@@ -1809,6 +1797,78 @@ function runTests() {
'Object.keys includes normal alias');
})) passed++; else failed++;
+ if (test('cleanup rejects reentrant writes without losing the outer transaction', () => {
+ resetAliases();
+ aliases.setAlias('existing', '/existing');
+ const nested = [];
+ const result = aliases.cleanupAliases(() => {
+ nested.push(aliases.setAlias('nested', '/nested'));
+ nested.push(aliases.deleteAlias('existing'));
+ nested.push(aliases.renameAlias('existing', 'renamed'));
+ nested.push(aliases.updateAliasTitle('existing', 'Nested'));
+ nested.push(aliases.cleanupAliases(() => true));
+ nested.push(aliases.saveAliases({ aliases: {} }));
+ return false;
+ });
+ assert.strictEqual(result.success, true);
+ assert.ok(nested.slice(0, -1).every(value => value.success === false));
+ assert.strictEqual(nested.at(-1), false);
+ assert.deepStrictEqual(aliases.loadAliases().aliases, {});
+ assert.strictEqual(aliases.setAlias('after-cleanup', '/next').success, true);
+ })) passed++; else failed++;
+
+ if (test('cleanup preserves callback errors and releases its lock', () => {
+ resetAliases();
+ aliases.setAlias('existing', '/existing');
+ const primary = new Error('session lookup failed');
+ assert.throws(() => aliases.cleanupAliases(() => { throw primary; }), error => error === primary);
+ assert.ok(aliases.resolveAlias('existing'));
+ assert.ok(!fs.existsSync(aliases.getAliasesPath() + '.ecc.lock'));
+ assert.strictEqual(aliases.setAlias('after-error', '/next').success, true);
+ })) passed++; else failed++;
+
+ if (test('cleanup propagates arbitrary thrown values even if lock release also fails', () => {
+ resetAliases();
+ aliases.setAlias('existing', '/existing');
+ const lockPath = aliases.getAliasesPath() + '.ecc.lock';
+ const originalRename = fs.renameSync;
+ const errors = [null, undefined, false, 0, Object.freeze(new Error('frozen')),
+ new Proxy(new Error('proxy'), { set() { throw new Error('Cannot annotate error'); } })];
+ for (const failRelease of [false, true]) {
+ for (const primary of errors) {
+ let caught = false;
+ fs.renameSync = function (source) {
+ if (failRelease && source === lockPath) throw new Error('release denied');
+ return originalRename.apply(this, arguments);
+ };
+ try {
+ aliases.cleanupAliases(() => { throw primary; });
+ } catch (error) {
+ caught = true;
+ assert.strictEqual(error, primary, 'Original thrown value is preserved');
+ } finally {
+ fs.renameSync = originalRename;
+ fs.rmSync(lockPath, { force: true });
+ }
+ assert.ok(caught, 'Callback failure must propagate');
+ }
+ }
+ assert.strictEqual(aliases.setAlias('after-release-error', '/next').success, true);
+ })) passed++; else failed++;
+
+ if (test('saveAliases replaces its complete snapshot without mutating the caller', () => {
+ resetAliases();
+ aliases.setAlias('existing', '/existing');
+ const snapshot = { aliases: { replacement: { sessionPath: '/replacement' } }, metadata: { caller: true } };
+ const before = JSON.stringify(snapshot);
+ assert.strictEqual(aliases.saveAliases(snapshot), true);
+ assert.strictEqual(JSON.stringify(snapshot), before);
+ assert.deepStrictEqual(Object.keys(aliases.loadAliases().aliases), ['replacement']);
+ })) passed++; else failed++;
+
+ if (origAgentDataHome === undefined) delete process.env.ECC_AGENT_DATA_HOME;
+ else process.env.ECC_AGENT_DATA_HOME = origAgentDataHome;
+
// Cleanup — restore both HOME and USERPROFILE (Windows)
process.env.HOME = origHome;
if (origUserProfile !== undefined) {