test(restart-chaos): add hosted mode for the release-swap proof on a real staging instance (#21153)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Hosted instances take an automatic release about every 40 minutes as
an overlap swap: a new server starts beside the old one, both serve for
a while, then the old one stops
> - The restart-chaos harness (`tests/restart-chaos/`) proves release
swaps only on servers it starts locally, with the release-swap cell RS1
(#21126) and the staging-mix workload (#21125)
> - The zero-downtime finish line needs the same proof on a real hosted
staging instance across real releases, with the same per-task grade
> - This pull request adds a hosted mode: the harness starts no server
and injects no fault; it runs the staging mix against one allowed hosted
instance through its API, detects each real release from `/api/health`,
and grades every started task with the RS1 grade module
> - The benefit is one comparable number per hosted run (`tasks
completed without human action / tasks started`) plus per-release
continuity, with no database access and no risk to other instances

## Linked Issues or Issue Description

Refs #21126
Refs #21125
Refs #21139

**Is your feature request related to a problem? Please describe.**
The release-swap proof runs only against local servers. It cannot show
what a real hosted instance does across its own automatic releases.

**Describe the solution you'd like**
A hosted mode in the harness. It takes one explicitly allowed staging or
test host, signs in with an existing board token, creates labelled test
agents and tasks, watches real releases through `/api/health`, grades
every task with the RS1 grade, reports web and API continuity, and
removes what it created.

**Describe alternatives you've considered**
Reading the hosted database directly. That needs production-grade
database credentials and gives a second, different collector. The API
path uses the same access a person has and reports the fields the API
cannot supply as unavailable.

## What Changed

- `hosted-guard.ts`: refuses to start unless `--hosted-base-url` is a
bare `https://` origin and `--hosted-allow` names the same host. Only
one stack under `.staging.paperclip.app` or `.test.paperclip.app` is
accepted. The shared staging instance, production, the fleet admin and
Cloud hosts are always refused. Every request is checked against that
origin before it is sent.
- `hosted-api.ts`: a bearer-token API client (token from
`PAPERCLIP_HOSTED_TOKEN` or the CLI store, never printed) that logs
every request for continuity, retries only reads, and a `/api/health`
probe.
- `hosted-release.ts`: pure release detection over health samples. It
reports each release's overlap window (two process identities
answering), failed and slow requests, time to the first answer from the
new build, its shape (`overlap`, `stop_then_start`, `clean_switch`) and
probe continuity (requests, failures, longest gap).
- `hosted-readers.ts`, `hosted-grade.ts`: API-backed readers for runs,
tasks, task views, pending questions and approvals, failure chains, next
events and duplicated comments and subtasks. The grade calls
`gradeReleaseSwapTask`, `summarizeGrades`, `swapMetrics` and
`releaseSwapMarkdown` from `release-swap-grade.ts` (#21126), clicks
Retry where the board offers it, and labels each failure. Fields the API
cannot supply (queued wakes, the owning server process, runs lost while
the old server lived, double executors, late-start and preparation
probes) are listed as unavailable.
- `hosted-setup.ts`: works in the signed-in user's company (Cloud
refuses company creation). Creates one labelled project, one labelled
agent per adapter and one labelled secret per provider key through the
normal APIs. Cleanup pauses and removes the agents, cancels their live
runs, hides their tasks, deletes the secrets and archives the project.
It touches only names that carry the run label.
- `hosted-workload.ts`: drives the staging-mix tasks from
`staging-mix.ts` (#21125) at `--hosted-concurrency` (default 5), posts
follow-ups during runs, and clicks an offered Retry once per failed run.
- `hosted.ts`, `hosted-config.ts`, `hosted-main.ts`: the entry point,
options, `--hosted-observe-only` (read-only release watch),
`--hosted-cleanup-only`, and the run. `main.ts` and `supervisor.ts` are
unchanged.
- Hands-off grading (`hosted-handsoff.ts`, `hosted-workload.ts`): no
Retry click during the wave or the settle period. Each task records when
a Retry banner first showed and whether it cleared by itself. After the
settle period the harness clicks Retry once on tasks that are not done
and records whether it worked. `SUMMARY.md` starts with `<pass> /
<started> tasks completed hands-off`, `Retry banner shown: <n>` and
`Retry worked / clicked: <w> / <c>`. `--hosted-retry-during-wave` keeps
the old behavior.
- Assigned-work invariant: the grade reads `GET
/api/companies/:id/assigned-work-invariant` once (from #21139) and
reports the company's violation counts and the sampled violations and
stalled slots of this run. A 404 on an older build is reported as not
available.
- `README.md`: a Hosted mode section with commands, the guard, sign-in,
setup, detection, grade, unavailable fields and cleanup.

## Verification

- `node server/node_modules/vitest/vitest.mjs run --config
tests/restart-chaos/vitest.config.ts
tests/restart-chaos/hosted-*.test.ts
tests/restart-chaos/release-swap-grade.test.ts`: 52 tests pass (38
hosted tests). They cover the host guard (allowed host, mismatched allow
flag, the shared staging instance, production, fleet admin, Cloud and
look-alike hosts, a userinfo trick in a route), token lookup, release
detection (overlap, stop-then-start, a restart on the same commit,
unsettled release, continuity), the API readers, the end-to-end API
grade with a Retry click and labels, the workload, and label-only
cleanup.
- `node server/node_modules/typescript/bin/tsc -p
tests/restart-chaos/tsconfig.json`: clean.
- Run without a token: the harness stops before any request and names
the missing sign-in. Run against the shared staging host: refused by the
guard.
- `pnpm verify` asks for broader CI coverage (exit 2, README is a global
CI input); required CI supplies it.
- Known failures on master, outside this diff:
`server/src/__tests__/storage-s3-multipart-throttle.test.ts` ("halves
new parts in flight once when a parallel burst of parts is throttled",
expected 3 to be 4) also fails on master and is being fixed separately.
`packages/paperclip-runner`
`src/drivers/acpx/native-distribution-integrity.test.ts` ("expires a
real ACPX permission on native child death without replaying its
mutation") is in the Runner package; this PR changes only
`tests/restart-chaos/`.
- Live smoke on one hosted staging instance (2 tasks): setup, workload,
grade and cleanup ran end to end. It showed two harness defects, now
fixed: an activity window that was too short for 90 s tool rounds, and
agent removal that needed termination first.
- Not run here: a hosted run across real releases (none reached the
instance during this work).

## Risks

- Low risk to the product: harness-only, no product code changes.
- The run writes to one hosted instance. The guard, the per-request
origin check and the label filter limit it to that instance and to
objects it created.
- The grade over the API cannot see queued wakes. A task whose only
owner is a queued wake grades as having no owner. The report says so.
- #21125 and #21126 are on master; this branch merges master and adds
only hosted files and the README section.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used through Claude
Code with tool use (shell, file edits). Default context window; no
extended thinking mode.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
DottaandClaude Opus 5.5 authored and GitHub committed 2026-11-12 13:19:20 -06:00
1 parent ef6d347f79
commit 6a24b417c0
18 files changed
+2033

No files matched your search

+107
View File
@@ -641,6 +641,112 @@ every grade, every failed run with its error code, message and last error events
probes, and the duplicates: two runs of one task executing at once, two Runner processes for one run, repeated
identical agent comments and repeated subtask titles. The wave fails unless every task passed.
## Hosted mode (`--hosted-base-url`, `--hosted-allow`)
```sh
set -a; source ~/.secrets; set +a
H=<name>.staging.paperclip.app
# Read-only: watch one release of the instance (GET /api/health every 2 s) and report its shape. No writes.
node cli/node_modules/tsx/dist/cli.mjs tests/restart-chaos/hosted.ts --hosted-base-url https://$H --hosted-allow $H --hosted-observe-only
# Smoke: 2 tasks, no release wait, 1-minute settle, then cleanup.
node cli/node_modules/tsx/dist/cli.mjs tests/restart-chaos/hosted.ts --hosted-base-url https://$H --hosted-allow $H \
--hosted-releases 0 --hosted-tasks 2 --hosted-turn-minutes 3 --hosted-label rc-hosted-smoke1
# A run across 3 real releases at 5 concurrent (default), then the same at 15.
node cli/node_modules/tsx/dist/cli.mjs tests/restart-chaos/hosted.ts --hosted-base-url https://$H --hosted-allow $H --hosted-releases 3 --hosted-label rc-hosted-r3c5
node cli/node_modules/tsx/dist/cli.mjs tests/restart-chaos/hosted.ts --hosted-base-url https://$H --hosted-allow $H --hosted-releases 3 --hosted-concurrency 15 --hosted-label rc-hosted-r3c15
# Remove everything one run created (also run automatically at the end of every run unless --hosted-keep).
node cli/node_modules/tsx/dist/cli.mjs tests/restart-chaos/hosted.ts --hosted-base-url https://$H --hosted-allow $H --hosted-cleanup-only --hosted-label rc-hosted-r3c5
```
Hosted mode runs the release-swap proof against a real hosted instance that takes automatic releases, instead of
servers the harness starts. It starts no server and injects no fault: each release the instance's own continuous
deploy rolls out is a swap.
**Target guard** (`hosted-guard.ts`). The harness refuses to start unless `--hosted-base-url` is a bare `https://`
origin and `--hosted-allow` names the same host. The host must be one stack under `.staging.paperclip.app` or
`.test.paperclip.app`. `paperclip.staging.paperclip.app`, production hosts, the fleet admin and Cloud hosts are
refused even when allowed explicitly. Every request is checked against that one origin before it is sent.
**Sign-in.** The harness uses a board token for the host: `PAPERCLIP_HOSTED_TOKEN`, or
`credentials["https://<host>"].token` in `~/.paperclip/auth.json` (the CLI's store). It never prints the token.
Hosted stacks sit behind the Cloud tenant gateway, which answers every request without a session, including
`/api/health` and the CLI's `POST /api/cli-auth/challenges`, with `401 tenant_session_required`. So
`paperclipai auth login --api-base https://<host>` cannot start there. A person who can sign in to the instance must
create the challenge from a signed-in browser tab, approve it, and store the token. Without a token, hosted mode
stops before any request.
**Setup** (`hosted-setup.ts`). Company creation is managed by Cloud, so the run works inside the signed-in user's
company (`--hosted-company <id>` when there are several). Everything it creates carries the run label
(`--hosted-label`, default `rc-hosted-<UTC minute>`): one project `Restart chaos <label>`, one agent per adapter
`RC <label> <adapter>`, and one company secret per provider key, `restart-chaos <label> <KEY>`. The keys come from
the harness's own environment (source `~/.secrets` first) and go to the instance only through its secrets API. The
default mix is OpenCode only (`--hosted-ratio opencode=100`, DeepSeek through OpenRouter), so the only stored key is
`OPENROUTER_API_KEY`; adding `codex` or `claude` to the ratio also stores `OPENAI_API_KEY` or `ANTHROPIC_API_KEY`.
The agents use the company's one sandbox environment (`--hosted-environment <id>` when there are several), the
warm Runner lifecycle, and `maxConcurrentRuns` split by the ratio. `results/hosted-<label>/hosted-state.json` keeps
the ids.
**Workload** (`hosted-workload.ts`). Staging-mix tasks (`staging-mix.ts`): rounds of a foreground tool command for
the seeded turn length (`--hosted-turn-minutes`, default 5–15), parents with two subtasks (`--hosted-subtask-share`,
default 30%), and board follow-up comments during a run (`--hosted-follow-up-share`, default 50%). The harness keeps
`--hosted-concurrency` tasks (default 5, at most 30) in flight. A task stops counting as in flight when it is done,
cancelled, blocked or in review, or has had no live run for 10 minutes. Grading is hands-off: the harness never
clicks Retry during the wave or the settle period. It records, per task, when a Retry banner first showed and whether
it cleared by itself. `--hosted-retry-during-wave` restores the old behavior of clicking an offered Retry at once. Tasks keep arriving until the `--hosted-releases`-th release (default 3)
is detected, then the run waits for it to settle. `--hosted-releases 0` runs a fixed batch (`--hosted-tasks`) with no
release wait, for a smoke. `--hosted-max-hours` (default 8) bounds the wait.
**Release detection** (`hosted-release.ts`). A probe reads `/api/health` every `--hosted-health-seconds` (default 2)
and records each answer's `serverInfo.processStartedAt` and `commit`. A new process identity is a release. For each
release the report gives:
- the window in which two process identities answered (the overlap);
- the failed and slow (2 s or more) health requests from the last answer of the old build only until 60 s after the
window;
- the time to the first answer from the new build;
- whether the commit changed.
A release is `overlap` when both builds answered and no request failed, and `stop_then_start` when requests failed
before the new build answered. `--hosted-observe-only` does only this, read-only, for `--hosted-releases` releases
(default 1), and writes the table to `SUMMARY.md`.
**Grade** (`hosted-grade.ts`, `hosted-readers.ts`). After the last release, the settle period (`--hosted-settle-minutes`,
default 15) and a bounded drain (`--hosted-drain-minutes`), every started task of the run's agents is graded once
with `gradeReleaseSwapTask` and `summarizeGrades` from `release-swap-grade.ts`, the same module as RS1. After the
settle period the harness clicks Retry once on each task that is not done and offers it, and records whether it
worked. A task that completed with no click passes. `SUMMARY.md` starts with three numbers:
`<pass> / <started> tasks completed hands-off`, `Retry banner shown: <n>` and `Retry worked / clicked: <w> / <c>`.
The next line gives the instance's assigned-work invariant (`GET /api/companies/:id/assigned-work-invariant`), read
once: the company's violation counts by clause and agents with stalled slots, and the sampled violations and stalled
slots that belong to this run. Builds without the endpoint answer 404, and the line says the invariant is not
available. Each failing task
carries one label: `nothing pending`, `blocked for a non-person reason` or `needed Retry` (with whether the click
worked). Retry is clicked through the API where the board offers it, as in RS1. Everything RS1 reads from Postgres
comes from the API here: runs from `/api/companies/:id/heartbeat-runs`, tasks from the issue list filtered to the
run's agents, the task view from `/api/issues/:id`, pending questions and approvals from the task's interactions and
approvals, failure chains and next events from `/api/heartbeat-runs/:id/events`, and duplicated comments and
subtasks from comments and the issue list. Per release the table counts failed runs and the time from the old
build's last answer to each surviving run's next event. Web and API continuity are reported for both the health
probe and every API request the harness made: requests, failures (any answer that is not 2xx, or no answer), slow
answers and the longest gap between successful answers. Runs come from the company run list, or from every task's
run list when that list is full, so no task's early runs are lost. A queued or running run with no activity for 5
minutes is not a live owner, the same window the drain uses.
These fields are unavailable over the API and are reported as unavailable, not guessed:
| Field | Why |
| --- | --- |
| queued wakes | no API read of a task's queued wake requests; a task resting only on a queued wake grades as having no owner |
| owning server process of a run, and runs lost while the old server was alive | the API does not expose a run's controller boot |
| double executors | needs database cross-server evidence |
| late start on the old server, preparation during recovery | the harness does not drive the release, so it cannot place probes on the outgoing server |
**Cleanup.** At the end of every run (unless `--hosted-keep`), and with `--hosted-cleanup-only --hosted-label <label>`:
pause the run's agents, cancel their queued and running runs (which releases their sandboxes), archive (hide) their
tasks, terminate and remove the agents (an agent with cost history stays terminated, as the product requires), delete
the run's secrets, and archive its project. A setup that fails part-way is cleaned up from `hosted-state.json`. Only objects whose name carries the
label are touched.
## Absolute symlink in the workspace (F1)
```sh
@@ -1792,6 +1898,7 @@ re-arms the task's own triggered faults instead of using their offsets.
| `daytona-runner-logs.ts` | K15 on Daytona: read-only capture of each wave sandbox's Runner stderr log, identity, state and process, memory and OOM evidence. |
| `daytona-sweep.ts` | Daytona R6: read-only reconciliation of this wave's labelled sandboxes with leases; cleanup only through Paperclip. |
| `staging-mix.ts`, `staging-mix-run.ts` | `--workload staging-mix`: options, the seeded plan (adapters, arrivals, fault slots), the SM task and its oracle, the follow-up and Retry step with the overlap probe, the arrival gate and the resource guard. |
| `hosted.ts`, `hosted-*.ts` | Hosted mode (entry point `hosted.ts`): target guard, authenticated API client and health probe, release detection, API-backed grade readers, setup and cleanup, workload driver and entry point. |
## Output (gitignored)
+124
View File
@@ -0,0 +1,124 @@
import { readFileSync } from "node:fs";
import os from "node:os";
import path from "node:path";
import { setTimeout as delay } from "node:timers/promises";
import { ChaosApiError, rateLimitDelayMs } from "./api.js";
import { assertSameOrigin, type HostedTarget } from "./hosted-guard.js";
import type { HealthSample } from "./hosted-release.js";
export const HOSTED_TOKEN_ENV = "PAPERCLIP_HOSTED_TOKEN";
const TRANSIENT_STATUSES = new Set([502, 503, 504]);
export function hostedAuthPaths(env: NodeJS.ProcessEnv = process.env): string[] {
const paths = [path.join(os.homedir(), ".paperclip", "auth.json")];
if (env.PAPERCLIP_HOME) paths.unshift(path.join(env.PAPERCLIP_HOME, "auth.json"));
return [...new Set(paths)];
}
export function hostedToken(target: HostedTarget, env: NodeJS.ProcessEnv = process.env, authPaths = hostedAuthPaths(env)): string {
const fromEnv = env[HOSTED_TOKEN_ENV]?.trim();
if (fromEnv) return fromEnv;
for (const authPath of authPaths) {
let store: { credentials?: Record<string, { apiBase?: string; token?: string }> } = {};
try { store = JSON.parse(readFileSync(authPath, "utf8")); } catch { continue; }
const entry = store.credentials?.[target.baseUrl] ?? store.credentials?.[`${target.baseUrl}/`];
if (entry?.token) return entry.token;
}
throw new Error(`No board sign-in for ${target.baseUrl} in ${authPaths.join(" or ")} (credentials["${target.baseUrl}"].token) and ${HOSTED_TOKEN_ENV} is unset. `
+ "Ask the owner to approve a board sign-in for this host first (README: Hosted mode, Sign-in).");
}
export interface RequestRecord { at: number; ok: boolean; reachable: boolean; status: number | null; ms: number; method: string }
export class HostedApi {
readonly requests: RequestRecord[] = [];
constructor(readonly target: HostedTarget, private readonly token: string, private readonly timeoutMs = 20_000,
private readonly fetcher: typeof fetch = fetch) {}
get baseUrl(): string { return this.target.baseUrl; }
private async once(method: string, route: string, body: unknown, timeoutMs: number): Promise<{ status: number | null; text: string; retryAfterMs: number | null }> {
const url = `${this.target.baseUrl}${route}`;
assertSameOrigin(this.target, url);
const started = Date.now();
try {
const response = await this.fetcher(url, { method, cache: "no-store", signal: AbortSignal.timeout(timeoutMs),
headers: { authorization: `Bearer ${this.token}`, accept: "application/json", origin: this.target.baseUrl,
...(body === undefined ? {} : { "content-type": "application/json" }) },
body: body === undefined ? undefined : JSON.stringify(body) });
const text = await response.text();
this.requests.push({ at: started, ok: response.ok, reachable: response.status < 500, status: response.status, ms: Date.now() - started, method });
return { status: response.ok ? 200 : response.status, text, retryAfterMs: rateLimitDelayMs(response, text) };
} catch (error) {
this.requests.push({ at: started, ok: false, reachable: false, status: null, ms: Date.now() - started, method });
return { status: null, text: error instanceof Error ? error.message : String(error), retryAfterMs: null };
}
}
private async request<T>(method: string, route: string, body?: unknown, timeoutMs = this.timeoutMs): Promise<T> {
for (let attempt = 1; ; attempt += 1) {
const result = await this.once(method, route, body, timeoutMs);
if (result.status === 200) return (result.text ? JSON.parse(result.text) : null) as T;
const transient = result.status === null || TRANSIENT_STATUSES.has(result.status) || result.retryAfterMs !== null;
const error = new ChaosApiError(result.status, result.status === null ? `${method} ${route} unreachable: ${result.text.slice(0, 200)}`
: `${method} ${route} returned ${result.status}: ${result.text.slice(0, 500)}`);
if (!transient || (method !== "GET" && result.retryAfterMs === null) || attempt >= 4) throw error;
await delay(Math.min(10_000, (result.retryAfterMs ?? 1_000) * attempt));
}
}
get<T>(route: string, timeoutMs?: number) { return this.request<T>("GET", route, undefined, timeoutMs); }
post<T>(route: string, body?: unknown, timeoutMs?: number) { return this.request<T>("POST", route, body ?? {}, timeoutMs); }
patch<T>(route: string, body?: unknown) { return this.request<T>("PATCH", route, body ?? {}); }
put<T>(route: string, body?: unknown) { return this.request<T>("PUT", route, body ?? {}); }
async delete(route: string, options?: { allowNotFound?: boolean }): Promise<void> {
try { await this.request<unknown>("DELETE", route); }
catch (error) { if (!(options?.allowNotFound && error instanceof ChaosApiError && error.status === 404)) throw error; }
}
async health(): Promise<HealthSample> {
const at = Date.now();
const result = await this.once("GET", "/api/health", undefined, 10_000);
const ms = Date.now() - at;
if (result.status !== 200) return { at, ok: false, status: result.status, ms, processStartedAt: null, commit: null, error: result.text.slice(0, 200) };
try {
const body = JSON.parse(result.text) as { commit?: string; serverInfo?: { processStartedAt?: string } };
return { at, ok: true, status: 200, ms, processStartedAt: body.serverInfo?.processStartedAt ?? null, commit: body.commit ?? null };
} catch (error) {
return { at, ok: false, status: 200, ms, processStartedAt: null, commit: null, error: `unparseable health: ${String(error)}` };
}
}
}
export class HealthProbe {
readonly samples: HealthSample[] = [];
private stopped = false;
private loop: Promise<void> | null = null;
constructor(private readonly api: Pick<HostedApi, "health">, private readonly intervalMs = 2_000,
private readonly onSample: (sample: HealthSample) => void = () => {}) {}
start(): this {
this.loop = (async () => {
while (!this.stopped) {
const started = Date.now();
const sample = await this.api.health();
this.samples.push(sample);
this.onSample(sample);
const wait = this.intervalMs - (Date.now() - started);
if (wait > 0 && !this.stopped) await delay(wait);
}
})();
return this;
}
async stop(): Promise<void> {
this.stopped = true;
await this.loop;
}
}
export function requestSamples(records: readonly RequestRecord[]): HealthSample[] {
return records.map(record => ({ at: record.at, ok: record.ok, status: record.status, ms: record.ms, processStartedAt: null, commit: null }));
}
+106
View File
@@ -0,0 +1,106 @@
import { parseArgs } from "node:util";
import { hostedTarget, type HostedTarget } from "./hosted-guard.js";
import { parseRange, parseRatio } from "./staging-mix.js";
import type { AdapterId } from "./types.js";
export type HostedMode = "run" | "observe" | "cleanup";
export interface HostedOptions {
mode: HostedMode;
target: HostedTarget;
label: string;
companyId: string | null;
environmentId: string | null;
releases: number;
concurrency: number;
tasks: number | null;
turnMinutes: [number, number];
ratio: Array<[AdapterId, number]>;
subtaskShare: number;
followUpShare: number;
settleMs: number;
drainMs: number;
maxWaitMs: number;
healthMs: number;
seed: number;
keep: boolean;
retryDuringWave: boolean;
}
export const HOSTED_FLAGS = ["hosted-base-url", "hosted-allow", "hosted-cleanup-only", "hosted-observe-only"] as const;
export function isHostedCommand(argv: readonly string[]): boolean {
return argv.some(arg => HOSTED_FLAGS.some(flag => arg === `--${flag}` || arg.startsWith(`--${flag}=`)));
}
const LABEL = /^[a-z0-9][a-z0-9-]{2,40}$/;
function whole(raw: string | undefined, name: string, fallback: number, min: number, max: number): number {
if (raw === undefined) return fallback;
if (!/^[0-9]+$/.test(raw)) throw new Error(`--${name} must be a whole number`);
const value = Number(raw);
if (value < min || value > max) throw new Error(`--${name} must be between ${min} and ${max}`);
return value;
}
export function defaultHostedLabel(now = new Date()): string {
return `rc-hosted-${now.toISOString().slice(0, 16).replace(/[-:T]/g, "").toLowerCase()}`;
}
export function parseHostedCommand(argv: readonly string[], now = new Date()): HostedOptions {
const { values } = parseArgs({
args: argv[0] === "--" ? argv.slice(1) : [...argv],
strict: true,
options: {
"hosted-base-url": { type: "string" },
"hosted-allow": { type: "string" },
"hosted-cleanup-only": { type: "boolean" },
"hosted-observe-only": { type: "boolean" },
"hosted-label": { type: "string" },
"hosted-company": { type: "string" },
"hosted-environment": { type: "string" },
"hosted-releases": { type: "string" },
"hosted-concurrency": { type: "string" },
"hosted-tasks": { type: "string" },
"hosted-turn-minutes": { type: "string" },
"hosted-ratio": { type: "string" },
"hosted-subtask-share": { type: "string" },
"hosted-follow-up-share": { type: "string" },
"hosted-settle-minutes": { type: "string" },
"hosted-drain-minutes": { type: "string" },
"hosted-max-hours": { type: "string" },
"hosted-health-seconds": { type: "string" },
"hosted-keep": { type: "boolean" },
"hosted-retry-during-wave": { type: "boolean" },
seed: { type: "string" },
},
});
const target = hostedTarget(values["hosted-base-url"], values["hosted-allow"]);
if (values["hosted-cleanup-only"] && values["hosted-observe-only"]) throw new Error("--hosted-cleanup-only and --hosted-observe-only exclude each other");
const mode: HostedMode = values["hosted-cleanup-only"] ? "cleanup" : values["hosted-observe-only"] ? "observe" : "run";
if (mode === "cleanup" && !values["hosted-label"]) throw new Error("--hosted-cleanup-only needs --hosted-label <the run's label>");
const label = values["hosted-label"] ?? defaultHostedLabel(now);
if (!LABEL.test(label)) throw new Error("--hosted-label takes 3–41 lowercase letters, digits and dashes");
const turnMinutes = parseRange(values["hosted-turn-minutes"] ?? "5-15", "hosted-turn-minutes", 1, 60);
if (mode === "run" && values["hosted-releases"] === "0" && values["hosted-tasks"] === undefined) throw new Error("--hosted-releases 0 runs a fixed batch; add --hosted-tasks <n>");
const settleMs = whole(values["hosted-settle-minutes"], "hosted-settle-minutes", 15, 1, 60) * 60_000;
return {
mode, target, label,
companyId: values["hosted-company"] ?? null,
environmentId: values["hosted-environment"] ?? null,
releases: whole(values["hosted-releases"], "hosted-releases", mode === "observe" ? 1 : 3, 0, 20),
concurrency: whole(values["hosted-concurrency"], "hosted-concurrency", 5, 1, 30),
tasks: values["hosted-tasks"] === undefined ? null : whole(values["hosted-tasks"], "hosted-tasks", 1, 1, 2_000),
turnMinutes,
ratio: parseRatio(values["hosted-ratio"] ?? "opencode=100"),
subtaskShare: whole(values["hosted-subtask-share"], "hosted-subtask-share", 30, 0, 100),
followUpShare: whole(values["hosted-follow-up-share"], "hosted-follow-up-share", 50, 0, 100),
settleMs,
drainMs: whole(values["hosted-drain-minutes"], "hosted-drain-minutes", Math.round(turnMinutes[1] * 1.5 + 20 + settleMs / 60_000), 1, 480) * 60_000,
maxWaitMs: whole(values["hosted-max-hours"], "hosted-max-hours", 8, 1, 24) * 3_600_000,
healthMs: whole(values["hosted-health-seconds"], "hosted-health-seconds", 2, 1, 30) * 1_000,
seed: whole(values.seed, "seed", Number(now.getTime() % 100_000), 0, 2 ** 31 - 1),
keep: values["hosted-keep"] === true,
retryDuringWave: values["hosted-retry-during-wave"] === true,
};
}
+171
View File
@@ -0,0 +1,171 @@
import { randomUUID } from "node:crypto";
import { writeFile } from "node:fs/promises";
import path from "node:path";
import { setTimeout as delay } from "node:timers/promises";
import type { HostedApi } from "./hosted-api.js";
import { trackBanner, type RetryBanner } from "./hosted-workload.js";
import { handsOffSummary, invariantLine, readAssignedWorkInvariant } from "./hosted-handsoff.js";
import { releaseMarkdown, type ContinuityReport, type DetectedRelease } from "./hosted-release.js";
import {
duplicateAgentComments, duplicateChildren, failureChain, firstEventAfter, gradeRuns, hostedCompanyRuns, hostedIssues, issueViewFields,
pendingPersonItems, startedIssues, UNAVAILABLE_OVER_API, type HostedRunRow,
} from "./hosted-readers.js";
import {
gradeReleaseSwapTask, overlappingRuns, releaseSwapMarkdown, summarizeGrades, swapMetrics, type RetryClick, type SwapRunFact, type SwapWindow, type TaskGrade,
} from "./release-swap-grade.js";
type Json = Record<string, any>;
export type GradeApi = Pick<HostedApi, "get" | "post">;
export const PROGRESS_WINDOW_MS = 5 * 60_000;
export interface HostedGradeInput {
api: GradeApi;
companyId: string;
agentIds: string[];
releases: DetectedRelease[];
health: () => ContinuityReport;
apiContinuity: () => ContinuityReport;
stopObserver: () => Promise<void>;
agentNames?: string[];
observedClicks: () => ReadonlyMap<string, RetryClick[]>;
banners?: () => ReadonlyMap<string, RetryBanner>;
lastReleaseAt: number;
settleMs: number;
drainMs: number;
dir: string;
cancelled: () => boolean;
record: (kind: string, data: Record<string, unknown>) => void;
pollMs?: number;
now?: () => number;
}
export function releaseWindows(releases: readonly DetectedRelease[]): SwapWindow[] {
return releases.map(release => ({ index: release.index, requestedAt: release.lastOldOnlyAt, spawnedAt: release.firstNewAt,
stopRequestedAt: release.lastOldAt, stoppedAt: release.lastOldAt, fromPid: null }));
}
export async function drainHosted(input: Pick<HostedGradeInput, "api" | "companyId" | "agentIds" | "lastReleaseAt" | "settleMs" | "drainMs" | "cancelled" | "record" | "pollMs" | "now">):
Promise<{ reason: "quiet" | "cap" | "cancelled"; progressing: number }> {
const now = input.now ?? Date.now;
const settledAt = input.lastReleaseAt + input.settleMs;
const capAt = Math.max(settledAt, input.lastReleaseAt + input.drainMs);
const window = PROGRESS_WINDOW_MS;
input.record("hosted_settling", { settleUntil: new Date(settledAt).toISOString(), capAt: new Date(capAt).toISOString() });
while (!input.cancelled() && now() < settledAt) await delay(Math.min(input.pollMs ?? 15_000, Math.max(1, settledAt - now())));
for (;;) {
const at = now();
const runs = await hostedCompanyRuns(input.api, input.companyId, input.agentIds);
const progressing = runs.filter(run => ["queued", "running", "scheduled_retry"].includes(run.status) && (run.lastActivityAt ?? 0) >= at - window).length;
if (input.cancelled()) return { reason: "cancelled", progressing };
if (!progressing) return { reason: "quiet", progressing };
if (at >= capAt) return { reason: "cap", progressing };
await delay(Math.min(input.pollMs ?? 30_000, Math.max(1, capAt - at)));
}
}
export async function gradeHosted(input: HostedGradeInput): Promise<{ headline: string; pass: boolean; markdown: string }> {
const { api, companyId, agentIds } = input;
const now = input.now ?? Date.now;
const drained = await drainHosted(input);
input.record("hosted_drained", drained);
await input.stopObserver();
const clicks = new Map<string, RetryClick[]>([...input.observedClicks()].map(([id, list]) => [id, [...list]]));
const views = new Map<string, Json>();
const readViews = async (ids: readonly string[]) => {
for (const id of ids) views.set(id, await api.get<Json>(`/api/issues/${id}`).catch(error => ({ status: "unreadable", error: String(error) })));
};
let runs = await hostedCompanyRuns(api, companyId, agentIds);
let issues = startedIssues(await hostedIssues(api, companyId, agentIds), runs);
await readViews(issues.map(issue => issue.id));
const banners = new Map<string, RetryBanner>(input.banners?.() ?? []);
for (const issue of issues) {
const view = views.get(issue.id)!;
const offered = view.status !== "done" && view.interruption?.canRetry === true && !view.interruption?.retryWait;
const next = trackBanner(banners.get(issue.id) ?? null, offered, now()).banner;
if (next) banners.set(issue.id, next);
}
const retried: string[] = [];
for (const issue of issues) {
const current = views.get(issue.id)!;
if (current.status === "done" || current.interruption?.canRetry !== true || current.interruption?.retryWait) continue;
const click: RetryClick = { at: now(), accepted: false, via: "grader" };
try {
const result = await api.post<{ accepted?: boolean }>(`/api/issues/${issue.id}/retry`, { idempotencyKey: randomUUID(), observedRunId: current.interruption?.observedRunId ?? null });
click.accepted = result?.accepted === true;
} catch (error) {
input.record("hosted_retry_click_failed", { issueId: issue.id, error: String(error) });
}
input.record("hosted_retry_clicked", { issueId: issue.id, accepted: click.accepted });
clicks.set(issue.id, [...(clicks.get(issue.id) ?? []), click]);
retried.push(issue.id);
}
if (retried.length) {
const until = now() + input.settleMs;
while (!input.cancelled() && now() < until) {
await delay(input.pollMs ?? 15_000);
await readViews(retried);
if (retried.every(id => views.get(id)?.status === "done")) break;
}
runs = await hostedCompanyRuns(api, companyId, agentIds);
const all = await hostedIssues(api, companyId, agentIds);
issues = startedIssues(all, runs);
await readViews(issues.map(issue => issue.id));
}
const allIssues = await hostedIssues(api, companyId, agentIds);
const person = await pendingPersonItems(api, issues.map(issue => issue.id));
const runsByIssue = new Map<string, HostedRunRow[]>();
for (const run of runs) if (run.issueId) runsByIssue.set(run.issueId, [...(runsByIssue.get(run.issueId) ?? []), run]);
const gradedAt = now();
const unreadable = issues.filter(issue => (views.get(issue.id) ?? { status: "unreadable" }).status === "unreadable" || person.unreadable.includes(issue.id));
if (unreadable.length) input.record("hosted_views_unreadable", { count: unreadable.length, issueIds: unreadable.map(issue => issue.id) });
const grades: TaskGrade[] = issues.filter(issue => !unreadable.includes(issue)).map(issue => gradeReleaseSwapTask({
now: gradedAt, staleAfterMs: PROGRESS_WINDOW_MS, issueId: issue.id, identifier: issue.identifier, title: issue.title, ...issueViewFields(views.get(issue.id)!),
runs: gradeRuns(runsByIssue.get(issue.id) ?? []), queuedWakes: 0, retryClicks: clicks.get(issue.id) ?? [],
pendingApproval: person.approvals.has(issue.id), pendingQuestion: person.questions.has(issue.id) }));
const facts: SwapRunFact[] = runs.map(run => ({ runId: run.runId, issueId: run.issueId, status: run.status, errorCode: run.errorCode,
startedAt: run.startedAt, finishedAt: run.finishedAt, ownerPidBeforeEnd: null }));
const windows = releaseWindows(input.releases);
const firstEvents = new Map<string, number>();
for (const window of windows) {
const stop = window.stopRequestedAt!;
for (const fact of facts.filter(fact => fact.startedAt !== null && fact.startedAt < stop && (fact.finishedAt === null || fact.finishedAt > stop))) {
const at = await firstEventAfter(api, fact.runId, stop);
if (at !== null) firstEvents.set(`${window.index}:${fact.runId}`, at);
}
}
const waveEnd = now();
const metrics = swapMetrics(windows, facts, firstEvents, waveEnd);
const duplicates = { overlappingRuns: overlappingRuns(facts, waveEnd), doubleExecutors: [] as string[],
duplicateComments: await duplicateAgentComments(api, issues.map(issue => issue.id)), duplicateChildren: duplicateChildren(allIssues) };
const result = summarizeGrades(grades, unreadable.length, drained.reason);
const handsOff = handsOffSummary(result, issues.map(issue => issue.id), banners);
const invariant = await readAssignedWorkInvariant(api, companyId, { identifiers: new Set(issues.flatMap(issue => issue.identifier ? [issue.identifier] : [])),
agentNames: new Set(input.agentNames ?? []) });
const failed = runs.filter(run => ["failed", "timed_out", "interrupted"].includes(run.status));
const failedRuns = [];
for (const run of failed) failedRuns.push({ ...run, release: [...windows].reverse().find(window => (run.finishedAt ?? 0) >= window.requestedAt)?.index ?? null,
chain: await failureChain(api, run.runId) });
const health = input.health();
const apiContinuity = input.apiContinuity();
const markdown = [
...handsOff.lines,
invariantLine(invariant),
"",
releaseSwapMarkdown(result, metrics, windows.map(() => null), duplicates, grades).trimEnd(),
"",
"Hosted mode: releases came from the instance's own deploys, detected by polling /api/health. Lost-while-old-alive and late/preparation probes are not measured (see Unavailable).",
...releaseMarkdown(input.releases, health, apiContinuity),
"",
"Unavailable over the API:",
...UNAVAILABLE_OVER_API.map(item => `- ${item}`),
"",
].join("\n");
await writeFile(path.join(input.dir, "hosted-release-swap.json"), `${JSON.stringify({ schema: "paperclip.restart-chaos.hosted-release-swap/v1", result, handsOff: { ...handsOff, banners: Object.fromEntries(banners) }, invariant,
releases: input.releases, health, api: apiContinuity, metrics, duplicates, failedRuns, grades, drained,
unavailable: UNAVAILABLE_OVER_API }, null, 2)}\n`, { mode: 0o600 });
await writeFile(path.join(input.dir, "SUMMARY.md"), markdown, { mode: 0o600 });
input.record("hosted_graded", { headline: result.headline, byVerdict: result.byVerdict, byLabel: result.byLabel, retry: result.retry,
failedPerRelease: metrics.map(metric => metric.failedRuns.length) });
return { headline: handsOff.lines[0]!, markdown,
pass: result.uncollected === 0 && result.stillRunning === 0 && result.started > 0 && result.completedWithoutHuman === result.started };
}
+71
View File
@@ -0,0 +1,71 @@
import { mkdtemp, rm, writeFile } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { describe, expect, it } from "vitest";
import { assertSameOrigin, hostedTarget } from "./hosted-guard.js";
import { isHostedCommand, parseHostedCommand } from "./hosted-config.js";
import { HostedApi, hostedToken } from "./hosted-api.js";
const approved = "release-proof-1.staging.paperclip.app";
describe("hosted target guard", () => {
it("accepts one explicitly allowed single-stack staging or test host", () => {
expect(hostedTarget(`https://${approved}`, approved)).toEqual({ baseUrl: `https://${approved}`, host: approved });
expect(hostedTarget(`https://${approved.toUpperCase()}/`, approved).host).toBe(approved);
expect(hostedTarget("https://load-check-2.test.paperclip.app", "load-check-2.test.paperclip.app").host)
.toBe("load-check-2.test.paperclip.app");
});
it("refuses a missing URL, a missing or different allow flag, and anything but a bare https origin", () => {
expect(() => hostedTarget(undefined, approved)).toThrow(/--hosted-base-url/);
expect(() => hostedTarget(`https://${approved}`, undefined)).toThrow(/--hosted-allow/);
expect(() => hostedTarget(`https://${approved}`, "other-stack.staging.paperclip.app")).toThrow(/does not match/);
expect(() => hostedTarget(`http://${approved}`, approved)).toThrow(/https/);
expect(() => hostedTarget(`https://${approved}/api`, approved)).toThrow(/bare origin/);
expect(() => hostedTarget(`https://${approved}:8443`, approved)).toThrow(/bare origin/);
expect(() => hostedTarget(`https://user:pw@${approved}`, approved)).toThrow(/bare origin/);
});
it("refuses the shared staging instance even when it is allowed explicitly", () => {
expect(() => hostedTarget("https://paperclip.staging.paperclip.app", "paperclip.staging.paperclip.app")).toThrow(/shared staging instance/);
});
it("refuses production, the fleet admin, Cloud and any host outside staging or test", () => {
for (const host of ["paperclip.app", "app.paperclip.app", "acme.paperclip.app", "admin-staging.paperclip.app", "my-staging.paperclip.app",
"admin.staging.paperclip.app", "my.staging.paperclip.app", "a.b.staging.paperclip.app", "evil.staging.paperclip.app.example.com", "localhost", "example.com"]) {
expect(() => hostedTarget(`https://${host}`, host), host).toThrow(/refused/);
}
});
it("keeps every request on the allowed origin", async () => {
const target = hostedTarget(`https://${approved}`, approved);
expect(() => assertSameOrigin(target, "https://paperclip.staging.paperclip.app/api/health")).toThrow(/Refusing/);
expect(() => assertSameOrigin(target, `https://${approved}/api/health`)).not.toThrow();
const seen: string[] = [];
const api = new HostedApi(target, "t", 1_000, (async (url: string) => { seen.push(url); return new Response("{}", { status: 200 }); }) as typeof fetch);
await api.get("/api/health");
await expect(api.get("@paperclip.staging.paperclip.app/api/health")).rejects.toThrow(/Refusing/);
expect(seen).toEqual([`https://${approved}/api/health`]);
});
it("takes the board token from the environment or the CLI store for exactly this host, and names what is missing", async () => {
const target = hostedTarget(`https://${approved}`, approved);
const dir = await mkdtemp(path.join(os.tmpdir(), "hosted-auth-"));
const store = path.join(dir, "auth.json");
await writeFile(store, JSON.stringify({ credentials: { "https://paperclip.staging.paperclip.app": { token: "other" }, [`https://${approved}`]: { token: "mine" } } }));
expect(hostedToken(target, {}, [path.join(dir, "missing.json"), store])).toBe("mine");
expect(hostedToken(target, { PAPERCLIP_HOSTED_TOKEN: "env" }, [store])).toBe("env");
expect(() => hostedToken(hostedTarget("https://other-stack.staging.paperclip.app", "other-stack.staging.paperclip.app"), {}, [store])).toThrow(/No board sign-in/);
await rm(dir, { recursive: true, force: true });
});
it("only enters hosted mode with the hosted flags and refuses a mismatched command", () => {
expect(isHostedCommand(["--env", "local"])).toBe(false);
expect(isHostedCommand([`--hosted-base-url=https://${approved}`])).toBe(true);
expect(() => parseHostedCommand(["--hosted-base-url", "https://paperclip.staging.paperclip.app", "--hosted-allow", "paperclip.staging.paperclip.app"])).toThrow(/refused/);
expect(() => parseHostedCommand(["--hosted-base-url", `https://${approved}`, "--hosted-allow", approved, "--hosted-cleanup-only"])).toThrow(/--hosted-label/);
expect(() => parseHostedCommand(["--hosted-base-url", `https://${approved}`, "--hosted-allow", approved, "--hosted-releases", "0"])).toThrow(/--hosted-tasks/);
const parsed = parseHostedCommand(["--hosted-base-url", `https://${approved}`, "--hosted-allow", approved], new Date("2026-11-12T17:30:00Z"));
expect(parsed).toMatchObject({ mode: "run", label: "rc-hosted-202611121730", releases: 3, concurrency: 5, ratio: [["opencode", 100]], turnMinutes: [5, 15] });
});
});
+38
View File
@@ -0,0 +1,38 @@
export const REFUSED_HOSTS: ReadonlySet<string> = new Set(["paperclip.staging.paperclip.app"]);
export const TEST_HOST_PATTERN = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.(?:staging|test)\.paperclip\.app$/;
const RESERVED_LABELS = new Set(["admin", "admin-staging", "my", "my-staging", "api", "cloud", "www", "app"]);
export interface HostedTarget {
baseUrl: string;
host: string;
}
export class HostedTargetError extends Error {
constructor(message: string) { super(message); this.name = "HostedTargetError"; }
}
export function hostedTarget(baseUrl: string | undefined, allow: string | undefined): HostedTarget {
if (!baseUrl) throw new HostedTargetError("Hosted mode needs --hosted-base-url <https://host>");
if (!allow) throw new HostedTargetError("Hosted mode needs --hosted-allow <host>, the same host as --hosted-base-url");
let url: URL;
try { url = new URL(baseUrl); } catch { throw new HostedTargetError(`--hosted-base-url is not a URL: ${baseUrl}`); }
if (url.protocol !== "https:") throw new HostedTargetError("--hosted-base-url must use https");
if (url.username || url.password || url.port || url.search || url.hash || (url.pathname !== "/" && url.pathname !== "")) {
throw new HostedTargetError("--hosted-base-url must be a bare origin (https://host), with no path, port, query or credentials");
}
const host = url.hostname.toLowerCase();
const allowed = allow.trim().toLowerCase();
if (host !== allowed) throw new HostedTargetError(`--hosted-allow ${allowed} does not match the --hosted-base-url host ${host}`);
if (REFUSED_HOSTS.has(host)) throw new HostedTargetError(`${host} is refused: the harness never writes to the shared staging instance`);
if (!TEST_HOST_PATTERN.test(host) || RESERVED_LABELS.has(host.split(".")[0]!)) {
throw new HostedTargetError(`${host} is refused: hosted mode only targets a single-stack <name>.staging.paperclip.app or <name>.test.paperclip.app host`);
}
return { baseUrl: `https://${host}`, host };
}
export function assertSameOrigin(target: HostedTarget, url: string): void {
const parsed = new URL(url);
if (parsed.protocol !== "https:" || parsed.hostname.toLowerCase() !== target.host || parsed.port) {
throw new HostedTargetError(`Refusing a request to ${parsed.origin}: hosted mode only talks to ${target.baseUrl}`);
}
}
@@ -0,0 +1,31 @@
import { describe, expect, it } from "vitest";
import { ChaosApiError } from "./api.js";
import { handsOffSummary, invariantLine, readAssignedWorkInvariant } from "./hosted-handsoff.js";
describe("hosted hands-off numbers", () => {
it("prints completed hands-off over started, banners shown, and Retry worked over clicked", () => {
const banners = new Map([["i1", { firstShownAt: 1, shown: false, clearedAt: 2, clearedByItself: true }], ["i2", { firstShownAt: 3, shown: true, clearedAt: null, clearedByItself: false }],
["foreign", { firstShownAt: 1, shown: true, clearedAt: null, clearedByItself: false }]]);
const summary = handsOffSummary({ completedWithoutHuman: 2, started: 3, retry: { tasks: 1, worked: 0, didNotWork: 1, pending: 0 } }, ["i1", "i2", "i3"], banners);
expect(summary.lines).toEqual(["2 / 3 tasks completed hands-off", "Retry banner shown: 2 (cleared by itself: 1)", "Retry worked / clicked: 0 / 1"]);
});
});
describe("assigned-work invariant read", () => {
it("reads the company counts once and scopes the sample and stalled slots to the run", async () => {
const api = { get: async <T>() => ({ openTasks: 7, checked: 7, truncated: false, violationCount: 3, violations: { no_owner: 2, held: 1 },
sample: [{ identifier: "GIT-5", reason: "no_owner" }, { identifier: "OTHER-1", reason: "held" }],
agentsWithStalledSlots: [{ agentName: "RC rc-x opencode", stalledRuns: 1, queuedRuns: 2 }, { agentName: "Someone", stalledRuns: 4, queuedRuns: 0 }] }) as T };
const counts = await readAssignedWorkInvariant(api, "c1", { identifiers: new Set(["GIT-5"]), agentNames: new Set(["RC rc-x opencode"]) });
expect(counts.run).toEqual({ sampledViolations: 1, byReason: { no_owner: 1 }, stalledSlots: [{ agentName: "RC rc-x opencode", stalledRuns: 1, queuedRuns: 2 }] });
expect(invariantLine(counts)).toBe("Assigned-work invariant: company 3 violation(s) over 7 open task(s) [no_owner 2, held 1], 2 agent(s) with stalled slots; "
+ "this run: 1 sampled violation(s), 1 agent(s) with stalled slots.");
});
it("tolerates an older build without the endpoint", async () => {
const api = { get: async <T>(): Promise<T> => { throw new ChaosApiError(404, "GET returned 404"); } };
const counts = await readAssignedWorkInvariant(api, "c1", { identifiers: new Set(), agentNames: new Set() });
expect(counts).toEqual({ available: false, status: 404 });
expect(invariantLine(counts)).toBe("Assigned-work invariant: not available on this build (HTTP 404).");
});
});
+66
View File
@@ -0,0 +1,66 @@
import { ChaosApiError } from "./api.js";
import type { HostedApi } from "./hosted-api.js";
import type { RetryBanner } from "./hosted-workload.js";
import type { ReleaseSwapResult } from "./release-swap-grade.js";
type Json = Record<string, any>;
export interface HandsOffSummary {
completedHandsOff: number;
started: number;
bannerShown: number;
bannerClearedByItself: number;
retryClicked: number;
retryWorked: number;
lines: [string, string, string];
}
export function handsOffSummary(result: Pick<ReleaseSwapResult, "completedWithoutHuman" | "started" | "retry">, issueIds: readonly string[],
banners: ReadonlyMap<string, RetryBanner>): HandsOffSummary {
const shown = issueIds.filter(id => banners.has(id));
const cleared = shown.filter(id => banners.get(id)!.clearedByItself && !banners.get(id)!.shown).length;
const summary = { completedHandsOff: result.completedWithoutHuman, started: result.started, bannerShown: shown.length, bannerClearedByItself: cleared,
retryClicked: result.retry.tasks, retryWorked: result.retry.worked };
return { ...summary, lines: [
`${summary.completedHandsOff} / ${summary.started} tasks completed hands-off`,
`Retry banner shown: ${summary.bannerShown} (cleared by itself: ${summary.bannerClearedByItself})`,
`Retry worked / clicked: ${summary.retryWorked} / ${summary.retryClicked}`,
] };
}
export interface InvariantCounts {
available: boolean;
status: number | null;
company?: { openTasks: number; checked: number; truncated: boolean; violationCount: number; violations: Record<string, number>; stalledSlotAgents: number };
run?: { sampledViolations: number; byReason: Record<string, number>; stalledSlots: Array<{ agentName: string; stalledRuns: number; queuedRuns: number }> };
}
export async function readAssignedWorkInvariant(api: Pick<HostedApi, "get">, companyId: string,
ours: { identifiers: ReadonlySet<string>; agentNames: ReadonlySet<string> }): Promise<InvariantCounts> {
let report: Json;
try {
report = await api.get<Json>(`/api/companies/${companyId}/assigned-work-invariant`);
} catch (error) {
return { available: false, status: error instanceof ChaosApiError ? error.status : null };
}
const sample = ((report.sample ?? []) as Json[]).filter(entry => entry.identifier && ours.identifiers.has(String(entry.identifier)));
const byReason: Record<string, number> = {};
for (const entry of sample) byReason[String(entry.reason)] = (byReason[String(entry.reason)] ?? 0) + 1;
const slots = (report.agentsWithStalledSlots ?? []) as Json[];
return {
available: true, status: 200,
company: { openTasks: Number(report.openTasks ?? 0), checked: Number(report.checked ?? 0), truncated: Boolean(report.truncated),
violationCount: Number(report.violationCount ?? 0), violations: { ...(report.violations ?? {}) }, stalledSlotAgents: slots.length },
run: { sampledViolations: sample.length, byReason,
stalledSlots: slots.filter(slot => ours.agentNames.has(String(slot.agentName))).map(slot => ({ agentName: String(slot.agentName),
stalledRuns: Number(slot.stalledRuns ?? 0), queuedRuns: Number(slot.queuedRuns ?? 0) })) },
};
}
export function invariantLine(counts: InvariantCounts): string {
if (!counts.available) return `Assigned-work invariant: not available on this build (HTTP ${counts.status ?? "no answer"}).`;
const company = counts.company!, run = counts.run!;
const reasons = Object.entries(company.violations).map(([reason, count]) => `${reason} ${count}`).join(", ") || "none";
return `Assigned-work invariant: company ${company.violationCount} violation(s) over ${company.openTasks} open task(s)${company.truncated ? " (lower bound)" : ""} [${reasons}], `
+ `${company.stalledSlotAgents} agent(s) with stalled slots; this run: ${run.sampledViolations} sampled violation(s), ${run.stalledSlots.length} agent(s) with stalled slots.`;
}
+161
View File
@@ -0,0 +1,161 @@
import { mkdtemp, readFile, rm } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import { ChaosApiError } from "./api.js";
import { HostedApi, requestSamples } from "./hosted-api.js";
import { parseHostedCommand } from "./hosted-config.js";
import { gradeHosted } from "./hosted-grade.js";
import { hostedTarget } from "./hosted-guard.js";
import { arrivalsDone, finalizeHosted, keepPolling, observedClicks } from "./hosted-main.js";
import { hostedCompanyRuns, hostedIssues, runEvents, RUN_PAGE, ISSUE_PAGE, EVENT_PAGE } from "./hosted-readers.js";
import { continuity } from "./hosted-release.js";
import { cleanupHosted, setupHosted, statePath } from "./hosted-setup.js";
import type { HostedTaskRecord } from "./hosted-workload.js";
type Json = Record<string, any>;
const dirs: string[] = [];
afterEach(async () => { for (const dir of dirs.splice(0)) await rm(dir, { recursive: true, force: true }); });
const tempDir = async () => { const dir = await mkdtemp(path.join(os.tmpdir(), "hosted-main-")); dirs.push(dir); return dir; };
const host = "release-proof-1.staging.paperclip.app";
describe("hosted run control", () => {
it("ends a fixed batch only when the plan is used up and no task is in flight", () => {
expect(arrivalsDone(0, 5, 0, [])).toBe(false);
expect(arrivalsDone(0, 0, 1, [])).toBe(false);
expect(arrivalsDone(0, 0, 0, [])).toBe(true);
expect(arrivalsDone(2, 0, 0, [])).toBe(false);
});
it("stops the observer before the grade reads Retry clicks, so a click during the drain fails the task", async () => {
const dir = await tempDir();
const record = { issueId: "i1", retryClicks: [] } as unknown as HostedTaskRecord;
const api = {
get: async <T>(route: string) => (route.includes("heartbeat-runs") ? [{ id: "r1", agentId: "a1", issueId: "i1", status: "succeeded", createdAt: 1, startedAt: 2, finishedAt: 3 }]
: route.includes("/issues?") ? [{ id: "i1", title: "a", status: "done", assigneeAgentId: "a1" }] : route === "/api/issues/i1" ? { status: "done" } : []) as T,
post: async <T>() => ({}) as T,
};
let stopped = false;
const graded = await gradeHosted({ api, companyId: "c1", agentIds: ["a1"], releases: [], health: () => continuity([]), apiContinuity: () => continuity([]),
stopObserver: async () => { stopped = true; record.retryClicks.push({ at: 0, accepted: true, via: "observer" }); },
observedClicks: () => observedClicks([record]), lastReleaseAt: Date.now() - 1_000, settleMs: 5, drainMs: 5, dir, cancelled: () => false, record: () => {}, pollMs: 5 });
expect(stopped).toBe(true);
expect(graded.headline).toBe("0 / 1 tasks completed hands-off");
});
it("stops background polling promptly and never polls after stop", async () => {
let polls = 0;
const polling = keepPolling({ poll: async () => { polls += 1; } }, 60_000);
await new Promise(resolve => setTimeout(resolve, 20));
const started = Date.now();
await polling.stop();
const after = polls;
await new Promise(resolve => setTimeout(resolve, 20));
expect(Date.now() - started).toBeLessThan(1_000);
expect(polls).toBe(after);
});
it("cleans up what a failed setup already created, from the saved state, keeping a terminated agent that has cost history", async () => {
const dir = await tempDir();
const writes: string[] = [];
let agentStatus = "idle";
const api = {
get: async <T>(route: string) => {
if (route.endsWith("/environments")) return [{ id: "e1", driver: "sandbox" }] as T;
if (route.endsWith("/agents")) return [{ id: "a1", name: "RC rc-x opencode" }] as T;
if (route === "/api/agents/a1") return { id: "a1", status: agentStatus } as T;
if (route.endsWith("/secrets")) return [{ id: "s1", name: "restart-chaos rc-x OPENROUTER_API_KEY" }] as T;
if (route.endsWith("/projects")) return [{ id: "p1", name: "Restart chaos rc-x" }] as T;
return [] as T;
},
post: async <T>(route: string) => {
writes.push(`POST ${route}`);
if (route.endsWith("/secrets")) return { id: "s1" } as T;
if (route.endsWith("/projects")) return { id: "p1" } as T;
if (route.endsWith("/terminate")) { agentStatus = "terminated"; return {} as T; }
throw new Error("agent creation failed");
},
patch: async <T>(route: string) => { writes.push(`PATCH ${route}`); return {} as T; },
delete: async (route: string) => {
writes.push(`DELETE ${route}`);
if (route === "/api/agents/a1") throw new ChaosApiError(409, `DELETE ${route} returned 409: {"code":"agent_cost_history_retained"}`);
},
};
const options = parseHostedCommand(["--hosted-base-url", `https://${host}`, "--hosted-allow", host, "--hosted-label", "rc-x"]);
await expect(setupHosted({ api, options, companyId: "c1", dir, env: { OPENROUTER_API_KEY: "k" }, record: () => {} })).rejects.toThrow(/agent creation failed/);
expect(JSON.parse(await readFile(statePath(dir), "utf8"))).toMatchObject({ companyId: "c1", projectId: "p1", secrets: [{ id: "s1" }] });
writes.length = 0;
expect(await finalizeHosted({ api, keep: false, label: "rc-x", dir, state: null, record: () => {} })).toMatchObject({ errors: [] });
expect(writes).toEqual(["PATCH /api/agents/a1", "POST /api/agents/a1/terminate", "DELETE /api/agents/a1", "DELETE /api/secrets/s1", "PATCH /api/projects/p1"]);
expect(await finalizeHosted({ api, keep: true, label: "rc-x", dir, state: null, record: () => {} })).toBeNull();
});
it("collects every page of a run agent's tasks before hiding any, so none is skipped as the list shrinks", async () => {
const hidden = new Set<string>();
const tasks = Array.from({ length: ISSUE_PAGE + 7 }, (_, index) => ({ id: `t${index}`, assigneeAgentId: "a1" }));
const api = {
get: async <T>(route: string) => {
if (route.endsWith("/agents")) return [{ id: "a1", name: "RC rc-x opencode", status: "terminated" }] as T;
if (route.includes("/issues?")) { const offset = Number(/offset=(\d+)/.exec(route)![1]); return tasks.filter(task => !hidden.has(task.id)).slice(offset, offset + ISSUE_PAGE) as T; }
if (route === "/api/agents/a1") return { id: "a1", status: "terminated" } as T;
return [] as T;
},
post: async <T>() => ({}) as T,
patch: async <T>(route: string) => { hidden.add(route.split("/").at(-1)!); return {} as T; },
delete: async () => {},
};
const report = await cleanupHosted({ api, label: "rc-x", companyId: "c1", state: null, record: () => {} });
expect(report).toMatchObject({ tasksArchived: ISSUE_PAGE + 7, errors: [] });
expect(hidden.size).toBe(ISSUE_PAGE + 7);
});
it("reports a cleanup read that failed instead of counting the object as removed", async () => {
const writes: string[] = [];
const unavailable = (route: string) => new ChaosApiError(503, `GET ${route} returned 503`);
const api = {
get: async <T>(route: string) => {
if (route.endsWith("/agents")) return [{ id: "a1", name: "RC rc-x opencode", status: "paused" }] as T;
if (route === "/api/agents/a1" || route.endsWith("/secrets")) throw unavailable(route);
return [] as T;
},
post: async <T>(route: string) => { writes.push(`POST ${route}`); return {} as T; },
patch: async <T>(route: string) => { writes.push(`PATCH ${route}`); return {} as T; },
delete: async (route: string) => { writes.push(`DELETE ${route}`); },
};
const report = await cleanupHosted({ api, label: "rc-x", companyId: "c1", state: null, record: () => {} });
expect(report.agentsRemoved).toBe(0);
expect(report.errors).toEqual([expect.stringMatching(/^remove agent a1: GET \/api\/agents\/a1 returned 503/), expect.stringMatching(/^read secrets: /)]);
expect(writes).toEqual(["PATCH /api/agents/a1"]);
});
});
describe("hosted readers collect complete history", () => {
it("pages through tasks and run events, and falls back to per-task runs when the company run list is full", async () => {
const issues = Array.from({ length: ISSUE_PAGE + 3 }, (_, index) => ({ id: `i${index}`, title: "t", status: "done", assigneeAgentId: "a1" }));
const seen: string[] = [];
const api = { get: async <T>(route: string) => {
seen.push(route);
if (route.includes("/issues?")) { const offset = Number(/offset=(\d+)/.exec(route)![1]); return issues.slice(offset, offset + ISSUE_PAGE) as T; }
if (route.includes("heartbeat-runs?")) return Array.from({ length: RUN_PAGE }, (_, index) => ({ id: `r${index}`, agentId: "a1", issueId: "i1", status: "succeeded" })) as T;
if (route === "/api/issues/i0/runs") return [{ runId: "old", agentId: "a1", status: "failed", errorCode: "process_lost" }, { runId: "foreign", agentId: "x", status: "failed" }] as T;
if (route.startsWith("/api/issues/")) return [] as T;
if (route.includes("/events?")) { const after = Number(/afterSeq=(\d+)/.exec(route)![1]); return (after < EVENT_PAGE
? Array.from({ length: EVENT_PAGE }, (_, index) => ({ seq: after + index + 1, createdAt: index })) : [{ seq: after + 1, createdAt: 9 }]) as T; }
return [] as T;
} };
expect(await hostedIssues(api, "c1", ["a1"])).toHaveLength(ISSUE_PAGE + 3);
const runs = await hostedCompanyRuns(api, "c1", ["a1"]);
expect(runs).toHaveLength(RUN_PAGE + 1);
expect(runs.find(run => run.runId === "old")).toMatchObject({ issueId: "i0", status: "failed", errorCode: "process_lost" });
expect(runs.some(run => run.runId === "foreign")).toBe(false);
expect(await runEvents(api, "r1")).toHaveLength(EVENT_PAGE + 1);
});
it("counts a refused request as a failure in continuity, not only server errors", async () => {
const statuses = [200, 401, 429, 503];
const api = new HostedApi(hostedTarget(`https://${host}`, host), "t", 1_000, (async () => new Response("{}", { status: statuses.shift()! })) as unknown as typeof fetch);
await api.get("/api/health");
await api.get("/api/health").catch(() => undefined);
expect(continuity(requestSamples(api.requests)).failures).toBeGreaterThanOrEqual(1);
expect(api.requests[1]).toMatchObject({ ok: false, reachable: true, status: 401 });
});
});
+163
View File
@@ -0,0 +1,163 @@
import { appendFileSync } from "node:fs";
import { mkdir, writeFile } from "node:fs/promises";
import path from "node:path";
import { setTimeout as delay } from "node:timers/promises";
import type { ChaosApi } from "./api.js";
import { HealthProbe, HostedApi, hostedToken, requestSamples } from "./hosted-api.js";
import { parseHostedCommand, type HostedOptions } from "./hosted-config.js";
import { gradeHosted } from "./hosted-grade.js";
import { continuity, detectReleases, identityOf, releaseMarkdown, type DetectedRelease, type HealthSample } from "./hosted-release.js";
import { cleanupHosted, inventory, loadState, resolveCompany, setupHosted, type HostedState } from "./hosted-setup.js";
import { HostedWorkload, planHostedTasks, type HostedTaskRecord } from "./hosted-workload.js";
import type { RetryClick } from "./release-swap-grade.js";
import { waitForAgentsReady } from "./seed.js";
import { Timeline } from "./timeline.js";
const resultsRoot = path.resolve(process.env.RESTART_CHAOS_RESULTS_DIR ?? path.join(import.meta.dirname, "results"));
const LOOP_MS = 5_000;
const POLL_MS = 15_000;
export function releasesReached(releases: readonly DetectedRelease[], wanted: number): boolean {
return wanted > 0 && releases.filter(release => release.settled).length >= wanted;
}
export function arrivalsDone(wanted: number, remaining: number, active: number, releases: readonly DetectedRelease[]): boolean {
return wanted === 0 ? remaining === 0 && active === 0 : releasesReached(releases, wanted);
}
export function observedClicks(records: readonly HostedTaskRecord[]): Map<string, RetryClick[]> {
return new Map(records.flatMap(entry => entry.issueId && entry.retryClicks.length ? [[entry.issueId, [...entry.retryClicks]] as const] : []));
}
export function keepPolling(workload: Pick<HostedWorkload, "poll">, pollMs = POLL_MS): { stop: () => Promise<void> } {
let running = true;
let wake: (() => void) | null = null;
const loop = (async () => {
while (running) {
await workload.poll().catch(() => undefined);
if (!running) break;
await new Promise<void>(resolve => { wake = resolve; setTimeout(resolve, pollMs).unref?.(); });
}
})();
return { stop: async () => { running = false; wake?.(); await loop; } };
}
export async function finalizeHosted(input: { api: Parameters<typeof cleanupHosted>[0]["api"]; keep: boolean; label: string; dir: string; state: HostedState | null;
record: (kind: string, data: Record<string, unknown>) => void }): Promise<{ errors: string[] } | null> {
if (input.keep) return null;
const state = input.state ?? await loadState(input.dir);
if (!state) return null;
return await cleanupHosted({ api: input.api, label: input.label, companyId: state.companyId, state, record: input.record })
.catch(error => ({ errors: [String(error)] }));
}
function watchIdentity(timeline: Timeline, samplesPath: string) {
let last: string | null = null;
let failing = false;
return (sample: HealthSample) => {
appendFileSync(samplesPath, `${JSON.stringify(sample)}\n`, { mode: 0o600 });
if (!sample.ok) {
if (!failing) timeline.add("hosted_health_failed", { status: sample.status, ms: sample.ms, error: sample.error ?? null });
failing = true;
return;
}
if (failing) timeline.add("hosted_health_recovered", { ms: sample.ms });
failing = false;
const identity = identityOf(sample);
if (identity !== last) timeline.add("hosted_health_identity", { commit: sample.commit, processStartedAt: sample.processStartedAt, previous: last });
last = identity;
};
}
async function observe(options: HostedOptions, probe: HealthProbe, api: HostedApi, dir: string, started: number, cancelled: () => boolean, timeline: Timeline): Promise<number> {
while (!cancelled() && Date.now() - started < options.maxWaitMs && !releasesReached(detectReleases(probe.samples, { now: Date.now() }), options.releases)) await delay(LOOP_MS);
await probe.stop();
const releases = detectReleases(probe.samples, { now: Date.now() });
const lines = releaseMarkdown(releases, continuity(probe.samples), continuity(requestSamples(api.requests)));
await writeFile(path.join(dir, "SUMMARY.md"), `${lines.join("\n")}\n`, { mode: 0o600 });
timeline.add("hosted_observed", { releases: releases.map(release => ({ shape: release.shape, firstNewAt: new Date(release.firstNewAt).toISOString(),
lastOldAt: new Date(release.lastOldAt).toISOString(), failed: release.failedRequests, commitChanged: release.commitChanged })) });
console.info(lines.join("\n"));
return releasesReached(releases, options.releases) ? 0 : 1;
}
export async function runHosted(argv: readonly string[]): Promise<number> {
const options = parseHostedCommand(argv);
const dir = path.join(resultsRoot, `hosted-${options.label}`);
await mkdir(dir, { recursive: true, mode: 0o700 });
const timeline = new Timeline(path.join(dir, "timeline.jsonl"));
const record = (kind: string, data: Record<string, unknown>) => { timeline.add(kind, data); };
let interrupted = false;
const onSignal = () => { interrupted = true; };
process.on("SIGINT", onSignal);
process.on("SIGTERM", onSignal);
const cancelled = () => interrupted;
const api = new HostedApi(options.target, hostedToken(options.target));
const me = await api.get<{ userId?: string; companyIds?: string[] }>("/api/cli-auth/me");
timeline.add("hosted_signed_in", { baseUrl: options.target.baseUrl, mode: options.mode, label: options.label, companies: me.companyIds?.length ?? 0 });
if (options.mode === "cleanup") {
const state = await loadState(dir);
const companyId = options.companyId ?? state?.companyId ?? await resolveCompany(api, null);
const report = await cleanupHosted({ api, label: options.label, companyId, state, record });
console.info(`Cleanup ${options.label}: ${JSON.stringify(report)}`);
return report.errors.length ? 1 : 0;
}
const census = await inventory(api, options.label);
timeline.add("hosted_inventory", { ...census });
const started = Date.now();
const probe = new HealthProbe(api, options.healthMs, watchIdentity(timeline, path.join(dir, "health.jsonl"))).start();
if (options.mode === "observe") return await observe(options, probe, api, dir, started, cancelled, timeline);
let state: HostedState | null = null;
let polling: { stop: () => Promise<void> } | null = null;
let exit = 2;
try {
const companyId = await resolveCompany(api, options.companyId);
state = await setupHosted({ api, options, companyId, dir, record });
await waitForAgentsReady(api as unknown as ChaosApi, Object.fromEntries(Object.entries(state.agents).map(([adapter, agent]) => [adapter, { id: agent!.id }])),
timeline, 10 * 60_000, 2_000, cancelled);
const plans = planHostedTasks(options, options.tasks ?? 2_000);
const workload = new HostedWorkload({ api, label: options.label, companyId, projectId: state.projectId, agents: state.agents, plans,
concurrency: options.concurrency, record, retryDuringWave: options.retryDuringWave });
let lastPoll = 0;
for (;;) {
const now = Date.now();
const releases = detectReleases(probe.samples, { now });
const reached = options.releases === 0 ? workload.remaining === 0 : releases.length >= options.releases;
if (!reached && !cancelled()) await workload.launchDue(now);
if (now - lastPoll >= POLL_MS) { lastPoll = now; await workload.poll(now); }
if (cancelled() || arrivalsDone(options.releases, workload.remaining, workload.active(now).length, releases) || now - started > options.maxWaitMs) break;
await delay(LOOP_MS);
}
for (const entry of workload.records) if (entry.issueId) state.issueIds.push(entry.issueId);
timeline.add("hosted_arrivals_ended", { launched: workload.launched, releases: detectReleases(probe.samples).length, interrupted, timedOut: Date.now() - started > options.maxWaitMs });
const releases = detectReleases(probe.samples, { now: Date.now() });
if (options.releases > 0 && !releasesReached(releases, options.releases)) timeline.add("hosted_releases_short", { wanted: options.releases, seen: releases.length });
polling = keepPolling(workload);
const graded = await gradeHosted({ api, companyId, agentIds: Object.values(state.agents).map(agent => agent!.id), releases,
health: () => continuity(probe.samples), apiContinuity: () => continuity(requestSamples(api.requests)),
stopObserver: () => polling!.stop(), observedClicks: () => observedClicks(workload.records), banners: () => new Map(workload.banners),
agentNames: Object.values(state.agents).map(agent => agent!.name),
lastReleaseAt: releases.at(-1)?.lastOldAt ?? Date.now(), settleMs: options.settleMs, drainMs: options.drainMs, dir, cancelled, record });
console.info(`\n${graded.markdown}`);
const short = options.releases > 0 && !releasesReached(releases, options.releases);
exit = graded.pass && !short && !interrupted ? 0 : 1;
} catch (error) {
timeline.add("harness_error", { error: error instanceof Error ? error.stack ?? error.message : String(error) });
console.error(error);
exit = 2;
} finally {
await polling?.stop();
await probe.stop();
await writeFile(path.join(dir, "health-summary.json"), `${JSON.stringify({ releases: detectReleases(probe.samples), health: continuity(probe.samples),
api: continuity(requestSamples(api.requests)), inventory: census }, null, 2)}\n`, { mode: 0o600 });
const cleaned = await finalizeHosted({ api, keep: options.keep, label: options.label, dir, state, record });
if (cleaned && cleaned.errors.length) exit = Math.max(exit, 1);
process.off("SIGINT", onSignal);
process.off("SIGTERM", onSignal);
}
console.info(`Hosted run ${options.label}: results ${dir}`);
return exit;
}
+145
View File
@@ -0,0 +1,145 @@
import { mkdtemp, readFile, rm } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import { gradeHosted, releaseWindows } from "./hosted-grade.js";
import {
duplicateAgentComments, duplicateChildren, failureChain, hostedCompanyRuns, hostedIssues, issueViewFields, pendingPersonItems, runRow, startedIssues,
} from "./hosted-readers.js";
import { cleanupHosted, pickEnvironment } from "./hosted-setup.js";
import { detectReleases } from "./hosted-release.js";
type Json = Record<string, any>;
const dirs: string[] = [];
afterEach(async () => { for (const dir of dirs.splice(0)) await rm(dir, { recursive: true, force: true }); });
function fakeApi(routes: Record<string, unknown | ((route: string) => unknown)>, writes: Array<{ method: string; route: string; body?: unknown }> = []) {
const read = (route: string) => {
const key = Object.keys(routes).find(candidate => route === candidate || route.startsWith(`${candidate}?`));
if (key === undefined) throw new Error(`GET ${route} returned 404`);
const value = routes[key];
return typeof value === "function" ? (value as (route: string) => unknown)(route) : value;
};
return {
get: async <T>(route: string) => read(route) as T,
post: async <T>(route: string, body?: unknown) => { writes.push({ method: "POST", route, body }); return (route.endsWith("/retry") ? { accepted: true } : {}) as T; },
patch: async <T>(route: string, body?: unknown) => { writes.push({ method: "PATCH", route, body }); return {} as T; },
delete: async (route: string) => { writes.push({ method: "DELETE", route }); },
};
}
const run = (overrides: Json): Json => ({ id: "r1", agentId: "a1", issueId: "i1", status: "succeeded", errorCode: null, error: null,
createdAt: "2026-11-12T17:00:00.000Z", startedAt: "2026-11-12T17:00:01.000Z", finishedAt: "2026-11-12T17:10:00.000Z",
updatedAt: "2026-11-12T17:10:00.000Z", lastOutputAt: null, ...overrides });
describe("hosted API readers", () => {
it("maps run rows from the company run list, keeps only the harness's agents, and never claims an owning server process", async () => {
const api = fakeApi({ "/api/companies/c1/heartbeat-runs": (route: string) => route.includes("agentId=a1")
? [run({}), run({ id: "foreign", agentId: "someone-else" }), run({ id: "r2", issueId: null, contextSnapshot: { issueId: "i2" }, status: "running",
finishedAt: null, lastOutputAt: "2026-11-12T17:20:00.000Z" })] : [] });
const rows = await hostedCompanyRuns(api, "c1", ["a1"]);
expect(rows.map(row => row.runId)).toEqual(["r1", "r2"]);
expect(rows[1]).toMatchObject({ issueId: "i2", status: "running", finishedAt: null, lastActivityAt: Date.parse("2026-11-12T17:20:00.000Z"), ownerPid: null });
expect(runRow(run({ error: "x".repeat(900) })).error).toHaveLength(400);
});
it("lists the harness's tasks, counts only ones that had a run, and reads a person's wait from interactions and approvals", async () => {
const api = fakeApi({
"/api/companies/c1/issues": [{ id: "i1", identifier: "PC-1", title: "[rc] a", status: "done", assigneeAgentId: "a1" },
{ id: "i2", title: "[rc] b", status: "blocked", assigneeAgentId: "a1" }, { id: "i3", title: "never ran", status: "todo", assigneeAgentId: "a1" },
{ id: "i4", title: "hidden", status: "todo", assigneeAgentId: "a1", hiddenAt: "2026-11-12T00:00:00Z" },
{ id: "x1", title: "not ours", status: "todo", assigneeAgentId: "other" }],
"/api/issues/i1/interactions": [], "/api/issues/i1/approvals": [],
"/api/issues/i2/interactions": [{ status: "pending" }], "/api/issues/i2/approvals": [{ status: "approved" }],
"/api/issues/i4/interactions": () => { throw new Error("boom"); },
});
const issues = await hostedIssues(api, "c1", ["a1"]);
expect(issues.map(issue => issue.id)).toEqual(["i1", "i2", "i3", "i4"]);
const started = startedIssues(issues, [runRow(run({})), runRow(run({ id: "r2", issueId: "i2" })), runRow(run({ id: "r4", issueId: "i4" }))]);
expect(started.map(issue => issue.id)).toEqual(["i1", "i2"]);
const person = await pendingPersonItems(api, ["i1", "i2", "i4"]);
expect([...person.questions]).toEqual(["i2"]);
expect([...person.approvals]).toEqual([]);
expect(person.unreadable).toEqual(["i4"]);
});
it("reads the same task view fields the local grade reads, failure chains, and duplicated side effects", async () => {
expect(issueViewFields({ status: "todo", scheduledRetry: true, interruption: { state: "failed", canRetry: true, userAction: "choose_model",
responsibility: "user", providerFailure: { category: "rate_limit" } }, activeRecoveryAction: { ownerType: "board" }, executionBlocker: { code: "x" },
blockedBy: [{ status: "done" }, { status: "todo" }] })).toEqual({ status: "todo", scheduledRetry: true, interruption: { state: "failed", canRetry: true,
retryWait: false, userAction: "choose_model", responsibility: "user", providerFailureCategory: "rate_limit" }, activeRecoveryOwner: "board", executionBlocker: true, openBlockers: 1 });
const api = fakeApi({
"/api/heartbeat-runs/r9/events": [{ eventType: "run.started", level: "info" }, { eventType: "runner.lost", level: "error", message: "process gone" }],
"/api/issues/i1/comments": [{ authorAgentId: "a1", body: "DONE-x" }, { authorAgentId: "a1", body: "DONE-x" }, { authorUserId: "u", body: "DONE-x" }],
});
expect(await failureChain(api, "r9")).toEqual(["runner.lost: process gone"]);
expect(await duplicateAgentComments(api, ["i1"])).toEqual([{ issueId: "i1", count: 2 }]);
expect(duplicateChildren([{ id: "s1", identifier: null, title: "SM sub 1", status: "done", parentId: "p", assigneeAgentId: "a1", hidden: false },
{ id: "s2", identifier: null, title: "SM sub 1", status: "done", parentId: "p", assigneeAgentId: "a1", hidden: false }])).toEqual([{ parentId: "p", title: "SM sub 1", count: 2 }]);
});
it("grades every started task with the release-swap grade over the API, clicks Retry where offered and labels each failure", async () => {
const dir = await mkdtemp(path.join(os.tmpdir(), "hosted-grade-"));
dirs.push(dir);
const writes: Array<{ method: string; route: string; body?: unknown }> = [];
let retried = false;
const api = fakeApi({
"/api/companies/c1/heartbeat-runs": () => [run({ id: "r1", issueId: "i1" }), run({ id: "r2", issueId: "i2", status: "failed", errorCode: "process_lost" }),
run({ id: "r3", issueId: "i3", status: "failed", errorCode: "controller_lease_lost" }),
...(retried ? [run({ id: "r4", issueId: "i2", createdAt: new Date().toISOString() })] : [])],
"/api/companies/c1/issues": [{ id: "i1", title: "a", status: "done", assigneeAgentId: "a1" }, { id: "i2", title: "b", status: "todo", assigneeAgentId: "a1" },
{ id: "i3", title: "c", status: "in_progress", assigneeAgentId: "a1" }],
"/api/issues/i1": { status: "done" },
"/api/issues/i2": () => retried ? { status: "done" } : { status: "todo", interruption: { state: "failed", canRetry: true, observedRunId: "r2" } },
"/api/issues/i3": { status: "in_progress" },
"/api/issues/i1/interactions": [], "/api/issues/i2/interactions": [], "/api/issues/i3/interactions": [],
"/api/issues/i1/approvals": [], "/api/issues/i2/approvals": [], "/api/issues/i3/approvals": [],
"/api/issues/i1/comments": [], "/api/issues/i2/comments": [], "/api/issues/i3/comments": [],
"/api/heartbeat-runs/r2/events": [], "/api/heartbeat-runs/r3/events": [], "/api/heartbeat-runs/r4/events": [],
}, writes);
const post = api.post;
api.post = async <T>(route: string, body?: unknown) => { if (route.endsWith("/retry")) retried = true; return post<T>(route, body); };
const releases = detectReleases([{ at: 0, ok: true, status: 200, ms: 1, processStartedAt: "a", commit: "x" },
{ at: 1_000, ok: true, status: 200, ms: 1, processStartedAt: "b", commit: "y" }], { now: 1_000_000 });
let latestApi = { requests: 0, failures: 0, slow: 0, longestGapMs: 0, longestGap: null as { from: number; to: number } | null };
const graded = await gradeHosted({ api, companyId: "c1", agentIds: ["a1"], releases, health: () => ({ requests: 2, failures: 0, slow: 0, longestGapMs: 1_000, longestGap: null }),
apiContinuity: () => latestApi, stopObserver: async () => { latestApi = { requests: 9, failures: 3, slow: 1, longestGapMs: 4_000, longestGap: { from: 0, to: 4_000 } }; }, observedClicks: () => new Map(), lastReleaseAt: Date.now() - 10_000,
settleMs: 5, drainMs: 5, dir, cancelled: () => false, record: () => {}, pollMs: 5 });
expect(writes.filter(write => write.route.endsWith("/retry"))).toEqual([{ method: "POST", route: "/api/issues/i2/retry", body: { idempotencyKey: expect.any(String), observedRunId: "r2" } }]);
expect(graded.headline).toBe("1 / 3 tasks completed hands-off");
expect(graded.markdown.split("\n").slice(0, 4)).toEqual(["1 / 3 tasks completed hands-off", "Retry banner shown: 1 (cleared by itself: 0)",
"Retry worked / clicked: 1 / 1", "Assigned-work invariant: not available on this build (HTTP no answer)."]);
expect(graded.pass).toBe(false);
const json = JSON.parse(await readFile(path.join(dir, "hosted-release-swap.json"), "utf8"));
expect(json.result.byLabel).toEqual({ "needed Retry (click worked)": 1, "nothing pending": 1 });
expect(json.failedRuns.map((failed: Json) => [failed.runId, failed.release])).toEqual([["r2", 1], ["r3", 1]]);
expect(graded.markdown).toContain("Unavailable over the API:");
expect(graded.markdown).toContain("API requests: 9 requests, 3 failed, 1 slow, longest gap between answers 4.0 s.");
expect(json.api).toMatchObject({ requests: 9, failures: 3 });
expect(releaseWindows(releases)[0]).toMatchObject({ index: 1, spawnedAt: 1_000, fromPid: null });
});
it("picks the company's sandbox environment over other remote drivers, or asks for one", async () => {
const both = fakeApi({ "/api/companies/c1/environments": [{ id: "local", driver: "local" }, { id: "computer", driver: "plugin" }, { id: "box", driver: "sandbox" }] });
expect(await pickEnvironment(both, "c1", null)).toBe("box");
expect(await pickEnvironment(both, "c1", "computer")).toBe("computer");
const two = fakeApi({ "/api/companies/c1/environments": [{ id: "a", driver: "sandbox" }, { id: "b", driver: "sandbox" }] });
await expect(pickEnvironment(two, "c1", null)).rejects.toThrow(/--hosted-environment/);
});
it("cleans up only what carries the run label: pauses and removes its agents, cancels their live runs, archives their tasks, deletes its secrets", async () => {
const writes: Array<{ method: string; route: string; body?: unknown }> = [];
const api = fakeApi({
"/api/companies/c1/agents": [{ id: "a1", name: "RC rc-x opencode" }, { id: "other", name: "Someone's agent" }, { id: "a9", name: "RC rc-xy opencode" }],
"/api/companies/c1/heartbeat-runs": (route: string) => route.includes("agentId=a1") ? [run({ status: "running" }), run({ id: "f", agentId: "other", status: "running" })] : [],
"/api/companies/c1/issues": (route: string) => route.includes("assigneeAgentId=a1") ? [{ id: "i1", assigneeAgentId: "a1" }, { id: "x", assigneeAgentId: "other" }] : [],
"/api/companies/c1/secrets": [{ id: "s1", name: "restart-chaos rc-x OPENROUTER_API_KEY" }, { id: "s2", name: "OPENROUTER_API_KEY" }, { id: "s3", name: "restart-chaos rc-xy OPENROUTER_API_KEY" }],
"/api/companies/c1/projects": [{ id: "p1", name: "Restart chaos rc-x" }, { id: "p2", name: "Real project" }],
"/api/agents/a1": { id: "a1", status: "terminated" },
}, writes);
const report = await cleanupHosted({ api, label: "rc-x", companyId: "c1", state: null, record: () => {} });
expect(writes.map(write => `${write.method} ${write.route}`)).toEqual(["PATCH /api/agents/a1", "POST /api/heartbeat-runs/r1/cancel", "PATCH /api/issues/i1",
"DELETE /api/agents/a1", "DELETE /api/secrets/s1", "PATCH /api/projects/p1"]);
expect(report).toMatchObject({ runsCancelled: 1, tasksArchived: 1, agentsPaused: 1, agentsRemoved: 1, secretsDeleted: 1, projectArchived: true, errors: [] });
});
});
+184
View File
@@ -0,0 +1,184 @@
import type { HostedApi } from "./hosted-api.js";
import type { GradeRun, GradeTaskInput } from "./release-swap-grade.js";
type Json = Record<string, any>;
export type ReadApi = Pick<HostedApi, "get">;
export const UNAVAILABLE_OVER_API = [
"queuedWakes: the API has no read of a task's queued wake requests, so a task whose only owner is a queued wake grades as having none",
"ownerPid / owning server process of each run: the API does not expose which server process (controller boot) owned a run",
"lostWhileOldAlive: needs the owning server process, so it is not computed",
"doubleExecutors: two Runner processes for one run come from database cross-server evidence, not the API",
"late-start and preparation-during-recovery evidence: the harness does not drive the release, so it cannot place probes on the outgoing server",
] as const;
export interface HostedRunRow {
runId: string;
agentId: string | null;
issueId: string | null;
status: string;
errorCode: string | null;
error: string | null;
createdAt: number | null;
startedAt: number | null;
finishedAt: number | null;
lastActivityAt: number | null;
ownerPid: null;
}
export interface HostedIssueRow {
id: string;
identifier: string | null;
title: string;
status: string;
parentId: string | null;
assigneeAgentId: string | null;
hidden: boolean;
}
const ms = (value: unknown): number | null => {
if (value === null || value === undefined || value === "") return null;
const parsed = typeof value === "number" ? value : Date.parse(String(value));
return Number.isFinite(parsed) ? parsed : null;
};
const text = (value: unknown): string | null => value === null || value === undefined ? null : String(value);
export function runRow(run: Json): HostedRunRow {
const activity = [ms(run.updatedAt), ms(run.lastOutputAt), ms(run.lastUsefulActionAt), ms(run.finishedAt)].filter((at): at is number => at !== null);
return {
runId: String(run.id), agentId: text(run.agentId), issueId: text(run.issueId ?? run.contextSnapshot?.issueId), status: String(run.status),
errorCode: text(run.errorCode), error: run.error ? String(run.error).slice(0, 400) : null,
createdAt: ms(run.createdAt), startedAt: ms(run.startedAt), finishedAt: ms(run.finishedAt),
lastActivityAt: activity.length ? Math.max(...activity) : null, ownerPid: null,
};
}
export const RUN_PAGE = 1_000;
export const ISSUE_PAGE = 500;
export const EVENT_PAGE = 500;
export async function hostedIssues(api: ReadApi, companyId: string, agentIds: readonly string[]): Promise<HostedIssueRow[]> {
const byId = new Map<string, HostedIssueRow>();
for (const agentId of agentIds) {
for (let offset = 0; ; offset += ISSUE_PAGE) {
const page = await api.get<Json[]>(`/api/companies/${companyId}/issues?assigneeAgentId=${encodeURIComponent(agentId)}&includeAgentCreatedTasks=true`
+ `&limit=${ISSUE_PAGE}&offset=${offset}`);
for (const issue of page) {
if (issue.assigneeAgentId !== agentId) continue;
byId.set(String(issue.id), { id: String(issue.id), identifier: text(issue.identifier), title: String(issue.title ?? ""), status: String(issue.status),
parentId: text(issue.parentId), assigneeAgentId: text(issue.assigneeAgentId), hidden: Boolean(issue.hiddenAt) });
}
if (page.length < ISSUE_PAGE) break;
}
}
return [...byId.values()];
}
export async function hostedCompanyRuns(api: ReadApi, companyId: string, agentIds: readonly string[]): Promise<HostedRunRow[]> {
const rows = new Map<string, HostedRunRow>();
let truncated = false;
for (const agentId of agentIds) {
const page = await api.get<Json[]>(`/api/companies/${companyId}/heartbeat-runs?agentId=${encodeURIComponent(agentId)}&limit=${RUN_PAGE}`);
if (page.length >= RUN_PAGE) truncated = true;
for (const run of page) if (run.agentId === agentId) rows.set(String(run.id), runRow(run));
}
if (!truncated) return [...rows.values()];
const ours = new Set(agentIds);
for (const issue of await hostedIssues(api, companyId, agentIds)) {
const runs = await api.get<Json[]>(`/api/issues/${issue.id}/runs`);
for (const run of runs) {
if (!ours.has(String(run.agentId)) || rows.has(String(run.runId))) continue;
rows.set(String(run.runId), runRow({ ...run, id: run.runId, issueId: issue.id }));
}
}
return [...rows.values()];
}
export function startedIssues(issues: readonly HostedIssueRow[], runs: readonly HostedRunRow[]): HostedIssueRow[] {
const withRun = new Set(runs.flatMap(run => run.issueId ? [run.issueId] : []));
return issues.filter(issue => !issue.hidden && withRun.has(issue.id));
}
export async function pendingPersonItems(api: ReadApi, issueIds: readonly string[]): Promise<{ questions: Set<string>; approvals: Set<string>; unreadable: string[] }> {
const questions = new Set<string>();
const approvals = new Set<string>();
const unreadable: string[] = [];
for (const id of issueIds) {
try {
const interactions = await api.get<Json[]>(`/api/issues/${id}/interactions`);
if (interactions.some(interaction => interaction.status === "pending")) questions.add(id);
const linked = await api.get<Json[]>(`/api/issues/${id}/approvals`);
if (linked.some(approval => ["pending", "revision_requested"].includes(String(approval.status ?? approval.approval?.status)))) approvals.add(id);
} catch {
unreadable.push(id);
}
}
return { questions, approvals, unreadable };
}
export function issueViewFields(issue: Json): Omit<GradeTaskInput, "issueId" | "identifier" | "title" | "runs" | "queuedWakes" | "retryClicks" | "pendingApproval" | "pendingQuestion"> {
const interruption = issue.interruption;
return {
status: String(issue.status),
scheduledRetry: Boolean(issue.scheduledRetry),
interruption: interruption ? { state: String(interruption.state), canRetry: interruption.canRetry === true, retryWait: Boolean(interruption.retryWait),
userAction: text(interruption.userAction), responsibility: text(interruption.responsibility), providerFailureCategory: text(interruption.providerFailure?.category) } : null,
activeRecoveryOwner: text(issue.activeRecoveryAction?.ownerType),
executionBlocker: Boolean(issue.executionBlocker),
openBlockers: (issue.blockedBy ?? []).filter((blocker: Json) => blocker.status !== "done" && blocker.status !== "cancelled").length,
};
}
export function gradeRuns(runs: readonly HostedRunRow[]): GradeRun[] {
return runs.map(run => ({ runId: run.runId, status: run.status, errorCode: run.errorCode, createdAt: run.createdAt, startedAt: run.startedAt,
finishedAt: run.finishedAt, lastActivityAt: run.lastActivityAt }));
}
export async function runEvents(api: ReadApi, runId: string): Promise<Json[]> {
const events: Json[] = [];
for (let afterSeq = 0; ;) {
const page = await api.get<Json[]>(`/api/heartbeat-runs/${runId}/events?afterSeq=${afterSeq}&limit=${EVENT_PAGE}`);
events.push(...page);
const last = Number(page.at(-1)?.seq);
if (page.length < EVENT_PAGE || !Number.isFinite(last) || last <= afterSeq) return events;
afterSeq = last;
}
}
export async function failureChain(api: ReadApi, runId: string): Promise<string[]> {
const events = await runEvents(api, runId).catch(() => [] as Json[]);
return events.filter(event => event.level === "error" || event.level === "warn" || /fail|error|lost/i.test(String(event.eventType)))
.slice(-6).map(event => `${event.eventType}${event.message ? `: ${String(event.message).slice(0, 240)}` : ""}`);
}
export async function firstEventAfter(api: ReadApi, runId: string, after: number): Promise<number | null> {
const events = await runEvents(api, runId).catch(() => [] as Json[]);
const times = events.map(event => ms(event.createdAt)).filter((at): at is number => at !== null && at > after);
return times.length ? Math.min(...times) : null;
}
export async function duplicateAgentComments(api: ReadApi, issueIds: readonly string[]): Promise<Array<{ issueId: string; count: number }>> {
const found: Array<{ issueId: string; count: number }> = [];
for (const id of issueIds) {
const comments = await api.get<Json[]>(`/api/issues/${id}/comments`).catch(() => [] as Json[]);
const counts = new Map<string, number>();
for (const comment of comments) if (comment.authorAgentId) {
const key = `${comment.authorAgentId}\u0000${comment.body}`;
counts.set(key, (counts.get(key) ?? 0) + 1);
}
for (const count of counts.values()) if (count > 1) found.push({ issueId: id, count });
}
return found;
}
export function duplicateChildren(issues: readonly HostedIssueRow[]): Array<{ parentId: string; title: string; count: number }> {
const counts = new Map<string, { parentId: string; title: string; count: number }>();
for (const issue of issues) {
if (!issue.parentId || issue.hidden) continue;
const key = `${issue.parentId}\u0000${issue.title}`;
const entry = counts.get(key) ?? { parentId: issue.parentId, title: issue.title, count: 0 };
entry.count += 1;
counts.set(key, entry);
}
return [...counts.values()].filter(entry => entry.count > 1);
}
@@ -0,0 +1,45 @@
import { describe, expect, it } from "vitest";
import { continuity, detectReleases, releaseMarkdown, type HealthSample } from "./hosted-release.js";
const A = { processStartedAt: "2026-11-12T16:00:00.000Z", commit: "aaaaaaaaaa" };
const B = { processStartedAt: "2026-11-12T16:40:00.000Z", commit: "bbbbbbbbbb" };
const C = { processStartedAt: "2026-11-12T17:20:00.000Z", commit: "bbbbbbbbbb" };
const ok = (at: number, build: typeof A, ms = 100): HealthSample => ({ at, ok: true, status: 200, ms, ...build });
const fail = (at: number, status: number | null = 502): HealthSample => ({ at, ok: false, status, ms: 50, processStartedAt: null, commit: null });
describe("hosted release detection", () => {
it("sees an overlap swap: two builds answer for a while, no request fails", () => {
const samples = [ok(0, A), ok(2_000, A), ok(4_000, B), ok(6_000, A), ok(8_000, B), ok(10_000, A), ok(12_000, B), ok(14_000, B), ok(80_000, B)];
const [release, ...rest] = detectReleases(samples);
expect(rest).toEqual([]);
expect(release).toMatchObject({ index: 1, shape: "overlap", commitChanged: true, lastOldOnlyAt: 2_000, firstNewAt: 4_000, lastOldAt: 10_000,
overlapWindow: { from: 4_000, to: 10_000 }, failedRequests: 0, timeToFirstNewMs: 2_000, settled: true });
});
it("sees a stop-then-start swap as a gap of failures before the new build answers", () => {
const samples = [ok(0, A), ok(2_000, A), fail(4_000), fail(6_000, null), fail(8_000, 503), ok(10_000, B, 2_500), ok(12_000, B)];
const [release] = detectReleases(samples, { now: 100_000 });
expect(release).toMatchObject({ shape: "stop_then_start", overlapWindow: null, failedRequests: 3, firstFailureAt: 4_000, timeToFirstNewMs: 6_000,
slowRequests: 1, lastOldAt: 2_000 });
});
it("counts each release once across a series, including a restart on the same commit, and does not settle an open one", () => {
const samples = [ok(0, A), ok(2_000, B), ok(4_000, A), ok(6_000, B), ok(100_000, B), ok(102_000, C), ok(104_000, B), ok(106_000, C)];
const releases = detectReleases(samples, { now: 110_000 });
expect(releases.map(release => [release.index, release.shape, release.commitChanged, release.settled])).toEqual([
[1, "overlap", true, true], [2, "overlap", false, false]]);
});
it("ignores failed samples when no build has answered yet, and reports none for a steady instance", () => {
expect(detectReleases([fail(0), ok(2_000, A), ok(4_000, A)])).toEqual([]);
expect(detectReleases([])).toEqual([]);
});
it("reports probe continuity: requests, failures, slow answers and the longest gap between answers", () => {
const report = continuity([ok(0, A), ok(2_000, A), fail(4_000), fail(6_000), ok(9_000, B, 3_000), ok(11_000, B)]);
expect(report).toEqual({ requests: 6, failures: 2, slow: 1, longestGapMs: 7_000, longestGap: { from: 2_000, to: 9_000 } });
const lines = releaseMarkdown(detectReleases([ok(0, A), ok(2_000, B), ok(4_000, A), ok(6_000, B)]), report, continuity([]));
expect(lines[0]).toBe("Health probe: 6 requests, 2 failed, 1 slow, longest gap between answers 7.0 s.");
expect(lines.at(-1)).toMatch(/^\| 1 \| overlap \| aaaaaaaaa → bbbbbbbbb \|/);
});
});
+116
View File
@@ -0,0 +1,116 @@
export interface HealthSample {
at: number;
ok: boolean;
status: number | null;
ms: number;
processStartedAt: string | null;
commit: string | null;
error?: string | null;
}
export type ReleaseShape = "overlap" | "stop_then_start" | "clean_switch";
export interface DetectedRelease {
index: number;
from: { processStartedAt: string | null; commit: string | null };
to: { processStartedAt: string | null; commit: string | null };
commitChanged: boolean;
lastOldOnlyAt: number;
firstNewAt: number;
lastOldAt: number;
overlapWindow: { from: number; to: number } | null;
shape: ReleaseShape;
failedRequests: number;
slowRequests: number;
firstFailureAt: number | null;
timeToFirstNewMs: number;
settled: boolean;
}
export interface ContinuityReport {
requests: number;
failures: number;
slow: number;
longestGapMs: number;
longestGap: { from: number; to: number } | null;
}
export const SLOW_REQUEST_MS = 2_000;
export const RELEASE_SETTLE_MS = 60_000;
export const identityOf = (sample: Pick<HealthSample, "processStartedAt" | "commit">) => `${sample.commit ?? "?"}@${sample.processStartedAt ?? "?"}`;
export function detectReleases(samples: readonly HealthSample[], options: { slowMs?: number; settleMs?: number; now?: number } = {}): DetectedRelease[] {
const slowMs = options.slowMs ?? SLOW_REQUEST_MS;
const settleMs = options.settleMs ?? RELEASE_SETTLE_MS;
const sorted = [...samples].sort((left, right) => left.at - right.at);
const now = options.now ?? sorted.at(-1)?.at ?? 0;
const releases: DetectedRelease[] = [];
let current: HealthSample | null = null;
let lastCurrentOnlyAt: number | null = null;
const retired = new Set<string>();
for (let position = 0; position < sorted.length; position += 1) {
const sample = sorted[position]!;
if (!sample.ok || !sample.processStartedAt) continue;
if (!current) { current = sample; lastCurrentOnlyAt = sample.at; continue; }
const identity = identityOf(sample);
if (identity === identityOf(current)) { lastCurrentOnlyAt = sample.at; continue; }
if (retired.has(identity)) continue;
const oldIdentity = identityOf(current);
const firstNewAt = sample.at;
const later = sorted.slice(position);
const oldAnswers = later.filter(entry => entry.ok && identityOf(entry) === oldIdentity);
const lastOldAt = oldAnswers.length ? oldAnswers.at(-1)!.at : lastCurrentOnlyAt!;
const windowFrom = lastCurrentOnlyAt!;
const windowTo = Math.max(firstNewAt, lastOldAt);
const inWindow = sorted.filter(entry => entry.at > windowFrom && entry.at <= windowTo + settleMs);
const failures = inWindow.filter(entry => !entry.ok);
const failedBeforeNew = sorted.filter(entry => entry.at > windowFrom && entry.at < firstNewAt && !entry.ok);
const overlap = lastOldAt > firstNewAt ? { from: firstNewAt, to: lastOldAt } : null;
const shape: ReleaseShape = overlap && failures.length === 0 ? "overlap" : failedBeforeNew.length ? "stop_then_start" : overlap ? "overlap" : "clean_switch";
releases.push({
index: releases.length + 1,
from: { processStartedAt: current.processStartedAt, commit: current.commit },
to: { processStartedAt: sample.processStartedAt, commit: sample.commit },
commitChanged: current.commit !== sample.commit,
lastOldOnlyAt: windowFrom, firstNewAt, lastOldAt, overlapWindow: overlap, shape,
failedRequests: failures.length,
slowRequests: inWindow.filter(entry => entry.ok && entry.ms >= slowMs).length,
firstFailureAt: failures[0]?.at ?? null,
timeToFirstNewMs: firstNewAt - (failedBeforeNew[0]?.at ?? windowFrom),
settled: now >= windowTo + settleMs,
});
retired.add(oldIdentity);
current = sample;
lastCurrentOnlyAt = sample.at;
}
return releases;
}
export function continuity(samples: readonly HealthSample[], slowMs = SLOW_REQUEST_MS): ContinuityReport {
const sorted = [...samples].sort((left, right) => left.at - right.at);
let previousOk: number | null = null;
let longest: { from: number; to: number } | null = null;
for (const sample of sorted) {
if (!sample.ok) continue;
if (previousOk !== null && (!longest || sample.at - previousOk > longest.to - longest.from)) longest = { from: previousOk, to: sample.at };
previousOk = sample.at;
}
return { requests: sorted.length, failures: sorted.filter(sample => !sample.ok).length, slow: sorted.filter(sample => sample.ok && sample.ms >= slowMs).length,
longestGapMs: longest ? longest.to - longest.from : 0, longestGap: longest };
}
export function releaseMarkdown(releases: readonly DetectedRelease[], health: ContinuityReport, api: ContinuityReport): string[] {
const iso = (at: number | null) => at === null ? "–" : new Date(at).toISOString();
const seconds = (ms: number) => `${(ms / 1000).toFixed(1)} s`;
return [
`Health probe: ${health.requests} requests, ${health.failures} failed, ${health.slow} slow, longest gap between answers ${seconds(health.longestGapMs)}.`,
`API requests: ${api.requests} requests, ${api.failures} failed, ${api.slow} slow, longest gap between answers ${seconds(api.longestGapMs)}.`,
"",
"| Release | Shape | Commit changed | New build first answered | Old build last answered | Two builds answering | Failed | Slow | Time to first new answer |",
"| --- | --- | --- | --- | --- | --- | --- | --- | --- |",
...releases.map(release => `| ${release.index} | ${release.shape} | ${release.commitChanged ? `${release.from.commit?.slice(0, 9) ?? "?"} → ${release.to.commit?.slice(0, 9) ?? "?"}` : "no"} | `
+ `${iso(release.firstNewAt)} | ${iso(release.lastOldAt)} | ${release.overlapWindow ? seconds(release.overlapWindow.to - release.overlapWindow.from) : "none"} | `
+ `${release.failedRequests} | ${release.slowRequests} | ${seconds(release.timeToFirstNewMs)} |`),
];
}
+218
View File
@@ -0,0 +1,218 @@
import { readFile, writeFile } from "node:fs/promises";
import path from "node:path";
import { setTimeout as delay } from "node:timers/promises";
import { runnerProfiles } from "../runner-e2e/catalog.js";
import type { SecretReference, SecretReferenceMap } from "../runner-e2e/types.js";
import { ChaosApiError } from "./api.js";
import { CREDENTIAL_FOR_ADAPTER, PROFILE_FOR_ADAPTER } from "./config.js";
import type { HostedApi } from "./hosted-api.js";
import type { HostedOptions } from "./hosted-config.js";
import { hostedIssues, type HostedIssueRow } from "./hosted-readers.js";
import { chaosLifecycleOverrides } from "./seed.js";
import { agentRunCaps } from "./staging-mix.js";
import type { AdapterId } from "./types.js";
type Json = Record<string, any>;
export type SetupApi = Pick<HostedApi, "get" | "post" | "patch" | "delete">;
export const projectName = (label: string) => `Restart chaos ${label}`;
export const agentName = (label: string, adapter: AdapterId) => `RC ${label} ${adapter}`;
export const secretName = (label: string, key: string) => `restart-chaos ${label} ${key}`;
export const taskTag = (label: string) => `[${label}]`;
export interface HostedState {
schema: "paperclip.restart-chaos.hosted-state/v1";
label: string;
baseUrl: string;
companyId: string;
projectId: string | null;
environmentId: string | null;
secrets: Array<{ id: string; key: string }>;
agents: Partial<Record<AdapterId, { id: string; name: string }>>;
issueIds: string[];
}
export const statePath = (dir: string) => path.join(dir, "hosted-state.json");
export async function saveState(dir: string, state: HostedState): Promise<void> {
await writeFile(statePath(dir), `${JSON.stringify(state, null, 2)}\n`, { mode: 0o600 });
}
export async function loadState(dir: string): Promise<HostedState | null> {
try { return JSON.parse(await readFile(statePath(dir), "utf8")) as HostedState; } catch { return null; }
}
export async function resolveCompany(api: SetupApi, requested: string | null): Promise<string> {
const me = await api.get<{ companyIds?: string[] }>("/api/cli-auth/me");
const companies = me.companyIds ?? [];
if (requested) {
if (!companies.includes(requested)) throw new Error(`The signed-in board user is not a member of company ${requested}`);
return requested;
}
if (companies.length !== 1) throw new Error(`The signed-in user belongs to ${companies.length} companies; pass --hosted-company <id>`);
return companies[0]!;
}
export interface InstanceInventory {
companies: number;
agents: number;
activeAgents: number;
liveRuns: number;
openTasks: number;
}
export async function inventory(api: SetupApi, label: string | null): Promise<InstanceInventory> {
const me = await api.get<{ companyIds?: string[] }>("/api/cli-auth/me");
const out: InstanceInventory = { companies: 0, agents: 0, activeAgents: 0, liveRuns: 0, openTasks: 0 };
for (const companyId of me.companyIds ?? []) {
out.companies += 1;
const all = await api.get<Json[]>(`/api/companies/${companyId}/agents`);
const isOurs = (agent: Json) => label !== null && String(agent.name).startsWith(`RC ${label} `);
const agents = all.filter(agent => !isOurs(agent));
const ours = new Set(all.filter(isOurs).map(agent => String(agent.id)));
out.agents += agents.length;
out.activeAgents += agents.filter(agent => !["paused", "terminated"].includes(String(agent.status))).length;
const live = await api.get<Json[]>(`/api/companies/${companyId}/live-runs`).catch(() => [] as Json[]);
out.liveRuns += live.filter(run => !ours.has(String(run.agentId))).length;
const issues = await api.get<Json[]>(`/api/companies/${companyId}/issues?limit=1000`).catch(() => [] as Json[]);
out.openTasks += issues.filter(issue => ["todo", "in_progress"].includes(String(issue.status)) && !ours.has(String(issue.assigneeAgentId))).length;
}
return out;
}
export function credentialKeys(ratio: ReadonlyArray<readonly [AdapterId, number]>): Array<(typeof CREDENTIAL_FOR_ADAPTER)[AdapterId]> {
return [...new Set(ratio.map(([adapter]) => CREDENTIAL_FOR_ADAPTER[adapter]))];
}
export async function pickEnvironment(api: SetupApi, companyId: string, requested: string | null): Promise<string> {
const environments = await api.get<Json[]>(`/api/companies/${companyId}/environments`);
if (requested) {
if (!environments.some(environment => environment.id === requested)) throw new Error(`Environment ${requested} is not in company ${companyId}`);
return requested;
}
const active = environments.filter(environment => environment.driver !== "local" && environment.status !== "archived");
const sandboxes = active.filter(environment => environment.driver === "sandbox");
const remote = sandboxes.length ? sandboxes : active;
if (remote.length !== 1) {
throw new Error(`Company ${companyId} has ${remote.length} sandbox environments (${remote.map(environment => `${environment.id} ${environment.driver}`).join(", ") || "none"}); `
+ "pass --hosted-environment <id>");
}
return String(remote[0]!.id);
}
export async function setupHosted(input: { api: SetupApi; options: HostedOptions; companyId: string; dir: string; env?: NodeJS.ProcessEnv;
record: (kind: string, data: Record<string, unknown>) => void }): Promise<HostedState> {
const { api, options, companyId, record } = input;
const env = input.env ?? process.env;
const keys = credentialKeys(options.ratio);
const missing = keys.filter(key => !env[key]);
if (missing.length) throw new Error(`Missing ${missing.join(", ")}; run with: set -a; source ~/.secrets; set +a`);
const state: HostedState = { schema: "paperclip.restart-chaos.hosted-state/v1", label: options.label, baseUrl: options.target.baseUrl, companyId,
projectId: null, environmentId: null, secrets: [], agents: {}, issueIds: [] };
await saveState(input.dir, state);
state.environmentId = await pickEnvironment(api, companyId, options.environmentId);
const secretRefs: SecretReferenceMap = {};
for (const key of keys) {
const created = await api.post<{ id: string }>(`/api/companies/${companyId}/secrets`, { name: secretName(options.label, key), value: env[key],
description: `Restart chaos hosted run ${options.label}; removed at cleanup` });
state.secrets.push({ id: String(created.id), key });
await saveState(input.dir, state);
secretRefs[key] = { type: "secret_ref", secretId: String(created.id), version: "latest" } satisfies SecretReference;
}
record("hosted_secrets_stored", { keys, count: state.secrets.length });
const project = await api.post<{ id: string }>(`/api/companies/${companyId}/projects`, { name: projectName(options.label),
description: `Restart chaos hosted release-swap run ${options.label}. Created and removed by tests/restart-chaos.` });
state.projectId = String(project.id);
await saveState(input.dir, state);
const caps = agentRunCaps(options.ratio, Math.max(options.ratio.length, options.concurrency));
for (const [adapter] of options.ratio) {
const profile = runnerProfiles.find(candidate => candidate.id === PROFILE_FOR_ADAPTER[adapter]);
if (!profile) throw new Error(`runner-e2e catalog has no profile ${PROFILE_FOR_ADAPTER[adapter]}`);
const payload = profile.buildAgent({ environmentId: state.environmentId, environmentFixtureId: "daytona", workspacePath: "",
secretRefs, executionId: options.label });
const runtimeConfig = (payload.runtimeConfig ?? {}) as Record<string, unknown>;
const name = agentName(options.label, adapter);
const created = await api.post<{ id: string }>(`/api/companies/${companyId}/agents`, { ...payload, name, title: "Restart chaos hosted worker",
adapterConfig: { ...((payload.adapterConfig ?? {}) as Record<string, unknown>), ...chaosLifecycleOverrides("warm") },
runtimeConfig: { ...runtimeConfig, heartbeat: { ...((runtimeConfig.heartbeat ?? {}) as Record<string, unknown>), enabled: false, maxConcurrentRuns: caps[adapter] ?? 1 } } });
state.agents[adapter] = { id: String(created.id), name };
await saveState(input.dir, state);
record("hosted_agent_created", { adapter, agentId: created.id, model: profile.model, maxConcurrentRuns: caps[adapter] ?? 1 });
}
return state;
}
export interface CleanupReport {
runsCancelled: number;
tasksArchived: number;
agentsPaused: number;
agentsRemoved: number;
secretsDeleted: number;
projectArchived: boolean;
errors: string[];
}
export const TERMINATE_WAIT_MS = 120_000;
async function removeAgent(api: SetupApi, agentId: string, pollMs: number): Promise<void> {
const current = await api.get<Json>(`/api/agents/${agentId}`).catch(error => {
if (error instanceof ChaosApiError && error.status === 404) return null;
throw error;
});
if (current === null) return;
if (current.status !== "terminated") await api.post(`/api/agents/${agentId}/terminate`);
for (const until = Date.now() + TERMINATE_WAIT_MS; ;) {
const agent = await api.get<Json>(`/api/agents/${agentId}`);
if (agent.status === "terminated") break;
if (Date.now() >= until) throw new Error(`agent still ${String(agent.status)} after ${TERMINATE_WAIT_MS / 1000} s; run --hosted-cleanup-only again`);
await delay(pollMs);
}
try {
await api.delete(`/api/agents/${agentId}`, { allowNotFound: true });
} catch (error) {
if (!(error instanceof ChaosApiError && error.status === 409 && error.message.includes("agent_cost_history_retained"))) throw error;
}
}
export async function cleanupHosted(input: { api: SetupApi; label: string; companyId: string; state: HostedState | null;
record: (kind: string, data: Record<string, unknown>) => void; terminatePollMs?: number }): Promise<CleanupReport> {
const { api, label, companyId } = input;
const report: CleanupReport = { runsCancelled: 0, tasksArchived: 0, agentsPaused: 0, agentsRemoved: 0, secretsDeleted: 0, projectArchived: false, errors: [] };
const attempt = async (what: string, action: () => Promise<unknown>) => {
try { await action(); return true; } catch (error) { report.errors.push(`${what}: ${error instanceof Error ? error.message : String(error)}`.slice(0, 300)); return false; }
};
const read = async (what: string, route: string): Promise<Json[]> => {
try { return await api.get<Json[]>(route); } catch (error) { report.errors.push(`${what}: ${error instanceof Error ? error.message : String(error)}`.slice(0, 300)); return []; }
};
const agentPrefix = `RC ${label} `;
const agents = (await api.get<Json[]>(`/api/companies/${companyId}/agents`)).filter(agent => String(agent.name).startsWith(agentPrefix));
const stateIds = new Set(Object.values(input.state?.agents ?? {}).map(agent => agent!.id));
const ours = agents.filter(agent => stateIds.size === 0 || stateIds.has(String(agent.id)));
for (const agent of ours) {
if (agent.status !== "terminated" && await attempt(`pause ${agent.id}`, () => api.patch(`/api/agents/${agent.id}`, { status: "paused" }))) report.agentsPaused += 1;
const runs = await read(`read runs of ${agent.id}`, `/api/companies/${companyId}/heartbeat-runs?agentId=${agent.id}&limit=1000`);
for (const run of runs.filter(run => run.agentId === agent.id && ["queued", "running", "scheduled_retry"].includes(String(run.status)))) {
if (await attempt(`cancel run ${run.id}`, () => api.post(`/api/heartbeat-runs/${run.id}/cancel`))) report.runsCancelled += 1;
}
let issues: HostedIssueRow[] = [];
try { issues = await hostedIssues(api, companyId, [String(agent.id)]); }
catch (error) { report.errors.push(`read tasks of ${agent.id}: ${error instanceof Error ? error.message : String(error)}`.slice(0, 300)); }
for (const issue of issues.filter(issue => !issue.hidden)) {
if (await attempt(`archive task ${issue.id}`, () => api.patch(`/api/issues/${issue.id}`, { hiddenAt: new Date().toISOString() }))) report.tasksArchived += 1;
}
}
for (const agent of ours) {
if (await attempt(`remove agent ${agent.id}`, () => removeAgent(api, String(agent.id), input.terminatePollMs ?? 2_000))) report.agentsRemoved += 1;
}
const secrets = (await read("read secrets", `/api/companies/${companyId}/secrets`))
.filter(secret => String(secret.name).startsWith(`restart-chaos ${label} `));
for (const secret of secrets) {
if (await attempt(`delete secret ${secret.id}`, () => api.delete(`/api/secrets/${secret.id}`, { allowNotFound: true }))) report.secretsDeleted += 1;
}
const projects = (await read("read projects", `/api/companies/${companyId}/projects`)).filter(project => project.name === projectName(label) && !project.archivedAt);
for (const project of projects) {
if (await attempt(`archive project ${project.id}`, () => api.patch(`/api/projects/${project.id}`, { archivedAt: new Date().toISOString() }))) report.projectArchived = true;
}
input.record("hosted_cleanup", { ...report });
return report;
}
@@ -0,0 +1,96 @@
import { describe, expect, it } from "vitest";
import { HostedWorkload, inFlight, planHostedTasks, trackBanner, IDLE_RELEASE_MS } from "./hosted-workload.js";
describe("hosted staging-mix workload", () => {
it("plans labelled tasks by the ratio and keeps only the concurrency in flight", async () => {
const plans = planHostedTasks({ ratio: [["opencode", 100]], turnMinutes: [3, 3], subtaskShare: 0, followUpShare: 100, seed: 7 }, 4);
expect(plans.map(plan => [plan.adapter, plan.task.rounds, plan.task.subtasks])).toEqual(Array(4).fill(["opencode", 2, 0]));
const posts: Array<{ route: string; body: any }> = [];
let issue = 0;
const state = { status: "in_progress", runs: [{ status: "running" }] as Array<{ status: string }>, interruption: null as any };
const api = {
post: async <T>(route: string, body?: unknown) => { posts.push({ route, body }); issue += 1; return (route.endsWith("/retry") ? { accepted: true } : { id: `i${issue}`, identifier: `PC-${issue}` }) as T; },
get: async <T>(route: string) => (route.endsWith("/runs") ? state.runs : { status: state.status, interruption: state.interruption }) as T,
};
const workload = new HostedWorkload({ api, label: "rc-x", companyId: "c1", projectId: "p1", agents: { opencode: { id: "a1", name: "RC rc-x opencode" } },
plans, concurrency: 2, record: () => {}, retryDuringWave: true });
expect(await workload.launchDue()).toBe(2);
expect(posts.map(post => post.route)).toEqual(["/api/companies/c1/issues", "/api/companies/c1/issues"]);
expect(posts[0]!.body).toMatchObject({ title: expect.stringMatching(/^\[rc-x\] Staging mix task [0-9a-f]{8}$/), assigneeAgentId: "a1", projectId: "p1", status: "todo" });
expect(await workload.launchDue()).toBe(0);
const later = Date.now() + 3 * 60_000;
await workload.poll(later);
expect(posts.filter(post => post.route.endsWith("/comments"))).toHaveLength(2);
state.runs = [{ status: "failed" }];
state.interruption = { canRetry: true, observedRunId: "r1" };
await workload.poll(later + 1);
await workload.poll(later + 2);
expect(posts.filter(post => post.route.endsWith("/retry")).map(post => post.body.observedRunId)).toEqual(["r1", "r1"]);
expect(workload.records[0]!.retryClicks).toEqual([{ at: later + 1, accepted: true, via: "observer" }]);
state.status = "done";
await workload.poll(later + 3);
expect(workload.active(later + 3)).toHaveLength(0);
expect(await workload.launchDue(later + 3)).toBe(2);
});
it("stops counting a task with no live run for ten minutes as in flight", () => {
const record = { plan: {} as never, issueId: "i1", identifier: null, createdAt: 0, createError: null, status: "in_progress", lastLiveAt: 0,
followUp: null, retryClicks: [], retriedRuns: [], doneAt: null };
expect(inFlight(record, IDLE_RELEASE_MS - 1)).toBe(true);
expect(inFlight(record, IDLE_RELEASE_MS)).toBe(false);
expect(inFlight({ ...record, status: "blocked" }, 1)).toBe(false);
});
it("by default never clicks Retry during the wave and records when the banner showed and whether it cleared by itself", async () => {
const plans = planHostedTasks({ ratio: [["opencode", 100]], turnMinutes: [3, 3], subtaskShare: 0, followUpShare: 0, seed: 7 }, 1);
const posts: string[] = [];
const state = { status: "in_progress", interruption: { canRetry: true, observedRunId: "r1" } as any, runs: [{ status: "failed" }] as Array<{ status: string }> };
const api = {
post: async <T>(route: string) => { posts.push(route); return { id: "i1" } as T; },
get: async <T>(route: string) => (route.endsWith("/runs") ? state.runs : { status: state.status, interruption: state.interruption }) as T,
};
const workload = new HostedWorkload({ api, label: "rc-x", companyId: "c1", projectId: null, agents: { opencode: { id: "a1", name: "n" } }, plans, concurrency: 1, record: () => {} });
await workload.launchDue();
const at = Date.now();
await workload.poll(at);
state.interruption = null;
state.runs = [{ status: "running" }];
await workload.poll(at + 1);
expect(posts).toEqual(["/api/companies/c1/issues"]);
expect(workload.records[0]!.retryClicks).toEqual([]);
expect(workload.banners.get("i1")).toEqual({ firstShownAt: at, shown: false, clearedAt: at + 1, clearedByItself: true });
});
it("keeps the first time a banner showed when it shows again", () => {
const first = trackBanner(null, true, 10).banner;
const cleared = trackBanner(first, false, 20).banner;
expect(trackBanner(cleared, true, 30).banner).toEqual({ firstShownAt: 10, shown: true, clearedAt: null, clearedByItself: false });
expect(trackBanner(null, false, 5)).toEqual({ banner: null, cleared: false });
});
it("keeps watching banners on agent-created subtasks and on resting parents, not only on tasks still admitted as in flight", async () => {
const plans = planHostedTasks({ ratio: [["opencode", 100]], turnMinutes: [3, 3], subtaskShare: 0, followUpShare: 0, seed: 7 }, 1);
const views: Record<string, any> = { p1: { status: "blocked", interruption: null }, s1: { status: "in_progress", interruption: { canRetry: true } },
s2: { status: "done" }, old: { status: "done" } };
const reads: string[] = [];
const api = {
post: async <T>() => ({ id: "p1" }) as T,
get: async <T>(route: string) => {
if (route.includes("/issues?")) return [{ id: "p1", assigneeAgentId: "a1", status: views.p1.status }, { id: "s1", assigneeAgentId: "a1", status: views.s1.status, parentId: "p1" },
{ id: "s2", assigneeAgentId: "a1", status: "done", parentId: "p1" }, { id: "x", assigneeAgentId: "a1", status: "todo", hiddenAt: "2026-11-12T00:00:00Z" }] as T;
if (route.endsWith("/runs")) return [] as T;
reads.push(route);
return views[route.split("/").at(-1)!] as T;
},
};
const workload = new HostedWorkload({ api, label: "rc-x", companyId: "c1", projectId: null, agents: { opencode: { id: "a1", name: "n" } }, plans, concurrency: 1, record: () => {} });
await workload.launchDue();
await workload.poll(1_000);
expect(workload.active(1_000)).toHaveLength(0);
views.s1 = { status: "done", interruption: null };
await workload.poll(2_000);
expect(workload.banners.get("s1")).toEqual({ firstShownAt: 1_000, shown: false, clearedAt: 2_000, clearedByItself: true });
expect(reads).not.toContain("/api/issues/s2");
expect(reads).not.toContain("/api/issues/x");
});
});
+184
View File
@@ -0,0 +1,184 @@
import { randomUUID } from "node:crypto";
import { createRng } from "./plan-primitives.js";import type { HostedApi } from "./hosted-api.js";
import type { HostedOptions } from "./hosted-config.js";
import { taskTag } from "./hosted-setup.js";
import { hostedIssues } from "./hosted-readers.js";
import type { RetryClick } from "./release-swap-grade.js";
import { assignAdapters, followUpComment, followUpRequestId, roundsFor, ROUND_SECONDS, stagingMixDescription, SUBTASKS_PER_PARENT, type StagingMixTask } from "./staging-mix.js";
import type { AdapterId } from "./types.js";
type Json = Record<string, any>;
export type WorkloadApi = Pick<HostedApi, "get" | "post">;
export interface HostedTaskPlan {
index: number;
adapter: AdapterId;
nonce: string;
task: StagingMixTask;
}
export interface RetryBanner {
firstShownAt: number;
shown: boolean;
clearedAt: number | null;
clearedByItself: boolean;
}
export function trackBanner(banner: RetryBanner | null, offered: boolean, now: number): { banner: RetryBanner | null; cleared: boolean } {
if (offered && !banner) return { banner: { firstShownAt: now, shown: true, clearedAt: null, clearedByItself: false }, cleared: false };
if (offered && banner && !banner.shown) return { banner: { ...banner, shown: true, clearedAt: null, clearedByItself: false }, cleared: false };
if (!offered && banner?.shown) return { banner: { ...banner, shown: false, clearedAt: now, clearedByItself: true }, cleared: true };
return { banner, cleared: false };
}
export interface HostedTaskRecord {
plan: HostedTaskPlan;
issueId: string | null;
identifier: string | null;
createdAt: number | null;
createError: string | null;
status: string;
lastLiveAt: number | null;
followUp: { at: number; commentId: string | null; error: string | null } | null;
retryClicks: RetryClick[];
retriedRuns: string[];
doneAt: number | null;
}
const LIVE = new Set(["queued", "running", "scheduled_retry"]);
const RESTING = new Set(["done", "cancelled", "blocked", "in_review"]);
const TERMINAL = new Set(["done", "cancelled"]);
export const IDLE_RELEASE_MS = 10 * 60_000;
export function planHostedTasks(options: Pick<HostedOptions, "ratio" | "turnMinutes" | "subtaskShare" | "followUpShare" | "seed">, count: number): HostedTaskPlan[] {
const rng = createRng((options.seed ^ 0x40575e) >>> 0);
const adapters = assignAdapters(options.ratio, count);
return adapters.map((adapter, index) => {
const turnMinutes = rng.int(options.turnMinutes[0], options.turnMinutes[1]);
const rounds = roundsFor(turnMinutes);
const turnMs = rounds * ROUND_SECONDS * 1_000;
const subtasks = rng.int(0, 99) < options.subtaskShare ? SUBTASKS_PER_PARENT : 0;
const followUpAfterMs = rng.int(0, 99) < options.followUpShare ? rng.int(Math.round(turnMs * 0.25), Math.round(turnMs * 0.7)) : null;
return { index, adapter, nonce: rng.hex(8), task: { turnMinutes, rounds, subtasks, followUpAfterMs, arriveAtMs: 0, holdMs: 0 } };
});
}
export function inFlight(record: HostedTaskRecord, now: number): boolean {
if (record.createError || !record.issueId) return false;
if (RESTING.has(record.status)) return false;
return now - (record.lastLiveAt ?? record.createdAt ?? now) < IDLE_RELEASE_MS;
}
export class HostedWorkload {
readonly records: HostedTaskRecord[] = [];
readonly banners = new Map<string, RetryBanner>();
private next = 0;
constructor(private readonly input: { api: WorkloadApi; label: string; companyId: string; projectId: string | null;
agents: Partial<Record<AdapterId, { id: string; name: string }>>; plans: HostedTaskPlan[]; concurrency: number;
record: (kind: string, data: Record<string, unknown>) => void; retryDuringWave?: boolean }) {}
get remaining(): number { return this.input.plans.length - this.next; }
get launched(): number { return this.next; }
active(now = Date.now()): HostedTaskRecord[] {
return this.records.filter(record => inFlight(record, now));
}
async launchDue(now = Date.now()): Promise<number> {
let launched = 0;
while (this.next < this.input.plans.length && this.active(now).length < this.input.concurrency) {
const plan = this.input.plans[this.next]!;
this.next += 1;
launched += 1;
const agent = this.input.agents[plan.adapter]!;
const record: HostedTaskRecord = { plan, issueId: null, identifier: null, createdAt: null, createError: null, status: "todo", lastLiveAt: null,
followUp: null, retryClicks: [], retriedRuns: [], doneAt: null };
this.records.push(record);
try {
const issue = await this.input.api.post<{ id: string; identifier?: string }>(`/api/companies/${this.input.companyId}/issues`, {
title: `${taskTag(this.input.label)} Staging mix ${plan.task.subtasks ? "parent" : "task"} ${plan.nonce}`,
description: stagingMixDescription(plan.nonce, plan.task, { self: agent, other: agent, companyId: this.input.companyId }),
status: "todo", priority: "medium", assigneeAgentId: agent.id, ...(this.input.projectId ? { projectId: this.input.projectId } : {}) });
record.issueId = String(issue.id);
record.identifier = issue.identifier ?? null;
record.createdAt = Date.now();
record.lastLiveAt = record.createdAt;
} catch (error) {
record.createError = error instanceof Error ? error.message : String(error);
}
this.input.record("hosted_task_created", { index: plan.index, adapter: plan.adapter, issueId: record.issueId, identifier: record.identifier,
turnMinutes: plan.task.turnMinutes, subtasks: plan.task.subtasks, error: record.createError });
}
return launched;
}
async poll(now = Date.now()): Promise<void> {
const seen = new Set<string>();
for (const record of this.active(now)) {
seen.add(record.issueId!);
await this.step(record, now).catch(error =>
this.input.record("hosted_task_poll_failed", { issueId: record.issueId, error: error instanceof Error ? error.message : String(error) }));
}
await this.observe(now, seen).catch(error => this.input.record("hosted_banner_observe_failed", { error: error instanceof Error ? error.message : String(error) }));
}
async observe(now: number, seen: ReadonlySet<string> = new Set()): Promise<void> {
const agentIds = Object.values(this.input.agents).map(agent => agent!.id);
for (const issue of await hostedIssues(this.input.api, this.input.companyId, agentIds)) {
if (issue.hidden || seen.has(issue.id)) continue;
if (TERMINAL.has(issue.status) && !this.banners.get(issue.id)?.shown) continue;
this.noteBanner(issue.id, await this.input.api.get<Json>(`/api/issues/${issue.id}`), now);
}
}
private noteBanner(issueId: string, view: Json, now: number): void {
const offered = view.status !== "done" && view.interruption?.canRetry === true && !view.interruption?.retryWait;
const previous = this.banners.get(issueId) ?? null;
const change = trackBanner(previous, offered, now);
if (change.banner === previous) return;
const clicked = this.records.some(record => record.issueId === issueId && record.retryClicks.length > 0);
this.banners.set(issueId, change.cleared && clicked ? { ...change.banner!, clearedByItself: false } : change.banner!);
this.input.record(change.cleared ? "hosted_retry_banner_cleared" : "hosted_retry_banner_shown", { issueId, observedRunId: view.interruption?.observedRunId ?? null });
}
private async step(record: HostedTaskRecord, now: number): Promise<void> {
const issue = await this.input.api.get<Json>(`/api/issues/${record.issueId}`);
const runs = await this.input.api.get<Json[]>(`/api/issues/${record.issueId}/runs`).catch(() => [] as Json[]);
record.status = String(issue.status);
if (record.status === "done" && record.doneAt === null) record.doneAt = now;
const live = runs.some(run => LIVE.has(String(run.status)));
if (live || issue.scheduledRetry) record.lastLiveAt = now;
const running = runs.some(run => run.status === "running");
const task = record.plan.task;
if (task.followUpAfterMs !== null && !record.followUp?.commentId && running && record.createdAt !== null && now >= record.createdAt + task.followUpAfterMs) {
const followUp = { at: now, commentId: null as string | null, error: null as string | null };
try {
const comment = await this.input.api.post<{ id?: string }>(`/api/issues/${record.issueId}/comments`, { body: followUpComment(record.plan.nonce),
clientRequestId: followUpRequestId(record.issueId!, record.plan.nonce) });
followUp.commentId = typeof comment?.id === "string" ? comment.id : null;
} catch (error) {
followUp.error = error instanceof Error ? error.message : String(error);
}
record.followUp = followUp;
this.input.record("hosted_follow_up", { issueId: record.issueId, commentId: followUp.commentId, error: followUp.error });
}
this.noteBanner(record.issueId!, issue, now);
if (!this.input.retryDuringWave) return;
const observedRunId = issue.interruption?.observedRunId ? String(issue.interruption.observedRunId) : null;
if (record.status !== "done" && issue.interruption?.canRetry === true && !issue.interruption?.retryWait && !live && !record.retriedRuns.includes(observedRunId ?? "")) {
record.retriedRuns.push(observedRunId ?? "");
const click: RetryClick = { at: now, accepted: null, via: "observer" };
try {
const result = await this.input.api.post<{ accepted?: boolean }>(`/api/issues/${record.issueId}/retry`, { idempotencyKey: randomUUID(),
observedRunId });
click.accepted = result?.accepted === true;
} catch {
click.accepted = false;
}
record.retryClicks.push(click);
record.lastLiveAt = now;
this.input.record("task_retry_clicked", { issueId: record.issueId, accepted: click.accepted });
}
}
}
+7
View File
@@ -0,0 +1,7 @@
import { isHostedCommand } from "./hosted-config.js";
import { runHosted } from "./hosted-main.js";
const argv = process.argv.slice(2);
process.exit(await (isHostedCommand(argv) ? runHosted(argv)
: Promise.reject(new Error("hosted.ts needs --hosted-base-url and --hosted-allow (README: Hosted mode)")))
.catch(error => { console.error(error); return 2; }));