mirror of
https://github.com/nightly-labs/openbot.git
synced 2026-12-02 10:36:19 +08:00
* feat(dev): make worktree dev stacks and ports conflict-free Several worktrees run dev on this machine at once. Port selection was a probe followed by a bind seconds later, and nothing was written down in between, so two `bun run dev` calls started together both won 5173 and the unsuffixed `OpenBot Dev` profile with it - two Electron clients writing one SQLite file. - `scripts/dev-automation/port-allocation.ts` puts read, choose and publish behind one machine-wide lock (`wx` create, stale break, holder-matched release). - `scripts/dev-automation/stack-registry.ts` records every port and pid a stack holds. `findAvailablePort` skips a published port without probing it, because a stack that won a port has not bound it yet. - `scripts/dev-stack.ts` adds `dev:status` and `dev:stop`, which read pids from the registry instead of matching a process name. This worktree is the default scope; `--pid=` and `--all` are explicit. - `scripts/dev-storybook.ts` allocates Storybook through the same registry with `--exact-port`, so the announced port is the real one. - A second stack in one worktree is refused unless `--force`, and `--isolated` keys the profile to the worktree path. - `registry-files.ts` holds the owner-only directory checks, the atomic write and the recycled-pid liveness both registries need. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(dev): prove a pid is ours before the stop command signals it Four review findings on the worktree dev-stack work, and what each cost. The port allocation lock created the file and then wrote it, so a waiter could read it in the moment it held nothing, take it for abandoned and break it - two allocators in the critical section, which is the collision the lock exists to stop. The holder now goes into a staging file that is published with `link`, atomic and EEXIST when taken. An unreadable lock is no longer breakable on sight either: it must also have sat there past the stale window. And a waiter that runs out its wait beside a live holder now fails with that holder's pid instead of helping itself. `dev:stop` signalled anything `kill(pid, 0)` said was taken. Pids get recycled, so that is how a stop command sends SIGTERM to a stranger's program. `verifyRecordedProcess` answers live, gone or unverified - and unverified, a pid this machine cannot date, is not permission to signal. What it refuses to touch it reports, leaves running, keeps in the registry and exits non-zero for; `bun run dev:forget` drops such a record once the developer has dealt with the process. Same reasoning one level down: a process group that outlived its recorded leader is named in the report rather than signalled, because the pgid belongs to nobody now. A record was pruned as soon as its recorded pids were gone, which freed a port that a surviving group still held - electron-vite exits and the Electron it started keeps the renderer port. Liveness now includes the group. `dev:status` reports every stack, since the one holding the port this worktree wanted is a sibling's. `stop` and `forget` stay on this worktree. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(dev): serialize recovery of a stale port allocation lock Breaking a lock is an unlink, and unlink cannot be made conditional on what the path holds. Two waiters that read one dead holder both deleted: the first published a lock of its own and started allocating, and the second deleted that replacement and started beside it - the same two allocators on one set of ports that the lock exists to prevent. Recovery now happens behind a second file. Whoever takes it reads the lock again before deleting anything, so a waiter that arrives late finds the replacement instead of the dead holder it saw a moment ago. Nothing ever breaks that second file: it is held across a few syscalls with no await between them, and a leak costs recovery rather than correctness - allocators wait, then fail with a message naming the file. Age no longer breaks a live holder's lock either. An allocation is milliseconds of work, so a lock held for a minute means something is wrong, but wrong is not finished: the holder may be stopped in a debugger and about to step into the critical section. The developer gets an error naming the pid instead. What replaces the age arm is evidence rather than patience - `verifyRecordedProcess` dates the holder, so a pid recycled since the lock was taken reads as gone and one recycled pid can no longer wedge every dev start on this machine. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(dev): make port lock ownership a generation, not a path Recovering a lock whose holder had died still had to delete the path, and `unlink` cannot be made conditional on what the path holds. A recoverer that read a missing or dead lock could therefore remove a lock another allocator had published in the meantime, and both would allocate ports at once - the collision the lock exists to stop. Taking the lock now means creating the next numbered lock file with an exclusive create, so ownership is only ever decided by a step the kernel makes atomic. A dead holder's lock is superseded rather than removed, and the judgement about it decides when to move on, never who won. The break lock this replaces is gone. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(dev): never remove a port lock another allocator may still take The generation an allocator asks for is the highest lock file it saw plus one, and the scan and the exclusive create are separate steps. Sweeping the superseded lock files away therefore let the numbering run backwards over a plan already made against them: recover the lock a dead holder left at 1, take 2, release 2, and an allocator arriving now finds an empty directory and takes 1, while one that read the directory earlier still holds a plan for 2 and no longer collides with anybody. Both then allocate ports. A lock file is now removed by nothing but its own live holder, releasing it. An allocator that read our lock as the highest generation read it as live, so it waited instead of planning a generation above it - nothing holds a plan our removal could let back down. The lock a crashed holder left behind stays where it is; nothing reads it, and it is what keeps the numbering from coming back down to it. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(dev): release a port lock by renaming it, never by deleting it Deleting our own lock on release still let a generation be handed out twice. The file need not be gone when another allocator *lists* it, only when it reads its contents: an allocator that listed our live lock and then found nothing there reads a null holder and a null age, judges it abandoned, and plans the generation above it - while the number it left behind goes to the next arrival, which no longer collides with that plan. Both then allocate. So no lock file is ever deleted now. Releasing renames it to `.released`, which gives up the claim in one step while the generation stays spoken for, and both suffixes count towards the numbering. A lock a crashed holder left behind is superseded where it lies. The files are tens of bytes in the per-user temporary directory, and the two registry readers beside them filter `.json`, so nothing else sees them. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(dev): mark a released port lock in place, keeping its path occupied Renaming the lock aside kept its generation spoken for but freed the path, and the path is what `link` arbitrates over. An allocator that planned a generation and was descheduled before creating it could therefore create it after its previous holder had released, and enter beside whoever had since taken the generation above. The rule is now that once a lock path exists it stays, and nothing ever frees it. A lock's state lives in its contents: releasing writes a released marker to a staging file and renames that onto our own lock path, which replaces the contents in one step and leaves the path occupied on both sides of it. Reading a lock is a tri-state - claimed by a holder, released, or unreadable - and an unreadable one is left alone for the stale window to recover, because that path has to stay occupied too. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(dev): never delete a stack record from the read that judged it `readDevStackRecords` and `readDevInstanceRecords` read a record, decided it was dead, and then removed its path. The file can change in between: a supervisor publishes a detached child and is killed a moment later, and a reader holding the older view deletes the version *with* the child. The child keeps the ports and nothing records them, which is the collision the port lock exists to stop. A record this checkout cannot parse is the same hazard without a race - a sibling worktree on a newer branch writes a schema this one has not learned yet, and its stack is live. So reading only filters. A dead record's ports are free from the first read that finds it dead, and `bun run dev:forget` is what removes the file, reading past the liveness filter to reach records no other command reports. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(dev): date an instance record before dev:forget deletes it `forgetDevStack` matched instance records by pid alone. That was survivable while a dead stack record was pruned by the next read; now the record waits on disk for `bun run dev:forget`, the pids it names have had every chance to be recycled, and an instance record lives at `<service>-<pid>.json`, so the app that takes a pid writes over the record of the app that had it. `dev:forget` on the old stack deleted a running app's record, and it left `dev:automation instances` until its next start. `claimOnDevInstance` answers whose the record is. Each instance record dates itself - its `startedAt` is when that instance published - so `verifyRecordedProcess` holds it against the start time the kernel reports and a live instance is never a dead stack's, whatever pid it holds. The worktree is checked too: it is the cheaper half of the same question and it still answers where a pid cannot be dated. A record of this worktree that cannot be dated is kept and reported rather than guessed at. No timestamp is carried from the supervisor through electron-vite into the Electron main process to do this: the spawn and the publish are two events and would date differently. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(dev): prevent isolated worktree profile collisions Use prefixed full SHA-256 identifiers while preserving numeric profile ids. Cover the reproduced five-digit collision and remove repeated lock and cleanup commentary. Validation: regression test failed before the fix; 31 focused tests pass. Lint passes with eight existing mobile warnings; typecheck and isolated runner dry-run pass. --------- Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
310 lines
13 KiB
TypeScript
310 lines
13 KiB
TypeScript
// What is running on this machine, and how to stop only your part of it.
|
|
//
|
|
// `pkill -f electron` and `pkill -f bun` are the commands this replaces, and
|
|
// both of them kill the other worktrees' work mid-write. The stack registry
|
|
// already knows which pids belong to which checkout, so stopping the right ones
|
|
// is a lookup rather than a pattern.
|
|
|
|
import { resolve } from "node:path";
|
|
import { fileURLToPath } from "node:url";
|
|
import { createOpenBotLogger, redactText, toLogValue } from "@openbot/logging";
|
|
import {
|
|
type DevInstanceRecord,
|
|
describeDevInstance,
|
|
readAllDevInstanceRecords,
|
|
readDevInstanceRecords,
|
|
removeDevInstanceRecord,
|
|
} from "./dev-automation/instance-registry";
|
|
import { isProcessGroupAlive, type RecordedProcessState, verifyRecordedProcess } from "./dev-automation/registry-files";
|
|
import {
|
|
type DevStackPort,
|
|
type DevStackRecord,
|
|
type DevStackService,
|
|
describeDevStack,
|
|
isOrphanedDevStack,
|
|
isSameWorktree,
|
|
readAllDevStackRecords,
|
|
readDevStackRecords,
|
|
removeDevStackRecord,
|
|
} from "./dev-automation/stack-registry";
|
|
import { type OwnedProcess, stopOwnedProcesses } from "./dev-services";
|
|
|
|
const logger = createOpenBotLogger("dev-stack", (line) => process.stderr.write(`${line}\n`));
|
|
|
|
const USAGE = "Usage: bun scripts/dev-stack.ts <status|stop|forget> [--all] [--pid=<supervisor pid>]";
|
|
|
|
export interface DevStackInvocation {
|
|
// `forget` drops a record without signalling anything. It is the way out of
|
|
// the one state `stop` refuses to resolve on its own: a recorded pid that is
|
|
// alive but that this machine cannot date, which `stop` will not signal
|
|
// because the pid may since have been recycled by an unrelated program.
|
|
command: "status" | "stop" | "forget";
|
|
all: boolean;
|
|
pid: number | null;
|
|
}
|
|
|
|
export function parseDevStackInvocation(args: string[]): DevStackInvocation {
|
|
const command = args.find((argument) => !argument.startsWith("--"));
|
|
if (command !== "status" && command !== "stop" && command !== "forget") throw new Error(USAGE);
|
|
const raw = args.find((argument) => argument.startsWith("--pid="))?.slice("--pid=".length);
|
|
const pid = raw === undefined ? null : Number(raw);
|
|
if (pid !== null && (!Number.isInteger(pid) || pid <= 0)) throw new Error("--pid must be a positive integer.");
|
|
const all = args.includes("--all");
|
|
if (all && pid !== null) throw new Error("Pass either --all or --pid=<pid>, not both.");
|
|
const unsupported = args.find(
|
|
(argument) => argument.startsWith("--") && argument !== "--all" && !argument.startsWith("--pid="),
|
|
);
|
|
if (unsupported) throw new Error(`Unknown option: ${unsupported}.\n${USAGE}`);
|
|
return { command, all, pid };
|
|
}
|
|
|
|
export type DevStackScope = { kind: "all" } | { kind: "pid"; pid: number } | { kind: "worktree"; projectRoot: string };
|
|
|
|
// Reading and killing get different defaults on purpose. `status` answers
|
|
// "what is on this machine", and the sibling stack holding the port this
|
|
// worktree wanted is the whole reason to ask - a report scoped to this
|
|
// worktree would leave it out and show nothing at all. `stop` and `forget`
|
|
// touch other people's processes, so they stay on this worktree until the
|
|
// developer names another one.
|
|
export function devStackScope(invocation: DevStackInvocation, projectRoot: string): DevStackScope {
|
|
if (invocation.pid !== null) return { kind: "pid", pid: invocation.pid };
|
|
if (invocation.all || invocation.command === "status") return { kind: "all" };
|
|
return { kind: "worktree", projectRoot };
|
|
}
|
|
|
|
// The default scope is this worktree and nothing else. A sibling's stack takes
|
|
// `--pid=` or `--all`, because "stop the dev servers" from inside one checkout
|
|
// almost never means "stop the four other agents working on this machine".
|
|
export function selectDevStacks(records: DevStackRecord[], scope: DevStackScope): DevStackRecord[] {
|
|
if (scope.kind === "all") return records;
|
|
if (scope.kind === "pid") return records.filter((record) => record.supervisorPid === scope.pid);
|
|
return records.filter((record) => isSameWorktree(record, scope.projectRoot));
|
|
}
|
|
|
|
function ownedProcess(pid: number): OwnedProcess {
|
|
// `exitCode: null` because nothing here was spawned by this process, so
|
|
// nothing has been reaped: liveness comes from signalling the pid.
|
|
return { pid, exitCode: null };
|
|
}
|
|
|
|
// Verify process identity before signalling. A live supervisor stops its own
|
|
// children; otherwise stop only child groups whose leaders are verified.
|
|
async function stopDevStack(record: DevStackRecord): Promise<boolean> {
|
|
let unresolved = false;
|
|
const refuse = (pid: number, what: string): void => {
|
|
logger.error(
|
|
`Cannot confirm pid ${pid} is still ${what} of this stack, so it was not signalled. ` +
|
|
"Stop it yourself, then drop the record with `bun run dev:forget`.",
|
|
);
|
|
unresolved = true;
|
|
};
|
|
|
|
const supervisor: RecordedProcessState = verifyRecordedProcess({
|
|
pid: record.supervisorPid,
|
|
startedAt: record.startedAt,
|
|
});
|
|
if (supervisor === "live") {
|
|
// "process", not its group: the supervisor sits in whatever group the
|
|
// shell or `bun run` that started it leads, so a group signal would go to
|
|
// that job instead of to the runner.
|
|
await stopOwnedProcesses([ownedProcess(record.supervisorPid)], "SIGTERM", { scope: "process", timeoutMs: 5_000 });
|
|
} else if (supervisor === "unverified") {
|
|
refuse(record.supervisorPid, "the runner");
|
|
}
|
|
|
|
const groups: OwnedProcess[] = [];
|
|
for (const entry of record.processes) {
|
|
const state = verifyRecordedProcess(entry);
|
|
if (state === "live") {
|
|
groups.push(ownedProcess(entry.pid));
|
|
} else if (state === "unverified") {
|
|
refuse(entry.pid, `the ${entry.name} process`);
|
|
} else if (isProcessGroupAlive(entry.pid)) {
|
|
// The leader is gone and its group is not. Something it started - the
|
|
// Electron behind electron-vite - still holds the port, but the pid that
|
|
// named the group belongs to nobody now, so signalling it would be
|
|
// signalling a group this record can no longer claim.
|
|
logger.error(
|
|
`The ${entry.name} process group ${entry.pid} outlived its leader and cannot be attributed to this stack. ` +
|
|
`Find what holds ${record.ports.map((port) => port.port).join(", ")} with lsof, and stop it yourself.`,
|
|
);
|
|
unresolved = true;
|
|
}
|
|
}
|
|
if (groups.length > 0) {
|
|
logger.info(`Stopping ${groups.length} process group(s) the supervisor left behind.`);
|
|
await stopOwnedProcesses(groups, "SIGTERM", { scope: "group", timeoutMs: 5_000 });
|
|
}
|
|
|
|
// Last, and only when nothing was left unresolved: while this record exists,
|
|
// its ports stay reserved and `dev:status` still names the pids. Dropping it
|
|
// over something this command refused to touch would turn a visible problem
|
|
// into an invisible one.
|
|
if (unresolved) return false;
|
|
forgetDevStack(record);
|
|
return true;
|
|
}
|
|
|
|
// A recycled pid can refer to another instance record at the same file path.
|
|
export type DevInstanceClaim = "ours" | "another" | "unverified";
|
|
|
|
// Keep live or unverifiable instances and records from other worktrees.
|
|
// Only a dead instance recorded by this stack can be removed.
|
|
export function claimOnDevInstance(
|
|
instance: DevInstanceRecord,
|
|
record: DevStackRecord,
|
|
verify: (entry: { pid: number; startedAt: number }) => RecordedProcessState = verifyRecordedProcess,
|
|
): DevInstanceClaim {
|
|
if (!record.processes.some((entry) => entry.pid === instance.pid)) return "another";
|
|
if (!isSameWorktree(instance, record.projectRoot)) return "another";
|
|
const state = verify(instance);
|
|
if (state === "live") return "another";
|
|
return state === "unverified" ? "unverified" : "ours";
|
|
}
|
|
|
|
// A stack record is a note about pids, so removing it removes nothing else.
|
|
function forgetDevStack(record: DevStackRecord): void {
|
|
removeDevStackRecord(record);
|
|
// A stack the supervisor never got to clean up leaves its instance records
|
|
// behind too, and nothing else deletes them: reading only filters. So this
|
|
// reads every record rather than the live ones, and drops the ones this
|
|
// stack still has a claim on.
|
|
for (const instance of readAllDevInstanceRecords()) {
|
|
const claim = claimOnDevInstance(instance, record);
|
|
if (claim === "ours") removeDevInstanceRecord(instance);
|
|
if (claim === "unverified") {
|
|
logger.error(
|
|
`Cannot confirm pid ${instance.pid} is still the ${instance.service} instance of this stack, ` +
|
|
"so its record was kept. `bun run dev:status` reports it, and the instance that owns it " +
|
|
"publishes over it on its next start.",
|
|
);
|
|
}
|
|
}
|
|
}
|
|
|
|
interface ReportableDevStackProcess {
|
|
name: DevStackService;
|
|
pid: number;
|
|
startedAt: number;
|
|
// "live" is this stack's process. "unverified" is a pid this machine cannot
|
|
// date, which `stop` refuses to signal. "gone" with `groupLive` is a
|
|
// survivor of a dead leader, still holding the port.
|
|
state: RecordedProcessState;
|
|
groupLive: boolean;
|
|
}
|
|
|
|
export interface ReportableDevStack {
|
|
supervisorPid: number;
|
|
services: DevStackService[];
|
|
ports: DevStackPort[];
|
|
projectRoot: string;
|
|
worktree: boolean;
|
|
orphaned: boolean;
|
|
startedAt: string;
|
|
processes: ReportableDevStackProcess[];
|
|
}
|
|
|
|
// `projectRoot` is a path the developer chose - a checkout under a directory
|
|
// named after an email, or one holding a token, would otherwise be copied into
|
|
// an agent's transcript verbatim. Selection keeps using the raw records.
|
|
function reportableStack(record: DevStackRecord, projectRoot: string): ReportableDevStack {
|
|
return {
|
|
supervisorPid: record.supervisorPid,
|
|
services: record.services,
|
|
ports: record.ports,
|
|
projectRoot: redactText(record.projectRoot),
|
|
worktree: isSameWorktree(record, projectRoot),
|
|
orphaned: isOrphanedDevStack(record),
|
|
startedAt: new Date(record.startedAt).toISOString(),
|
|
processes: record.processes.map((entry) => ({
|
|
...entry,
|
|
state: verifyRecordedProcess(entry),
|
|
groupLive: isProcessGroupAlive(entry.pid),
|
|
})),
|
|
};
|
|
}
|
|
|
|
async function main(): Promise<void> {
|
|
const invocation = parseDevStackInvocation(process.argv.slice(2));
|
|
const projectRoot = resolve(process.cwd());
|
|
// `forget` is the one command that acts on a record because it is dead, so
|
|
// it is the one that reads past the liveness filter. Everything else asks
|
|
// what is running.
|
|
const records = invocation.command === "forget" ? readAllDevStackRecords() : readDevStackRecords();
|
|
|
|
if (invocation.command === "status") {
|
|
const document = {
|
|
stacks: selectDevStacks(records, devStackScope(invocation, projectRoot)).map((record) =>
|
|
reportableStack(record, projectRoot),
|
|
),
|
|
instances: readDevInstanceRecords().map((record) => ({
|
|
...record,
|
|
profile: redactText(record.profile),
|
|
projectRoot: redactText(record.projectRoot),
|
|
})),
|
|
};
|
|
process.stdout.write(`${JSON.stringify(document, null, 2)}\n`);
|
|
return;
|
|
}
|
|
|
|
const scope = devStackScope(invocation, projectRoot);
|
|
const selected = selectDevStacks(records, scope);
|
|
if (selected.length === 0) {
|
|
if (scope.kind === "worktree" && records.length > 0) {
|
|
const elsewhere = invocation.command === "forget" ? "Recorded elsewhere" : "Live elsewhere";
|
|
logger.info(
|
|
`No dev stack belongs to this worktree. ${elsewhere}:\n${records.map((record) => `- ${describeDevStack(record)}`).join("\n")}`,
|
|
);
|
|
logger.info(`Name one of those with --pid=<supervisor pid>, or every stack with --all.`);
|
|
return;
|
|
}
|
|
logger.info("No dev stack is running.");
|
|
return;
|
|
}
|
|
const settled: DevStackRecord[] = [];
|
|
for (const record of selected) {
|
|
if (invocation.command === "forget") {
|
|
logger.info(`Forgetting ${describeDevStack(record)}. Nothing was signalled.`);
|
|
forgetDevStack(record);
|
|
settled.push(record);
|
|
continue;
|
|
}
|
|
logger.info(`Stopping ${describeDevStack(record)}`);
|
|
if (await stopDevStack(record)) settled.push(record);
|
|
}
|
|
// A record this command refused to touch is the whole reason to fail: the
|
|
// exit code is what a script driving `dev:stop` reads, and a silent success
|
|
// there would let it start a stack on a port somebody still holds.
|
|
if (settled.length < selected.length) process.exitCode = 1;
|
|
const remaining = readDevInstanceRecords();
|
|
if (remaining.length > 0) {
|
|
logger.info(`Still published:\n${remaining.map((record) => `- ${describeDevInstance(record)}`).join("\n")}`);
|
|
}
|
|
process.stdout.write(
|
|
`${JSON.stringify(
|
|
{
|
|
[invocation.command === "forget" ? "forgotten" : "stopped"]: settled.map((record) => ({
|
|
supervisorPid: record.supervisorPid,
|
|
services: record.services,
|
|
})),
|
|
unresolved: selected
|
|
.filter((record) => !settled.includes(record))
|
|
.map((record) => ({ supervisorPid: record.supervisorPid, services: record.services })),
|
|
},
|
|
null,
|
|
2,
|
|
)}\n`,
|
|
);
|
|
}
|
|
|
|
// Only when run as a command, like its siblings. Importing this file - a test
|
|
// covering the scope rules, an editor's language server - must never signal a
|
|
// process or delete a record as a side effect of the import.
|
|
const invokedFile = process.argv[1] ? resolve(process.argv[1]) : "";
|
|
if (invokedFile === fileURLToPath(import.meta.url)) {
|
|
void main().catch((error) => {
|
|
logger.error(error instanceof Error ? error.message : toLogValue(error));
|
|
process.exitCode = 1;
|
|
});
|
|
}
|