feat(cli): guard history turns with --exclusive, --who and --if-open (#5518)

* feat(cli): guard history turns with --exclusive, --who and --if-open

* fix(cli): make exclusive history turns atomic

Re-read the open turn only after acquiring history ownership so
concurrent exclusive begins cannot both claim the same project.
Cover the race with a deterministic two-process regression test.

* fix(cli): refuse a second exclusive turn while a preview is open

The preview's begin window now rejects another agent's live turn, and an
idle turn no longer blocks exclusive begin. The two-process test waits on
pids collected from claim drafts instead of seeing both files at once.
This commit is contained in:
Xuanru Li
2026-10-13 04:22:41 +00:00
committed by GitHub
parent 945c61ebb6
commit 7c73b3caee
7 changed files with 303 additions and 69 deletions
+55 -41
View File
@@ -1,6 +1,6 @@
import { randomUUID } from "node:crypto";
import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
import { dirname, join } from "node:path";
import { dirname, join, resolve } from "node:path";
import {
DEFAULT_HISTORY_ROOT,
HistoryBusyError,
@@ -40,7 +40,11 @@ export interface Owner {
undo(id: string, who: HistoryWho, mode?: UndoMode): Promise<HistoryResult>;
restore(point: string, who: HistoryWho): Promise<HistoryEntry | null>;
pin(id: string, pinned: boolean): Promise<void>;
begin(who: HistoryWho, label: string): Promise<{ id: string; startedAt: number }>;
begin(
who: HistoryWho,
label: string,
exclusive?: boolean,
): Promise<{ id: string; startedAt: number }>;
end(id: string): Promise<HistoryEntry | null>;
close(): Promise<void>;
}
@@ -49,7 +53,7 @@ export type Reader = Pick<Owner, "via" | "list" | "peek" | "blob">;
/** Swapped by tests. */
export const historyDeps = {
historyRoot: DEFAULT_HISTORY_ROOT,
historyRoot: resolve(process.env.HYPERFRAMES_HISTORY_ROOT || DEFAULT_HISTORY_ROOT),
findServer: (projectDir: string) => findPreviewServerForProject(projectDir),
/** A turn with no write for this long has ended, through a preview or not. */
turnIdleMs: MAX_WINDOW_IDLE_MS,
@@ -144,8 +148,13 @@ function previewOwner(route: (path: string) => string): Owner {
undo: (id, who, mode) => json("/undo", { entryId: id, who, mode }),
restore: (point, who) => json("/restore", { point, who }),
pin: async (id, pinned) => void (await json("/pin", { entryId: id, pinned })),
begin: async (who, label) => {
const opened = await json("/window", { who, label, idleMs: historyDeps.turnIdleMs });
begin: async (who, label, exclusive) => {
const opened = await json("/window", {
who,
label,
idleMs: historyDeps.turnIdleMs,
...(exclusive && { exclusive: true }),
});
return { id: opened.windowId, startedAt: opened.startedAt ?? historyDeps.now() };
},
// A preview restarted since begin committed the window on its way down.
@@ -157,42 +166,48 @@ function previewOwner(route: (path: string) => string): Owner {
};
}
async function directOwner(projectDir: string, turn: Turn | null): Promise<Owner> {
async function directOwner(projectDir: string): Promise<{ owner: Owner; turn: Turn | null }> {
let turn: Turn | null = null;
const history = await openProjectHistory({
projectDir,
historyRoot: historyDeps.historyRoot,
now: () => historyDeps.now(),
pruneGoneProjectsBudgetMs: 1000,
ownerWaitMs: historyDeps.ownerWaitMs,
// A turn begun through a preview that has since stopped is still the agent's, until its idle limit.
...(turn && {
closedWindow: {
id: turn.id,
who: turn.who,
label: turn.label,
startedAt: turn.startedAt,
lastWriteAt: turn.lastWriteAt,
idleMs: historyDeps.turnIdleMs,
},
}),
closedWindowAfterOwnership: () => {
turn = readTurn(projectDir);
return turn
? {
id: turn.id,
who: turn.who,
label: turn.label,
startedAt: turn.startedAt,
lastWriteAt: turn.lastWriteAt,
idleMs: historyDeps.turnIdleMs,
}
: undefined;
},
});
return {
via: "direct",
list: async () => history.list(),
peek: async (point) => history.peek(point),
blob: (hash) => history.readBlob(hash),
undo: (id, who, mode) => history.undo(id, { who, ...(mode && { mode }) }),
restore: (point, who) => history.restore(point, who),
pin: async (id, pinned) => history.pin(id, pinned),
// Opening filed every earlier write; the turn's own writes are filed to it when the next open passes it.
begin: async () => ({ id: randomUUID(), startedAt: historyDeps.now() }),
end: async (id) => history.list().find((entry) => entry.id === id) ?? null,
close: () => history.close(),
turn,
owner: {
via: "direct",
list: async () => history.list(),
peek: async (point) => history.peek(point),
blob: (hash) => history.readBlob(hash),
undo: (id, who, mode) => history.undo(id, { who, ...(mode && { mode }) }),
restore: (point, who) => history.restore(point, who),
pin: async (id, pinned) => history.pin(id, pinned),
// Opening filed every earlier write; the turn's own writes are filed to it when the next open passes it.
begin: async () => ({ id: randomUUID(), startedAt: historyDeps.now() }),
end: async (id) => history.list().find((entry) => entry.id === id) ?? null,
close: () => history.close(),
},
};
}
/** One owner: a preview that keeps this project's history, else the engine, which refuses a second opener. */
async function connect(projectDir: string, turn: Turn | null): Promise<Owner> {
async function connect(projectDir: string): Promise<{ owner: Owner; turn: Turn | null }> {
const server = await historyDeps.findServer(projectDir);
if (server) {
const route = (path: string) => studioApiUrl(server, `history${path}`);
@@ -201,9 +216,9 @@ async function connect(projectDir: string, turn: Turn | null): Promise<Owner> {
(response) => response.status,
() => 404,
);
if (status !== 404) return previewOwner(route);
if (status !== 404) return { owner: previewOwner(route), turn: readTurn(projectDir) };
}
return directOwner(projectDir, turn);
return directOwner(projectDir);
}
/** Runs `task` with the project's history. ponytail: with no preview, a command mid-turn splits the turn in two. */
@@ -212,24 +227,23 @@ export async function withOwner<T>(
task: (owner: Owner, turn: Turn | null, projectDir: string) => Promise<T>,
): Promise<T> {
const { dir: projectDir } = resolveProject(dir);
const turn = readTurn(projectDir);
const owner = await connect(projectDir, turn);
const { owner, turn } = await connect(projectDir);
try {
return await task(owner, turn, projectDir);
} finally {
// This open filed the turn so far under its id; the turn goes on under a fresh one, from its last write.
const direct = owner.via === "direct" && turn;
let kept: HistoryListItem | undefined;
try {
kept = direct ? (await owner.list()).find((entry) => entry.id === turn.id) : undefined;
if (owner.via === "direct" && turn) {
const kept = (await owner.list()).find((entry) => entry.id === turn.id);
if (readTurn(projectDir)?.id === turn.id) {
const lastWriteAt = kept ? kept.endedAt : turn.lastWriteAt;
const parts = kept ? [...turn.parts, kept.id] : turn.parts;
writeTurn(projectDir, { ...turn, via: "direct", id: randomUUID(), lastWriteAt, parts });
}
}
} finally {
await owner.close();
}
if (direct && readTurn(projectDir)?.id === turn.id) {
const lastWriteAt = kept ? kept.endedAt : turn.lastWriteAt;
const parts = kept ? [...turn.parts, kept.id] : turn.parts;
writeTurn(projectDir, { ...turn, via: "direct", id: randomUUID(), lastWriteAt, parts });
}
}
}