11import path from 'node:path' ;
22import { randomUUID } from 'node:crypto' ;
3+ import { realpath } from 'node:fs/promises' ;
4+ import { createFileStateStore } from '../backend/local-backend.js' ;
5+ import { StateKeyConflictError } from '../storage/storage-error.js' ;
36import type { StorageProvider } from '../storage/storage-provider.js' ;
47
8+ async function ensureMemoryIndex ( storage : StorageProvider , indexPath : string ) : Promise < void > {
9+ try {
10+ await storage . createIfAbsent ( indexPath , '[]\n' ) ;
11+ } catch ( error ) {
12+ if ( ! ( error instanceof StateKeyConflictError ) ) throw error ;
13+ }
14+ }
15+
516export type MemoryClass =
617 | 'TRANSIENT'
718 | 'LOCAL'
@@ -596,9 +607,11 @@ export async function ensureMemoryGovernanceDefaults(
596607 }
597608
598609 const indexPath = path . join ( memoryDir , 'index.json' ) ;
599- if ( ! await storage . exists ( indexPath ) ) {
600- await storage . write ( indexPath , '[]\n' ) ;
610+ try {
611+ await storage . createIfAbsent ( indexPath , '[]\n' ) ;
601612 created . push ( path . join ( '.squad' , 'memory' , 'index.json' ) ) ;
613+ } catch ( error ) {
614+ if ( ! ( error instanceof StateKeyConflictError ) ) throw error ;
602615 }
603616
604617 const auditPath = path . join ( memoryDir , 'audit.jsonl' ) ;
@@ -615,12 +628,6 @@ export class LocalMemoryStore {
615628 private readonly copilotProvider : HostInjectedCopilotMemoryAdapter ;
616629 private readonly registeredProviders : MemoryProvider [ ] ;
617630 private readonly providerTimeoutMs : number ;
618- /**
619- * Async mutex tail for index read-modify-write operations.
620- * Each caller enqueues behind the current tail so concurrent writes
621- * are serialized without OS-level file locking.
622- */
623- private indexLockTail : Promise < unknown > = Promise . resolve ( ) ;
624631
625632 constructor (
626633 private readonly storage : StorageProvider ,
@@ -642,22 +649,24 @@ export class LocalMemoryStore {
642649 * Serialize all index read-modify-write operations.
643650 *
644651 * All callers that do readIndex() → mutate → writeIndex() must go through
645- * this method so concurrent writes within the same store instance cannot
646- * interleave and lose entries. The critical section is purely async
647- * (no thread blocking), so this is safe in Node.js single-thread land .
652+ * this method so concurrent writers cannot interleave and lose entries.
653+ * The file lock coordinates callers across store instances and processes
654+ * sharing the same .squad directory .
648655 */
649656 private async withIndexLock < T > ( fn : ( ) => Promise < T > ) : Promise < T > {
650- let unlock ! : ( ) => void ;
651- // Append a new "release" promise to the tail of the lock chain.
652- // The next caller will wait for this release before proceeding.
653- const release = new Promise < void > ( resolve => { unlock = resolve ; } ) ;
654- const prev = this . indexLockTail ;
655- this . indexLockTail = release ;
656- await prev ;
657+ const resolvedSquadDir = path . resolve ( this . squadDir ) ;
658+ let lockRoot = resolvedSquadDir ;
659+ try {
660+ lockRoot = await realpath ( resolvedSquadDir ) ;
661+ } catch ( error ) {
662+ if ( ( error as NodeJS . ErrnoException ) . code !== 'ENOENT' ) throw error ;
663+ }
664+ const fileLock = createFileStateStore ( lockRoot ) ;
665+ const releaseFileLock = await fileLock . lockAsync ! ( 'backend/locks/memory-index' ) ;
657666 try {
658667 return await fn ( ) ;
659668 } finally {
660- unlock ( ) ;
669+ releaseFileLock ( ) ;
661670 }
662671 }
663672
@@ -1328,9 +1337,7 @@ export class LocalMemoryStore {
13281337 await this . storage . write ( configPath , JSON . stringify ( DEFAULT_CONFIG , null , 2 ) + '\n' ) ;
13291338 }
13301339 const indexPath = path . join ( memoryDir , 'index.json' ) ;
1331- if ( ! await this . storage . exists ( indexPath ) ) {
1332- await this . storage . write ( indexPath , '[]\n' ) ;
1333- }
1340+ await ensureMemoryIndex ( this . storage , indexPath ) ;
13341341 const auditPath = path . join ( memoryDir , 'audit.jsonl' ) ;
13351342 if ( ! await this . storage . exists ( auditPath ) ) {
13361343 await this . storage . write ( auditPath , '' ) ;
@@ -1414,11 +1421,28 @@ export class LocalMemoryStore {
14141421
14151422 private async writeIndex ( index : MemoryIndexEntry [ ] ) : Promise < void > {
14161423 const indexPath = path . join ( this . squadDir , 'memory' , 'index.json' ) ;
1417- const tmpPath = `${ indexPath } .tmp` ;
1418- // Write to a temp file first, then atomically rename into place.
1419- // This prevents a crash mid-write from leaving a partial/corrupt index.
1424+ const tmpPath = `${ indexPath } .${ process . pid } .${ randomUUID ( ) } .tmp` ;
14201425 await this . storage . write ( tmpPath , JSON . stringify ( index , null , 2 ) + '\n' ) ;
1421- await this . storage . rename ( tmpPath , indexPath ) ;
1426+ try {
1427+ for ( let attempt = 0 ; ; attempt ++ ) {
1428+ try {
1429+ await this . storage . rename ( tmpPath , indexPath ) ;
1430+ return ;
1431+ } catch ( error ) {
1432+ const code = typeof error === 'object' && error !== null && 'code' in error
1433+ ? String ( error . code )
1434+ : undefined ;
1435+ const retryable = process . platform === 'win32'
1436+ && [ 'EACCES' , 'EBUSY' , 'EPERM' ] . includes ( code ?? '' )
1437+ && attempt < 4 ;
1438+ if ( ! retryable ) throw error ;
1439+ await new Promise ( resolve => setTimeout ( resolve , 10 * 2 ** attempt ) ) ;
1440+ }
1441+ }
1442+ } catch ( error ) {
1443+ try { await this . storage . delete ( tmpPath ) ; } catch { /* preserve the rename error */ }
1444+ throw error ;
1445+ }
14221446 }
14231447
14241448 private async audit ( record : Omit < MemoryAuditRecord , 'timestamp' > ) : Promise < void > {
0 commit comments