mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-01 09:39:53 +01:00
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - The restart-chaos harness has a hosted mode. Its gate D requires 0
failed health probes across 10 consecutive releases on a hosted test
stack.
> - The harness runs on a home Mac over Wi-Fi. Three classes of failed
probe occurred: isolated 503s from the cloud idle sweep (a real bug, now
fixed), timeouts while the Mac slept with the lid closed, and `fetch
failed` errors during a Wi-Fi access point change.
> - The records keep only the status, the duration and `fetch failed`.
Each failure needs a manual investigation, and a client-side network
fault fails the gate the same way as a server outage.
> - This pull request records the evidence for every failed request and
gives each failure a class: client-side, server-side or unclassified.
> - The benefit is that a gate D failure explains itself, and only
server-side or unclassified failures fail the gate.
## Linked Issues or Issue Description
**What happened?**
Gate D failed on health probes that the stack did not cause. On
2026-11-23 at 02:28Z, the Mac slept: a 10 s abort fired after 18.5 s,
and the 2 s probe loop had a 16 s gap. At 08:05:35Z and 08:05:55Z,
undici reported `fetch failed` after 42 ms and 1240 ms, during a Wi-Fi
access point change. The saved records showed only `{status, ms, error:
"fetch failed"}`.
**Expected behavior**
Each failed request records why it failed: undici's error cause, the
socket, the connection reuse, the answer headers and body, the client
clock, and a control probe to a neutral endpoint. Gate D counts only
server-side and unclassified failures. Client-side failures stay visible
in `SUMMARY.md` as information.
**Steps to reproduce**
Run hosted gate D from a laptop on Wi-Fi, and sleep the laptop or change
the access point during the run. Before this change, the gate fails with
a bare `fetch failed` record.
## What Changed
- New `tests/restart-chaos/hosted-diagnostics.ts`:
- A fresh-connection client for the health probe (`node:https` with
`agent: false` and `connection: close`). Each probe opens and closes its
own connection, so a keep-alive race cannot look like an outage. It
records DNS, connect, TLS and first-byte times and the remote address.
- A connection tracker on undici's diagnostics channels. It tags each
API request's socket as new or reused, with the remote address, connect
time and time to first byte.
- Error-cause capture: `code`, `errno`, `syscall`, `hostname`,
`address`, `port`, message, and the socket's addresses and byte counts
for `UND_ERR_SOCKET`.
- Answer evidence for a non-2xx answer: status, the listed headers only
(`x-paperclip-status`, `retry-after`, `server`, `via`,
`x-railway-request-id`, `x-railway-edge`, `cf-ray`, `date`,
`content-type`, `cache-control`, `connection`), the first 512 bytes of
the body, and the parsed `error` and `statusPage.code`.
- Client clock: `timerLagMs` (elapsed minus timeout when an abort
fires), wall clock against monotonic clock, `monitorEventLoopDelay`
maximum, and the pause before each health probe.
- The classifier (`classifyFailure`) and the summary lines for
`SUMMARY.md`.
- `hosted-api.ts`: every failed request runs one control probe to
`https://www.cloudflare.com/cdn-cgi/trace` and, for a GET that did not
time out, one immediate retry of the same URL (2 s limit). The failure
is recorded at once; the control and retry outcomes are attached in the
background, and `settleDiagnostics()` waits for them before grading and
before `requests.jsonl` is saved. Concurrent failures share one control
probe per second. The control probe and the retry are not counted as
requests. The retry logic of the API client does not change. Only the
live entry point sets `live: true`, which turns on the fresh-connection
health client and the control probe; unit tests never reach the network.
- The fresh-connection client follows up to 3 same-origin redirects. A
cut-short answer keeps its status, headers and partial body beside the
error. A retry whose body cannot be read is recorded as failed.
- `hosted-gate.ts`: the health-probe check counts `server +
unclassified` from one class summary built from each failure's stored
class. The check line shows the three counts. Without class evidence,
every failure counts as unclassified.
- `hosted-release.ts`: release detection skips client-side failures, so
a client-side failure in a swap gap does not make a release
stop-then-start.
- `hosted-main.ts`: a failed probe's line is written to `health.jsonl`
when its evidence is complete, with a `hosted_health_failure_classified`
timeline event.
- `hosted-grade.ts` and `hosted-main.ts`: `SUMMARY.md` lists each health
probe failure with its class, reason and evidence. Client-side failures
are marked as information. The request breakdown lines show the class
counts. The timeline's `hosted_health_failed` event carries the class
and reason.
- Classes:
- Server-side: any HTTP answer that is not a readable 2xx; a reset or
refused connection while the control probe succeeded; a timeout while
the control probe succeeded and the client did not stall.
- Client-side: a `client_stall` (abort more than 1 s late, clock jump
over 1 s, event-loop delay over 1 s, or a pause before the probe longer
than twice the interval); a failed control probe; a client DNS failure
(`EAI_AGAIN`, or an `ENOTFOUND` that the immediate retry does not
repeat).
- Unclassified: all other failures. They fail gate D.
- The macOS Wi-Fi BSSID and RSSI capture is not included. On current
macOS it needs `sudo wdutil` or location permission, so it is not
simple.
- README: a "Failure evidence" paragraph and the new gate D health rule.
## Verification
- `npx vitest run --config tests/restart-chaos/vitest.config.ts`: 74
files, 939 tests pass.
- `node scripts/typecheck-test-projects.mjs tests/restart-chaos`:
passes.
- New tests in `tests/restart-chaos/hosted-diagnostics.test.ts`:
- `counts a reset as server-side when the control probe to the neutral
endpoint succeeded`
- `counts a reset as client-side when the control probe failed too`
- `counts a stalled client timer as client-side even when the control
probe succeeded`
- `counts a client DNS failure as client-side`
- `leaves a failure without enough evidence unclassified, and gate D
fails on it`
- `passes gate D with only client-side failures and keeps them visible
as informational lines`
- `records the 503's status, headers, body excerpt, parsed error and
statusPage code, and counts it server-side`
- `records undici's error cause and socket for a reset, and classifies
it by the control probe`
- `does not repeat a failed non-GET request as the immediate retry`
- `passes the gap before each probe to the health check`
- `opens a fresh connection for every health probe and records its
phases`
- `tags an API request's socket as new or reused`
- `reports a reset on a fresh connection with the socket's addresses and
byte counts`
- A manual smoke run against the control endpoint recorded `reused:
false`, the remote address, and DNS, connect, TLS and first-byte times.
An unknown host recorded `ENOTFOUND` with `syscall: getaddrinfo`.
## Risks
- Low risk. The change is in the test harness only. No product code
changes.
- Each failed request now adds one control probe and, for a GET that did
not time out, one retry with a 2 s limit. They run in the background, so
the health probe cadence and the API client's own retries do not wait
for them. The grade waits for them before it classifies; a diagnosis
that is still pending counts as unclassified.
- Each request sends an extra `x-restart-chaos-request` header to the
stack. The server ignores it.
- The client-side rules can hide a real server fault only when the
client also could not reach the neutral endpoint, or when the client
stalled. Every other failure counts against the gate.
- Release detection and the swap-shape check still read every failed
probe. That behavior does not change.
> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.
## Model Used
- Provider: Anthropic. Model: Claude Opus 5.5 (`claude-opus-5-5`), run
in Claude Code as an agent with tool use (shell, file edits, test runs).
Standard context window.
## 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
- [x] All Paperclip CI gates are green
- [x] 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>
249 lines
16 KiB
TypeScript
249 lines
16 KiB
TypeScript
import { mkdtemp, rm } from "node:fs/promises";
|
|
import os from "node:os";
|
|
import path from "node:path";
|
|
import { afterEach, describe, expect, it } from "vitest";
|
|
import { hostedGate, hostedQueueWait, hostedR1, releaseOutages, subtaskRecord } from "./hosted-gate.js";
|
|
import { gradeHosted } from "./hosted-grade.js";
|
|
import { continuity } from "./hosted-release.js";
|
|
import { runRow, type HostedRunRow } from "./hosted-readers.js";
|
|
import type { DetectedRelease, HealthSample } from "./hosted-release.js";
|
|
import type { HostedTaskRecord } from "./hosted-workload.js";
|
|
import type { SwapMetrics } from "./release-swap-grade.js";
|
|
import { roundsFor, stagingMixBudgetMs, SUBTASK_ROUNDS } from "./staging-mix.js";
|
|
|
|
const dirs: string[] = [];
|
|
afterEach(async () => { for (const dir of dirs.splice(0)) await rm(dir, { recursive: true, force: true }); });
|
|
|
|
const T0 = Date.parse("2026-11-21T10:00:00.000Z");
|
|
const MIN = 60_000;
|
|
const at = (minutes: number) => new Date(T0 + minutes * MIN).toISOString();
|
|
const task = { turnMinutes: 5, rounds: roundsFor(5), subtasks: 0, followUpAfterMs: null, arriveAtMs: 0, holdMs: 0 };
|
|
const BUDGET_MIN = stagingMixBudgetMs(task) / MIN;
|
|
|
|
function record(overrides: Partial<HostedTaskRecord> = {}): HostedTaskRecord {
|
|
return { plan: { index: 0, adapter: "opencode", nonce: "abcd1234", task }, issueId: "i1", identifier: "GIT-1", createdAt: T0, createError: null,
|
|
status: "done", lastLiveAt: null, followUp: null, retryClicks: [], retriedRuns: [], doneAt: null, ...overrides };
|
|
}
|
|
|
|
const run = (id: string, created: number, started: number | null, finished: number | null, extra: Record<string, unknown> = {}): HostedRunRow =>
|
|
runRow({ id, agentId: "a1", issueId: "i1", status: finished === null ? "running" : "succeeded", createdAt: at(created), startedAt: started === null ? null : at(started),
|
|
finishedAt: finished === null ? null : at(finished), invocationSource: "assignment", ...extra });
|
|
|
|
const agents = [{ id: "a1", runtimeConfig: { heartbeat: { maxConcurrentRuns: 1 } } }];
|
|
const qw = (companyRuns: HostedRunRow[]) => hostedQueueWait(["a1"], agents, companyRuns).queueWait;
|
|
|
|
function release(overrides: Partial<DetectedRelease> = {}): DetectedRelease {
|
|
return { index: 1, from: { processStartedAt: "a", commit: "c1" }, to: { processStartedAt: "b", commit: "c2" }, commitChanged: true, lastOldOnlyAt: T0,
|
|
firstNewAt: T0 + MIN, lastOldAt: T0 + 2 * MIN, overlapWindow: { from: T0 + MIN, to: T0 + 2 * MIN }, shape: "overlap", failedRequests: 0, slowRequests: 0,
|
|
firstFailureAt: null, timeToFirstNewMs: MIN, settled: true, ...overrides };
|
|
}
|
|
|
|
describe("hosted R1", () => {
|
|
it("passes a task done inside the staging-mix budget and fails one done after it with no fair queue wait", () => {
|
|
const fast = hostedR1({ record: record(), view: { status: "done", completedAt: at(10) }, runs: [run("r1", 0, 0, 10)], queueWait: qw([run("r1", 0, 0, 10)]), outages: [] });
|
|
expect(fast.verdict).toBe("pass");
|
|
const late = BUDGET_MIN + 5;
|
|
const slow = hostedR1({ record: record(), view: { status: "done", completedAt: at(late) }, runs: [run("r1", 0, 0, late)], queueWait: qw([run("r1", 0, 0, late)]), outages: [] });
|
|
expect(slow).toMatchObject({ verdict: "fail" });
|
|
expect(slow.detail).toMatch(/^done_too_late/);
|
|
});
|
|
|
|
it("credits the first run's queue wait when the agent's only slot was busy the whole time", () => {
|
|
const wait = 30;
|
|
const done = wait + BUDGET_MIN - 5;
|
|
const busy = run("other", -1, -1, wait, { issueId: "i0" });
|
|
const mine = run("r1", 0, wait, done);
|
|
const graded = hostedR1({ record: record(), view: { status: "done", completedAt: at(done) }, runs: [mine], queueWait: qw([busy, mine]), outages: [] });
|
|
expect(graded.verdict).toBe("pass");
|
|
expect(graded.detail).toContain("fair queue wait");
|
|
});
|
|
|
|
it("fails an unfair wait: a newer assignment run of the same agent started ahead of the task's run", () => {
|
|
const wait = 30;
|
|
const done = wait + BUDGET_MIN - 5;
|
|
const overtaker = run("newer", 1, 2, wait, { issueId: "i0" });
|
|
const mine = run("r1", 0, wait, done);
|
|
const graded = hostedR1({ record: record(), view: { status: "done", completedAt: at(done) }, runs: [mine], queueWait: qw([overtaker, mine]), outages: [] });
|
|
expect(graded.verdict).toBe("fail");
|
|
expect(graded.detail).toMatch(/^unfair_queue_wait/);
|
|
});
|
|
|
|
it("credits outage time only for a release whose health probes failed before the new build answered", () => {
|
|
expect(releaseOutages([release()])).toEqual([]);
|
|
const outage = releaseOutages([release({ shape: "stop_then_start", firstFailureAt: T0 + 10 * MIN, firstNewAt: T0 + 20 * MIN })]);
|
|
expect(outage).toHaveLength(1);
|
|
expect(outage[0]).toMatchObject({ startedAt: T0 + 10 * MIN, readyAt: T0 + 20 * MIN });
|
|
const done = BUDGET_MIN + 5;
|
|
const graded = hostedR1({ record: record(), view: { status: "done", completedAt: at(done) }, runs: [run("r1", 0, 0, done)], queueWait: qw([run("r1", 0, 0, done)]), outages: outage });
|
|
expect(graded.verdict).toBe("pass");
|
|
});
|
|
|
|
it("never credits a follow-up run's queue wait, because the API has no wake evidence", () => {
|
|
const first = run("r1", 0, 0, 5);
|
|
const busy = run("other", 4, 4, 40, { issueId: "i0" });
|
|
const follow = run("r2", 6, 40, 45, { invocationSource: "automation", contextSnapshot: { wakeCommentIds: ["c1"] } });
|
|
const done = 45;
|
|
expect(done).toBeGreaterThan(BUDGET_MIN);
|
|
const graded = hostedR1({ record: record({ followUp: { at: T0 + 6 * MIN - 1, commentId: "c1", error: null } }), view: { status: "done", completedAt: at(done) },
|
|
runs: [first, follow], queueWait: qw([first, busy, follow]), outages: [] });
|
|
expect(graded.verdict).toBe("fail");
|
|
expect(graded.detail).toContain("no wake evidence for follow-up run r2");
|
|
});
|
|
|
|
it("names an agent whose maxConcurrentRuns cannot be read", () => {
|
|
expect(hostedQueueWait(["a1", "a2"], [agents[0]!, { id: "a2", runtimeConfig: null }], []).missing).toEqual(["a2"]);
|
|
expect(hostedQueueWait(["a1"], [], []).missing).toEqual(["a1"]);
|
|
});
|
|
|
|
it("marks a task that needed Retry n/a for R1 and fails one that did not rest done", () => {
|
|
const retried = hostedR1({ record: record({ retryClicks: [{ at: T0, accepted: true, via: "grader" }] }), view: { status: "done", completedAt: at(10) },
|
|
runs: [], queueWait: qw([]), outages: [] });
|
|
expect(retried.verdict).toBe("n/a");
|
|
const open = hostedR1({ record: record(), view: { status: "in_progress" }, runs: [run("r1", 0, 0, null)], queueWait: qw([]), outages: [] });
|
|
expect(open.detail).toMatch(/^rested_not_done/);
|
|
});
|
|
});
|
|
|
|
describe("gate D verdict", () => {
|
|
const metric = (index: number, survivors: number): SwapMetrics => ({ index, failedRuns: [], lostWhileOldAlive: [],
|
|
survivors: Array.from({ length: survivors }, (_, n) => ({ runId: `r${n}`, nextEventAfterMs: 1_000 })), nextEventP50Ms: 1_000, nextEventMaxMs: 1_000, survivorsWithoutEvent: 0 });
|
|
const clean = { handsOffPass: true, wantedReleases: 1, createErrors: 0, slotEvidenceMissing: [] as string[], r1: [{ identifier: "GIT-1", result: { verdict: "pass" as const, detail: "done" } }], bannersShown: 0,
|
|
health: { requests: 100, failures: 0, slow: 0, longestGapMs: 2_000, longestGap: null },
|
|
duplicates: { overlappingRuns: [], duplicateComments: [], duplicateChildren: [] }, releases: [release()], metrics: [metric(1, 3)] };
|
|
|
|
it("passes only when every criterion holds", () => {
|
|
const gate = hostedGate(clean);
|
|
expect(gate.pass).toBe(true);
|
|
expect(gate.lines[0]).toBe("Gate D: PASS");
|
|
});
|
|
|
|
it.each([
|
|
["a banner", { bannersShown: 1 }, "Retry banners"],
|
|
["a failed health probe", { health: { ...clean.health, failures: 1 } }, "health probes"],
|
|
["a duplicated comment", { duplicates: { ...clean.duplicates, duplicateComments: [{ issueId: "i1", count: 2 }] } }, "duplicates"],
|
|
["a stop-then-start release", { releases: [release({ shape: "stop_then_start" })] }, "swap shape"],
|
|
["a release with no live run", { metrics: [metric(1, 0)] }, "releases under load"],
|
|
["no release", { releases: [], metrics: [] }, "releases under load"],
|
|
["an R1 failure", { r1: [{ identifier: "GIT-2", result: { verdict: "fail" as const, detail: "done_too_late 9s > 1s" } }] }, "R1"],
|
|
["a task that was not hands-off", { handsOffPass: false }, "hands-off"],
|
|
["a task that could not be created", { createErrors: 1 }, "tasks created"],
|
|
["unreadable agent slots", { slotEvidenceMissing: ["a1"] }, "agent slot evidence"],
|
|
])("fails on %s", (_name, change, check) => {
|
|
const gate = hostedGate({ ...clean, ...change });
|
|
expect(gate.pass).toBe(false);
|
|
expect(gate.lines.find(line => line.includes(`FAIL ${check}`))).toBeDefined();
|
|
});
|
|
|
|
it("does not require a release for a fixed batch (--hosted-releases 0)", () => {
|
|
const gate = hostedGate({ ...clean, wantedReleases: 0, releases: [], metrics: [] });
|
|
expect(gate.pass).toBe(true);
|
|
expect(gate.lines.some(line => line.includes("releases under load"))).toBe(false);
|
|
});
|
|
});
|
|
|
|
describe("hosted grade with the run's task records", () => {
|
|
const issue = (id: string, extra: Record<string, unknown> = {}) => ({ id, identifier: id.toUpperCase(), title: id, status: "done", assigneeAgentId: "a1",
|
|
createdAt: at(0), completedAt: at(10), ...extra });
|
|
const apiFor = (issues: Json[], runs: Json[]) => ({
|
|
get: async <T>(route: string) => (route.includes("heartbeat-runs") ? runs : route.includes("/issues?") ? issues
|
|
: route.startsWith("/api/issues/") && !route.slice("/api/issues/".length).includes("/") ? issues.find(entry => route.endsWith(`/${entry.id}`)) ?? { status: "unreadable" }
|
|
: route.endsWith("/agents") ? (agentList ?? (() => { throw new Error("forbidden"); })()) : []) as T,
|
|
post: async <T>() => ({}) as T,
|
|
});
|
|
type Json = Record<string, any>;
|
|
let events: string[] = [];
|
|
let agentList: Json[] | null = agents;
|
|
const grade = async (issues: Json[], runs: Json[], tasks: HostedTaskRecord[], wantedReleases: number) => {
|
|
events = [];
|
|
const dir = await mkdtemp(path.join(os.tmpdir(), "hosted-gate-"));
|
|
dirs.push(dir);
|
|
return gradeHosted({ api: apiFor(issues, runs), companyId: "c1", agentIds: ["a1"], releases: [], health: () => continuity([]), apiContinuity: () => continuity([]),
|
|
stopObserver: async () => {}, observedClicks: () => new Map(), lastReleaseAt: Date.now() - 1_000, settleMs: 5, drainMs: 5, dir, cancelled: () => false,
|
|
record: event => events.push(event), pollMs: 5, tasks: () => tasks, wantedReleases });
|
|
};
|
|
const runOf = (id: string, issueId: string, created: number, finished: number) => ({ id, agentId: "a1", issueId, status: "succeeded", invocationSource: "assignment",
|
|
createdAt: at(created), startedAt: at(created), finishedAt: at(finished) });
|
|
|
|
it("passes a healthy fixed batch with no release", async () => {
|
|
const graded = await grade([issue("i1")], [runOf("r1", "i1", 0, 10)], [record()], 0);
|
|
expect(graded.pass).toBe(true);
|
|
expect(graded.markdown).toContain("Gate D: PASS");
|
|
});
|
|
|
|
it("grades an agent-created subtask on its own two-round budget", async () => {
|
|
const budget = stagingMixBudgetMs({ ...task, rounds: SUBTASK_ROUNDS }) / MIN;
|
|
const late = budget + 5;
|
|
const child = issue("c1", { parentId: "i1", createdAt: at(1), completedAt: at(1 + late) });
|
|
const graded = await grade([issue("i1", { completedAt: at(late + 2) }), child], [runOf("r1", "i1", 0, 3), runOf("r2", "c1", 1, 1 + late), runOf("r3", "i1", late + 1, late + 2)],
|
|
[record({ plan: { ...record().plan, task: { ...task, subtasks: 2 } } })], 0);
|
|
expect(graded.pass).toBe(false);
|
|
expect(graded.markdown).toMatch(/FAIL R1: 1 failed \(C1: done_too_late/);
|
|
});
|
|
|
|
it("builds a subtask record from its issue view", () => {
|
|
const child = subtaskRecord({ id: "c1", identifier: "GIT-9", status: "done", createdAt: at(3) }, []);
|
|
expect(child).toMatchObject({ issueId: "c1", identifier: "GIT-9", createdAt: T0 + 3 * MIN, createError: null });
|
|
expect(child.plan.task.rounds).toBe(SUBTASK_ROUNDS);
|
|
expect(subtaskRecord({ id: "c2", status: "done" }, []).createError).toBe("subtask has no createdAt");
|
|
expect(subtaskRecord({ id: "c3", status: "done", createdAt: T0 }, []).createdAt).toBe(T0);
|
|
});
|
|
|
|
it("reads a numeric completedAt as well as an ISO string", () => {
|
|
const graded = hostedR1({ record: record(), view: { status: "done", completedAt: T0 + 10 * MIN }, runs: [run("r1", 0, 0, 10)], queueWait: qw([run("r1", 0, 0, 10)]), outages: [] });
|
|
expect(graded.verdict).toBe("pass");
|
|
});
|
|
|
|
it("grades only subtasks of launched tasks, not another issue the agent created", async () => {
|
|
const budget = stagingMixBudgetMs({ ...task, rounds: SUBTASK_ROUNDS }) / MIN;
|
|
const late = budget + 5;
|
|
const stray = issue("x1", { createdAt: at(1), completedAt: at(1 + late) });
|
|
const graded = await grade([issue("i1"), stray], [runOf("r1", "i1", 0, 10), runOf("r2", "x1", 1, 1 + late)], [record()], 0);
|
|
expect(graded.markdown).not.toContain("FAIL R1");
|
|
});
|
|
|
|
it("stops the health probe, settles the frozen samples, and detects releases from them before grading", async () => {
|
|
const order: string[] = [];
|
|
const failure = { url: "/api/health", method: "GET", aborted: false, answer: null, cause: { name: "Error", message: "reset", code: "ECONNRESET" }, connection: null,
|
|
clock: { timeoutMs: 10_000, elapsedMs: 40, monotonicMs: 40, timerLagMs: null, clockJumpMs: 0, loopDelayMaxMs: 20, gapBeforeMs: null, intervalMs: 2_000 },
|
|
control: null, retry: null, controlReachedThisRun: true, class: "unclassified" as const, reason: "diagnosis pending", state: "pending" as const };
|
|
const answer = (at: number, processStartedAt: string) => ({ at, ok: true, status: 200, ms: 40, processStartedAt, commit: "c" });
|
|
const samples = [answer(T0, "old"), answer(T0 + 2_000, "old"), { at: T0 + 4_000, ok: false, status: null, ms: 40, processStartedAt: null, commit: null, failure },
|
|
answer(T0 + 6_000, "new")];
|
|
const stale = await gradeHealth(samples, order, async () => {
|
|
order.push("settle");
|
|
Object.assign(failure, { control: { url: "c", ok: false, status: null, ms: 40, error: { name: "TypeError", message: "fetch failed" }, remoteAddress: null },
|
|
class: "client", reason: "control failed too", state: "settled" });
|
|
return 0;
|
|
});
|
|
expect(order.slice(0, 2)).toEqual(["stop", "settle"]);
|
|
expect(stale.markdown).toContain("- pass health probes: 1 of 4 failed (0 server-side, 0 unclassified, 1 client-side, informational)");
|
|
expect(stale.markdown).toContain("- pass swap shape: no stop-then-start release");
|
|
Object.assign(failure, { class: "unclassified", reason: "diagnosis pending", state: "pending" });
|
|
const pending = await gradeHealth(samples, [], async () => 1);
|
|
expect(pending.pass).toBe(false);
|
|
expect(pending.markdown).toContain("FAIL swap shape: stop-then-start at release 1");
|
|
expect(pending.markdown).toContain("diagnosis did not finish before the grade");
|
|
});
|
|
|
|
const gradeHealth = async (samples: HealthSample[], order: string[], settle: () => Promise<number>) => {
|
|
const dir = await mkdtemp(path.join(os.tmpdir(), "hosted-gate-"));
|
|
dirs.push(dir);
|
|
return gradeHosted({ api: apiFor([issue("i1")], [runOf("r1", "i1", 0, 10)]), companyId: "c1", agentIds: ["a1"], releases: [], health: () => continuity([]),
|
|
healthSamples: () => samples, stopHealthProbe: async () => { order.push("stop"); }, settleDiagnostics: settle, apiContinuity: () => continuity([]),
|
|
stopObserver: async () => {}, observedClicks: () => new Map(), lastReleaseAt: Date.now() - 1_000, settleMs: 5, drainMs: 5, dir, cancelled: () => false,
|
|
record: () => {}, pollMs: 5, tasks: () => [record()], wantedReleases: 0 });
|
|
};
|
|
|
|
it("fails the gate and records why when the agent list cannot be read", async () => {
|
|
agentList = null;
|
|
try {
|
|
const graded = await grade([issue("i1")], [runOf("r1", "i1", 0, 10)], [record()], 0);
|
|
expect(graded.pass).toBe(false);
|
|
expect(graded.markdown).toContain("FAIL agent slot evidence");
|
|
expect(events).toEqual(expect.arrayContaining(["hosted_agents_unavailable", "hosted_agent_slots_unavailable"]));
|
|
} finally {
|
|
agentList = agents;
|
|
}
|
|
});
|
|
});
|