Files
PaperClipAI/server/src/__tests__/run-liveness.test.ts
1fe89eb8f8 Enforce durable external-wait liveness (#9373)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - The heartbeat/recovery subsystem decides whether an agent run has a
durable continuation path after the process stops.
> - External waits need stricter semantics than local background
watchers: a killed local process is not durable, while a first-class
blocker/monitor/scheduled wake is.
> - Without that distinction, recovery can repeatedly treat
adapter-failed continuations as live work and obscure the real reason a
task stopped.
> - This pull request adds explicit durable external-wait liveness
handling and documents the expected execution semantics.
> - It also improves operator-visible recovery evidence so invalid
external-wait paths explain why they were rejected.
> - The benefit is clearer recovery behavior, fewer duplicate
continuation recoveries, and a safer contract for monitor-backed
external waits.

## Linked Issues or Issue Description

- Refs #5978
- Related PRs: #4988, #7495, #8502

## What Changed

- Added durable external-wait liveness classification so
local/background watchers are not accepted as durable live paths after
the owning process exits.
- Preserved first-class blocker/monitor/scheduled wake paths as valid
external-wait continuations.
- Added backend regression coverage for killed watcher failure,
monitor-backed durable wait resumption, normal completion, blocker
behavior, and no duplicate recovery.
- Added adapter utility coverage for terminal cleanup behavior used by
local process adapters.
- Surfaced invalid external-wait recovery evidence in the recovery
action card and run ledger.
- Updated execution semantics documentation and the V1 implementation
contract.

## Verification

- `pnpm check:token-gates` passed.
- `pnpm -r typecheck` passed.
- `node scripts/run-vitest-stable.mjs --mode general --group
general-server` equivalent lane passed in CI-clean env: 238 files, 2164
tests passed, 1 skipped.
- `node scripts/run-vitest-stable.mjs --mode general --group
general-workspaces-a` passed in fully Paperclip-env-clean env: UI 305
files / 2430 tests; CLI 43 files / 230 tests.
- `node scripts/run-vitest-stable.mjs --mode general --group
general-workspaces-b` passed in fully Paperclip-env-clean env:
shared/db/adapters/plugin packages all green.
- `node scripts/run-vitest-stable.mjs --mode serialized` passed in fully
Paperclip-env-clean env: 107 serialized server suites green, including
84/84 heartbeat-process-recovery tests.
- `pnpm build` passed in fully Paperclip-env-clean env.

Notes: running `pnpm test:run` directly inside the Paperclip heartbeat
environment exposed local harness env contamination in existing tests
(`PAPERCLIP_CONFIG`, `PAPERCLIP_DB_BACKUP_DIR`, and
`PAPERCLIP_WORKTREE_START_POINT`). Re-running the same lanes with
inherited `PAPERCLIP_*` and port env removed produced the CI-equivalent
green results above.

## Risks

- Medium behavioral risk: this changes recovery classification for
stopped local external-wait processes, so adapters relying on unmanaged
background watchers must use blockers, monitors, scheduled wakes, or
explicit durable handoff instead.
- Low UI risk: recovery-card copy changes are covered by component tests
and Storybook screenshot QA.
- No database migration is included.

> 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

- OpenAI Codex, GPT-5-based coding agent, tool-enabled terminal/code
execution. Exact context-window metadata was not exposed in the runtime.

## 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

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-10 13:21:12 -05:00

232 lines
7.3 KiB
TypeScript

import { describe, expect, it } from "vitest";
import { classifyRunLiveness } from "../services/run-liveness.ts";
const baseInput = {
runStatus: "succeeded",
issue: {
status: "in_progress",
title: "Implement feature",
description: "Add the requested behavior.",
},
resultJson: null,
stdoutExcerpt: null,
stderrExcerpt: null,
error: null,
errorCode: null,
continuationAttempt: 0,
evidence: null,
};
describe("run liveness classifier", () => {
it("classifies text-only future work as plan_only", () => {
const classification = classifyRunLiveness({
...baseInput,
resultJson: {
summary: "I will inspect the repo next and then implement the fix.",
},
});
expect(classification.livenessState).toBe("plan_only");
expect(classification.actionability).toBe("runnable");
expect(classification.nextAction).toContain("inspect the repo");
});
it("classifies empty successful output as empty_response", () => {
const classification = classifyRunLiveness(baseInput);
expect(classification.livenessState).toBe("empty_response");
expect(classification.actionability).toBe("unknown");
});
it("treats issue comments, documents, products, and actions as progress", () => {
const latestEvidenceAt = new Date("2026-04-18T12:00:00Z");
const classification = classifyRunLiveness({
...baseInput,
resultJson: {
summary: "Updated implementation.",
},
evidence: {
issueCommentsCreated: 1,
documentRevisionsCreated: 1,
workProductsCreated: 1,
toolOrActionEventsCreated: 1,
latestEvidenceAt,
},
});
expect(classification.livenessState).toBe("advanced");
expect(classification.lastUsefulActionAt).toBe(latestEvidenceAt);
});
it("does not treat workspace operations alone as concrete progress", () => {
const classification = classifyRunLiveness({
...baseInput,
resultJson: {
summary: "I will inspect the repo next.",
},
evidence: {
workspaceOperationsCreated: 1,
latestEvidenceAt: new Date("2026-04-18T12:00:00Z"),
},
});
expect(classification.livenessState).toBe("plan_only");
expect(classification.lastUsefulActionAt).toBeNull();
});
it("exempts planning/document tasks from plan-only retry classification", () => {
const classification = classifyRunLiveness({
...baseInput,
issue: {
status: "in_progress",
title: "Draft implementation plan",
description: "Create a plan for the work.",
},
resultJson: {
summary: "Plan:\n- Inspect files\n- Implement after approval",
},
});
expect(classification.livenessState).toBe("advanced");
});
it("exempts runs that update the plan document from plan-only classification", () => {
const classification = classifyRunLiveness({
...baseInput,
resultJson: {
summary: "Next steps:\n- inspect files\n- implement the service",
},
evidence: {
documentRevisionsCreated: 1,
planDocumentRevisionsCreated: 1,
latestEvidenceAt: new Date("2026-04-18T12:00:00Z"),
},
});
expect(classification.livenessState).toBe("advanced");
});
it("classifies done issues as completed", () => {
const classification = classifyRunLiveness({
...baseInput,
issue: {
...baseInput.issue,
status: "done",
},
resultJson: {
summary: "Finished the implementation.",
},
});
expect(classification.livenessState).toBe("completed");
});
it("classifies declared blockers as blocked", () => {
const classification = classifyRunLiveness({
...baseInput,
resultJson: {
summary: "I cannot proceed because I need access credentials.",
},
});
expect(classification.livenessState).toBe("blocked");
expect(classification.actionability).toBe("blocked_external");
});
it("treats PAP-2000-style validation output as runnable follow-up, not an external blocker", () => {
const classification = classifyRunLiveness({
...baseInput,
resultJson: {
summary: "PAP-1949 remains blocked until PAP-2000 is resolved.",
},
issueCommentBodies: [
[
"Validation is ready for the next pass.",
"",
"- Blocked chain context: PAP-1949 -> PAP-1999 -> PAP-2000",
"- Next action: run npm test and report the row counts.",
].join("\n"),
],
});
expect(classification.livenessState).toBe("plan_only");
expect(classification.actionability).toBe("runnable");
expect(classification.nextAction).toBe("run npm test and report the row counts.");
});
it("prefers durable comments over raw transcript next-action noise", () => {
const classification = classifyRunLiveness({
...baseInput,
issueCommentBodies: ["Next action: run pnpm test -- --runInBand."],
stdoutExcerpt: [
"tool_call: write",
"command: rm -rf production-data",
"Next action: deploy to production",
].join("\n"),
});
expect(classification.actionability).toBe("runnable");
expect(classification.nextAction).toBe("run pnpm test -- --runInBand.");
});
it("keeps approval requests out of automatic continuation", () => {
const classification = classifyRunLiveness({
...baseInput,
resultJson: {
summary: "Next action: wait for board approval before continuing.",
},
});
expect(classification.livenessState).toBe("blocked");
expect(classification.actionability).toBe("approval_required");
expect(classification.nextAction).toBe("wait for board approval before continuing.");
});
it("routes production-sensitive next actions to manager review", () => {
const classification = classifyRunLiveness({
...baseInput,
resultJson: {
summary: "Next action: deploy to production and verify live traffic.",
},
});
expect(classification.livenessState).toBe("needs_followup");
expect(classification.actionability).toBe("manager_review");
expect(classification.nextAction).toBe("deploy to production and verify live traffic.");
});
it("uses killed background-task evidence instead of a generic failed-run reason", () => {
const classification = classifyRunLiveness({
...baseInput,
runStatus: "failed",
errorCode: "process_lost",
resultJson: {
stopReason: "unmanaged_background_task_stopped",
unmanagedBackgroundTask: {
kind: "orphaned_process_group_cleanup",
stopped: true,
stopReason: "unmanaged_background_task_stopped",
reason: "unmanaged background task stopped; no durable live path",
},
},
});
expect(classification.livenessState).toBe("failed");
expect(classification.livenessReason).toBe("unmanaged background task stopped; no durable live path");
});
it("marks unclear useful output as unknown actionability", () => {
const classification = classifyRunLiveness({
...baseInput,
resultJson: {
summary: "Observed mixed output and left notes for a later pass.",
},
});
expect(classification.livenessState).toBe("needs_followup");
expect(classification.actionability).toBe("unknown");
expect(classification.nextAction).toBeNull();
});
});