Multiplayer agent harness for work.
Require readable descriptions for background jobs (#2084)
Regan Belld20ec14d8a94
diff --git a/docs/sandbox-resources.md b/docs/sandbox-resources.mdindex a91132e03..e3107d32b 100644--- a/docs/sandbox-resources.md+++ b/docs/sandbox-resources.md@@ -18,7 +18,7 @@ In Isolated posture, agent inventory and operations stay in the current owning s| `status`, `restart` | optional `sandbox_id`, `purpose` || `retire` | `sandbox_id`, `purpose` || `exec` | `command`, `purpose`, optional `sandbox_id`, `timeout_seconds`, and supported routing/credential parameters |-| `start_process` | `command`, optional `sandbox_id`, `timeout_seconds`, `purpose`; returns a process ID |+| `start_process` | `command`, `purpose`, optional `sandbox_id`, `timeout_seconds`; returns a process ID || `read_process` | `process_id`, optional `since_cursor`, `wait_seconds`, `max_bytes` || `write_stdin` | `process_id`, `data`; newline is not appended || `signal_process` | `process_id`, optional `signal` (`TERM`, `KILL`, `INT`, `HUP`, `QUIT`) |@@ -26,7 +26,7 @@ In Isolated posture, agent inventory and operations stay in the current owning s| `watch_process` | `process_id`, optional `since_cursor`, `pattern`, `instructions`; returns a monitor ID || `unwatch_process` | `monitor_id` |-Process actions also accept optional `purpose` for approval context. Unrelated fields are rejected rather than silently ignored. `exec` retains the enabled scoped, scratch, owner-auth and reached-room routing options and command credential handles. Process starts use the default or a named authorized resource; subsequent operations use the process ID's durable saved target, even after the scope default changes. Watches retain their durable monitor registration and wake this conversation with output or exit. Provider loss or expiry can still interrupt a process.+`start_process` requires a short `purpose` (about five words) describing the job. It is saved with the process and displayed instead of the command; the raw command remains available in expanded job output. Other process actions accept optional `purpose` for approval context. Unrelated fields are rejected rather than silently ignored. `exec` retains the enabled scoped, scratch, owner-auth and reached-room routing options and command credential handles. Process starts use the default or a named authorized resource; subsequent operations use the process ID's durable saved target, even after the scope default changes. Watches retain their durable monitor registration and wake this conversation with output or exit. Provider loss or expiry can still interrupt a process.Execution and process handlers retain their existing approval and output-screening paths. Strict sandbox approvals are scoped to each action (`tool:sandbox:exec`, for example); an older broad `tool:sandbox` grant does not authorize newly exposed command or process actions. Transcript entries identify the actual `sandbox` action. Files publication, application deployment, and file read/write remain separate capabilities; unsupported resize and clone actions are not advertised.diff --git a/plugins/web-ui/src/chat.ts b/plugins/web-ui/src/chat.tsindex 889357f65..114a4c693 100644--- a/plugins/web-ui/src/chat.ts+++ b/plugins/web-ui/src/chat.ts@@ -2423,11 +2423,15 @@ export function createChatSurface(@click=${() => toggleJobOutput(j.processId)}>${icon(Terminal, 13)}- <code class="bg-row-cmd">${j.command}</code>+ ${+ j.purpose+ ? html`<span class="bg-row-cmd bg-job-purpose">${j.purpose}</span>`+ : html`<code class="bg-row-cmd">${j.command}</code>`+ }<span class="bg-row-meta">started ${relTime(j.startedAt)} · ${status}</span><span class="bg-row-toggle">${icon(ChevronRight, 13)}</span></button>- ${open ? html`<pre class="bg-row-output">${out ? out.text || "(no output yet)" : "Loading output…"}</pre>` : nothing}+ ${open ? html`<pre class="bg-row-output">${j.purpose ? `${j.command}\n\n` : ""}${out ? out.text || "(no output yet)" : "Loading output…"}</pre>` : nothing}</div>`;}diff --git a/plugins/web-ui/src/core-bridge.ts b/plugins/web-ui/src/core-bridge.tsindex 406fdb80b..63832f740 100644--- a/plugins/web-ui/src/core-bridge.ts+++ b/plugins/web-ui/src/core-bridge.ts@@ -212,7 +212,7 @@ export async function loadInheritedTranscript(}export interface SessionBackgroundView {- jobs: Array<{ processId: string; command: string; startedAt: number; expiresAt: number }>;+ jobs: Array<{ processId: string; command: string; purpose?: string; startedAt: number; expiresAt: number }>;watches: Array<{id: string;processId: string;diff --git a/plugins/web-ui/src/shell.css b/plugins/web-ui/src/shell.cssindex 418ea2bf4..04cb07ed7 100644--- a/plugins/web-ui/src/shell.css+++ b/plugins/web-ui/src/shell.css@@ -3439,7 +3439,8 @@ qm-markdown .tok-in {font-family: ui-monospace, SFMono-Regular, Menlo, monospace;font-size: 11.5px;}-.bg-row.watch .bg-row-cmd {+.bg-row.watch .bg-row-cmd,+.bg-row-cmd.bg-job-purpose {font-family: inherit;font-size: 12px;}diff --git a/scripts/monitor-smoke.ts b/scripts/monitor-smoke.tsindex 4cea093db..d2833e91a 100644--- a/scripts/monitor-smoke.ts+++ b/scripts/monitor-smoke.ts@@ -119,7 +119,7 @@ try {await sb.writeFile(h, "diffusion.py", DIFFUSION_PY);console.log(`[${ts()}] background-start the diffusion job (ttl 60min) …`);- const s = await broker.start(h, "bash job.sh", 60 * 60_000);+ const s = await broker.start(h, "bash job.sh", "Image generation smoke test", 60 * 60_000);ok(!!s.processId && s.status.state === "running", `job ${s.processId} is running`);console.log(" early output:", JSON.stringify(s.output.trim().split("\n").slice(0, 2)));diff --git a/skills-seed/publish/SKILL.md b/skills-seed/publish/SKILL.mdindex 3241688d4..e7f7b7788 100644--- a/skills-seed/publish/SKILL.md+++ b/skills-seed/publish/SKILL.md@@ -96,7 +96,7 @@ the same as the app _working_. So for anything browsable, sanity-check it locallpublish:1. Run it locally. Start the server in the background on a port — e.g.- `PORT=8080 node server.js` via `sandbox` action `start_process` (`background` action `start`+ `PORT=8080 node server.js` via `sandbox` action `start_process` with `purpose: "App preview server"` (`background` action `start`before sandbox-resource activation), so it keeps serving while you check.2. Probe it with `curl` — confirm it answers, returns the status you expect, and the mainpage/endpoint is actually there (real content, not a stack trace or a blank 500):diff --git a/skills-seed/taste-skill/SKILL.md b/skills-seed/taste-skill/SKILL.mdindex 24b727894..14a6c2bc2 100644--- a/skills-seed/taste-skill/SKILL.md+++ b/skills-seed/taste-skill/SKILL.md@@ -40,7 +40,7 @@ workspace, verify it locally, and when it should outlive the turn ship it with t- **`files` actions `write` / `read`** — author and inspect workspace files.- **`sandbox` action `exec`** — install deps and run build steps (`execute` before sandbox-resource activation).-- **`sandbox` action `start_process`** — run a dev server (`PORT=8080 node server.js`) so you can look at it (`background` action `start` before activation).+- **`sandbox` action `start_process`** — run a dev server (`PORT=8080 node server.js`, `purpose: "App preview server"`) so you can look at it (`background` action `start` before activation).- **local headless Chromium** — confirm the page renders, the content is there, no consoleerrors, layout and links intact: `chromium --headless --no-sandbox --disable-gpu--dump-dom http://localhost:<port>` (or `--screenshot=/tmp/page.png`, then use `files` action `read` on thediff --git a/src/api/app-sessions.ts b/src/api/app-sessions.tsindex 6a7bd4704..e15761aec 100644--- a/src/api/app-sessions.ts+++ b/src/api/app-sessions.ts@@ -531,7 +531,13 @@ export function createSessionMethods(const jobs = ((await deps.processes?.listLive(now)) ?? []).filter((r) => r.kind === "background" && r.sessionRef === session.threadRef).sort((a, b) => b.startedAt - a.startedAt)- .map((r) => ({ processId: r.processId, command: r.command, startedAt: r.startedAt, expiresAt: r.expiresAt }));+ .map((r) => ({+ processId: r.processId,+ command: r.command,+ ...(r.purpose ? { purpose: r.purpose } : {}),+ startedAt: r.startedAt,+ expiresAt: r.expiresAt,+ }));const watches = ((await deps.monitors?.enabled()) ?? []).filter((m) => m.threadRef === session.threadRef && m.expiresAt > now).sort((a, b) => b.createdAt - a.createdAt)diff --git a/src/api/app-types.ts b/src/api/app-types.tsindex b8d28ee58..34e3f438c 100644--- a/src/api/app-types.ts+++ b/src/api/app-types.ts@@ -217,7 +217,7 @@ interface DeploymentGitUrl {}interface SessionBackgroundView {- jobs: Array<{ processId: string; command: string; startedAt: number; expiresAt: number }>;+ jobs: Array<{ processId: string; command: string; purpose?: string; startedAt: number; expiresAt: number }>;watches: Array<{id: string;processId: string;diff --git a/src/connectors/background-exec-broker.ts b/src/connectors/background-exec-broker.tsindex 00958bc23..fc0cb8a3f 100644--- a/src/connectors/background-exec-broker.ts+++ b/src/connectors/background-exec-broker.ts@@ -42,6 +42,7 @@ export interface BackgroundStopResult {export interface BackgroundJobSummary {processId: string;command: string;+ purpose?: string;status: ProcessState;registryStatus: ProcessStatus;startedAt: number;@@ -55,7 +56,7 @@ export interface BackgroundWriteResult {export interface BackgroundExecBroker {handleFor?(processId: string): Promise<SandboxHandle | null>;- start(handle: SandboxHandle, command: string, ttlMs?: number): Promise<BackgroundStartResult>;+ start(handle: SandboxHandle, command: string, purpose: string, ttlMs?: number): Promise<BackgroundStartResult>;poll(handle: SandboxHandle,processId: string,@@ -92,7 +93,9 @@ export function createBackgroundBroker(deps: BackgroundExecBrokerDeps): Backgrouif (!deps.provisionSandbox) throw new Error("background job sandbox is unavailable");return deps.provisionSandbox(rec.sandboxId);},- async start(handle, command, ttlMs): Promise<BackgroundStartResult> {+ async start(handle, command, purpose, ttlMs): Promise<BackgroundStartResult> {+ if (!purpose?.trim()) throw new Error("background start requires a short purpose describing the job");+ purpose = redactCommand(purpose.replace(/\s+/g, " ").trim(), handle.env);const ttl = Math.min(ttlMs ?? defaultTtlMs, maxTtlMs);const normalized = `bg: ${command.replace(/\s+/g, " ").trim()}`;@@ -145,6 +148,7 @@ export function createBackgroundBroker(deps: BackgroundExecBrokerDeps): Backgrou...(handle.resourceId ? { sandboxId: handle.resourceId } : {}),kind: "background",command: redacted,+ purpose,ttlMs: ttl,...(deps.sessionRef ? { sessionRef: deps.sessionRef } : {}),});@@ -220,6 +224,7 @@ export function createBackgroundBroker(deps: BackgroundExecBrokerDeps): Backgrou.map((r) => ({processId: r.processId,command: r.command,+ ...(r.purpose ? { purpose: r.purpose } : {}),status: stateFromRow(r.status),registryStatus: r.status,startedAt: r.startedAt,diff --git a/src/core/orchestrator/prompt-blocks.ts b/src/core/orchestrator/prompt-blocks.tsindex 6f71d4e73..54b511ef2 100644--- a/src/core/orchestrator/prompt-blocks.ts+++ b/src/core/orchestrator/prompt-blocks.ts@@ -57,7 +57,7 @@ export function renderStandingObligations(crons: Cron[], webhooks: Webhook[], mo...monitors.toSorted((a, b) => a.id.localeCompare(b.id)).slice(0, OBLIGATIONS_CAP)- .map((m) => `- job watch on \`${m.processId}\`: ${snippet(m.command)}`),+ .map((m) => `- job watch on \`${m.processId}\`: ${snippet(m.purpose ?? m.command)}`),];return ["## Already scheduled here",diff --git a/src/harness/agent-tools.ts b/src/harness/agent-tools.tsindex aee3c3c58..8c955d71e 100644--- a/src/harness/agent-tools.ts+++ b/src/harness/agent-tools.ts@@ -1862,7 +1862,10 @@ export function createAgentTools(ref: ToolContextRef, opts?: AgentToolsOptions):},),purpose: Type.Optional(- Type.String({ description: "Human-readable purpose, at most 4 words (e.g. 'Start preview server')." }),+ Type.String({+ description:+ "Short job description, about 5 words (e.g. 'App preview server'). Required for start; displayed to the user instead of code.",+ }),),command: Type.Optional(Type.String({ description: "start only: the shell command to run in the background." })),process_id: Type.Optional(@@ -1946,7 +1949,15 @@ export function createAgentTools(ref: ToolContextRef, opts?: AgentToolsOptions):text("[error] background start requires `command`."),true,);+ if (!params.purpose?.trim())+ return recordResult(+ callId,+ { tool: "background", action: params.action, error: "start requires purpose" },+ text("[error] background start requires `purpose`: a short description of the job, about 5 words."),+ true,+ );const r = await tc.backgroundStart(params.command, {+ purpose: params.purpose,...(params.timeout_seconds ? { ttlSeconds: params.timeout_seconds } : {}),...(params.sandbox_id ? { sandboxId: params.sandbox_id } : {}),});@@ -2144,7 +2155,7 @@ export function createAgentTools(ref: ToolContextRef, opts?: AgentToolsOptions):? jobs.map((j) =>- `${j.processId} ${j.registryStatus === "reaped" ? "stopped (ttl)" : fmtStatus(j.status)} ${new Date(j.startedAt).toISOString()} ${j.command}`,+ `${j.processId} ${j.registryStatus === "reaped" ? "stopped (ttl)" : fmtStatus(j.status)} ${new Date(j.startedAt).toISOString()} ${j.purpose ?? j.command}${j.purpose ? `\n ${j.command}` : ""}`,).join("\n"): "(no background jobs)",@@ -2209,7 +2220,7 @@ export function createAgentTools(ref: ToolContextRef, opts?: AgentToolsOptions):purpose: Type.Optional(Type.String({description:- "Human-readable intent label, at most 4 words (e.g. 'Check Python version'). Describe the purpose, not the code. Required for exec and management actions; optional for process actions.",+ "Human-readable intent label, about 5 words (e.g. 'App preview server'). Describe what the job does, not the code. Required for exec, management actions, and start_process; optional for other process actions.",}),),timeout_seconds: Type.Optional(@@ -2244,7 +2255,7 @@ export function createAgentTools(ref: ToolContextRef, opts?: AgentToolsOptions):set_default: ["purpose", "sandbox_id"],retire: ["purpose", "sandbox_id"],exec: ["purpose", "command"],- start_process: ["command"],+ start_process: ["purpose", "command"],read_process: ["process_id"],write_stdin: ["process_id", "data"],signal_process: ["process_id"],diff --git a/src/monitors/monitor-broker.ts b/src/monitors/monitor-broker.tsindex 9bc1df38c..3bdf70dd6 100644--- a/src/monitors/monitor-broker.ts+++ b/src/monitors/monitor-broker.ts@@ -149,6 +149,7 @@ export function createMonitorBroker(deps: MonitorBrokerDeps): MonitorBroker {...(deps.destination ? { destination: deps.destination } : {}),processId,command: rec.command,+ ...(rec.purpose ? { purpose: rec.purpose } : {}),threadRef: deps.threadRef,...(opts?.instructions !== undefined ? { instructions: opts.instructions } : {}),...(opts?.pattern !== undefined ? { pattern: opts.pattern } : {}),diff --git a/src/monitors/monitor-poller.ts b/src/monitors/monitor-poller.tsindex 3ebf5c48d..6cd667073 100644--- a/src/monitors/monitor-poller.ts+++ b/src/monitors/monitor-poller.ts@@ -107,7 +107,7 @@ function renderEvent(m: Monitor, output: string, ev: MonitorEvent): { input: strsurface: "monitor",attrs: { "process-id": m.processId },at: new Date(),- why: `You are watching background job ${m.processId} (\`${m.command}\`) in this conversation. ${what}`,+ why: `You are watching background job ${m.processId} (${m.purpose ? `“${m.purpose}”` : `\`${m.command}\``}) in this conversation. ${what}`,...(m.instructions? { orders: { note: "what you asked for when you armed this watch — follow it exactly", text: m.instructions } }: {}),@@ -157,7 +157,10 @@ export function createMonitorPoller(deps: MonitorPollerDeps): MonitorPoller {threadRef: m.threadRef,...(m.destination ? { destination: m.destination } : {}),...(withErrorNotice- ? { errorNotice: (s) => `⚠️ A background-job update (\`${m.command}\`) could not run: ${s}` }+ ? {+ errorNotice: (s) =>+ `⚠️ A background-job update (${m.purpose ? `“${m.purpose}”` : `\`${m.command}\``}) could not run: ${s}`,+ }: {}),});}diff --git a/src/monitors/monitor-store.ts b/src/monitors/monitor-store.tsindex f4633c93c..f1425e7eb 100644--- a/src/monitors/monitor-store.ts+++ b/src/monitors/monitor-store.ts@@ -11,6 +11,7 @@ import {interface CreateMonitorInput extends CreateTriggerInput {processId: string;command: string;+ purpose?: string;threadRef: string;instructions?: string;pattern?: string;@@ -49,6 +50,7 @@ export function createMonitorStore(backing: DurableMap<Monitor> = createMemoryMa...buildTriggerBase(input, randomUUID(), Date.now()),processId: input.processId,command: input.command,+ ...(input.purpose ? { purpose: input.purpose } : {}),threadRef: input.threadRef,...(input.instructions !== undefined ? { instructions: input.instructions } : {}),...(input.pattern !== undefined ? { pattern: input.pattern } : {}),diff --git a/src/processes/process-registry.ts b/src/processes/process-registry.tsindex bc29d6ddd..88752a404 100644--- a/src/processes/process-registry.ts+++ b/src/processes/process-registry.ts@@ -16,6 +16,7 @@ export interface ProcessRecord {sandboxId?: string;kind: ProcessKind;command: string;+ purpose?: string;startedAt: number;expiresAt: number;status: ProcessStatus;@@ -29,6 +30,7 @@ interface NewProcessRecord {sandboxId?: string;kind: ProcessKind;command: string;+ purpose?: string;ttlMs: number;sessionRef?: string;runId?: string;@@ -54,6 +56,7 @@ function newRecord(rec: NewProcessRecord, now: number): ProcessRecord {...(rec.sandboxId ? { sandboxId: rec.sandboxId } : {}),kind: rec.kind,command: rec.command,+ ...(rec.purpose ? { purpose: rec.purpose } : {}),startedAt: now,expiresAt: now + rec.ttlMs,status: "running",@@ -107,6 +110,7 @@ function pgRowToRecord(r: Record<string, unknown>): ProcessRecord {...(r.sandbox_id ? { sandboxId: r.sandbox_id as string } : {}),kind: r.kind as ProcessKind,command: r.command as string,+ ...(r.purpose ? { purpose: r.purpose as string } : {}),startedAt: Number(r.started_at),expiresAt: Number(r.expires_at),status: r.status as ProcessStatus,@@ -132,12 +136,20 @@ export function createPostgresProcessRegistry(connectionString: string): Processstatements: ["ALTER TABLE process_sessions ADD COLUMN IF NOT EXISTS sandbox_id TEXT"],};pg.registerMigration(migration);+ const purposeMigration = {+ id: "processes/registry/0003",+ statements: ["ALTER TABLE process_sessions ADD COLUMN IF NOT EXISTS purpose TEXT"],+ };+ pg.registerMigration(purposeMigration);let ready: Promise<void> | undefined;const q: typeof pg.q = async (...args) => {- ready ??= pg.migrate(migration).catch((error) => {- ready = undefined;- throw error;- });+ ready ??= pg+ .migrate(migration)+ .then(() => pg.migrate(purposeMigration))+ .catch((error) => {+ ready = undefined;+ throw error;+ });await ready;return pg.q(...args);};@@ -145,8 +157,8 @@ export function createPostgresProcessRegistry(connectionString: string): Processasync register(rec) {const row = newRecord(rec, Date.now());await q(- `INSERT INTO process_sessions(process_id, scope_id, kind, command, started_at, expires_at, status, session_ref, run_id, sandbox_id)- VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)`,+ `INSERT INTO process_sessions(process_id, scope_id, kind, command, started_at, expires_at, status, session_ref, run_id, sandbox_id, purpose)+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)`,[row.processId,row.scopeId,@@ -158,6 +170,7 @@ export function createPostgresProcessRegistry(connectionString: string): Processrow.sessionRef ?? null,row.runId ?? null,row.sandboxId ?? null,+ row.purpose ?? null,],);return row;diff --git a/src/tools/primitives.ts b/src/tools/primitives.tsindex 467504556..1537945da 100644--- a/src/tools/primitives.ts+++ b/src/tools/primitives.ts@@ -243,7 +243,10 @@ export interface ToolContext extends SurfaceToolDeps {timeoutMs: number,signal?: AbortSignal,): Promise<ClientToolResult | "timeout" | "cancelled">;- backgroundStart(command: string, opts?: { ttlSeconds?: number; sandboxId?: string }): Promise<BackgroundStartResult>;+ backgroundStart(+ command: string,+ opts: { purpose: string; ttlSeconds?: number; sandboxId?: string },+ ): Promise<BackgroundStartResult>;backgroundPoll(processId: string,opts?: { sinceCursor?: number; maxBytes?: number; waitSeconds?: number },@@ -1225,7 +1228,7 @@ export function createToolContext(deps: ToolContextDeps): ToolContext {async backgroundStart(command: string,- opts?: { ttlSeconds?: number; sandboxId?: string },+ opts: { purpose: string; ttlSeconds?: number; sandboxId?: string },): Promise<BackgroundStartResult> {if (!deps.backgroundBroker) throw new Error(BACKGROUND_UNAVAILABLE_MESSAGE);let handle: SandboxHandle;@@ -1242,6 +1245,7 @@ export function createToolContext(deps: ToolContextDeps): ToolContext {deps.backgroundBroker!.start(handle,deps.scopedCommand?.(command, handle.env) ?? command,+ opts.purpose,opts?.ttlSeconds ? opts.ttlSeconds * 1000 : undefined,),() => true,diff --git a/src/types.ts b/src/types.tsindex 3a1af014c..bc3d8795c 100644--- a/src/types.ts+++ b/src/types.ts@@ -319,6 +319,7 @@ export interface Webhook extends TriggerBase {export interface Monitor extends TriggerBase {processId: string;command: string;+ purpose?: string;threadRef: string;instructions?: string;pattern?: string;diff --git a/test/agent-tools.test.ts b/test/agent-tools.test.tsindex 719af5a98..b9fdef63c 100644--- a/test/agent-tools.test.ts+++ b/test/agent-tools.test.ts@@ -1958,7 +1958,9 @@ test("background dispatches each action and emits tool_call/tool_result", asyncassert.match(background.description, /\$AGENT_CREDENTIAL_TOKEN all work/);assert.match(background.description, /expire 48 hours after the turn/);- const started = textOf(await call(background, { action: "start", command: "npm run build" }));+ const started = textOf(+ await call(background, { action: "start", command: "npm run build", purpose: "Run background tests" }),+ );assert.match(started, /started bg-1/);assert.match(started, /running/);@@ -2041,7 +2043,7 @@ test("background surfaces a policy denial/approval as a tool_result, not a throwconst out = textOf(await call(createAgentTools({ current: denyTC }).find((t) => t.name === "background"),- { action: "start", command: "rm -rf /" },+ { action: "start", command: "rm -rf /", purpose: "Run background tests" },),);assert.match(out, /\[denied by policy\]/);@@ -2058,7 +2060,7 @@ test("background surfaces a policy denial/approval as a tool_result, not a throwconst out2 = textOf(await call(createAgentTools(ref).find((t) => t.name === "background"),- { action: "start", command: "deploy prod" },+ { action: "start", command: "deploy prod", purpose: "Run background tests" },),);assert.match(out2, /\[blocked: needs human approval\]/);@@ -2650,7 +2652,7 @@ test("background job output is external while background bookkeeping stays inter},};const background = createAgentTools(ref).find((t) => t.name === "background")!;- await call(background, { action: "start", command: "npm test" });+ await call(background, { action: "start", command: "npm test", purpose: "Run background tests" });await call(background, { action: "poll", process_id: "bg-1" });await call(background, { action: "poll", process_id: "bg-net" });await call(background, { action: "list" });@@ -2736,7 +2738,13 @@ test("unified sandbox dispatches every process action and preserves cursors, sig{ sandboxResources: true },).find((t) => t.name === "sandbox")!;const actions = [- { action: "start_process", command: "npm test", sandbox_id: "box-a", timeout_seconds: 123 },+ {+ action: "start_process",+ command: "npm test",+ purpose: "Run background tests",+ sandbox_id: "box-a",+ timeout_seconds: 123,+ },{ action: "read_process", process_id: "bg-1", since_cursor: 7, wait_seconds: 2, max_bytes: 99 },{ action: "write_stdin", process_id: "bg-1", data: "yes\n" },{ action: "signal_process", process_id: "bg-1", signal: "INT" },@@ -2752,7 +2760,10 @@ test("unified sandbox dispatches every process action and preserves cursors, sig];for (const action of actions) assert.doesNotMatch(textOut(await call(tool, action)), /\[error\]/);assert.deepEqual(calls, [- { method: "backgroundStart", args: ["npm test", { ttlSeconds: 123, sandboxId: "box-a" }] },+ {+ method: "backgroundStart",+ args: ["npm test", { purpose: "Run background tests", ttlSeconds: 123, sandboxId: "box-a" }],+ },{ method: "backgroundPoll", args: ["bg-1", { sinceCursor: 7, waitSeconds: 2, maxBytes: 99 }] },{ method: "backgroundWrite", args: ["bg-1", "yes\n"] },{ method: "backgroundStop", args: ["bg-1", "INT"] },@@ -2786,7 +2797,7 @@ test("unified sandbox advertised schemas and handlers accept minimal arguments f{ action: "set_default", sandbox_id: null, purpose: "Clear the default" },{ action: "retire", sandbox_id: "box-a", purpose: "Retire a computer" },{ action: "exec", command: "echo ok", purpose: "Check execution" },- { action: "start_process", command: "echo ok" },+ { action: "start_process", command: "echo ok", purpose: "Run background tests" },{ action: "read_process", process_id: "bg-1" },{ action: "write_stdin", process_id: "bg-1", data: "" },{ action: "signal_process", process_id: "bg-1" },@@ -2825,14 +2836,14 @@ test("unified sandbox rejects missing, mistyped and unrelated action fields befo{ action: "__proto__" },{ action: "constructor" },{ action: "exec", purpose: "test" },- { action: "start_process", command: " " },+ { action: "start_process", command: " ", purpose: "Run background tests" },{ action: "read_process", process_id: "job", sandbox_id: "other-box" },{ action: "write_stdin", process_id: "job" },{ action: "signal_process", process_id: "job", signal: "NOPE" },{ action: "watch_process", process_id: "job", since_cursor: -1 },{ action: "unwatch_process", monitor_id: null },{ action: "list_processes", command: "ignored" },- { action: "start_process", command: "echo ok", scope: "scratch" },+ { action: "start_process", command: "echo ok", purpose: "Run background tests", scope: "scratch" },{ action: "retire", sandbox_id: null, purpose: "test" },{ action: "create", backend: "modal", command: "ignored", purpose: "test" },])@@ -2926,7 +2937,7 @@ test("unified sandbox keeps strict approval and quarantined output associated witoolApprovalGate: () => false,};const tool = createAgentTools(ref, { sandboxResources: true }).find((t) => t.name === "sandbox")!;- await call(tool, { action: "start_process", command: "test" });+ await call(tool, { action: "start_process", command: "test", purpose: "Run background tests" });assert.equal(ref.pendingApprovals?.[0]?.approvalKey, "tool:sandbox:start_process");assert.deepEqual(entries.map((e) => [e.tool, e.action]),@@ -3422,7 +3433,9 @@ test("conversation coordinators cannot execute commands through any command tool/unsupported sandbox action/,);assert.match(- textOut(await call(sandbox, { action: "start_process", command: "echo forbidden" })),+ textOut(+ await call(sandbox, { action: "start_process", command: "echo forbidden", purpose: "Run background tests" }),+ ),/unsupported sandbox action/,);assert.ok(tools.some((tool) => tool.name === "subagents"));@@ -3746,7 +3759,7 @@ test("sandbox call traces preserve purpose across execution, management, processfor (const params of [{ action: "exec", command: "pwd" },{ action: "status" },- { action: "start_process", command: "echo ready" },+ { action: "start_process", command: "echo ready", purpose: "Run background tests" },{ action: "exec", command: "pwd", scope: "scratch" },{ action: "exec" },]) {@@ -4173,3 +4186,53 @@ test("a tool result recorded after shutdown fires is marked interrupted; user Stassert.deepEqual(strategy(emitted), { kind: "continue" });}});++test("background starts require a nonblank purpose as a repairable tool result", async () => {+ let started = false;+ const current = {+ ...fakeToolContext(),+ async backgroundStart() {+ started = true;+ throw new Error("must not start");+ },+ };+ for (const [name, action, options] of [+ ["background", "start", {}],+ ["sandbox", "start_process", { sandboxResources: true }],+ ] as const) {+ const events: Array<Record<string, unknown>> = [];+ const tool = createAgentTools(+ {+ current,+ scopeLabel: "personal:U1",+ emit: (entry) => {+ events.push(entry.payload as Record<string, unknown>);+ },+ },+ options,+ ).find((t) => t.name === name)!;+ for (const purpose of [undefined, "", " \n "]) {+ const result = await call(tool, {+ action,+ command: "node server.js",+ ...(purpose === undefined ? {} : { purpose }),+ });+ assert.match(textOut(result), /requires.*purpose/);+ assert.equal(events.at(-1)?.isError, true);+ }+ }+ assert.equal(started, false);+});++test("background list labels jobs by purpose and retains commands and legacy fallback", async () => {+ const current = fakeToolContext();+ const legacy = (await current.backgroundList())[0]!;+ current.backgroundList = async () => [+ { ...legacy, purpose: "Run regression tests" },+ { ...legacy, processId: "old-job" },+ ];+ const tool = createAgentTools({ current }, { sandboxResources: true }).find((t) => t.name === "sandbox")!;+ const result = textOut(await call(tool, { action: "list_processes" }));+ assert.match(result, /Run regression tests\n {2}bg: npm test/);+ assert.match(result, /old-job[^\n]*bg: npm test/);+});diff --git a/test/background-exec-broker.test.ts b/test/background-exec-broker.test.tsindex bde3752a7..bff95d487 100644--- a/test/background-exec-broker.test.ts+++ b/test/background-exec-broker.test.ts@@ -130,7 +130,7 @@ function build(opts?: { ttlMs?: number; ttlMaxMs?: number; scopeId?: string; seetest("start registers a REDACTED background row and returns an id + initial output + cursor", async () => {const { broker, registry, starts } = build();- const r = await broker.start(handle, "npm run build");+ const r = await broker.start(handle, "npm run build", "Run background tests");assert.equal(r.reattached, false);assert.ok(r.processId);assert.equal(starts.length, 1);@@ -143,13 +143,13 @@ test("start registers a REDACTED background row and returns an id + initial outptest("start does not leak the foreground turn's env to a durable background job", async () => {const { broker, starts } = build();- await broker.start({ ...handle, env: { AGENT_API_TOKEN: "turn-token" } }, "long-job");+ await broker.start({ ...handle, env: { AGENT_API_TOKEN: "turn-token" } }, "long-job", "Run background tests");assert.deepEqual(starts[0]!.opts?.env, { PYTHONUNBUFFERED: "1" });});test("write forwards data to the job's stdin and reports byte count + liveness", async () => {const { broker, writes } = build();- const r = await broker.start(handle, "aws sso login --use-device-code");+ const r = await broker.start(handle, "aws sso login --use-device-code", "Run background tests");const w = await broker.write(handle, r.processId, "ABCD-1234\n");assert.equal(w.processId, r.processId);assert.equal(w.bytes, 10);@@ -164,7 +164,7 @@ test("write to an unknown / foreign-scope job is rejected", async () => {test("start surfaces output produced during the brief initial poll (fails if the poll loop is removed)", async () => {const { broker, starts } = build({ seedOutput: "hello from the job\n" });- const r = await broker.start(handle, "echo hi; sleep 5");+ const r = await broker.start(handle, "echo hi; sleep 5", "Run background tests");assert.equal(starts.length, 1);assert.equal(r.status.state, "running");assert.match(r.output, /hello from the job/);@@ -173,7 +173,7 @@ test("start surfaces output produced during the brief initial poll (fails if thetest("poll paginates by cursor and a second poll drains the next slice past max_bytes", async () => {const { broker, appendOutput } = build();- const { processId } = await broker.start(handle, "long-job");+ const { processId } = await broker.start(handle, "long-job", "Run background tests");appendOutput(processId, "ABCDEFGHIJ");const first = await broker.poll(handle, processId, { sinceCursor: 0, maxBytes: 4 });@@ -192,7 +192,7 @@ test("poll paginates by cursor and a second poll drains the next slice past max_test("on exit, poll markStatus('exited') but does NOT delete the row (final output stays readable)", async () => {const { broker, registry, appendOutput, finish } = build();- const { processId } = await broker.start(handle, "quick-job");+ const { processId } = await broker.start(handle, "quick-job", "Run background tests");appendOutput(processId, "done\n");finish(processId, 0);@@ -207,7 +207,7 @@ test("on exit, poll markStatus('exited') but does NOT delete the row (final outptest("stop signals then re-reads status: stopped:true only when the re-read shows exited", async () => {const { broker, registry, signals } = build();- const { processId } = await broker.start(handle, "server");+ const { processId } = await broker.start(handle, "server", "Run background tests");const r = await broker.stop(handle, processId);assert.equal(signals.length, 1);@@ -219,7 +219,7 @@ test("stop signals then re-reads status: stopped:true only when the re-read showtest("stop is idempotent — re-stopping a dead pid is a no-op (still stopped:true)", async () => {const { broker } = build();- const { processId } = await broker.start(handle, "server");+ const { processId } = await broker.start(handle, "server", "Run background tests");await broker.stop(handle, processId);const again = await broker.stop(handle, processId);assert.equal(again.stopped, true);@@ -237,7 +237,7 @@ test("stop reports stopped:false while the process is still winding down", asynctermGraceMs: 30,killGraceMs: 30,});- const { processId } = await broker.start(handle, "stubborn-server");+ const { processId } = await broker.start(handle, "stubborn-server", "Run background tests");const r = await broker.stop(handle, processId);assert.equal(r.stopped, false);assert.equal(r.status.state, "running");@@ -262,7 +262,7 @@ test("stop actually waits the TERM grace: a process exiting shortly after TERM itermGraceMs: 2_000,killGraceMs: 100,});- const { processId } = await broker.start(handle, "graceful-server");+ const { processId } = await broker.start(handle, "graceful-server", "Run background tests");const r = await broker.stop(handle, processId);assert.deepEqual(signals, ["TERM"], "the grace period elapsed for real — no instant KILL escalation");@@ -277,7 +277,7 @@ test("CROSS-SCOPE GUARD: poll/stop of another scope's processId is refused (invaconst brokerA = createBackgroundBroker({ sandbox: fake.sandbox, registry, scopeId: "personal:A", pollMs: 20 });const brokerB = createBackgroundBroker({ sandbox: fake.sandbox, registry, scopeId: "personal:B", pollMs: 20 });- const { processId } = await brokerA.start(handle, "secret-job");+ const { processId } = await brokerA.start(handle, "secret-job", "Run background tests");await assert.rejects(brokerB.poll(handle, processId), /no such background job/);await assert.rejects(brokerB.stop(handle, processId), /no such background job/);await assert.rejects(brokerA.poll(handle, "p-does-not-exist"), /no such background job/);@@ -290,8 +290,8 @@ test("CROSS-SCOPE GUARD: poll/stop of another scope's processId is refused (invatest("reattach by FULL command key: a second start of the same command reattaches to ONE process", async () => {const { broker, registry, starts } = build();- const first = await broker.start(handle, "npm test");- const second = await broker.start(handle, "npm test");+ const first = await broker.start(handle, "npm test", "Run background tests");+ const second = await broker.start(handle, "npm test", "Run background tests");assert.equal(starts.length, 1, "no second startProcess");assert.equal(second.processId, first.processId);assert.equal(second.reattached, true);@@ -300,11 +300,11 @@ test("reattach by FULL command key: a second start of the same command reattachetest("start does NOT reattach to a matching command whose process has already exited", async () => {const { broker, registry, starts, appendOutput, finish } = build();- const first = await broker.start(handle, "glab auth login --device");+ const first = await broker.start(handle, "glab auth login --device", "Run background tests");appendOutput(first.processId, "Waiting for authorization...\nDevice authorization failed\n");finish(first.processId, 1);- const second = await broker.start(handle, "glab auth login --device");+ const second = await broker.start(handle, "glab auth login --device", "Run background tests");assert.equal(second.reattached, false, "an expired device-code flow must start fresh");assert.notEqual(second.processId, first.processId);assert.equal(starts.length, 2);@@ -314,8 +314,8 @@ test("start does NOT reattach to a matching command whose process has already extest("two commands sharing a long prefix do NOT reattach to each other (Bugbot rule)", async () => {const { broker, starts } = build();- const a = await broker.start(handle, "npm test -- --grep alpha");- const b = await broker.start(handle, "npm test -- --grep beta");+ const a = await broker.start(handle, "npm test -- --grep alpha", "Run background tests");+ const b = await broker.start(handle, "npm test -- --grep beta", "Run background tests");assert.notEqual(a.processId, b.processId);assert.equal(b.reattached, false);assert.equal(starts.length, 2);@@ -324,7 +324,11 @@ test("two commands sharing a long prefix do NOT reattach to each other (Bugbot rtest("a known injected env value in the command is stored value-masked", async () => {const { broker, registry } = build();const envHandle: SandboxHandle = { ...handle, env: { GITHUB_TOKEN: "ghp_secretvalue12345" } };- await broker.start(envHandle, "git clone https://x:[email protected]/org/repo.git");+ await broker.start(+ envHandle,+ "git clone https://x:[email protected]/org/repo.git",+ "Run background tests",+ );const row = (await registry.listByScope(SCOPE))[0]!;assert.ok(!row.command.includes("ghp_secretvalue12345"), `leaked in: ${row.command}`);assert.match(row.command, /<redacted:GITHUB_TOKEN>/);@@ -332,8 +336,8 @@ test("a known injected env value in the command is stored value-masked", async (test("whitespace is normalized before keying so spacing differences reattach to one job", async () => {const { broker, starts } = build();- const a = await broker.start(handle, "npm run build");- const b = await broker.start(handle, "npm run build");+ const a = await broker.start(handle, "npm run build", "Run background tests");+ const b = await broker.start(handle, "npm run build", "Run background tests");assert.equal(a.processId, b.processId);assert.equal(starts.length, 1);});@@ -341,19 +345,19 @@ test("whitespace is normalized before keying so spacing differences reattach totest("a secret-bearing command is stored REDACTED but does NOT reattach (a redacted key aliases distinct secrets)", async () => {const { broker, registry, starts } = build();const cmd = "deploy --token sekret123 --target prod";- await broker.start(handle, cmd);+ await broker.start(handle, cmd, "Run background tests");const row = (await registry.listByScope(SCOPE))[0]!;assert.equal(row.command, redactCommand("bg: deploy --token sekret123 --target prod"));assert.match(row.command, /<redacted>/);- const again = await broker.start(handle, cmd);+ const again = await broker.start(handle, cmd, "Run background tests");assert.equal(again.reattached, false);assert.equal(starts.length, 2);});test("two commands differing only in a redacted secret VALUE launch TWO distinct jobs (no alias reattach)", async () => {const { broker, starts } = build();- const a = await broker.start(handle, "deploy --token AAA --target prod");- const b = await broker.start(handle, "deploy --token BBB --target prod");+ const a = await broker.start(handle, "deploy --token AAA --target prod", "Run background tests");+ const b = await broker.start(handle, "deploy --token BBB --target prod", "Run background tests");assert.notEqual(a.processId, b.processId);assert.equal(b.reattached, false);assert.equal(starts.length, 2);@@ -361,10 +365,10 @@ test("two commands differing only in a redacted secret VALUE launch TWO distincttest("liveness probe: a row whose backend process is gone is deleted and a fresh process launched", async () => {const { broker, registry, starts, vanish } = build();- const first = await broker.start(handle, "long-build");+ const first = await broker.start(handle, "long-build", "Run background tests");vanish(first.processId);- const second = await broker.start(handle, "long-build");+ const second = await broker.start(handle, "long-build", "Run background tests");assert.equal(second.reattached, false, "stale row dropped → a fresh launch, not a reattach");assert.notEqual(second.processId, first.processId);assert.equal(starts.length, 2);@@ -375,11 +379,11 @@ test("liveness probe: a row whose backend process is gone is deleted and a freshtest("liveness probe: a transient backend error preserves the running process and registry row", async () => {const { broker, registry, starts, failNextRead } = build();- const first = await broker.start(handle, "long-build");+ const first = await broker.start(handle, "long-build", "Run background tests");const error = new Error("backend unavailable");failNextRead(first.processId, error);- await assert.rejects(broker.start(handle, "long-build"), error);+ await assert.rejects(broker.start(handle, "long-build", "Run background tests"), error);assert.equal(starts.length, 1);assert.equal((await registry.get(first.processId))?.status, "running");});@@ -388,7 +392,7 @@ test("TTL clamp: a requested lifetime above the max is clamped (mirrors PR C's cconst ttlMaxMs = 60 * 60_000;const { broker, registry } = build({ ttlMs: 30 * 60_000, ttlMaxMs });const before = Date.now();- const r = await broker.start(handle, "huge-job", 10 * 60 * 60_000);+ const r = await broker.start(handle, "huge-job", "Run background tests", 10 * 60 * 60_000);const row = await registry.get(r.processId);assert.ok(row);assert.ok(row!.expiresAt <= before + ttlMaxMs + 1000);@@ -399,7 +403,7 @@ test("TTL default: omitting a lifetime uses the configured default", async () =>const ttlMs = 30 * 60_000;const { broker, registry } = build({ ttlMs, ttlMaxMs: 60 * 60_000 });const before = Date.now();- const r = await broker.start(handle, "default-ttl-job");+ const r = await broker.start(handle, "default-ttl-job", "Run background tests");const row = await registry.get(r.processId);assert.ok(row!.expiresAt >= before + ttlMs - 1000);assert.ok(row!.expiresAt <= before + ttlMs + 1000);@@ -407,8 +411,8 @@ test("TTL default: omitting a lifetime uses the configured default", async () =>test("list reports the scope's background jobs from the registry (id, status, startedAt, command)", async () => {const { broker, finish } = build();- const a = await broker.start(handle, "job-a");- const b = await broker.start(handle, "job-b");+ const a = await broker.start(handle, "job-a", "Run background tests");+ const b = await broker.start(handle, "job-b", "Run background tests");finish(b.processId, 0);await broker.poll(handle, b.processId);@@ -422,8 +426,8 @@ test("list reports the scope's background jobs from the registry (id, status, sttest("list distinguishes a TTL-reaped row from a clean exit (registry view, not 'exited 0')", async () => {const { broker, registry } = build();- const clean = await broker.start(handle, "clean-job");- const killed = await broker.start(handle, "ttl-job");+ const clean = await broker.start(handle, "clean-job", "Run background tests");+ const killed = await broker.start(handle, "ttl-job", "Run background tests");await registry.markStatus(killed.processId, "reaped");const byId = new Map((await broker.list()).map((j) => [j.processId, j]));@@ -444,11 +448,11 @@ test("start stamps the conversation's sessionRef on the registry row", async ()sessionRef: "web:U1:thread-9",pollMs: 20,});- const { processId } = await broker.start(handle, "sleep 60");+ const { processId } = await broker.start(handle, "sleep 60", "Run background tests");assert.equal((await registry.get(processId))?.sessionRef, "web:U1:thread-9");const bare = createBackgroundBroker({ sandbox: fake.sandbox, registry, scopeId: SCOPE, pollMs: 20 });- const { processId: p2 } = await bare.start(handle, "sleep 61");+ const { processId: p2 } = await bare.start(handle, "sleep 61", "Run background tests");assert.equal((await registry.get(p2))?.sessionRef, undefined);});@@ -468,8 +472,8 @@ test("background jobs retain sandbox identity across default changes and reattacreturn id === a.resourceId ? a : b;},});- const first = await broker.start(a, "work");- const second = await broker.start(b, "work");+ const first = await broker.start(a, "work", "Run background tests");+ const second = await broker.start(b, "work", "Run background tests");assert.notEqual(first.processId, second.processId);assert.equal((await registry.get(first.processId))?.sandboxId, a.resourceId);assert.equal((await broker.handleFor!(first.processId))?.id, a.id);@@ -478,3 +482,25 @@ test("background jobs retain sandbox identity across default changes and reattacawait broker.stop(b, first.processId);assert.deepEqual(selected, [a.resourceId, a.resourceId, a.resourceId, a.resourceId]);});++test("start requires a purpose before launching, and persists a trimmed, redacted label", async () => {+ const { sandbox, starts } = fakeSandbox();+ const registry = createMemoryProcessRegistry();+ const broker = createBackgroundBroker({ sandbox, registry, scopeId: SCOPE, pollMs: 0 });+ for (const purpose of [undefined, "", " \n "]) {+ await assert.rejects(broker.start(handle, "node server.js", purpose as string), /requires a short purpose/);+ }+ assert.equal(starts.length, 0);+ const result = await broker.start(+ { ...handle, env: { TOKEN: "secretvalue12345" } },+ "node server.js",+ " Preview\nsecretvalue12345 server ",+ );+ const row = await registry.get(result.processId);+ assert.equal(row?.purpose, redactCommand("Preview secretvalue12345 server", { TOKEN: "secretvalue12345" }));+ assert.equal(row?.command, "bg: node server.js");+ assert.equal((await broker.list())[0]?.purpose, row?.purpose);+ await broker.start(handle, "node server.js", "Another description");+ assert.equal(starts.length, 1, "labels must not alter command-based reattachment");+ assert.equal((await registry.get(result.processId))?.purpose, row?.purpose);+});diff --git a/test/background-tool-context.test.ts b/test/background-tool-context.test.tsindex 7ef1227a6..fcaa580c6 100644--- a/test/background-tool-context.test.ts+++ b/test/background-tool-context.test.ts@@ -84,7 +84,10 @@ test("backgroundStart routes a denied command to CommandDenied BEFORE the brokerrules: [{ pattern: "rm\\s+-rf", decision: "deny", reason: "destructive" }],}),});- await assert.rejects(ctx.backgroundStart("rm -rf /"), (e) => e instanceof CommandDenied);+ await assert.rejects(+ ctx.backgroundStart("rm -rf /", { purpose: "Run background tests" }),+ (e) => e instanceof CommandDenied,+ );assert.equal(calls.start, 0, "the broker must not be reached for a denied command");});@@ -97,7 +100,10 @@ test("backgroundStart routes a require_approval command to NeedsApproval BEFORErules: [{ pattern: "deploy prod", decision: "require_approval", reason: "prod" }],}),});- await assert.rejects(ctx.backgroundStart("deploy prod"), (e) => e instanceof NeedsApproval);+ await assert.rejects(+ ctx.backgroundStart("deploy prod", { purpose: "Run background tests" }),+ (e) => e instanceof NeedsApproval,+ );assert.equal(calls.start, 0);});@@ -111,7 +117,7 @@ test("an already-approved require_approval command DOES reach the broker", asyncrules: [{ pattern: "deploy prod", decision: "require_approval", reason: "prod" }],}),});- await ctx.backgroundStart("deploy prod");+ await ctx.backgroundStart("deploy prod", { purpose: "Run background tests" });assert.equal(calls.start, 1);});@@ -120,10 +126,14 @@ test("ledger replay: a start result is CACHED — a crash-replay returns the samconst { broker, calls } = recordingBroker();const run = "run-1";- const first = await ctxFor({ backgroundBroker: broker, ledger, runId: run }).backgroundStart("npm test");+ const first = await ctxFor({ backgroundBroker: broker, ledger, runId: run }).backgroundStart("npm test", {+ purpose: "Run background tests",+ });assert.equal(calls.start, 1);- const replay = await ctxFor({ backgroundBroker: broker, ledger, runId: run }).backgroundStart("npm test");+ const replay = await ctxFor({ backgroundBroker: broker, ledger, runId: run }).backgroundStart("npm test", {+ purpose: "Run background tests",+ });assert.equal(calls.start, 1, "no second startProcess on replay");assert.deepEqual(replay, first);});@@ -174,7 +184,7 @@ test("callIndex advances on every once() — a non-cached poll between two cacheconst run = "run-5";const ctx1 = ctxFor({ backgroundBroker: broker, ledger, runId: run });- await ctx1.backgroundStart("npm test");+ await ctx1.backgroundStart("npm test", { purpose: "Run background tests" });setPollState("running");await ctx1.backgroundPoll("p-1");setPollState("exited");@@ -184,7 +194,7 @@ test("callIndex advances on every once() — a non-cached poll between two cachesetPollState("exited");const ctx2 = ctxFor({ backgroundBroker: broker, ledger, runId: run });- await ctx2.backgroundStart("npm test");+ await ctx2.backgroundStart("npm test", { purpose: "Run background tests" });await ctx2.backgroundPoll("p-1");await ctx2.backgroundPoll("p-1");assert.equal(calls.start, 1, "start stayed cached across replay (deterministic key)");@@ -195,7 +205,7 @@ test("off-Fly degradation: with NO broker the four mutating methods throw the 'uconst ctx = ctxFor({});const guidance = /isn't available.*execute/s;- await assert.rejects(ctx.backgroundStart("npm test"), guidance);+ await assert.rejects(ctx.backgroundStart("npm test", { purpose: "Run background tests" }), guidance);await assert.rejects(ctx.backgroundPoll("p-1"), guidance);await assert.rejects(ctx.backgroundStop("p-1"), guidance);await assert.rejects(ctx.backgroundWrite("p-1", "ABCD-1234\n"), guidance);diff --git a/test/monitor-broker.test.ts b/test/monitor-broker.test.tsindex 1a27949c2..de802c9e8 100644--- a/test/monitor-broker.test.ts+++ b/test/monitor-broker.test.ts@@ -22,6 +22,7 @@ async function harness(readOutputTail: ReadOutputTail = async () => ({ outputTaiscopeId: SCOPE,kind: "background",command: "bg: npm test",+ purpose: "Run regression tests",ttlMs: 60_000,});const broker = createMonitorBroker({@@ -52,6 +53,7 @@ test("watch arms a monitor inheriting the turn's owner, scope, thread, and destiassert.equal(m?.pattern, "FAIL");assert.equal(m?.instructions, "summarize failures");assert.equal(m?.command, "bg: npm test");+ assert.equal(m?.purpose, "Run regression tests");});test("watching the same job in the same thread twice reattaches instead of double-arming", async () => {diff --git a/test/monitor-poller.test.ts b/test/monitor-poller.test.tsindex 85160a278..e23c91b9c 100644--- a/test/monitor-poller.test.ts+++ b/test/monitor-poller.test.ts@@ -519,3 +519,15 @@ test("an unwatch between the tick snapshot and the poll is honored", async () =>assert.equal((await h.monitors.get(fired.id))?.enabled, true);assert.equal(await h.monitors.get(victim.id), null);});++test("watch wakes and Slack notices use the saved purpose with a legacy command fallback", async () => {+ for (const purpose of [undefined, "Run regression tests"]) {+ const h = await harness({ result: { status: "refused", reason: "rate limit exceeded" } });+ await h.arm(purpose ? { purpose } : {});+ h.append("p-1", "compiling...\n");+ await h.poller.tick();+ assert.ok(h.calls[0]?.text.includes(purpose ?? "bg: npm run build"));+ const notices = await h.deliveries.pending("slack");+ assert.ok(notices[0]?.text.includes(purpose ?? "bg: npm run build"));+ }+});diff --git a/test/process-registry.test.ts b/test/process-registry.test.tsindex feeb68575..8be08d40f 100644--- a/test/process-registry.test.ts+++ b/test/process-registry.test.ts@@ -103,6 +103,7 @@ test("[postgres] honors the registry contract (durable across a restart)", { skiscopeId: scope,kind: "dev-server",command: "npm run dev",+ purpose: "Preview app server",ttlMs: 60_000,});assert.equal(rec.status, "running");@@ -113,6 +114,7 @@ test("[postgres] honors the registry contract (durable across a restart)", { skiassert.equal(live.length, 1);assert.equal(live[0]!.processId, id(1));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 });assert.equal(@@ -131,3 +133,19 @@ function id(n: number): string {const s = n.toString(16).padStart(12, "0");return `00000000-0000-0000-0000-${s}`;}++test("registry preserves purpose without replacing the command and accepts legacy rows", async () => {+ const registry = createMemoryProcessRegistry();+ for (const purpose of [undefined, "Preview app server"]) {+ const row = await registry.register({+ processId: purpose ?? "legacy",+ scopeId: "personal:U1",+ kind: "background",+ command: "bg: node server.js",+ ttlMs: 60_000,+ ...(purpose ? { purpose } : {}),+ });+ assert.equal((await registry.get(row.processId))?.purpose, purpose);+ assert.equal((await registry.get(row.processId))?.command, "bg: node server.js");+ }+});diff --git a/test/sandbox-open-continuity.test.ts b/test/sandbox-open-continuity.test.tsindex ded6250c1..fb46f50f9 100644--- a/test/sandbox-open-continuity.test.ts+++ b/test/sandbox-open-continuity.test.ts@@ -313,11 +313,14 @@ test("Open personal credentials never flow into another shared computer", asynctest("background starts use the authorized personal target and recheck revocation", async () => {const f = fixture();- await f.tools.backgroundStart("node work.js", { sandboxId: "personal-box" });+ await f.tools.backgroundStart("node work.js", { purpose: "Run background tests", sandboxId: "personal-box" });assert.equal(f.starts[0]?.scopeId, "personal:alice");assert.equal(f.starts[0]?.env, undefined);f.state.member = false;- await assert.rejects(f.tools.backgroundStart("node work.js", { sandboxId: "personal-box" }), /authorized/);+ await assert.rejects(+ f.tools.backgroundStart("node work.js", { purpose: "Run background tests", sandboxId: "personal-box" }),+ /authorized/,+ );});test("untrusted background authority and copying room command credentials are refused", async () => {@@ -338,7 +341,9 @@ test("target command denials and approvals apply before either execution path caconst f = fixture();f.state.targetPolicy = { mode: "denylist", rules: [{ pattern: "blocked", decision }] };await assert.rejects(f.tools.execute("blocked", { sandboxId: "personal-box" }));- await assert.rejects(f.tools.backgroundStart("blocked", { sandboxId: "personal-box" }));+ await assert.rejects(+ f.tools.backgroundStart("blocked", { purpose: "Run background tests", sandboxId: "personal-box" }),+ );assert.deepEqual(f.provisions, []);}});@@ -404,17 +409,23 @@ test("two requiring policies produce one target-qualified one-shot approval", asf.state.sourcePolicy = { mode: "denylist", rules: [{ pattern: "protected", decision: "require_approval" }] };f.state.targetPolicy = { mode: "denylist", rules: [{ pattern: "command", decision: "require_approval" }] };let approvalKey = "";- await assert.rejects(f.tools[method]("protected command", { sandboxId: "personal-box" }), (err: unknown) => {- assert.ok(err instanceof NeedsApproval);- assert.deepEqual(err.grantModes, { session: false, always: false });- approvalKey = err.approvalKey!;- assert.deepEqual(JSON.parse(approvalKey.slice("sandbox:".length)), ["personal:alice", "protected", "command"]);- return true;- });+ await assert.rejects(+ f.tools[method]("protected command", { purpose: "Run background tests", sandboxId: "personal-box" }),+ (err: unknown) => {+ assert.ok(err instanceof NeedsApproval);+ assert.deepEqual(err.grantModes, { session: false, always: false });+ approvalKey = err.approvalKey!;+ assert.deepEqual(JSON.parse(approvalKey.slice("sandbox:".length)), ["personal:alice", "protected", "command"]);+ return true;+ },+ );assert.deepEqual(f.approvalCalls, [[approvalKey, true]]);f.approve(approvalKey);- await f.tools[method]("protected command", { sandboxId: "personal-box" });- await assert.rejects(f.tools[method]("protected command", { sandboxId: "personal-box" }), NeedsApproval);+ await f.tools[method]("protected command", { purpose: "Run background tests", sandboxId: "personal-box" });+ await assert.rejects(+ f.tools[method]("protected command", { purpose: "Run background tests", sandboxId: "personal-box" }),+ NeedsApproval,+ );}});diff --git a/test/sandbox-resources.test.ts b/test/sandbox-resources.test.tsindex 40ca24dba..12fd9ce6b 100644--- a/test/sandbox-resources.test.ts+++ b/test/sandbox-resources.test.ts@@ -696,7 +696,7 @@ test("retirement waits for background startup to commit its live registry row",return register(row);};const broker = createBackgroundBroker({ sandbox: router, registry, scopeId: "personal:alice", pollMs: 0 });- const starting = broker.start(handle, "sleep 60");+ const starting = broker.start(handle, "sleep 60", "Run background tests");await entering.promise;let destroyed = false;backend.destroyScope = async () => {@@ -730,7 +730,7 @@ test("failed background registration kills its process and releases the resourcesignals.push(`${id}:${signal}`);};const broker = createBackgroundBroker({ sandbox: router, registry, scopeId: "personal:alice", pollMs: 0 });- await assert.rejects(broker.start(handle, "sleep 60"), /registry unavailable/);+ await assert.rejects(broker.start(handle, "sleep 60", "Run background tests"), /registry unavailable/);assert.deepEqual(signals, ["unregistered:KILL"]);await resources.retire("alice", record.id);assert.equal((await resources.get(record.id)).cleanupPending, false);diff --git a/test/sessions-background-activity.test.ts b/test/sessions-background-activity.test.tsindex 4972f0c4d..922aab110 100644--- a/test/sessions-background-activity.test.ts+++ b/test/sessions-background-activity.test.ts@@ -118,13 +118,14 @@ test("sessionBackground spells the badge out for the viewer — and stays invisiconst r = await app.turn(dm("start the job", thread));const sessionId = r.sessionId!;- await processes!.register(registryRow("p-1", thread));+ await processes!.register({ ...registryRow("p-1", thread), purpose: "Preview app server" });await monitors.create(watchInput(thread, { pattern: "error|FAILED", instructions: "summarize failures" }));const view = await app.sessionBackground(sessionId, "U1");assert.equal(view?.jobs.length, 1);assert.equal(view?.jobs[0]?.processId, "p-1");assert.equal(view?.jobs[0]?.command, "sleep 600");+ assert.equal(view?.jobs[0]?.purpose, "Preview app server");assert.ok((view?.jobs[0]?.expiresAt ?? 0) > Date.now(), "jobs carry their TTL deadline");assert.equal(view?.watches.length, 1);assert.equal(view?.watches[0]?.pattern, "error|FAILED");diff --git a/test/skill-tool.test.ts b/test/skill-tool.test.tsindex fdcb68c95..6f7f2327b 100644--- a/test/skill-tool.test.ts+++ b/test/skill-tool.test.ts@@ -70,7 +70,7 @@ test("execute, read, write and background never trigger skill synchronization",});await tc.execute("cd skills/google-workspace && python scripts/gmail.py");await tc.read("skills/google-workspace/SKILL.md");- await tc.backgroundStart("sh skills/.packs/selected/job.sh");+ await tc.backgroundStart("sh skills/.packs/selected/job.sh", { purpose: "Run background tests" });assert.equal(loads, 0);assert.equal(calls.length, 2);});