Skip to content

Local-first 🧠 memory for Hermes Agent that lives in your Obsidian vault and remembers project context. Nightly 😴 dream passes turn repeat corrections into confirmed preferences with measurable confidence. Adapters ship for Claude Code, Codex, and OpenClaw, with an MCP server for anything else.

TypeScript

fix: one holder per hook-state scope through a stale-lock takeover (v1.86.2) (#261)

Serg Erosheb183b6c3b2ee
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index df47d265..b3e35026 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "1.86.1",
+ "version": "1.86.2",
"description": "Plugin-first second brain package for AI agents and humans.",
"author": {
"name": "Open Second Brain contributors"
diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json
index f089a57f..8a716a79 100644
--- a/.codex-plugin/plugin.json
+++ b/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "1.86.1",
+ "version": "1.86.2",
"description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.",
"author": {
"name": "Open Second Brain contributors",
diff --git a/CHANGELOG.md b/CHANGELOG.md
index fe444fdb..5ae170e8 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,16 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
+## [1.86.2] - 2026-10-16
+
+Open Second Brain 1.86.2 closes a concurrency defect in the per-session hook-state lock: after a stale lock was taken over, two or more hook processes could hold the same scope at once, so a queued re-grounding part could be delivered more than once.
+
+### Fixed
+
+- **A stale hook-state lock takeover can no longer admit a second holder.** A contender that judged an abandoned scope lock stale could act after another contender had already taken it over and re-acquired, move that live lock aside, and leave the lock name empty long enough for a third contender to acquire beside it; from then on each holder's release deleted the next holder's lock, and concurrent takers on the Windows runner each received every queued re-grounding part. A takeover now removes the judged file only for the one contender whose exclusive claim on that file's identity wins, and only while the name still holds that file, so a live holder's lock is never moved or removed.
+- **A lock release removes only the lock its holder created.** The release and the process-exit sweep of the shared lock primitive leave a lock file in place once its name holds another holder's file, so one lost lock can no longer cascade into several holders.
+- **The same claim guards the other stale-lock breakers.** The lineage gap-sidecar trim lock and the deferred session-capture worker lock break an abandoned lock through the same claim, and the capture worker's release removes only its own lock; the hook-state prune removes old scope locks through it too and sweeps old takeover claims. A claim older than a minute no longer blocks a takeover, so a winner that died between its claim and the removal, or a new abandoned lock that reuses an old inode, cannot leave a lock unbreakable, and every successful takeover sweeps that lock's old claims, so the stores without a prune of their own (the capture worker lock in the temp directory, the lineage gap lock) do not accumulate them.
+
## [1.86.1] - 2026-10-16
Open Second Brain 1.86.1 repairs what the review of v1.86.0 found and closes two embedding-loss defects: a vault that had the retrieval trust gate on keeps excluding after the upgrade, a barren session mine records its tombstone in the documented flow, the undistilled census reads the session store once so the SessionStart nudge stays inside its budget, and a search index left on an older schema is upgraded in place with every stored embedding kept instead of being rebuilt keyword-only.
@@ -8591,6 +8601,7 @@ Hermes / Claude Code / Codex / OpenClaw configurations do not change.
- Sandbox vault and plugin manifest fixtures for tests.
- GitHub release workflow for tag-based and manually dispatched releases.
+[1.86.2]: https://github.com/itechmeat/open-second-brain/compare/v1.86.1...v1.86.2
[1.86.1]: https://github.com/itechmeat/open-second-brain/compare/v1.86.0...v1.86.1
[1.86.0]: https://github.com/itechmeat/open-second-brain/compare/v1.85.0...v1.86.0
[1.85.0]: https://github.com/itechmeat/open-second-brain/compare/v1.84.1...v1.85.0
diff --git a/hooks/lib/session-state.ts b/hooks/lib/session-state.ts
index b783f92b..e3ae52ac 100644
--- a/hooks/lib/session-state.ts
+++ b/hooks/lib/session-state.ts
@@ -18,18 +18,14 @@
*/
import { createHash } from "node:crypto";
-import {
- linkSync,
- lstatSync,
- mkdirSync,
- readdirSync,
- renameSync,
- statSync,
- unlinkSync,
-} from "node:fs";
+import { type BigIntStats, lstatSync, mkdirSync, readdirSync, unlinkSync } from "node:fs";
import { dirname, join } from "node:path";
-import { acquireLockSync, type LockHandle } from "../../src/core/brain/sync-lockfile.ts";
+import {
+ acquireLockSync,
+ type LockHandle,
+ removeStaleLockSync,
+} from "../../src/core/brain/sync-lockfile.ts";
import {
resolveSessionScope,
SESSION_SCOPE_MAX_LENGTH,
@@ -49,14 +45,19 @@ const HOOK_STATE_DIR = "hook-state";
/** A scope state file name: a scope slug plus `.json`, nothing else. */
const SCOPE_FILE_RE = new RegExp(`^[a-z0-9-]{1,${SESSION_SCOPE_MAX_LENGTH}}\\.json$`);
+/** A scope lockfile name: `<slug>.json.lock`. */
+const SCOPE_LOCK_RE = new RegExp(`^[a-z0-9-]{1,${SESSION_SCOPE_MAX_LENGTH}}\\.json\\.lock$`);
+
/**
* Residue a killed hook can leave beside a scope file: an atomic-write temp
* file (`.<slug>.json.<pid>.<ms>.<rand>.tmp`), an abandoned scope lockfile
- * (`<slug>.json.lock`) and a stale-lock aside (`<slug>.json.lock.stale-<pid>`).
+ * (`<slug>.json.lock`), a takeover claim (`<slug>.json.lock.takeover-<ino>-<mtime>[-<gen>]`,
+ * see `removeStaleLockSync` in `src/core/brain/sync-lockfile.ts`) and the stale-lock aside earlier releases
+ * moved a lock to (`<slug>.json.lock.stale-<pid>`).
*/
const SCOPE_RESIDUE_RE = new RegExp(
`^(?:\\.[a-z0-9-]{1,${SESSION_SCOPE_MAX_LENGTH}}\\.json\\.\\d+\\.\\d+\\.[0-9a-f]+\\.tmp` +
- `|[a-z0-9-]{1,${SESSION_SCOPE_MAX_LENGTH}}\\.json\\.lock(?:\\.stale-\\d+)?)$`,
+ `|[a-z0-9-]{1,${SESSION_SCOPE_MAX_LENGTH}}\\.json\\.lock(?:\\.stale-\\d+|\\.takeover-\\d+-\\d+(?:-\\d+)?)?)$`,
);
/** Scope slug used when no session id is available (single flat lane). */
@@ -214,60 +215,34 @@ function tryLock(path: string): LockHandle | null {
}
}
-/** Whether the file at `path` was last modified more than the stale threshold ago. */
-function isStale(path: string): boolean {
- return Date.now() - statSync(path).mtimeMs > HOOK_STATE_STALE_LOCK_MS;
+/** Whether a lockfile was last modified more than the stale threshold ago. */
+function isStale(st: BigIntStats): boolean {
+ return Date.now() - Number(st.mtimeMs) > HOOK_STATE_STALE_LOCK_MS;
}
/**
* Take over the scope lockfile when its mtime is older than
* {@link HOOK_STATE_STALE_LOCK_MS}, the residue of a hook killed mid-update.
- * Returns `true` when it removed one.
- *
- * The takeover is a rename to a per-process aside name, not an unlink in
- * place: a rename moves exactly one file, so of two contenders that both saw
- * the stale lock, only one moves it. The other's rename then either fails
- * (nothing there) or moves the winner's fresh lock, which the re-check of the
- * moved file catches; that lock is linked back under its name (`link` never
- * overwrites) and the takeover reports `false`. Every I/O error reports
- * `false`.
+ * Returns `true` when it removed one, after which the caller makes one fresh
+ * acquire attempt like any other contender.
*
- * One residual race remains: while a moved live lock is aside, between the
- * rename and the link back, the lock name is absent, so a third contender
- * arriving in that window acquires alongside the live holder; the link back
- * then fails and the live holder's lock is lost. That needs a crash residue,
- * three contenders on one scope and an arrival within microseconds, and the
- * worst outcome is a lost update to the operator's own session state.
+ * The staleness judgement and the removal are tied to one file through
+ * `removeStaleLockSync` in `src/core/brain/sync-lockfile.ts`: the identity
+ * read with the judgement is the one it claims and re-checks, so a
+ * contender whose judgement is out of date (the abandoned lock was already
+ * taken over and a live holder re-acquired) removes nothing. A live
+ * holder's lock is never moved or removed, and a release removes only a
+ * lock its holder still owns, so the scope has at most one holder at a time
+ * through a takeover. Every I/O error reports `false`.
*/
-function clearStaleLock(path: string, stale: (path: string) => boolean = isStale): boolean {
- const lockPath = path + ".lock";
- const aside = `${lockPath}.stale-${process.pid}`;
- try {
- if (!stale(lockPath)) return false;
- renameSync(lockPath, aside);
- } catch {
- return false;
- }
- try {
- if (stale(aside)) return true;
- // Moved a live holder's lock: put it back before anyone can see the gap widen.
- linkSync(aside, lockPath);
- return false;
- } catch {
- return false;
- } finally {
- try {
- unlinkSync(aside);
- } catch {
- // already gone
- }
- }
+function clearStaleLock(path: string, stale: (st: BigIntStats) => boolean = isStale): boolean {
+ return removeStaleLockSync(path + ".lock", stale);
}
/**
* Test-only entry to {@link clearStaleLock} with an injected stale check, so
- * a test can reach the "moved a live lock" branch, which otherwise needs an
- * mtime change between the two checks.
+ * a test can run another contender's takeover between this contender's
+ * judgement and its act - an interleaving real processes reach only by luck.
*
* The leading underscore is this repo's marker for a test-only export.
*/
@@ -278,7 +253,7 @@ export const _clearStaleLockForTests = clearStaleLock;
* Acquire the scope's advisory lock. The read-merge-write is not atomic on its
* own, so two concurrent hook processes could otherwise each read the file,
* merge their own key, and clobber the other's stamp. A stale lockfile is
- * taken over once (rename aside, then one fresh attempt). With `tryOnce` a contended
+ * taken over once (claimed and removed, then one fresh attempt). With `tryOnce` a contended
* lock yields `null` immediately; otherwise it retries within a bounded budget
* before yielding `null`, and the caller degrades rather than throwing.
*/
@@ -382,7 +357,10 @@ const PRUNE_MAX_FILES = 200;
* Delete scope state files (`<slug>.json`) and their write and lock residue
* (see {@link SCOPE_RESIDUE_RE}) whose mtime is older than `maxAgeMs`,
* removing at most `maxFiles` per sweep. A lock that old is far past
- * {@link HOOK_STATE_STALE_LOCK_MS}, so no live hook holds it. Symlinks and
+ * {@link HOOK_STATE_STALE_LOCK_MS}, so no live hook holds it; it is removed
+ * through the same claim a hook's takeover uses (`removeStaleLockSync`),
+ * which leaves a fresh claim file behind for
+ * a later sweep. Symlinks and
* any name outside those shapes are left alone, and nothing is swept
* when `.open-second-brain` or `hook-state` is itself a symlink: a vault
* received from elsewhere could otherwise point the sweep at any directory.
@@ -404,15 +382,28 @@ export function pruneHookStateFiles(
} catch {
return 0;
}
+ // Locks last: removing a lock also sweeps its old takeover claims, which
+ // this loop would then find gone and not count. Directory order differs
+ // between filesystems, so fix the order rather than depend on it.
+ names.sort((a, b) => Number(SCOPE_LOCK_RE.test(a)) - Number(SCOPE_LOCK_RE.test(b)));
let removed = 0;
for (const name of names) {
if (removed >= maxFiles) break;
if (!SCOPE_FILE_RE.test(name) && !SCOPE_RESIDUE_RE.test(name)) continue;
const path = join(dir, name);
try {
- const st = lstatSync(path);
- if (!st.isFile() || nowMs - st.mtimeMs <= maxAgeMs) continue;
- unlinkSync(path);
+ const st = lstatSync(path, { bigint: true });
+ if (!st.isFile() || nowMs - Number(st.mtimeMs) <= maxAgeMs) continue;
+ // A lock goes through the takeover claim, like a hook's takeover, so the
+ // sweep and a hook that judged the same lock stale never both remove it
+ // (the second would remove the first's freshly re-acquired lock).
+ if (SCOPE_LOCK_RE.test(name)) {
+ if (!removeStaleLockSync(path, (seen) => nowMs - Number(seen.mtimeMs) > maxAgeMs)) {
+ continue;
+ }
+ } else {
+ unlinkSync(path);
+ }
removed += 1;
} catch {
// vanished or unremovable; leave it for the next sweep
diff --git a/hooks/session-capture.ts b/hooks/session-capture.ts
index 6f410782..efc48916 100644
--- a/hooks/session-capture.ts
+++ b/hooks/session-capture.ts
@@ -27,7 +27,15 @@
import { spawn } from "node:child_process";
import { createHash, randomBytes } from "node:crypto";
-import { closeSync, openSync, readFileSync, statSync, unlinkSync, writeFileSync } from "node:fs";
+import {
+ closeSync,
+ fstatSync,
+ lstatSync,
+ openSync,
+ readFileSync,
+ unlinkSync,
+ writeFileSync,
+} from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
@@ -37,6 +45,7 @@ import {
lifecycleEventNeedsDedup,
} from "../src/core/brain/session-lifecycle.ts";
import { hookAuditDir } from "../src/core/brain/paths.ts";
+import { removeStaleLockSync } from "../src/core/brain/sync-lockfile.ts";
import { SafeguardTimeoutError, type Safeguard } from "../src/core/brain/safeguard.ts";
import {
armProcessCeiling,
@@ -110,26 +119,50 @@ function lockPath(vault: string): string {
return join(tmpdir(), `o2b-capture-${key}.lock`);
}
-/** Take the per-vault worker lock; returns its release, or null on timeout. */
+/** Whether a worker lock is older than {@link WORKER_LOCK_STALE_MS}. */
+function workerLockAbandoned(st: { readonly mtimeMs: bigint }): boolean {
+ return Date.now() - Number(st.mtimeMs) > WORKER_LOCK_STALE_MS;
+}
+
+/**
+ * Take the per-vault worker lock; returns its release, or null on timeout.
+ *
+ * A lock older than {@link WORKER_LOCK_STALE_MS} is removed through
+ * `removeStaleLockSync`, so of two waiters that both judged it abandoned
+ * only one removes it, and the other never removes the lock the first then
+ * takes. The release removes the lock only while it is still the file this
+ * worker created.
+ */
async function acquireWorkerLock(vault: string): Promise<(() => void) | null> {
const path = lockPath(vault);
const deadline = Date.now() + WORKER_LOCK_WAIT_MS;
for (;;) {
+ let fd = -1;
try {
- closeSync(openSync(path, "wx"));
+ fd = openSync(path, "wx");
+ } catch {
+ removeStaleLockSync(path, workerLockAbandoned);
+ }
+ if (fd >= 0) {
+ let mine: { readonly dev: bigint; readonly ino: bigint } | null = null;
+ try {
+ mine = fstatSync(fd, { bigint: true });
+ } catch {
+ // unknown identity: release falls back to removing the name
+ } finally {
+ closeSync(fd);
+ }
return () => {
try {
+ const now = lstatSync(path, { bigint: true });
+ if (mine !== null && mine.ino !== 0n && (now.dev !== mine.dev || now.ino !== mine.ino)) {
+ return; // taken over and re-acquired by another worker: theirs now
+ }
unlinkSync(path);
} catch {
// already gone
}
};
- } catch {
- try {
- if (Date.now() - statSync(path).mtimeMs > WORKER_LOCK_STALE_MS) unlinkSync(path);
- } catch {
- // raced with the holder's release; retry
- }
}
if (Date.now() >= deadline) return null;
// oxlint-disable-next-line no-await-in-loop -- polling a lock, sequential by design
diff --git a/openclaw.plugin.json b/openclaw.plugin.json
index ff0818d8..99c20d42 100644
--- a/openclaw.plugin.json
+++ b/openclaw.plugin.json
@@ -2,7 +2,7 @@
"id": "open-second-brain",
"name": "Open Second Brain",
"description": "Second brain for AI agents using Obsidian-compatible Markdown vaults.",
- "version": "1.86.1",
+ "version": "1.86.2",
"activation": { "onStartup": true },
"skills": ["./skills"],
"contracts": {
diff --git a/package.json b/package.json
index aee8730c..4368ef72 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "1.86.1",
+ "version": "1.86.2",
"private": false,
"description": "Second brain for AI agents using Obsidian-compatible Markdown vaults. Works with Hermes, Claude Code, Codex, and OpenClaw.",
"keywords": [
diff --git a/plugin.yaml b/plugin.yaml
index 8032f9ca..b8ef5a64 100644
--- a/plugin.yaml
+++ b/plugin.yaml
@@ -1,5 +1,5 @@
name: open-second-brain
-version: "1.86.1"
+version: "1.86.2"
description: "Open Second Brain - native Hermes memory provider backed by an Obsidian-compatible Markdown vault."
author: "Open Second Brain contributors"
memory_provider: true
diff --git a/plugins/codex/.codex-plugin/plugin.json b/plugins/codex/.codex-plugin/plugin.json
index 02030d69..41208a8a 100644
--- a/plugins/codex/.codex-plugin/plugin.json
+++ b/plugins/codex/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "1.86.1",
+ "version": "1.86.2",
"description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.",
"author": {
"name": "Open Second Brain contributors",
diff --git a/plugins/hermes/plugin.yaml b/plugins/hermes/plugin.yaml
index 8032f9ca..b8ef5a64 100644
--- a/plugins/hermes/plugin.yaml
+++ b/plugins/hermes/plugin.yaml
@@ -1,5 +1,5 @@
name: open-second-brain
-version: "1.86.1"
+version: "1.86.2"
description: "Open Second Brain - native Hermes memory provider backed by an Obsidian-compatible Markdown vault."
author: "Open Second Brain contributors"
memory_provider: true
diff --git a/pyproject.toml b/pyproject.toml
index fea2ca56..26ef8734 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -10,7 +10,7 @@ build-backend = "setuptools.build_meta"
# CLI entry points (those moved to `package.json` `bin`).
[project]
name = "open-second-brain"
-version = "1.86.1"
+version = "1.86.2"
description = "Hermes Python shim for Open Second Brain. Most of the project (CLI, MCP server, OpenClaw plugin) is TypeScript on Bun; see package.json."
readme = "README.md"
requires-python = ">=3.11"
diff --git a/src/core/brain/destructive-sites.ts b/src/core/brain/destructive-sites.ts
index bdb93407..a6513b3a 100644
--- a/src/core/brain/destructive-sites.ts
+++ b/src/core/brain/destructive-sites.ts
@@ -337,17 +337,13 @@ export const DESTRUCTIVE_SITES: Readonly<Record<string, DestructiveSiteDeclarati
calls: ["unlinkSync"],
recovery: UNARCHIVED_BRAIN,
reason:
- "the lock release and the process-exit sweep that releases any lock still held. " +
- "A lock file's meaning comes entirely from its exclusive creation; removing one " +
- "grants access rather than destroying anything.",
- },
- "src/core/brain/lineage/ledger.ts": {
- calls: ["unlinkSync"],
- recovery: UNARCHIVED_BRAIN,
- reason:
- "breaks a lock its own mtime has proved stale past a fixed threshold, with the " +
- "original `ELOCKED` rethrown when it has not. The ledger the lock protects is " +
- "append-only and is not touched here.",
+ "the lock release and the process-exit sweep that releases any lock still held, " +
+ "each only while the lock file is still the one its holder created, and " +
+ "`removeStaleLockSync`, which removes an abandoned lock for the one contender whose " +
+ "exclusive takeover claim on that file won (the lineage gap-sidecar trim lock and " +
+ "the hook-state scope locks break theirs through it). A lock file's meaning comes " +
+ "entirely from its exclusive creation; removing one grants access rather than " +
+ "destroying anything.",
},
// --- Rewrites through a temp file ------------------------------------
diff --git a/src/core/brain/lineage/ledger.ts b/src/core/brain/lineage/ledger.ts
index 952a6d32..e695045b 100644
--- a/src/core/brain/lineage/ledger.ts
+++ b/src/core/brain/lineage/ledger.ts
@@ -64,7 +64,7 @@
* they ride the integrity chain without any change to it.
*/
-import { appendFileSync, existsSync, mkdirSync, readFileSync, statSync, unlinkSync } from "node:fs";
+import { appendFileSync, existsSync, mkdirSync, readFileSync } from "node:fs";
import { dirname, join, posix } from "node:path";
import { atomicWriteFileSync } from "../../fs-atomic.ts";
@@ -84,7 +84,7 @@ import {
type ShardedRow,
} from "../ledger-shards.ts";
import { BRAIN_ROOT_REL, ensureInsideVault } from "../paths.ts";
-import { acquireLockSync, type LockHandle } from "../sync-lockfile.ts";
+import { acquireLockSync, type LockHandle, removeStaleLockSync } from "../sync-lockfile.ts";
import { assertVaultIdentityForWrite, VaultIdentityMismatchError } from "../vault-identity.ts";
import type { SessionLineage } from "./types.ts";
@@ -1072,8 +1072,11 @@ function acquireGapLock(path: string, nowMs: number): LockHandle {
const errno = err as NodeJS.ErrnoException;
if (errno.code !== "ELOCKED") throw err;
const lockPath = typeof errno.path === "string" ? errno.path : `${path}.lock`;
- if (nowMs - statSync(lockPath).mtimeMs <= GAP_LOCK_STALE_MS) throw err;
- unlinkSync(lockPath);
+ // Removed only by the one contender that claims this abandoned file, so
+ // two trims that both judged it stale cannot both break it.
+ const abandoned = (st: { readonly mtimeMs: bigint }): boolean =>
+ nowMs - Number(st.mtimeMs) > GAP_LOCK_STALE_MS;
+ if (!removeStaleLockSync(lockPath, abandoned)) throw err;
// Exactly one retry. A second ELOCKED means a live writer took the
// lock in between, which is contention rather than abandonment.
return acquireLockSync(path);
diff --git a/src/core/brain/sync-lockfile.ts b/src/core/brain/sync-lockfile.ts
index aea7fdc0..72578ea5 100644
--- a/src/core/brain/sync-lockfile.ts
+++ b/src/core/brain/sync-lockfile.ts
@@ -26,6 +26,14 @@
* the other was not used is reading the right question, and this is the
* answer.
*
+ * Ownership: a handle remembers the identity (device and inode) of the file
+ * its exclusive create made, and {@link LockHandle.release} and the exit hook
+ * remove the lock name only while it still names that file. A lock name
+ * that something else removed and another process re-created belongs to
+ * that process, and deleting it would let a third process in beside it; an
+ * abandoned-lock takeover ({@link removeStaleLockSync}) is one remover, an
+ * operator clearing a lock by hand another.
+ *
* Stale-lock recovery: on normal process exit the cleanup hook unlinks
* any still-held locks. On hard crash (SIGKILL, OOM, or the second
* Ctrl-C that falls through to the default SIGINT disposition) the
@@ -53,6 +61,7 @@
*/
import {
+ type BigIntStats,
closeSync,
constants as fsConstants,
fstatSync,
@@ -63,38 +72,77 @@ import {
unlinkSync,
writeSync,
} from "node:fs";
-import { dirname, join } from "node:path";
+import { basename, dirname, join } from "node:path";
import { BRAIN_ROOT_REL, DERIVED_STORE_DIR } from "./path-constants.ts";
export interface LockHandle {
/** Filesystem path to the underlying `.lock` file. */
readonly path: string;
- /** Release the lock. Idempotent: a second call is a no-op. */
+ /**
+ * Release the lock: remove the `.lock` file while its name still holds the
+ * file this handle created, and leave a lock someone else now holds alone.
+ * Idempotent: a second call is a no-op.
+ */
release(): void;
}
const LOCK_SUFFIX = ".lock";
-// Held locks, tracked at module scope so the exit hook can clean up.
-const heldLocks = new Set<string>();
+/**
+ * The file a holder created: device and inode as exact bigints. `null` when
+ * the platform reports no inode (some network and FAT volumes answer 0),
+ * where ownership cannot be told apart and release falls back to removing
+ * the name.
+ */
+type LockIdentity = { readonly dev: bigint; readonly ino: bigint } | null;
+
+// Held locks and the file each holder created, tracked at module scope so the
+// exit hook can clean up.
+const heldLocks = new Map<string, LockIdentity>();
let exitHookInstalled = false;
function ensureExitHook(): void {
if (exitHookInstalled) return;
exitHookInstalled = true;
process.on("exit", () => {
- for (const lockPath of heldLocks) {
- try {
- unlinkSync(lockPath);
- } catch {
- // best-effort; the next acquire will see ELOCKED and surface it
+ for (const [lockPath, identity] of heldLocks) {
+ if (ownsLockName(lockPath, identity)) {
+ try {
+ unlinkSync(lockPath);
+ } catch {
+ // best-effort; the next acquire will see ELOCKED and surface it
+ }
}
}
heldLocks.clear();
});
}
+/** Identity of the file behind an open descriptor; `null` when it has none. */
+function identityOf(fd: number): LockIdentity {
+ try {
+ const st = fstatSync(fd, { bigint: true });
+ return st.ino === 0n ? null : { dev: st.dev, ino: st.ino };
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Whether `lockPath` still names the file this holder created. A missing name
+ * is not owned (nothing to remove); an unknown identity is presumed owned, the
+ * behaviour before ownership was tracked.
+ */
+function ownsLockName(lockPath: string, identity: LockIdentity): boolean {
+ try {
+ const st = lstatSync(lockPath, { bigint: true });
+ return identity === null || (st.dev === identity.dev && st.ino === identity.ino);
+ } catch {
+ return false;
+ }
+}
+
/**
* Whether a failed exclusive create is Windows reporting a lock that is
* mid-release rather than a real permission problem.
@@ -142,8 +190,8 @@ function nameIsOccupied(path: string): boolean {
/**
* Acquire an exclusive lock for `target`. Returns a handle whose
* {@link LockHandle.release} method unlinks the underlying `.lock`
- * file. Throws `Error & { code: 'ELOCKED' }` if the lock is already
- * held.
+ * file while it is still the one this call created. Throws
+ * `Error & { code: 'ELOCKED' }` if the lock is already held.
*
* The target file itself does NOT need to exist - first-time writes
* acquire the lock before creating the target. The parent directory
@@ -180,6 +228,8 @@ export function acquireLockSync(target: string): LockHandle {
}
}
+ const identity = identityOf(fd);
+
// Stamp pid + timestamp into the lock body. The contents are
// purely diagnostic - the doctor surface reads them when reporting
// stale locks. Failure to write is non-fatal: the lock semantics
@@ -198,14 +248,19 @@ export function acquireLockSync(target: string): LockHandle {
}
}
- heldLocks.add(lockPath);
+ heldLocks.set(lockPath, identity);
let released = false;
return {
path: lockPath,
release(): void {
if (released) return;
released = true;
- heldLocks.delete(lockPath);
+ // A newer handle in this process may have re-registered the path; its
+ // registration is the one the exit sweep must still see.
+ if (heldLocks.get(lockPath) === identity) heldLocks.delete(lockPath);
+ // The name no longer holds this holder's file: whoever holds it now
+ // keeps it. Removing it would admit a second holder beside them.
+ if (!ownsLockName(lockPath, identity)) return;
// Anything past our own stamp was appended by a waiter (see
// `markWaiting`): someone is queued for this lock, so a re-acquire from
// this process steps back first. Best-effort, like the stamp itself.
@@ -225,6 +280,137 @@ export function acquireLockSync(target: string): LockHandle {
};
}
+/** Whether two stats describe the same file in the same state. */
+function sameLockFile(a: BigIntStats, b: BigIntStats): boolean {
+ return a.dev === b.dev && a.ino === b.ino && a.mtimeNs === b.mtimeNs;
+}
+
+/**
+ * Remove an abandoned lock file: the file at `lockPath` when `stale` judges
+ * it abandoned, only while the name still holds that same file, and only for
+ * the one caller that claims that file first. Returns `true` when this call
+ * removed it; the caller then makes a fresh acquire attempt like any other
+ * contender. Never throws.
+ *
+ * A plain "stat, judge, unlink" lets two contenders that both judged the same
+ * abandoned lock both remove something: the first removes the abandoned
+ * lock and re-acquires, the second then removes that fresh lock and
+ * acquires too, and from there each holder's release can remove the next
+ * one's lock. Here the judgement and the removal are tied to one file.
+ *
+ * The claim is an exclusive create of a name derived from the judged file's
+ * identity (`<lock>.takeover-<inode>-<mtime ns>`): every contender that judged
+ * the same file races for the same claim name, and exclusive create is a
+ * compare-and-swap on Linux, macOS and Windows alike, so exactly one of them
+ * goes on. A fresh claim is never removed - it is the tombstone that turns
+ * away a late contender still acting on its judgement of that same file
+ * after the winner has re-acquired under the same name. A claim older than
+ * {@link TAKEOVER_CLAIM_STALE_MS} turns nobody away any more: it is the
+ * residue of a winner that died between the claim and the unlink, or of an
+ * earlier takeover whose inode and mtime a new abandoned lock happens to
+ * reuse. Such a claim does not block the takeover - contenders move on to
+ * the next claim generation (`<lock>.takeover-<inode>-<mtime ns>-<n>`), again
+ * one exclusive create every contender races for, so no claim is ever
+ * deleted on the contended path. After a successful removal the winner
+ * sweeps this lock's claims older than the threshold, so stores without a
+ * sweep of their own (the session-capture worker lock in `tmpdir()`, the
+ * lineage gap lock) do not accumulate them.
+ *
+ * The winner then re-reads the name and removes it only while it still
+ * holds the judged file, so a lock that was replaced by a fresh one in the
+ * meantime is never removed. Between that read and the unlink the name can
+ * only change if the judged lock's own holder releases it, which the
+ * staleness judgement presumes dead, as long as every other remover of the
+ * lock goes through this function.
+ */
+export function removeStaleLockSync(
+ lockPath: string,
+ stale: (st: BigIntStats) => boolean,
+): boolean {
+ let seen: BigIntStats;
+ try {
+ seen = lstatSync(lockPath, { bigint: true });
+ if (!stale(seen)) return false;
+ } catch {
+ return false;
+ }
+ const claimed = claimTakeover(`${lockPath}.takeover-${seen.ino}-${seen.mtimeNs}`);
+ if (claimed === "exhausted") {
+ // Every generation is a dead claim: clear them so the next attempt can claim.
+ sweepTakeoverClaims(lockPath);
+ return false;
+ }
+ if (!claimed) return false;
+ try {
+ if (!sameLockFile(lstatSync(lockPath, { bigint: true }), seen)) return false;
+ unlinkSync(lockPath);
+ } catch {
+ return false;
+ }
+ sweepTakeoverClaims(lockPath);
+ return true;
+}
+
+/**
+ * Age past which a takeover claim no longer turns a contender away. A winner
+ * goes from its claim to the unlink in microseconds, and a contender acts on
+ * its judgement within one acquire attempt, so a minute-old claim belongs to
+ * nobody still running.
+ */
+export const TAKEOVER_CLAIM_STALE_MS = 60_000;
+
+/** How many claim generations one judged lock file may need (see {@link removeStaleLockSync}). */
+const TAKEOVER_CLAIM_GENERATIONS = 4;
+
+function claimIsStale(path: string): boolean {
+ try {
+ return Date.now() - lstatSync(path).mtimeMs > TAKEOVER_CLAIM_STALE_MS;
+ } catch {
+ return false;
+ }
+}
+
+/**
+ * Exclusive-create the first free claim generation for one judged lock file.
+ * An existing fresh claim means another contender won; an existing stale
+ * claim sends every contender to the next generation. `"exhausted"` means
+ * every generation holds a stale claim.
+ */
+function claimTakeover(base: string): boolean | "exhausted" {
+ for (let gen = 0; gen < TAKEOVER_CLAIM_GENERATIONS; gen++) {
+ const claim = gen === 0 ? base : `${base}-${gen}`;
+ try {
+ closeSync(openSync(claim, "wx", 0o600));
+ return true;
+ } catch (err) {
+ if ((err as NodeJS.ErrnoException).code !== "EEXIST") return false;
+ if (!claimIsStale(claim)) return false;
+ }
+ }
+ return "exhausted";
+}
+
+/** Remove this lock's takeover claims older than {@link TAKEOVER_CLAIM_STALE_MS}. Never throws. */
+function sweepTakeoverClaims(lockPath: string): void {
+ const prefix = `${basename(lockPath)}.takeover-`;
+ let names: string[];
+ try {
+ names = readdirSync(dirname(lockPath));
+ } catch {
+ return;
+ }
+ for (const name of names) {
+ if (!name.startsWith(prefix)) continue;
+ const claim = join(dirname(lockPath), name);
+ if (!claimIsStale(claim)) continue;
+ try {
+ unlinkSync(claim);
+ } catch {
+ // already gone
+ }
+ }
+}
+
/**
* How long {@link acquireLockSyncWithRetry} keeps waiting, and the ceiling on
* one sleep between attempts.
diff --git a/tests/core/architecture/write-site-census.test.ts b/tests/core/architecture/write-site-census.test.ts
index e85722e2..f940b362 100644
--- a/tests/core/architecture/write-site-census.test.ts
+++ b/tests/core/architecture/write-site-census.test.ts
@@ -407,12 +407,12 @@ const DIRECT_WRITE_EXCLUSIONS: Readonly<Record<string, WriteExclusion>> = Object
},
"src/core/brain/lineage/ledger.ts": {
categories: [C.appendOnlyLedger, C.lockPrimitive],
- calls: ["appendFileSync", "unlinkSync"],
+ calls: ["appendFileSync"],
reason:
"appends one record line; the COMPACTION arm beside it already uses " +
"`atomicWriteFileSync`, because rewriting is a different operation from " +
- "appending. The `unlinkSync` breaks a lock proven stale by its own mtime, with " +
- "exactly one retry.",
+ "appending. The trim lock it proves stale by its own mtime is broken through " +
+ "`removeStaleLockSync` in `sync-lockfile.ts`, with exactly one retry.",
},
"src/core/brain/freeze.ts": {
categories: [C.lockPrimitive, C.retentionDelete],
@@ -1005,7 +1005,9 @@ const DIRECT_WRITE_EXCLUSIONS: Readonly<Record<string, WriteExclusion>> = Object
reason:
"the lock itself. Its semantics come from the exclusive create; the body it " +
"writes is a diagnostic pid/timestamp stamp whose failure is deliberately " +
- "non-fatal, and the unlink is the release.",
+ "non-fatal, and the unlink is the release (only of a lock file its holder still " +
+ "owns) or the removal of an abandoned lock by the one contender whose exclusive " +
+ "takeover claim on that file won.",
},
// --- Metadata only -----------------------------------------------------
diff --git a/tests/core/brain/sync-lockfile.test.ts b/tests/core/brain/sync-lockfile.test.ts
index e08454cb..2599e732 100644
--- a/tests/core/brain/sync-lockfile.test.ts
+++ b/tests/core/brain/sync-lockfile.test.ts
@@ -8,11 +8,14 @@
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
import {
existsSync,
+ lstatSync,
mkdirSync,
mkdtempSync,
readdirSync,
readFileSync,
rmSync,
+ unlinkSync,
+ utimesSync,
writeFileSync,
} from "node:fs";
import { tmpdir } from "node:os";
@@ -26,7 +29,9 @@ import {
LOCK_WAIT_BUDGET_MS,
LOCK_WAIT_INTERACTIVE_MS,
lockScanRoots,
+ removeStaleLockSync,
scanStaleLocks,
+ TAKEOVER_CLAIM_STALE_MS,
} from "../../../src/core/brain/sync-lockfile.ts";
let tmpRoot: string;
@@ -104,6 +109,45 @@ describe("acquireLockSync", () => {
handle.release();
}
});
+
+ test("release leaves a lock file it no longer owns in place", () => {
+ // A takeover removed this holder's lock and another process acquired the
+ // name; the first holder's release must not delete the second's lock.
+ const target = join(tmpRoot, "pref-owned.md");
+ const first = acquireLockSync(target);
+ unlinkSync(target + ".lock");
+ const second = acquireLockSync(target);
+ try {
+ first.release();
+ expect(existsSync(target + ".lock")).toBe(true);
+ expect(() => acquireLockSync(target)).toThrow(/lock busy/);
+ } finally {
+ second.release();
+ }
+ expect(existsSync(target + ".lock")).toBe(false);
+ });
+});
+
+describe("exit sweep after a stale handle's release", () => {
+ test("a newer handle's lock is still removed at exit after an older handle released", () => {
+ // The older handle lost its lock to a takeover; the newer handle in the
+ // same process re-registered the path. The older release must not drop
+ // that registration, or the exit sweep would leave the newer lock behind.
+ const target = join(tmpRoot, "pref-exit.md");
+ const module = resolve(import.meta.dir, "../../../src/core/brain/sync-lockfile.ts");
+ const script = `
+ const { unlinkSync } = await import("node:fs");
+ const { acquireLockSync } = await import(${JSON.stringify(module)});
+ const target = ${JSON.stringify(target)};
+ const first = acquireLockSync(target);
+ unlinkSync(target + ".lock");
+ acquireLockSync(target);
+ first.release();
+ `;
+ const child = Bun.spawnSync([process.execPath, "-e", script]);
+ expect(child.exitCode).toBe(0);
+ expect(existsSync(target + ".lock")).toBe(false);
+ });
});
describe("isWindowsDeletePending", () => {
@@ -390,3 +434,60 @@ describe("acquireLockSyncWithRetry — what the caller gives up while it waits",
expect(generate).toContain("acquireLockSyncWithRetry(dir, LOCK_WAIT_INTERACTIVE_MS)");
});
});
+
+describe("removeStaleLockSync takeover claims", () => {
+ const abandoned = () => true;
+
+ function plantLock(name: string): { lock: string; claim: string } {
+ const lock = join(tmpRoot, `${name}.lock`);
+ writeFileSync(lock, "left behind by a killed holder\n");
+ const st = lstatSync(lock, { bigint: true });
+ return { lock, claim: `${lock}.takeover-${st.ino}-${st.mtimeNs}` };
+ }
+
+ function age(path: string, ms: number): void {
+ const at = (Date.now() - ms) / 1000;
+ utimesSync(path, at, at);
+ }
+
+ test("a fresh claim on the same lock file turns a late contender away", () => {
+ const { lock, claim } = plantLock("fresh-claim");
+ writeFileSync(claim, "");
+ expect(removeStaleLockSync(lock, abandoned)).toBe(false);
+ expect(existsSync(lock)).toBe(true);
+ });
+
+ test("a stale claim left by a dead winner does not make the lock unbreakable", () => {
+ const { lock, claim } = plantLock("dead-winner");
+ writeFileSync(claim, "");
+ age(claim, TAKEOVER_CLAIM_STALE_MS + 5_000);
+ expect(removeStaleLockSync(lock, abandoned)).toBe(true);
+ expect(existsSync(lock)).toBe(false);
+ });
+
+ test("a lock whose every claim generation is stale is cleared for the next attempt", () => {
+ const { lock, claim } = plantLock("exhausted");
+ const generations = [claim, `${claim}-1`, `${claim}-2`, `${claim}-3`];
+ for (const path of generations) {
+ writeFileSync(path, "");
+ age(path, TAKEOVER_CLAIM_STALE_MS + 5_000);
+ }
+ expect(removeStaleLockSync(lock, abandoned)).toBe(false);
+ expect(generations.some((path) => existsSync(path))).toBe(false);
+ expect(removeStaleLockSync(lock, abandoned)).toBe(true);
+ });
+
+ test("a successful takeover sweeps this lock's stale claims and keeps fresh ones", () => {
+ const { lock } = plantLock("sweep");
+ const oldClaim = `${lock}.takeover-1-2`;
+ const freshClaim = `${lock}.takeover-3-4`;
+ const otherLockClaim = join(tmpRoot, "other.lock.takeover-5-6");
+ for (const path of [oldClaim, freshClaim, otherLockClaim]) writeFileSync(path, "");
+ age(oldClaim, TAKEOVER_CLAIM_STALE_MS + 5_000);
+ age(otherLockClaim, TAKEOVER_CLAIM_STALE_MS + 5_000);
+ expect(removeStaleLockSync(lock, abandoned)).toBe(true);
+ expect(existsSync(oldClaim)).toBe(false);
+ expect(existsSync(freshClaim)).toBe(true);
+ expect(existsSync(otherLockClaim)).toBe(true);
+ });
+});
diff --git a/tests/hooks/session-state.test.ts b/tests/hooks/session-state.test.ts
index e6e80f07..21f9b8a4 100644
--- a/tests/hooks/session-state.test.ts
+++ b/tests/hooks/session-state.test.ts
@@ -25,7 +25,11 @@ import {
updateHookState,
writeHookStamp,
} from "../../hooks/lib/session-state.ts";
-import { _resetHeldLocksForTests } from "../../src/core/brain/sync-lockfile.ts";
+import {
+ _resetHeldLocksForTests,
+ acquireLockSync,
+ type LockHandle,
+} from "../../src/core/brain/sync-lockfile.ts";
import { IS_WINDOWS } from "../helpers/platform.ts";
let vault: string;
@@ -276,51 +280,67 @@ describe("updateHookState", () => {
expect(outcome).toEqual({ status: "ok", result: "took" });
expect(readHookStamp(vault, "sess-1", KEY_A)).not.toBeNull();
expect(existsSync(lockPath)).toBe(false);
- expect(readdirSync(dir()).filter((name) => name.includes(".stale-"))).toEqual([]);
+ // Only the takeover's claim stays behind; no aside or second lock.
+ expect(
+ readdirSync(dir()).filter((name) => name.includes(".lock") && !name.includes(".takeover-")),
+ ).toEqual([]);
} finally {
_resetHeldLocksForTests();
}
});
- test("the stale takeover moves the lockfile aside by rename, never unlinks it in place", () => {
+ test("a lock replaced by a fresh one after the stale judgement is not removed", () => {
const lockPath = holdLock("sess-1");
const old = (Date.now() - HOOK_STATE_STALE_LOCK_MS - 5_000) / 1000;
utimesSync(lockPath, old, old);
- // Occupy the rename target with a non-empty directory: the rename fails,
- // so a takeover that goes through it must leave the stale lock in place.
- const aside = `${lockPath}.stale-${process.pid}`;
- mkdirSync(aside);
- writeFileSync(join(aside, "keep"), "");
+ let liveIno: bigint | null = null;
+ // Judged stale, then replaced by a live holder's lock before the act.
+ const judgeThenReplace = (): boolean => {
+ unlinkSync(lockPath);
+ writeFileSync(lockPath, "held by a live hook\n");
+ liveIno = statSync(lockPath, { bigint: true }).ino;
+ return true;
+ };
try {
- const outcome = updateHookState(vault, "sess-1", (state) => ({ state, result: 1 }), {
- tryOnce: true,
- });
- expect(outcome).toEqual({ status: "busy" });
- expect(existsSync(lockPath)).toBe(true);
+ expect(_clearStaleLockForTests(hookStateFilePath(vault, "sess-1"), judgeThenReplace)).toBe(
+ false,
+ );
+ expect(statSync(lockPath, { bigint: true }).ino).toBe(liveIno!);
} finally {
unlinkSync(lockPath);
- rmSync(aside, { recursive: true, force: true });
- _resetHeldLocksForTests();
}
});
- test("a takeover that moved a live lock puts it back and reports no takeover", () => {
+ test("a contender acting on a stale judgement another contender already acted on leaves the winner's lock alone", () => {
const lockPath = holdLock("sess-1");
- const liveIno = statSync(lockPath, { bigint: true }).ino;
- // The lock reads stale at the first check, but the file the rename moved
- // is fresh: another contender re-acquired in between.
- const staleOnlyUnderLockName = (path: string): boolean => path === lockPath;
+ const old = (Date.now() - HOOK_STATE_STALE_LOCK_MS - 5_000) / 1000;
+ utimesSync(lockPath, old, old);
+ const path = hookStateFilePath(vault, "sess-1");
+ const handles: LockHandle[] = [];
+ let winnerIno: bigint | null = null;
+ let judgements = 0;
+ // This contender read the abandoned lock and judged it stale; before it
+ // acts, another contender takes the same lock over and acquires. Any
+ // later judgement (of whatever this contender then holds in its hand)
+ // lets a third contender in if the lock name is empty at that moment.
+ const judge = (): boolean => {
+ judgements += 1;
+ if (judgements === 1) {
+ expect(_clearStaleLockForTests(path)).toBe(true);
+ handles.push(acquireLockSync(path));
+ winnerIno = statSync(lockPath, { bigint: true }).ino;
+ return true;
+ }
+ if (!existsSync(lockPath)) handles.push(acquireLockSync(path));
+ return false;
+ };
try {
- const tookOver = _clearStaleLockForTests(
- hookStateFilePath(vault, "sess-1"),
- staleOnlyUnderLockName,
- );
- expect(tookOver).toBe(false);
- expect(existsSync(lockPath)).toBe(true);
- expect(statSync(lockPath, { bigint: true }).ino).toBe(liveIno);
- expect(readdirSync(dir()).filter((name) => name.includes(".stale-"))).toEqual([]);
+ expect(_clearStaleLockForTests(path, judge)).toBe(false);
+ expect(handles).toHaveLength(1);
+ expect(statSync(lockPath, { bigint: true }).ino).toBe(winnerIno!);
} finally {
- unlinkSync(lockPath);
+ for (const handle of handles) handle.release();
+ _resetHeldLocksForTests();
}
});
@@ -486,12 +506,14 @@ describe("pruneHookStateFiles", () => {
const oldTmp = seed(".default.json.1.2.ab.tmp", 8 * DAY, now);
const oldLock = seed("default.json.lock", 8 * DAY, now);
const oldAside = seed("default.json.lock.stale-9", 8 * DAY, now);
+ const oldClaim = seed("default.json.lock.takeover-12-345", 8 * DAY, now);
const freshLock = seed("aa-sess.json.lock", 1 * DAY, now);
const freshTmp = seed(".aa-sess.json.3.4.cd.tmp", 1 * DAY, now);
const txt = seed("notes.txt", 8 * DAY, now);
const foreignTmp = seed(".Upper.json.1.2.ab.tmp", 8 * DAY, now);
- expect(pruneHookStateFiles(vault, { nowMs: now })).toBe(3);
+ expect(pruneHookStateFiles(vault, { nowMs: now })).toBe(4);
expect(existsSync(oldTmp)).toBe(false);
+ expect(existsSync(oldClaim)).toBe(false);
expect(existsSync(oldLock)).toBe(false);
expect(existsSync(oldAside)).toBe(false);
expect(existsSync(freshLock)).toBe(true);
diff --git a/uv.lock b/uv.lock
index 03c02a96..5b1ccce5 100644
--- a/uv.lock
+++ b/uv.lock
@@ -4,5 +4,5 @@ requires-python = ">=3.11"
[[package]]
name = "open-second-brain"
-version = "1.86.1"
+version = "1.86.2"
source = { editable = "." }