mirror of
https://github.com/nightly-labs/openbot.git
synced 2026-12-02 02:33:10 +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>
99 lines
3.9 KiB
TypeScript
99 lines
3.9 KiB
TypeScript
// Which stacks a command selects is its whole blast radius. `dev:stop` signals
|
|
// processes that belong to whatever else runs on this machine - four agents in
|
|
// four worktrees, in the case this was written for - so it stays inside the
|
|
// checkout it was run from until the developer names another one. `dev:status`
|
|
// is the opposite: the stack holding the port this worktree wanted is a
|
|
// sibling's, and a report that hid it would answer nothing.
|
|
import { describe, expect, it } from "vitest";
|
|
import type { DevInstanceRecord } from "./dev-automation/instance-registry";
|
|
import type { DevStackRecord } from "./dev-automation/stack-registry";
|
|
import { claimOnDevInstance, devStackScope, parseDevStackInvocation, selectDevStacks } from "./dev-stack";
|
|
|
|
function stack(projectRoot: string, supervisorPid: number): DevStackRecord {
|
|
return {
|
|
services: ["app"],
|
|
projectRoot,
|
|
supervisorPid,
|
|
startedAt: 1_000,
|
|
ports: [{ name: "app-renderer", port: 5_173 }],
|
|
processes: [],
|
|
};
|
|
}
|
|
|
|
const here = stack("/worktrees/one", 4_242);
|
|
const sibling = stack("/worktrees/two", 5_252);
|
|
|
|
function selectFor(args: string[]): DevStackRecord[] {
|
|
const invocation = parseDevStackInvocation(args);
|
|
return selectDevStacks([here, sibling], devStackScope(invocation, "/worktrees/one"));
|
|
}
|
|
|
|
describe("what a dev-stack command acts on", () => {
|
|
it("stops this worktree's stack and leaves the sibling running", () => {
|
|
expect(selectFor(["stop"])).toEqual([here]);
|
|
});
|
|
|
|
it("stops a sibling only when it is named", () => {
|
|
expect(selectFor(["stop", "--pid=5252"])).toEqual([sibling]);
|
|
expect(selectFor(["stop", "--all"])).toEqual([here, sibling]);
|
|
});
|
|
|
|
it("reports every stack on the machine, because the one holding your port is a sibling's", () => {
|
|
expect(selectFor(["status"])).toEqual([here, sibling]);
|
|
});
|
|
|
|
it("forgets records the same way it stops them: this worktree, unless told otherwise", () => {
|
|
expect(selectFor(["forget"])).toEqual([here]);
|
|
expect(selectFor(["forget", "--all"])).toEqual([here, sibling]);
|
|
});
|
|
|
|
it("refuses a command it does not have", () => {
|
|
expect(() => parseDevStackInvocation(["kill"])).toThrow("status|stop|forget");
|
|
});
|
|
});
|
|
|
|
// A dead stack record waits on disk for `dev:forget`, so the pids it names
|
|
// have had every chance to be recycled by the time anything acts on them.
|
|
// Deleting an instance record by pid alone deletes whatever app holds that pid
|
|
// now: it vanishes from `dev:automation instances` until it restarts.
|
|
describe("which instance records a forgotten stack takes with it", () => {
|
|
const record: DevStackRecord = {
|
|
...stack("/worktrees/one", 4_242),
|
|
processes: [{ name: "app", pid: 7_000, startedAt: 1_000 }],
|
|
};
|
|
|
|
function instance(overrides: Partial<DevInstanceRecord> = {}): DevInstanceRecord {
|
|
return {
|
|
service: "app",
|
|
instanceId: "5173",
|
|
profile: "OpenBot Dev",
|
|
projectRoot: "/worktrees/one",
|
|
rendererPort: 5_173,
|
|
remoteDebuggingPort: 9_333,
|
|
pid: 7_000,
|
|
startedAt: 1_000,
|
|
...overrides,
|
|
};
|
|
}
|
|
|
|
it("takes the record of its own instance, whose process is gone", () => {
|
|
expect(claimOnDevInstance(instance(), record, () => "gone")).toBe("ours");
|
|
});
|
|
|
|
it("leaves the record of a live instance that recycled the pid", () => {
|
|
expect(claimOnDevInstance(instance({ startedAt: 9_000 }), record, () => "live")).toBe("another");
|
|
});
|
|
|
|
it("leaves another worktree's record even where nothing can date the pid", () => {
|
|
expect(claimOnDevInstance(instance({ projectRoot: "/worktrees/two" }), record, () => "unverified")).toBe("another");
|
|
});
|
|
|
|
it("keeps a record of this worktree it cannot date, rather than guess", () => {
|
|
expect(claimOnDevInstance(instance(), record, () => "unverified")).toBe("unverified");
|
|
});
|
|
|
|
it("leaves a pid this stack never started", () => {
|
|
expect(claimOnDevInstance(instance({ pid: 8_000 }), record, () => "gone")).toBe("another");
|
|
});
|
|
});
|