Experience
Projects
My Stack
Case studies
Contact me
Open my CV

·6 min read

Parallel AI checks kept overwriting my kanban board, so I added a lock and a merge

Two things were about to write kanban.json at the same moment: an AI check that had just finished reading a project's git history, and me, dragging a card into another column. Whichever wrote second would silently erase the other. DailyBrief 1.8.0 made that collision routine, because per-project checks now ran in parallel and the board file was shared by all of them and by the Electron main process.

Project
DailyBrief
Date
Oct 2026
Stack
Electron, Node.js, PowerShell
Commit
9bc8366

Why the file became a hazard

DailyBrief keeps a kanban board in a JSON file that AI runs patch and the page saves whole. The commit that introduced parallel checks (9bc8366, "parallel checks, locked merged board saves") put several writers in play at once: one check per project, several running together, each ending with a patch applied to kanban.json, questions.json or ideas.json.

The comment I left at the top of core/lock.ps1 states the failure plainly: several AI runs may finish at the same time, and without a lock "the last writer silently drops the others' changes". There is no error to see. Both writes succeed. One of them is just gone.

First attempt: a named mutex

The first version of the lock, in 360d660, was a Windows named mutex taken from PowerShell:

powershell
$m = New-Object System.Threading.Mutex($false, ('Local\DailyBriefBoard-' + $env:USERNAME))

That serialized the scripts against each other. It did nothing for the other writer: main.js, which saves the board when the user edits it. Node has no named-mutex API without a native module, so the main process could not take the same lock. 41edea9 ("share board lockfile with main.js") replaced the mutex with a file protocol both sides implement:

  • board.lock is created exclusively. In Node that is the wx flag, in PowerShell FileMode.CreateNew. Creation succeeding means the lock is held.
  • The content is <pid> <iso time>, for diagnostics only.
  • A lock file older than 120 seconds is considered stale, its holder having crashed, and may be removed.
  • Release is deleting the file.

The Node side is short enough to quote the core of it:

js
function tryAcquire(file, staleMs) {
  try {
    fs.writeFileSync(file, process.pid + ' ' + new Date().toISOString(), { flag: 'wx' });
    return true;
  } catch (e) {
    if (e.code !== 'EEXIST') throw e;
  }
  // Held by someone: steal it only when the holder is clearly gone.
  try {
    const age = Date.now() - fs.statSync(file).mtimeMs;
    if (age > staleMs) {
      try { fs.unlinkSync(file); } catch (e) { /* someone else stole it first */ }
    }
  } catch (e) { /* vanished between attempts: the next try may win */ }
  return false;
}

Waiting never blocks the Electron main process. Attempts are spaced 75 ms apart with timers, up to a 10 second timeout, and withBoardLock releases the file in a finally, so a throwing body does not leave it behind.

A PowerShell trap in the same commit

The PowerShell half has a comment explaining a trap:

powershell
# A static .NET call, not New-Object: New-Object reports a failed
# constructor as a non-terminating error, so the catch never ran and
# the body went ahead without the lock.
$fs = [IO.File]::Open($path, [IO.FileMode]::CreateNew, [IO.FileAccess]::Write, [IO.FileShare]::None)

When the lock file already existed, the failed constructor did not throw into my catch. The script carried on as if it held the lock. A lock that fails open is worse than no lock, because it looks like protection. Calling the static method makes the failure a real exception.

The lock is not enough

A lock only stops two writers from interleaving. It does not stop a stale write. The page loads the board, the user spends a minute editing, and an AI run patches the file in that minute. When the page saves, it sends back its whole board, built from the old copy. Under a perfect lock that save still overwrites the run's patch, just politely.

The comment in src/boardlock.js says it directly: a value read before acquiring the lock and written inside it is still a lost update. So the save handler re-reads the file inside the lock and merges three versions: base, the board the page was last given; mine, what it sends back; theirs, what is on disk right now.

js
let theirs = readJson(KANBAN_FILE);
// An unreadable file must not read as "a script deleted every task"
if (!theirs || !Array.isArray(theirs.tasks)) theirs = base || clean;
merged = mergeBoard(base || theirs, clean, theirs, { mineFields: KANBAN_FIELDS, normalize: normalizeTask });
fs.writeFileSync(KANBAN_FILE, JSON.stringify(merged, null, 2), 'utf8');

The merge rules

src/boardmerge.js merges per task id, separately for tasks and archive. The rules are written at the top of the file:

  • Only in mine means the user added it: keep it.
  • Only in theirs means a script added it: keep it.
  • Gone from mine while theirs still equals base: the user deleted it, so delete it. If a script changed it meanwhile, keep it.
  • Both sides changed a task: per field, mine wins if mine changed that field, otherwise theirs.
  • History arrays, comments and aiNotes, are never dropped. Entries from both sides are kept, matched by timestamp and text, and a comment acknowledged on either side stays acknowledged.

Two details took thought. The page only owns some fields, the ones sanitizeKanban keeps. A field the page never sends is not a deletion, so mineFields tells the merge which absences count. And the sanitizer trims, for example to the last 10 AI notes. Comparing mine with the raw base would read that trim as a user edit, so normalize runs the sanitizer over the base task first.

Key order is another trap: PowerShell and Node serialize JSON with different key order, so equality goes through a canon function that sorts keys before comparing.

Failing closed

If the lock cannot be obtained within the timeout, the code throws EBOARDLOCK and lockedBoardWrite does not write. The comment above it: an unlocked write is "exactly the lost update the lock exists to prevent". The user gets a message that the board is busy and the change was not saved. I would rather ask someone to retry than save quietly the wrong thing.

The lock has a test with eight concurrent callers doing a read, a 5 ms pause and a write on a counter file. The test asserts that at most one caller is ever inside and that the counter ends at 8. Further tests cover stealing a stale lock, timing out against a fresh one without running the body, and releasing when the body throws.

What I took from it

Adding concurrency to a feature means listing every writer, not just the new ones. The scripts were the obvious writers. The page save was the one that would have lost data in ordinary use. And a lock is the cheap half of the fix: the harder half is deciding, field by field, whose change should win.

#electron#concurrency#file-locking#powershell

Keep reading

Have a project in mind?