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): preserve committed results on lock cleanup errors

Yann Roberto184c657788d3
diff --git a/scripts/lib/install/claude-settings-lock.js b/scripts/lib/install/claude-settings-lock.js
index 88c72580f..d258d00cb 100644
--- a/scripts/lib/install/claude-settings-lock.js
+++ b/scripts/lib/install/claude-settings-lock.js
@@ -141,6 +141,15 @@ function recoverSettingsLock(lockPath, label = 'Claude settings') {
}
}
+/**
+ * Acquire exclusive settings access, optionally waiting for another writer.
+ * A recovery guard (`.ecc.lock.recover`) is never removed by a contender: if its
+ * owner crashes during recovery, inspect and remove the orphaned guard manually
+ * only after confirming no ECC process is active.
+ * @param {string} settingsPath - Settings file protected by the lock
+ * @param {object} options - Diagnostic label and bounded wait duration
+ * @returns {Function} Release callback for the acquired lock
+ */
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.');
diff --git a/scripts/lib/session-aliases.d.ts b/scripts/lib/session-aliases.d.ts
index 3930dc722..87d4da87d 100644
--- a/scripts/lib/session-aliases.d.ts
+++ b/scripts/lib/session-aliases.d.ts
@@ -84,8 +84,9 @@ export function getAliasesPath(): string;
export function loadAliases(): AliasStore;
/**
- * Save aliases to disk with atomic write (temp file + rename).
- * Creates backup before writing; restores on failure.
+ * Atomically replace the complete snapshot under the alias transaction lock.
+ * A failed publication leaves the previous snapshot intact. This does not merge
+ * snapshots loaded before locking; use the mutation functions for updates.
*/
export function saveAliases(aliases: AliasStore): boolean;
diff --git a/scripts/lib/session-aliases.js b/scripts/lib/session-aliases.js
index b57664472..8abe38ab8 100644
--- a/scripts/lib/session-aliases.js
+++ b/scripts/lib/session-aliases.js
@@ -85,6 +85,16 @@ function loadAliases() {
// by the outer transaction's snapshot.
const activeWrites = new Set();
+/**
+ * Run a synchronous alias transaction with exclusive access to its snapshot.
+ * Lock acquisition or reentry failure returns the caller's failure value.
+ * Release errors are logged without replacing the callback's result or error:
+ * a successfully published snapshot remains committed even if cleanup fails.
+ * @template T
+ * @param {function(): T} callback - Transaction to execute while holding the lock
+ * @param {T} failure - Result when the transaction cannot start
+ * @returns {T} The transaction result, or failure if it could not start
+ */
function withAliasesLock(callback, failure) {
const aliasesPath = path.resolve(getAliasesPath());
if (activeWrites.has(aliasesPath)) {
@@ -118,17 +128,18 @@ function withAliasesLock(callback, failure) {
}
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;
}
+ if (callbackFailed) throw primaryError;
return result;
}
+/**
+ * Publish a complete alias snapshot while the caller holds the transaction lock.
+ * @param {object} aliases - Snapshot to publish without mutating the caller
+ * @returns {boolean} Whether atomic replacement succeeded
+ */
function saveAliasesUnlocked(aliases) {
try {
const snapshot = {
@@ -467,26 +478,56 @@ function cleanupAliasesUnlocked(sessionExists) {
};
}
+/**
+ * Create or update an alias using the latest snapshot under the transaction lock.
+ * @param {string} alias - Alias name (alphanumeric, dash, underscore)
+ * @param {string} sessionPath - Session directory path
+ * @param {string|null} title - Optional title for the alias
+ * @returns {object} Result with success status and the saved alias details
+ */
function setAlias(alias, sessionPath, title = null) {
return withAliasesLock(() => setAliasUnlocked(alias, sessionPath, title),
{ success: false, error: 'Failed to save alias' });
}
+/**
+ * Delete an alias without overwriting other writers' completed changes.
+ * @param {string} alias - Alias name to delete
+ * @returns {object} Result with success status and the deleted session path
+ */
function deleteAlias(alias) {
return withAliasesLock(() => deleteAliasUnlocked(alias),
{ success: false, error: 'Failed to delete alias' });
}
+/**
+ * Rename an existing alias in one locked read-modify-write transaction.
+ * @param {string} oldAlias - Current alias name
+ * @param {string} newAlias - New unused alias name
+ * @returns {object} Result with success status and the renamed alias details
+ */
function renameAlias(oldAlias, newAlias) {
return withAliasesLock(() => renameAliasUnlocked(oldAlias, newAlias),
{ success: false, error: 'Failed to save renamed alias' });
}
+/**
+ * Update an existing alias title using the latest locked snapshot.
+ * @param {string} alias - Alias name
+ * @param {string|null} title - New title, or null to clear it
+ * @returns {object} Result with success status and the updated title
+ */
function updateAliasTitle(alias, title) {
return withAliasesLock(() => updateAliasTitleUnlocked(alias, title),
{ success: false, error: 'Failed to update alias title' });
}
+/**
+ * Remove aliases whose sessions no longer exist in a single locked transaction.
+ * The synchronous callback must not write aliases; its exceptions propagate.
+ * @param {function(string): boolean} sessionExists - Check whether a session exists
+ * @returns {object} Checked count, removed aliases, and any operation failure
+ */
function cleanupAliases(sessionExists) {
return withAliasesLock(() => cleanupAliasesUnlocked(sessionExists),
{ success: false, totalChecked: 0, removed: 0, removedAliases: [], error: 'Failed to save after cleanup' });
diff --git a/tests/lib/session-aliases.test.js b/tests/lib/session-aliases.test.js
index f2593b033..3ab5fa35c 100644
--- a/tests/lib/session-aliases.test.js
+++ b/tests/lib/session-aliases.test.js
@@ -1856,6 +1856,86 @@ function runTests() {
assert.strictEqual(aliases.setAlias('after-release-error', '/next').success, true);
})) passed++; else failed++;
+ if (test('successful writes keep their results when releasing the lock fails', () => {
+ const cases = [
+ {
+ run: () => aliases.setAlias('added', '/added', 'Added'),
+ expected: { success: true, isNew: true, alias: 'added', sessionPath: '/added', title: 'Added' },
+ verify: data => assert.strictEqual(data.added.sessionPath, '/added')
+ },
+ {
+ run: () => aliases.deleteAlias('existing'),
+ expected: { success: true, alias: 'existing', deletedSessionPath: '/existing' },
+ verify: data => assert.deepStrictEqual(data, {})
+ },
+ {
+ run: () => aliases.renameAlias('existing', 'renamed'),
+ expected: { success: true, oldAlias: 'existing', newAlias: 'renamed', sessionPath: '/existing' },
+ verify: data => assert.deepStrictEqual(Object.keys(data), ['renamed'])
+ },
+ {
+ run: () => aliases.updateAliasTitle('existing', 'Updated'),
+ expected: { success: true, alias: 'existing', title: 'Updated' },
+ verify: data => assert.strictEqual(data.existing.title, 'Updated')
+ },
+ {
+ run: () => aliases.cleanupAliases(() => false),
+ expected: { success: true, totalChecked: 1, removed: 1,
+ removedAliases: [{ name: 'existing', sessionPath: '/existing' }] },
+ verify: data => assert.deepStrictEqual(data, {})
+ },
+ {
+ run: () => aliases.saveAliases({ aliases: { replacement: { sessionPath: '/replacement' } } }),
+ expected: true,
+ verify: data => assert.deepStrictEqual(data, { replacement: { sessionPath: '/replacement' } })
+ }
+ ];
+ for (const entry of cases) {
+ resetAliases();
+ aliases.setAlias('existing', '/existing');
+ const lockPath = aliases.getAliasesPath() + '.ecc.lock';
+ const originalRename = fs.renameSync;
+ const originalError = console.error;
+ const warnings = [];
+ try {
+ fs.renameSync = function (source) {
+ if (source === lockPath) throw new Error('release denied');
+ return originalRename.apply(this, arguments);
+ };
+ console.error = message => warnings.push(message);
+ assert.deepStrictEqual(entry.run(), entry.expected);
+ entry.verify(aliases.loadAliases().aliases);
+ assert.ok(warnings.some(message => message.includes('release denied')),
+ 'A release failure remains visible to the caller');
+ } finally {
+ fs.renameSync = originalRename;
+ console.error = originalError;
+ fs.rmSync(lockPath, { force: true });
+ }
+ assert.strictEqual(aliases.setAlias('after-release-error', '/next').success, true,
+ 'The local reentry guard is cleared after a release failure');
+ }
+ })) passed++; else failed++;
+
+ if (test('a release failure preserves the original operation failure result', () => {
+ resetAliases();
+ aliases.setAlias('existing', '/existing');
+ const lockPath = aliases.getAliasesPath() + '.ecc.lock';
+ const originalRename = fs.renameSync;
+ try {
+ fs.renameSync = function (source) {
+ if (source === lockPath) throw new Error('release denied');
+ return originalRename.apply(this, arguments);
+ };
+ assert.deepStrictEqual(aliases.deleteAlias('missing'),
+ { success: false, error: "Alias 'missing' not found" });
+ assert.ok(aliases.resolveAlias('existing'));
+ } finally {
+ fs.renameSync = originalRename;
+ fs.rmSync(lockPath, { force: true });
+ }
+ })) passed++; else failed++;
+
if (test('saveAliases replaces its complete snapshot without mutating the caller', () => {
resetAliases();
aliases.setAlias('existing', '/existing');