Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Skill resolver hook: release the session lock when the deadline ends a turn

garrytan5bf0876f5913
diff --git a/src/core/skills/resolver/hook-lane.ts b/src/core/skills/resolver/hook-lane.ts
index 367f185b8e..f1675baa57 100644
--- a/src/core/skills/resolver/hook-lane.ts
+++ b/src/core/skills/resolver/hook-lane.ts
@@ -45,6 +45,7 @@
* capped at 256 KB; doctor's skill_resolver check reads it.
*/
import { createHash } from 'node:crypto';
+import { unlinkSync } from 'node:fs';
import { appendFile, mkdir, readFile, realpath, stat, truncate, unlink, writeFile } from 'node:fs/promises';
import { homedir } from 'node:os';
import { join } from 'node:path';
@@ -54,10 +55,11 @@ import { claudeManagedSettingsPaths, claudeUserSettingsPath, codexHooksPath } fr
import { shellWords } from '../../setup/hook-launcher.ts';
import { isSkillResolverCommand, isSkillResolverEntry } from '../../setup/skill-resolver-lane.ts';
import { assertCatalogName, catalogFile, logsDir, resolverHome } from './paths.ts';
-import { commitSessionAsync, sessionKey, type TurnDelta } from './session.ts';
+import { type CommitHold, commitSessionAsync, sessionKey, type TurnDelta } from './session.ts';
import type { TurnOutput } from './resolve.ts';
import type { LaneWorkerTurn } from './hook-worker.ts';
import { startLaneWorker } from './lane-worker.ts';
+import { releaseLease } from './lock.ts';
export { WORKER_SRC_PATH } from './lane-worker.ts';
@@ -217,7 +219,7 @@ export async function runSkillResolverLane(event: string, harness: LaneHarness,
try { home = resolverHome(env); } catch { return 0; }
const deadlineMs = io.deadlineMs ?? (Number(env.GBRAIN_TEST_SKILL_LANE_DEADLINE_MS) || LANE_DEADLINE_MS);
const elapsed = () => performance.now() - t0;
- const ctl: LaneCtl = { expired: false, worker: null, logged: false };
+ const ctl: LaneCtl = { expired: false, worker: null, logged: false, commit: {} };
if (event === 'user-prompt') ctl.worker = startLaneWorker(env);
const log = (t: Turn) => appendLaneLog(home, { at: new Date().toISOString(), harness, event, outcome: t.outcome, ...(t.code ? { code: t.code } : {}), ms: Math.round(elapsed() * 10) / 10, ...(t.catalogs ? { catalogs: t.catalogs } : {}), ...(t.dropped_chars ? { dropped_chars: t.dropped_chars } : {}) });
@@ -228,6 +230,9 @@ export async function runSkillResolverLane(event: string, harness: LaneHarness,
if (result === 'deadline') {
ctl.expired = true;
void ctl.worker?.terminate();
+ const { tmp, lease } = ctl.commit;
+ if (tmp) try { unlinkSync(tmp); } catch { /* renamed or never created */ }
+ if (lease) releaseLease(lease);
if (ctl.logged) await Promise.race([log({ outcome: 'timeout', code: 'skill_resolve_timeout' }), new Promise(r => setTimeout(r, 5))]);
(io.exit ?? ((c: number) => process.exit(c)))(0);
return 0;
@@ -238,7 +243,7 @@ export async function runSkillResolverLane(event: string, harness: LaneHarness,
return 0;
}
-interface LaneCtl { expired: boolean; worker: Worker | null; logged: boolean }
+interface LaneCtl { expired: boolean; worker: Worker | null; logged: boolean; commit: CommitHold }
async function laneTurn(event: 'user-prompt' | 'session-start', harness: LaneHarness, home: string, env: NodeJS.ProcessEnv, io: LaneIo, ctl: LaneCtl, elapsed: () => number, deadlineMs: number): Promise<Turn> {
const settings = await readLaneSettings(home, env);
@@ -292,7 +297,9 @@ async function laneTurn(event: 'user-prompt' | 'session-start', harness: LaneHar
if (payload.length > settings.payloadChars) return { outcome: 'payload_dropped', catalogs, dropped_chars: payload.length };
await (io.write ?? writeStdout)(`${payload}\n`);
}
- if (posted.pending && !ctl.expired) await commitSessionAsync(home, posted.pending.key, posted.pending.delta);
+ const stall = env.GBRAIN_TEST_SKILL_LANE_STALL;
+ if (stall === 'commit-held' || stall === 'commit-written') ctl.commit.at = (stage) => (`commit-${stage}` === stall ? new Promise(() => {}) : Promise.resolve());
+ if (posted.pending && !ctl.expired) await commitSessionAsync(home, posted.pending.key, posted.pending.delta, ctl.commit);
return { outcome, catalogs };
}
diff --git a/src/core/skills/resolver/hook-worker.ts b/src/core/skills/resolver/hook-worker.ts
index c31b715d7a..6b9a7d6a00 100644
--- a/src/core/skills/resolver/hook-worker.ts
+++ b/src/core/skills/resolver/hook-worker.ts
@@ -10,7 +10,9 @@
*
* GBRAIN_TEST_SKILL_LANE_STALL (tests only) forces a slow stage: block
* (synchronous 10 s busy loop), hang (never answers), late (answers after
- * 300 ms). GBRAIN_TEST_SKILL_LANE_DEADLINE_MS (tests only, hook-lane.ts)
+ * 300 ms); commit-held and commit-written (hook-lane.ts) stop the main
+ * thread's commit once it holds the lease, or once its temp file is
+ * written. GBRAIN_TEST_SKILL_LANE_DEADLINE_MS (tests only, hook-lane.ts)
* widens the lane's deadline so a loaded test machine can assert delivery.
*/
import { parentPort, workerData } from 'node:worker_threads';
diff --git a/src/core/skills/resolver/session.ts b/src/core/skills/resolver/session.ts
index 6cdb0d447d..725041b6c9 100644
--- a/src/core/skills/resolver/session.ts
+++ b/src/core/skills/resolver/session.ts
@@ -18,7 +18,7 @@ const { mkdir, open, readdir, readFile, rename, stat, unlink } = promises;
import { randomBytes } from 'node:crypto';
import { join } from 'node:path';
import { ensureDir, writeFileDurable } from './fsutil.ts';
-import { acquireLease, releaseLease, releaseLeaseAsync, tryAcquireLeaseAsync } from './lock.ts';
+import { acquireLease, type Lease, releaseLease, releaseLeaseAsync, tryAcquireLeaseAsync } from './lock.ts';
import { sessionsDir } from './paths.ts';
export const MAX_SESSION_FILES = 10_000;
@@ -93,7 +93,9 @@ function applyDelta(s: SessionState, delta: TurnDelta): SessionState {
* lease is retried a few times over at most ~15 ms, then the commit is
* skipped (a skipped commit only means a repeat).
*/
-export async function commitSessionAsync(home: string, key: string, delta: TurnDelta): Promise<boolean> {
+export interface CommitHold { lease?: Lease | null; tmp?: string | null; at?: (stage: 'held' | 'written') => Promise<void> }
+
+export async function commitSessionAsync(home: string, key: string, delta: TurnDelta, hold: CommitHold = {}): Promise<boolean> {
const dir = sessionsDir(home);
const p = statePath(home, key);
try {
@@ -107,7 +109,9 @@ export async function commitSessionAsync(home: string, key: string, delta: TurnD
if (!lease && attempt < 3) await new Promise(r => setTimeout(r, 2 ** attempt * 2));
}
if (!lease) return false;
+ hold.lease = lease;
try {
+ await hold.at?.('held');
let s = freshState();
if (!delta.reset) {
try {
@@ -118,12 +122,15 @@ export async function commitSessionAsync(home: string, key: string, delta: TurnD
} catch { /* none or unreadable: fresh */ }
}
const tmp = join(dir, `.${key}.json.tmp-${randomBytes(6).toString('hex')}`);
+ hold.tmp = tmp;
const fh = await open(tmp, 'wx', 0o600);
try { await fh.writeFile(JSON.stringify(applyDelta(s, delta))); await fh.sync(); } finally { await fh.close(); }
- try { await rename(tmp, p); } catch (e) { await unlink(tmp).catch(() => {}); throw e; }
+ await hold.at?.('written');
+ try { await rename(tmp, p); } catch (e) { await unlink(tmp).catch(() => {}); throw e; } finally { hold.tmp = null; }
return true;
} finally {
await releaseLeaseAsync(lease);
+ hold.lease = null;
}
} catch {
return false;
diff --git a/test/skill-resolver-hook-lane.test.ts b/test/skill-resolver-hook-lane.test.ts
index 6b153fb6a9..86fdeb4b76 100644
--- a/test/skill-resolver-hook-lane.test.ts
+++ b/test/skill-resolver-hook-lane.test.ts
@@ -166,6 +166,27 @@ describe('skill-resolver lane: deadline, measured outside the process', () => {
}
});
+describe('skill-resolver lane: a deadline during the dedupe commit', () => {
+ for (const stall of ['commit-held', 'commit-written'] as const) {
+ test(`${stall}: the exit releases the session lease and removes the temp file, so the next turn commits`, async () => {
+ const b = box();
+ seedSkills(claudeSkills(b));
+ await setup(b, 'claude-code');
+ const cmd = wired(b, 'claude-code');
+ const turn = { prompt: 'please deploy the widget to staging', session_id: 'sess-l' };
+ const r = await hook(b, cmd, turn, { GBRAIN_TEST_SKILL_LANE_STALL: stall, GBRAIN_TEST_SKILL_LANE_DEADLINE_MS: '3000' });
+ expect(r.exitCode).toBe(0);
+ expect(contextOf(r)).toContain('id: "deploy-widget"');
+ expect(laneLog(b).at(-1)).toMatchObject({ outcome: 'timeout', code: 'skill_resolve_timeout' });
+ expect(sessions(b)).toEqual([]);
+ const again = await hook(b, cmd, turn, WIDE);
+ expect(contextOf(again)).toContain('id: "deploy-widget"');
+ expect(sessions(b).filter((s) => !s.startsWith('.')).map((s) => s.endsWith('.json'))).toEqual([true]);
+ expect((await hook(b, cmd, turn, WIDE)).stdout).toBe('');
+ });
+ }
+});
+
describe('skill-resolver lane: the CLI fast path keeps the hook contract', () => {
test('GBRAIN_HOOKS=0 silences the lane, whether exported or set in the env file the CLI preflight loads', async () => {
const b = box();