Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

Tie background jobs to their computer and keep refused credential drops usable (#2227)

Regan Bellc77e801e5aa9
diff --git a/src/api/routes/secret-drop.ts b/src/api/routes/secret-drop.ts
index aa8a3e462..afd0f3a02 100644
--- a/src/api/routes/secret-drop.ts
+++ b/src/api/routes/secret-drop.ts
@@ -13,7 +13,7 @@ import { escapeHtml } from "../../../plugins/chassis/src/http.ts";
import { sendJson } from "../http.ts";
import type { ApiCtx, Route } from "./route.ts";
import { audit, resolveCapabilityDestination, verifiedConversationSpeaker } from "./shared.ts";
-import { swallow } from "../../util/errors.ts";
+import { reportFailureAs, swallow } from "../../util/errors.ts";
const TRIGGERED = "secret-drop links can only be minted on a turn a person sent — this turn was fired by a trigger";
@@ -105,7 +105,7 @@ function dropScopeAuthorized(ctx: ApiCtx, rec: SecretDropRecord, claims?: Capabi
...(claims?.liveActor ? { liveActor: true } : {}),
...(claims?.members ? { members: claims.members } : {}),
})
- .catch(() => false);
+ .catch(reportFailureAs("secret drop: conversation membership check", false));
}
async function dropLinkClaims(
@@ -308,10 +308,9 @@ async function redeemDrop(ctx: ApiCtx): Promise<void> {
}
const attestation = linkClaims === true ? undefined : linkClaims;
if (!(await dropScopeAuthorized(ctx, peeked.rec, attestation))) {
- await deps.secretDrops.redeem(params.id!).catch(() => null);
return sendJson(res, 409, {
error: "scope_changed",
- message: "conversation membership changed — ask the agent for a fresh link",
+ message: "couldn't confirm you're still in this conversation — try again, or ask the agent for a fresh link",
});
}
const dropFieldDefs = peeked.rec.fields;
diff --git a/src/connectors/background-exec-broker.ts b/src/connectors/background-exec-broker.ts
index 846bd80fd..76477d25b 100644
--- a/src/connectors/background-exec-broker.ts
+++ b/src/connectors/background-exec-broker.ts
@@ -110,12 +110,15 @@ export function createBackgroundBroker(deps: BackgroundExecBrokerDeps): Backgrou
async handleFor(processId) {
const rec = await deps.registry.get(processId);
if (!rec || rec.scopeId !== deps.scopeId || rec.kind !== "background") throw new Error("no such background job");
- if (!rec.sandboxId) return null;
+ if (!rec.sandboxId) throw new Error("this background job has no recorded computer and can no longer be reached");
if (!deps.provisionSandbox) throw new Error("background job sandbox is unavailable");
return deps.provisionSandbox(rec.sandboxId);
},
async start(handle, command, purpose, ttlMs, credentials): Promise<BackgroundStartResult> {
if (!purpose?.trim()) throw new Error("background start requires a short purpose describing the job");
+ const sandboxId = handle.resourceId;
+ if (!sandboxId)
+ throw new Error("background jobs need a lasting computer; this computer is discarded when the turn ends");
purpose = redactCommand(purpose.replace(/\s+/g, " ").trim(), handle.env);
const ttl = Math.min(ttlMs ?? defaultTtlMs, maxTtlMs);
@@ -129,7 +132,7 @@ export function createBackgroundBroker(deps: BackgroundExecBrokerDeps): Backgrou
r.kind === "background" &&
r.command === redacted &&
r.status === "running" &&
- r.sandboxId === handle.resourceId,
+ r.sandboxId === sandboxId,
)?.processId ?? null)
: null;
@@ -176,7 +179,7 @@ export function createBackgroundBroker(deps: BackgroundExecBrokerDeps): Backgrou
await deps.registry.register({
processId: id,
scopeId: deps.scopeId,
- ...(handle.resourceId ? { sandboxId: handle.resourceId } : {}),
+ sandboxId,
kind: "background",
command: redacted,
purpose,
diff --git a/src/core/orchestrator/sandboxes.ts b/src/core/orchestrator/sandboxes.ts
index 188775ad1..b6b002f2a 100644
--- a/src/core/orchestrator/sandboxes.ts
+++ b/src/core/orchestrator/sandboxes.ts
@@ -571,14 +571,9 @@ export function createTurnSandboxes(ctx: TurnSandboxContext) {
const prepareTurnFiles = async (handle: SandboxHandle): Promise<void> => {
await Promise.all([pruneSkills(handle), clearStaleTurnFiles(handle)]);
};
- const hasLiveProcesses = async (handle: SandboxHandle, fallbackScope: ScopeId): Promise<boolean> => {
- if (!deps.processes) return false;
- if (!handle.resourceId) return (await deps.processes.liveByScope(fallbackScope)).length > 0;
- return (await deps.processes.listLive()).some(
- (process) =>
- process.sandboxId === handle.resourceId ||
- (!process.sandboxId && process.scopeId === (handle.scopeId ?? fallbackScope)),
- );
+ const hasLiveProcesses = async (handle: SandboxHandle): Promise<boolean> => {
+ if (!deps.processes || !handle.resourceId) return false;
+ return (await deps.processes.listLive()).some((process) => process.sandboxId === handle.resourceId);
};
const reclaimBox = async (): Promise<void> => {
let ownerCleanupError: unknown;
@@ -586,14 +581,14 @@ export function createTurnSandboxes(ctx: TurnSandboxContext) {
if (ownerAuthProvisionInFlight)
await ownerAuthProvisionInFlight.catch(swallowAs("orchestrator: owner auth provision", undefined));
ownerAuthProvisionInFlight = null;
- const reachEntries = [...reachBoxes.entries()];
+ const reachHandles = [...reachBoxes.values()];
reachBoxes.clear();
await Promise.all(
- reachEntries.map(async ([target, h]) => {
+ reachHandles.map(async (h) => {
let keepReachWarm = await releaseHold(h).catch(swallowAs("orchestrator: reach hold release", true));
if (!keepReachWarm && deps.processes && supportsProcessSessions(deps.sandbox)) {
try {
- keepReachWarm = await hasLiveProcesses(h, target);
+ keepReachWarm = await hasLiveProcesses(h);
} catch (e) {
swallow("orchestrator: reach live process check", e);
keepReachWarm = false;
@@ -678,9 +673,7 @@ export function createTurnSandboxes(ctx: TurnSandboxContext) {
await deps.sandbox.teardown(handle, {
keepWarm:
(await releaseHold(handle).catch(swallowAs("orchestrator: resource hold release", true))) ||
- (await hasLiveProcesses(handle, memoryScopeId).catch(
- swallowAs("orchestrator: live process check", true),
- )),
+ (await hasLiveProcesses(handle).catch(swallowAs("orchestrator: live process check", true))),
});
}
})(),
@@ -705,7 +698,7 @@ export function createTurnSandboxes(ctx: TurnSandboxContext) {
let keepWarm = await releaseHold(handle).catch(swallowAs("orchestrator: hold release", true));
if (!keepWarm && deps.processes && supportsProcessSessions(deps.sandbox)) {
try {
- keepWarm = await hasLiveProcesses(handle, memoryScopeId);
+ keepWarm = await hasLiveProcesses(handle);
} catch (e) {
swallow("orchestrator: live process check", e);
keepWarm = false;
diff --git a/src/monitors/monitor-poller.ts b/src/monitors/monitor-poller.ts
index df096d45e..724bcbcf0 100644
--- a/src/monitors/monitor-poller.ts
+++ b/src/monitors/monitor-poller.ts
@@ -278,19 +278,18 @@ export function createMonitorPoller(deps: MonitorPollerDeps): MonitorPoller {
break;
}
const rec = await deps.processes.get(m.processId);
- if (!rec) {
+ if (!rec?.sandboxId) {
await reportLost(m);
fires++;
continue;
}
- const targetKey = rec.sandboxId ?? rec.scopeId;
+ const targetKey = rec.sandboxId;
let handle = handles.get(targetKey);
if (!handle) {
try {
- handle = await sandbox.provision(
- [{ scopeId: rec.scopeId, mode: "rw", mountPath: "" }],
- rec.sandboxId ? { sandboxId: rec.sandboxId } : undefined,
- );
+ handle = await sandbox.provision([{ scopeId: rec.scopeId, mode: "rw", mountPath: "" }], {
+ sandboxId: rec.sandboxId,
+ });
} catch (e) {
await deps.monitors.recordError(m.id, errMessage(e));
continue;
diff --git a/src/processes/process-reaper.ts b/src/processes/process-reaper.ts
index 253d37432..eb023c015 100644
--- a/src/processes/process-reaper.ts
+++ b/src/processes/process-reaper.ts
@@ -21,10 +21,10 @@ export function createReaperKillHook(
const termGraceMs = opts?.termGraceMs ?? 5_000;
const killGraceMs = opts?.killGraceMs ?? 2_000;
return async (rec) => {
- const handle = await sandbox.provision(
- [{ scopeId: rec.scopeId, mode: "rw", mountPath: "" }],
- rec.sandboxId ? { sandboxId: rec.sandboxId } : undefined,
- );
+ if (!rec.sandboxId) return;
+ const handle = await sandbox.provision([{ scopeId: rec.scopeId, mode: "rw", mountPath: "" }], {
+ sandboxId: rec.sandboxId,
+ });
try {
try {
await sandbox.signalProcess(handle, rec.processId, "TERM");
diff --git a/src/processes/process-registry.ts b/src/processes/process-registry.ts
index baed529c9..db1667db4 100644
--- a/src/processes/process-registry.ts
+++ b/src/processes/process-registry.ts
@@ -29,7 +29,7 @@ export interface ProcessRecord {
interface NewProcessRecord {
processId: string;
scopeId: string;
- sandboxId?: string;
+ sandboxId: string;
kind: ProcessKind;
command: string;
purpose?: string;
@@ -58,7 +58,7 @@ function newRecord(rec: NewProcessRecord, now: number): ProcessRecord {
return {
processId: rec.processId,
scopeId: rec.scopeId,
- ...(rec.sandboxId ? { sandboxId: rec.sandboxId } : {}),
+ sandboxId: rec.sandboxId,
kind: rec.kind,
command: rec.command,
...(rec.purpose ? { purpose: rec.purpose } : {}),
@@ -195,7 +195,7 @@ export function createPostgresProcessRegistry(connectionString: string): Process
row.status,
row.sessionRef ?? null,
row.runId ?? null,
- row.sandboxId ?? null,
+ row.sandboxId,
row.purpose ?? null,
rec.credentialFiles ? JSON.stringify(rec.credentialFiles) : null,
],
diff --git a/src/processes/reconcile.ts b/src/processes/reconcile.ts
index 8048b5480..7aaddf9e3 100644
--- a/src/processes/reconcile.ts
+++ b/src/processes/reconcile.ts
@@ -8,9 +8,7 @@ export async function reconcileProcesses(
scopeId: string,
onExit?: (handle: SandboxHandle, processId: string) => Promise<void>,
): Promise<void> {
- const records = (await registry.listByScope(scopeId)).filter(
- (r) => !r.sandboxId || r.sandboxId === handle.resourceId,
- );
+ const records = (await registry.listByScope(scopeId)).filter((r) => r.sandboxId === handle.resourceId);
const running = records.filter((r) => r.status === "running");
const finished = records.filter((r) => r.status !== "running" && r.credentialsPending).map((r) => r.processId);
if (running.length) {
diff --git a/src/wiring.ts b/src/wiring.ts
index 7a420442a..dea433bf7 100644
--- a/src/wiring.ts
+++ b/src/wiring.ts
@@ -1175,19 +1175,9 @@ export function buildApp(
defaultBackend: config.sandboxBackend,
lock: advisoryLock,
beforeRetire: async (record) => {
- if (
- (await processes?.liveByScope(record.ownerScopeId))?.some(
- (process) => !process.sandboxId || process.sandboxId === record.id,
- )
- )
+ if ((await processes?.liveByScope(record.ownerScopeId))?.some((process) => process.sandboxId === record.id))
throw new Error("stop this sandbox's background jobs before retiring it");
},
- beforeDefaultChange: async (scopeId) => {
- if ((await processes?.liveByScope(scopeId))?.some((process) => !process.sandboxId))
- throw new Error(
- "legacy background work has no saved sandbox target; finish or stop it before changing the default",
- );
- },
provisionOptions: async (scopeId) => {
const secret = config.capabilitySecret ?? config.signingSecret;
if (!secret) return {};
diff --git a/test/background-exec-broker.test.ts b/test/background-exec-broker.test.ts
index bff95d487..6bdcd2344 100644
--- a/test/background-exec-broker.test.ts
+++ b/test/background-exec-broker.test.ts
@@ -6,7 +6,7 @@ import { redactCommand } from "../src/sandbox/exec-process-session.ts";
import type { ProcessSandbox, ProcessSession, SandboxHandle, StartProcessOptions } from "../src/sandbox/sandbox.ts";
const SCOPE = "personal:U1";
-const handle: SandboxHandle = { id: "vm", rootDir: "/workspace", homeDir: "/root" };
+const handle: SandboxHandle = { id: "vm", rootDir: "/workspace", homeDir: "/root", resourceId: "sandbox-1" };
function fakeSandbox(opts?: { seedOutput?: string }) {
interface Proc {
@@ -504,3 +504,20 @@ test("start requires a purpose before launching, and persists a trimmed, redacte
assert.equal(starts.length, 1, "labels must not alter command-based reattachment");
assert.equal((await registry.get(result.processId))?.purpose, row?.purpose);
});
+
+test("a computer discarded at the end of the turn cannot host a background job", async () => {
+ const { broker, registry, starts } = build();
+ const { resourceId: _resourceId, ...scratch } = handle;
+ await assert.rejects(broker.start(scratch, "npm run dev", "Run dev server"), /lasting computer/);
+ assert.equal(starts.length, 0);
+ assert.deepEqual(await registry.listByScope(SCOPE), []);
+});
+
+test("every registered background job records the computer it runs on", async () => {
+ const { broker, registry } = build();
+ await broker.start(handle, "npm run dev", "Run dev server");
+ assert.deepEqual(
+ (await registry.listByScope(SCOPE)).map((row) => row.sandboxId),
+ ["sandbox-1"],
+ );
+});
diff --git a/test/durable-process-sessions.test.ts b/test/durable-process-sessions.test.ts
index eff81b85e..b40fc4d6a 100644
--- a/test/durable-process-sessions.test.ts
+++ b/test/durable-process-sessions.test.ts
@@ -44,7 +44,7 @@ function fakeProcessSandbox() {
processSessions: true,
},
async provision(): Promise<SandboxHandle> {
- return { id: "vm", rootDir: "/workspace", homeDir: "/root" };
+ return { id: "vm", rootDir: "/workspace", homeDir: "/root", resourceId: "sandbox-1" };
},
async run(_h, command) {
if (/get-caller-identity|auth status|print-access-token/.test(command)) {
@@ -162,6 +162,7 @@ test("a live durable process keeps the computer warm; none lets it suspend", asy
await reg.register({
processId: live.processId,
scopeId: await memoryScope(),
+ sandboxId: "sandbox-1",
kind: "build",
command: "long build",
ttlMs: 600_000,
@@ -181,6 +182,7 @@ test("reattach reconciles a session whose process died while core was down", asy
await reg.register({
processId: "00000000-0000-0000-0000-0000000000ff",
scopeId: await memoryScope(),
+ sandboxId: "sandbox-1",
kind: "build",
command: "aws-sso: aws sso login",
ttlMs: 600_000,
diff --git a/test/execute-file-credentials.test.ts b/test/execute-file-credentials.test.ts
index 54429d1e4..51f4a5d23 100644
--- a/test/execute-file-credentials.test.ts
+++ b/test/execute-file-credentials.test.ts
@@ -40,7 +40,7 @@ async function fixture(t: TestContext) {
origin: "agent-session:original",
accountLabel: "original owner",
});
- const handle: SandboxHandle = { id: "default", rootDir: root, homeDir: root };
+ const handle: SandboxHandle = { id: "default", rootDir: root, homeDir: root, resourceId: "sandbox-1" };
const commands: Array<{ handle: SandboxHandle; command: string }> = [];
const sandbox = {
async run(h: SandboxHandle, command: string) {
@@ -321,6 +321,7 @@ function background(
registry,
scopeId: scope,
pollMs: 10,
+ provisionSandbox: async () => f.handle,
onExit: (h, processId) => finish(h, processId),
});
const ctx = (b = broker()) => f.context({ sandbox, backgroundBroker: b });
diff --git a/test/monitor-broker.test.ts b/test/monitor-broker.test.ts
index de802c9e8..dec0bb775 100644
--- a/test/monitor-broker.test.ts
+++ b/test/monitor-broker.test.ts
@@ -20,6 +20,7 @@ async function harness(readOutputTail: ReadOutputTail = async () => ({ outputTai
const rec = await registry.register({
processId: "p-1",
scopeId: SCOPE,
+ sandboxId: "sandbox-1",
kind: "background",
command: "bg: npm test",
purpose: "Run regression tests",
@@ -89,6 +90,7 @@ test("watch refuses a job from another scope and an unknown job", async () => {
await registry.register({
processId: "p-other",
scopeId: "personal:U2",
+ sandboxId: "sandbox-1",
kind: "background",
command: "bg: x",
ttlMs: 60_000,
diff --git a/test/monitor-poller.test.ts b/test/monitor-poller.test.ts
index e23c91b9c..cbd84df5c 100644
--- a/test/monitor-poller.test.ts
+++ b/test/monitor-poller.test.ts
@@ -128,6 +128,7 @@ async function harness(opts?: {
await processes.register({
processId: "p-1",
scopeId: SCOPE,
+ sandboxId: "sandbox-1",
kind: "background",
command: "bg: npm run build",
ttlMs: 600_000,
diff --git a/test/process-reaper.test.ts b/test/process-reaper.test.ts
index cfab26389..27ab8b3a6 100644
--- a/test/process-reaper.test.ts
+++ b/test/process-reaper.test.ts
@@ -49,7 +49,14 @@ const bgId = (n: number) => `00000000-0000-0000-0000-${n.toString(16).padStart(1
test("reaper flips expired sessions and calls kill for each", async () => {
const reg = createMemoryProcessRegistry();
- await reg.register({ processId: ID, scopeId: "s", kind: "build", command: "aws sso login", ttlMs: -1 });
+ await reg.register({
+ processId: ID,
+ scopeId: "s",
+ sandboxId: "sandbox-1",
+ kind: "build",
+ command: "aws sso login",
+ ttlMs: -1,
+ });
const killed: string[] = [];
const reaper = createProcessReaper(reg, {
intervalMs: 60_000,
@@ -64,7 +71,15 @@ test("reaper flips expired sessions and calls kill for each", async () => {
test("reaper calls onReaped for each reaped record (so a reaped run's death can notify the conversation)", async () => {
const reg = createMemoryProcessRegistry();
- await reg.register({ processId: ID, scopeId: "s", kind: "background", command: "bg: x", ttlMs: -1, runId: "run-7" });
+ await reg.register({
+ processId: ID,
+ scopeId: "s",
+ sandboxId: "sandbox-1",
+ kind: "background",
+ command: "bg: x",
+ ttlMs: -1,
+ runId: "run-7",
+ });
const seen: Array<{ kind: string; runId?: string }> = [];
const reaper = createProcessReaper(reg, {
intervalMs: 60_000,
@@ -81,7 +96,15 @@ test("reaper calls onReaped for each reaped record (so a reaped run's death can
test("a row deleted mid-sweep (a run that finished between snapshot and mark) is neither counted nor notified", async () => {
const reg = createMemoryProcessRegistry();
- await reg.register({ processId: ID, scopeId: "s", kind: "background", command: "bg: x", ttlMs: -1, runId: "run-9" });
+ await reg.register({
+ processId: ID,
+ scopeId: "s",
+ sandboxId: "sandbox-1",
+ kind: "background",
+ command: "bg: x",
+ ttlMs: -1,
+ runId: "run-9",
+ });
const notified: string[] = [];
const reaper = createProcessReaper(reg, {
intervalMs: 60_000,
@@ -96,7 +119,15 @@ test("a row deleted mid-sweep (a run that finished between snapshot and mark) is
test("an onReaped failure does not abort the sweep or un-reap the record", async () => {
const reg = createMemoryProcessRegistry();
- await reg.register({ processId: ID, scopeId: "s", kind: "background", command: "bg: x", ttlMs: -1, runId: "run-7" });
+ await reg.register({
+ processId: ID,
+ scopeId: "s",
+ sandboxId: "sandbox-1",
+ kind: "background",
+ command: "bg: x",
+ ttlMs: -1,
+ runId: "run-7",
+ });
const reaper = createProcessReaper(reg, {
intervalMs: 60_000,
onReaped: async () => {
@@ -109,7 +140,14 @@ test("an onReaped failure does not abort the sweep or un-reap the record", async
test("reaper leaves unexpired sessions alone", async () => {
const reg = createMemoryProcessRegistry();
- await reg.register({ processId: ID, scopeId: "s", kind: "build", command: "make", ttlMs: 60_000 });
+ await reg.register({
+ processId: ID,
+ scopeId: "s",
+ sandboxId: "sandbox-1",
+ kind: "build",
+ command: "make",
+ ttlMs: 60_000,
+ });
const reaper = createProcessReaper(reg, { intervalMs: 60_000 });
assert.equal((await reaper.sweep()).reaped, 0);
assert.equal((await reg.liveByScope("s")).length, 1);
@@ -117,8 +155,22 @@ test("reaper leaves unexpired sessions alone", async () => {
test("a kill failure does not abort the sweep, leaves the record running, and is retried next sweep", async () => {
const reg = createMemoryProcessRegistry();
- await reg.register({ processId: bgId(1), scopeId: "s", kind: "build", command: "x", ttlMs: -1 });
- await reg.register({ processId: bgId(2), scopeId: "s", kind: "background", command: "bg: y", ttlMs: -1 });
+ await reg.register({
+ processId: bgId(1),
+ scopeId: "s",
+ sandboxId: "sandbox-1",
+ kind: "build",
+ command: "x",
+ ttlMs: -1,
+ });
+ await reg.register({
+ processId: bgId(2),
+ scopeId: "s",
+ sandboxId: "sandbox-1",
+ kind: "background",
+ command: "bg: y",
+ ttlMs: -1,
+ });
let failFirst = true;
const reaper = createProcessReaper(reg, {
intervalMs: 60_000,
@@ -141,14 +193,23 @@ test("kill hook SIGTERMs every expired kind — background, build, and dev-serve
await reg.register({
processId: bgId(1),
scopeId: "personal:A",
+ sandboxId: "sandbox-1",
kind: "background",
command: "bg: npm run build",
ttlMs: -1,
});
- await reg.register({ processId: bgId(2), scopeId: "personal:B", kind: "build", command: "aws sso login", ttlMs: -1 });
+ await reg.register({
+ processId: bgId(2),
+ scopeId: "personal:B",
+ sandboxId: "sandbox-1",
+ kind: "build",
+ command: "aws sso login",
+ ttlMs: -1,
+ });
await reg.register({
processId: bgId(3),
scopeId: "personal:C",
+ sandboxId: "sandbox-1",
kind: "dev-server",
command: "npm run dev",
ttlMs: -1,
@@ -168,7 +229,7 @@ test("kill hook SIGTERMs every expired kind — background, build, and dev-serve
assert.equal(provisions.length, 3);
assert.deepEqual(provisions[0]!.layers, [{ scopeId: "personal:A", mode: "rw", mountPath: "" }]);
- assert.equal(provisions[0]!.opts, undefined);
+ assert.deepEqual(provisions[0]!.opts, { sandboxId: "sandbox-1" });
assert.equal(teardowns.length, 3);
assert.equal(teardowns[0]!.opts?.keepWarm, true);
@@ -177,7 +238,14 @@ test("kill hook SIGTERMs every expired kind — background, build, and dev-serve
test("kill hook escalates TERM → KILL when the grace period passes without an exit", async () => {
const reg = createMemoryProcessRegistry();
- await reg.register({ processId: ID, scopeId: "s", kind: "background", command: "bg: stubborn", ttlMs: -1 });
+ await reg.register({
+ processId: ID,
+ scopeId: "s",
+ sandboxId: "sandbox-1",
+ kind: "background",
+ command: "bg: stubborn",
+ ttlMs: -1,
+ });
const { sandbox, signals } = killSpySandbox({ diesOn: "KILL" });
const reaper = createProcessReaper(reg, { intervalMs: 60_000, kill: createReaperKillHook(sandbox, FAST_GRACE) });
@@ -191,7 +259,14 @@ test("kill hook escalates TERM → KILL when the grace period passes without an
test("a process that survives TERM+KILL is NOT marked reaped (zombie stays visible, kill retried)", async () => {
const reg = createMemoryProcessRegistry();
- await reg.register({ processId: ID, scopeId: "s", kind: "background", command: "bg: immortal", ttlMs: -1 });
+ await reg.register({
+ processId: ID,
+ scopeId: "s",
+ sandboxId: "sandbox-1",
+ kind: "background",
+ command: "bg: immortal",
+ ttlMs: -1,
+ });
const { sandbox, signals } = killSpySandbox({ diesOn: "never" });
const reaper = createProcessReaper(reg, { intervalMs: 60_000, kill: createReaperKillHook(sandbox, FAST_GRACE) });
@@ -208,7 +283,14 @@ test("a process that survives TERM+KILL is NOT marked reaped (zombie stays visib
test("only the leader instance's interval sweep reaps (one replica kills, not all of them)", async () => {
const reg = createMemoryProcessRegistry();
- await reg.register({ processId: ID, scopeId: "s", kind: "background", command: "bg: x", ttlMs: -1 });
+ await reg.register({
+ processId: ID,
+ scopeId: "s",
+ sandboxId: "sandbox-1",
+ kind: "background",
+ command: "bg: x",
+ ttlMs: -1,
+ });
let leader = false;
const lease: LeaderLease = {
@@ -239,7 +321,14 @@ test("only the leader instance's interval sweep reaps (one replica kills, not al
test("a vanished process session counts as a confirmed kill", async () => {
const reg = createMemoryProcessRegistry();
- await reg.register({ processId: ID, scopeId: "s", kind: "background", command: "bg: x", ttlMs: -1 });
+ await reg.register({
+ processId: ID,
+ scopeId: "s",
+ sandboxId: "sandbox-1",
+ kind: "background",
+ command: "bg: x",
+ ttlMs: -1,
+ });
const { sandbox, teardowns } = killSpySandbox({ vanished: true });
const reaper = createProcessReaper(reg, { intervalMs: 60_000, kill: createReaperKillHook(sandbox, FAST_GRACE) });
@@ -250,10 +339,34 @@ test("a vanished process session counts as a confirmed kill", async () => {
test("a non-Error 'no such process' rejection also counts as a confirmed kill", async () => {
const reg = createMemoryProcessRegistry();
- await reg.register({ processId: ID, scopeId: "s", kind: "background", command: "bg: x", ttlMs: -1 });
+ await reg.register({
+ processId: ID,
+ scopeId: "s",
+ sandboxId: "sandbox-1",
+ kind: "background",
+ command: "bg: x",
+ ttlMs: -1,
+ });
const { sandbox } = killSpySandbox({ vanished: "string-throw" });
const reaper = createProcessReaper(reg, { intervalMs: 60_000, kill: createReaperKillHook(sandbox, FAST_GRACE) });
assert.equal((await reaper.sweep()).reaped, 1);
assert.equal((await reg.get(ID))!.status, "reaped");
});
+
+test("an expired job with no recorded computer is retired without touching the scope's current computer", async () => {
+ const reg = createMemoryProcessRegistry();
+ await reg.register({
+ processId: bgId(9),
+ scopeId: "personal:A",
+ kind: "background",
+ command: "bg: npm run dev",
+ ttlMs: -1,
+ } as unknown as Parameters<typeof reg.register>[0]);
+ const { sandbox, provisions, signals } = killSpySandbox();
+ const reaper = createProcessReaper(reg, { intervalMs: 60_000, kill: createReaperKillHook(sandbox, FAST_GRACE) });
+ assert.equal((await reaper.sweep()).reaped, 1);
+ assert.equal(provisions.length, 0);
+ assert.equal(signals.length, 0);
+ assert.equal((await reg.get(bgId(9)))!.status, "reaped");
+});
diff --git a/test/process-registry.test.ts b/test/process-registry.test.ts
index e8fbedd4c..4d6d8b9a6 100644
--- a/test/process-registry.test.ts
+++ b/test/process-registry.test.ts
@@ -17,6 +17,7 @@ for (const b of backends()) {
const rec = await reg.register({
processId: id(1),
scopeId: "personal:U1",
+ sandboxId: "sandbox-1",
kind: "build",
command: "aws-sso: aws sso login",
ttlMs: 60_000,
@@ -32,7 +33,14 @@ for (const b of backends()) {
test(`[${b.name}] expired running sessions are not live; listExpired surfaces them WITHOUT flipping status`, async () => {
const reg = b.make();
- await reg.register({ processId: id(2), scopeId: "s", kind: "build", command: "x", ttlMs: -1 });
+ await reg.register({
+ processId: id(2),
+ scopeId: "s",
+ sandboxId: "sandbox-1",
+ kind: "build",
+ command: "x",
+ ttlMs: -1,
+ });
assert.equal((await reg.liveByScope("s")).length, 0, "an expired session is not live");
const expired = await reg.listExpired();
@@ -47,7 +55,14 @@ for (const b of backends()) {
test(`[${b.name}] markStatus and delete`, async () => {
const reg = b.make();
- await reg.register({ processId: id(3), scopeId: "s", kind: "build", command: "make", ttlMs: 60_000 });
+ await reg.register({
+ processId: id(3),
+ scopeId: "s",
+ sandboxId: "sandbox-1",
+ kind: "build",
+ command: "make",
+ ttlMs: 60_000,
+ });
await reg.markStatus(id(3), "exited");
assert.equal((await reg.liveByScope("s")).length, 0);
assert.equal((await reg.get(id(3)))!.status, "exited");
@@ -58,7 +73,14 @@ for (const b of backends()) {
test(`[${b.name}] only declared kinds may be registered`, async () => {
const reg = b.make();
await assert.rejects(
- reg.register({ processId: id(4), scopeId: "s", kind: "shell" as never, command: "sh", ttlMs: 1000 }),
+ reg.register({
+ processId: id(4),
+ scopeId: "s",
+ sandboxId: "sandbox-1",
+ kind: "shell" as never,
+ command: "sh",
+ ttlMs: 1000,
+ }),
/not declared/,
);
});
@@ -81,6 +103,7 @@ for (const b of backends()) {
const rec = await reg.register({
processId: id(7),
scopeId: "personal:U1",
+ sandboxId: "sandbox-1",
kind: "background",
command: "bg: npm test",
ttlMs: 1_800_000,
@@ -101,6 +124,7 @@ test("[postgres] honors the registry contract (durable across a restart)", { ski
const rec = await reg.register({
processId: id(1),
scopeId: scope,
+ sandboxId: "sandbox-1",
kind: "dev-server",
command: "npm run dev",
purpose: "Preview app server",
@@ -116,7 +140,14 @@ test("[postgres] honors the registry contract (durable across a restart)", { ski
assert.equal(typeof live[0]!.expiresAt, "number");
assert.equal(live[0]!.purpose, "Preview app server");
- await reg2.register({ processId: id(2), scopeId: scope, kind: "build", command: "y", ttlMs: -1 });
+ await reg2.register({
+ processId: id(2),
+ scopeId: scope,
+ sandboxId: "sandbox-1",
+ kind: "build",
+ command: "y",
+ ttlMs: -1,
+ });
assert.equal(
(await reg2.listExpired()).some((r) => r.processId === id(2)),
true,
@@ -144,6 +175,7 @@ for (const [name, make] of [
await reg.register({
processId,
scopeId: "personal:U1",
+ sandboxId: "sandbox-1",
kind: "background",
command: "x",
ttlMs: 60_000,
@@ -174,6 +206,7 @@ test("registry preserves purpose without replacing the command and accepts legac
const row = await registry.register({
processId: purpose ?? "legacy",
scopeId: "personal:U1",
+ sandboxId: "sandbox-1",
kind: "background",
command: "bg: node server.js",
ttlMs: 60_000,
diff --git a/test/secret-drop.test.ts b/test/secret-drop.test.ts
index 7d33bcdae..ce1def51d 100644
--- a/test/secret-drop.test.ts
+++ b/test/secret-drop.test.ts
@@ -370,7 +370,7 @@ describe("/v1/keychain/drops — mint, form, redeem", async () => {
);
});
- it("a Project roster change invalidates an unredeemed drop", async () => {
+ it("a Project roster change refuses an unredeemed drop on every attempt", async () => {
await built.app.upsertDirectory([
{ principalId: "U_PROJECT_OWNER", displayName: "Owner", type: "internal" },
{ principalId: "U_PROJECT_MEMBER", displayName: "Member", type: "internal" },
@@ -385,10 +385,13 @@ describe("/v1/keychain/drops — mint, form, redeem", async () => {
const { dropId, formPath } = (await minted.json()) as { dropId: string; formPath: string };
assert.equal((await built.app.addProjectMember(project.id, "U_PROJECT_OWNER", "U_PROJECT_MEMBER")).status, "ok");
- assert.equal(
- (await redeem(dropId, { secret: "must-not-save" }, "U_PROJECT_OWNER", linkToken(formPath))).status,
- 409,
- );
+ for (let attempt = 0; attempt < 2; attempt++)
+ assert.equal(
+ (await redeem(dropId, { secret: "must-not-save" }, "U_PROJECT_OWNER", linkToken(formPath))).status,
+ 409,
+ );
+ assert.ok((await built.secretDrops.peek(dropId)).ok);
+
assert.ok(
!(await built.keychain!.listByOwner("U_PROJECT_OWNER")).some(
(credential) => credential.service === "project-stale",
@@ -396,6 +399,31 @@ describe("/v1/keychain/drops — mint, form, redeem", async () => {
);
});
+ it("a membership lookup outage leaves the drop link usable for a retry", async () => {
+ const minted = await post(
+ "/v1/keychain/drops",
+ { service: "outage-drop", purpose: "survive a membership outage" },
+ await capFor("U_A", scopeId("channel", "C1")),
+ );
+ const { dropId, formPath } = (await minted.json()) as { dropId: string; formPath: string };
+ const directory = built.directory as unknown as Record<string, unknown>;
+ const originals = Object.fromEntries(
+ ["channelMember", "channelMembership", "channelPrivacy", "get"].map((name) => [name, directory[name]]),
+ );
+ for (const name of Object.keys(originals))
+ directory[name] = async () => {
+ throw new Error("membership store unavailable");
+ };
+ try {
+ const failed = await redeem(dropId, { secret: "sk_outage" }, "U_A", linkToken(formPath));
+ assert.equal(failed.status, 409);
+ assert.ok((await built.secretDrops.peek(dropId)).ok);
+ } finally {
+ Object.assign(directory, originals);
+ }
+ assert.equal((await redeem(dropId, { secret: "sk_outage" }, "U_A", linkToken(formPath))).status, 200);
+ });
+
it("an agent-declared fields[] drop renders each input, saves them all, and materializes them in order", async () => {
const fields = [
{ key: "DOORDASH_EMAIL", label: "Email", secret: false },
diff --git a/test/sessions-background-activity.test.ts b/test/sessions-background-activity.test.ts
index 922aab110..1f0044055 100644
--- a/test/sessions-background-activity.test.ts
+++ b/test/sessions-background-activity.test.ts
@@ -61,6 +61,7 @@ function registryRow(
scopeId: "personal:U1",
kind: over.kind ?? ("background" as const),
command: "sleep 600",
+ sandboxId: "sandbox-1",
ttlMs: over.ttlMs ?? 60_000,
...(sessionRef ? { sessionRef } : {}),
};